]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render.rs
Auto merge of #50748 - steveklabnik:remove-simd-note, r=alexcrichton
[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
36 pub use self::ExternalLocation::*;
37
38 use std::borrow::Cow;
39 use std::cell::RefCell;
40 use std::cmp::Ordering;
41 use std::collections::{BTreeMap, HashSet, VecDeque};
42 use std::default::Default;
43 use std::error;
44 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
45 use std::fs::{self, File, OpenOptions};
46 use std::io::prelude::*;
47 use std::io::{self, BufWriter, BufReader};
48 use std::iter::repeat;
49 use std::mem;
50 use std::path::{PathBuf, Path, Component};
51 use std::str;
52 use std::sync::Arc;
53
54 use externalfiles::ExternalHtml;
55
56 use serialize::json::{ToJson, Json, as_json};
57 use syntax::ast;
58 use syntax::codemap::FileName;
59 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
60 use rustc::middle::privacy::AccessLevels;
61 use rustc::middle::stability;
62 use rustc::hir;
63 use rustc::util::nodemap::{FxHashMap, FxHashSet};
64 use rustc_data_structures::flock;
65 use rustc_target::spec::abi;
66
67 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
68 use doctree;
69 use fold::DocFolder;
70 use html::escape::Escape;
71 use html::format::{ConstnessSpace};
72 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
73 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
74 use html::format::fmt_impl_for_trait_page;
75 use html::item_type::ItemType;
76 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine};
77 use html::{highlight, layout};
78
79 /// A pair of name and its optional document.
80 pub type NameDoc = (String, Option<String>);
81
82 /// Major driving force in all rustdoc rendering. This contains information
83 /// about where in the tree-like hierarchy rendering is occurring and controls
84 /// how the current page is being rendered.
85 ///
86 /// It is intended that this context is a lightweight object which can be fairly
87 /// easily cloned because it is cloned per work-job (about once per item in the
88 /// rustdoc tree).
89 #[derive(Clone)]
90 pub struct Context {
91     /// Current hierarchy of components leading down to what's currently being
92     /// rendered
93     pub current: Vec<String>,
94     /// The current destination folder of where HTML artifacts should be placed.
95     /// This changes as the context descends into the module hierarchy.
96     pub dst: PathBuf,
97     /// A flag, which when `true`, will render pages which redirect to the
98     /// real location of an item. This is used to allow external links to
99     /// publicly reused items to redirect to the right location.
100     pub render_redirect_pages: bool,
101     pub shared: Arc<SharedContext>,
102 }
103
104 pub struct SharedContext {
105     /// The path to the crate root source minus the file name.
106     /// Used for simplifying paths to the highlighted source code files.
107     pub src_root: PathBuf,
108     /// This describes the layout of each page, and is not modified after
109     /// creation of the context (contains info like the favicon and added html).
110     pub layout: layout::Layout,
111     /// This flag indicates whether `[src]` links should be generated or not. If
112     /// the source files are present in the html rendering, then this will be
113     /// `true`.
114     pub include_sources: bool,
115     /// The local file sources we've emitted and their respective url-paths.
116     pub local_sources: FxHashMap<PathBuf, String>,
117     /// All the passes that were run on this crate.
118     pub passes: FxHashSet<String>,
119     /// The base-URL of the issue tracker for when an item has been tagged with
120     /// an issue number.
121     pub issue_tracker_base_url: Option<String>,
122     /// The given user css file which allow to customize the generated
123     /// documentation theme.
124     pub css_file_extension: Option<PathBuf>,
125     /// The directories that have already been created in this doc run. Used to reduce the number
126     /// of spurious `create_dir_all` calls.
127     pub created_dirs: RefCell<FxHashSet<PathBuf>>,
128     /// This flag indicates whether listings of modules (in the side bar and documentation itself)
129     /// should be ordered alphabetically or in order of appearance (in the source code).
130     pub sort_modules_alphabetically: bool,
131     /// Additional themes to be added to the generated docs.
132     pub themes: Vec<PathBuf>,
133     /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
134     /// "light-v2.css").
135     pub resource_suffix: String,
136 }
137
138 impl SharedContext {
139     fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
140         let mut dirs = self.created_dirs.borrow_mut();
141         if !dirs.contains(dst) {
142             fs::create_dir_all(dst)?;
143             dirs.insert(dst.to_path_buf());
144         }
145
146         Ok(())
147     }
148 }
149
150 impl SharedContext {
151     /// Returns whether the `collapse-docs` pass was run on this crate.
152     pub fn was_collapsed(&self) -> bool {
153         self.passes.contains("collapse-docs")
154     }
155
156     /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
157     /// `collapsed_doc_value` of the given item.
158     pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
159         if self.was_collapsed() {
160             item.collapsed_doc_value().map(|s| s.into())
161         } else {
162             item.doc_value().map(|s| s.into())
163         }
164     }
165 }
166
167 /// Indicates where an external crate can be found.
168 pub enum ExternalLocation {
169     /// Remote URL root of the external crate
170     Remote(String),
171     /// This external crate can be found in the local doc/ folder
172     Local,
173     /// The external crate could not be found.
174     Unknown,
175 }
176
177 /// Metadata about implementations for a type or trait.
178 #[derive(Clone)]
179 pub struct Impl {
180     pub impl_item: clean::Item,
181 }
182
183 impl Impl {
184     fn inner_impl(&self) -> &clean::Impl {
185         match self.impl_item.inner {
186             clean::ImplItem(ref impl_) => impl_,
187             _ => panic!("non-impl item found in impl")
188         }
189     }
190
191     fn trait_did(&self) -> Option<DefId> {
192         self.inner_impl().trait_.def_id()
193     }
194 }
195
196 #[derive(Debug)]
197 pub struct Error {
198     file: PathBuf,
199     error: io::Error,
200 }
201
202 impl error::Error for Error {
203     fn description(&self) -> &str {
204         self.error.description()
205     }
206 }
207
208 impl Display for Error {
209     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
210         write!(f, "\"{}\": {}", self.file.display(), self.error)
211     }
212 }
213
214 impl Error {
215     pub fn new(e: io::Error, file: &Path) -> Error {
216         Error {
217             file: file.to_path_buf(),
218             error: e,
219         }
220     }
221 }
222
223 macro_rules! try_none {
224     ($e:expr, $file:expr) => ({
225         use std::io;
226         match $e {
227             Some(e) => e,
228             None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
229                                           $file))
230         }
231     })
232 }
233
234 macro_rules! try_err {
235     ($e:expr, $file:expr) => ({
236         match $e {
237             Ok(e) => e,
238             Err(e) => return Err(Error::new(e, $file)),
239         }
240     })
241 }
242
243 /// This cache is used to store information about the `clean::Crate` being
244 /// rendered in order to provide more useful documentation. This contains
245 /// information like all implementors of a trait, all traits a type implements,
246 /// documentation for all known traits, etc.
247 ///
248 /// This structure purposefully does not implement `Clone` because it's intended
249 /// to be a fairly large and expensive structure to clone. Instead this adheres
250 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
251 /// rendering threads.
252 #[derive(Default)]
253 pub struct Cache {
254     /// Mapping of typaram ids to the name of the type parameter. This is used
255     /// when pretty-printing a type (so pretty printing doesn't have to
256     /// painfully maintain a context like this)
257     pub typarams: FxHashMap<DefId, String>,
258
259     /// Maps a type id to all known implementations for that type. This is only
260     /// recognized for intra-crate `ResolvedPath` types, and is used to print
261     /// out extra documentation on the page of an enum/struct.
262     ///
263     /// The values of the map are a list of implementations and documentation
264     /// found on that implementation.
265     pub impls: FxHashMap<DefId, Vec<Impl>>,
266
267     /// Maintains a mapping of local crate node ids to the fully qualified name
268     /// and "short type description" of that node. This is used when generating
269     /// URLs when a type is being linked to. External paths are not located in
270     /// this map because the `External` type itself has all the information
271     /// necessary.
272     pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
273
274     /// Similar to `paths`, but only holds external paths. This is only used for
275     /// generating explicit hyperlinks to other crates.
276     pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
277
278     /// Maps local def ids of exported types to fully qualified paths.
279     /// Unlike 'paths', this mapping ignores any renames that occur
280     /// due to 'use' statements.
281     ///
282     /// This map is used when writing out the special 'implementors'
283     /// javascript file. By using the exact path that the type
284     /// is declared with, we ensure that each path will be identical
285     /// to the path used if the corresponding type is inlined. By
286     /// doing this, we can detect duplicate impls on a trait page, and only display
287     /// the impl for the inlined type.
288     pub exact_paths: FxHashMap<DefId, Vec<String>>,
289
290     /// This map contains information about all known traits of this crate.
291     /// Implementations of a crate should inherit the documentation of the
292     /// parent trait if no extra documentation is specified, and default methods
293     /// should show up in documentation about trait implementations.
294     pub traits: FxHashMap<DefId, clean::Trait>,
295
296     /// When rendering traits, it's often useful to be able to list all
297     /// implementors of the trait, and this mapping is exactly, that: a mapping
298     /// of trait ids to the list of known implementors of the trait
299     pub implementors: FxHashMap<DefId, Vec<Impl>>,
300
301     /// Cache of where external crate documentation can be found.
302     pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
303
304     /// Cache of where documentation for primitives can be found.
305     pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
306
307     // Note that external items for which `doc(hidden)` applies to are shown as
308     // non-reachable while local items aren't. This is because we're reusing
309     // the access levels from crateanalysis.
310     pub access_levels: Arc<AccessLevels<DefId>>,
311
312     /// The version of the crate being documented, if given fron the `--crate-version` flag.
313     pub crate_version: Option<String>,
314
315     // Private fields only used when initially crawling a crate to build a cache
316
317     stack: Vec<String>,
318     parent_stack: Vec<DefId>,
319     parent_is_trait_impl: bool,
320     search_index: Vec<IndexItem>,
321     stripped_mod: bool,
322     deref_trait_did: Option<DefId>,
323     deref_mut_trait_did: Option<DefId>,
324     owned_box_did: Option<DefId>,
325     masked_crates: FxHashSet<CrateNum>,
326
327     // In rare case where a structure is defined in one module but implemented
328     // in another, if the implementing module is parsed before defining module,
329     // then the fully qualified name of the structure isn't presented in `paths`
330     // yet when its implementation methods are being indexed. Caches such methods
331     // and their parent id here and indexes them at the end of crate parsing.
332     orphan_impl_items: Vec<(DefId, clean::Item)>,
333
334     /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
335     /// we need the alias element to have an array of items.
336     aliases: FxHashMap<String, Vec<IndexItem>>,
337 }
338
339 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
340 /// Later on moved into `CACHE_KEY`.
341 #[derive(Default)]
342 pub struct RenderInfo {
343     pub inlined: FxHashSet<DefId>,
344     pub external_paths: ::core::ExternalPaths,
345     pub external_typarams: FxHashMap<DefId, String>,
346     pub exact_paths: FxHashMap<DefId, Vec<String>>,
347     pub deref_trait_did: Option<DefId>,
348     pub deref_mut_trait_did: Option<DefId>,
349     pub owned_box_did: Option<DefId>,
350 }
351
352 /// Helper struct to render all source code to HTML pages
353 struct SourceCollector<'a> {
354     scx: &'a mut SharedContext,
355
356     /// Root destination to place all HTML output into
357     dst: PathBuf,
358 }
359
360 /// Wrapper struct to render the source code of a file. This will do things like
361 /// adding line numbers to the left-hand side.
362 struct Source<'a>(&'a str);
363
364 // Helper structs for rendering items/sidebars and carrying along contextual
365 // information
366
367 #[derive(Copy, Clone)]
368 struct Item<'a> {
369     cx: &'a Context,
370     item: &'a clean::Item,
371 }
372
373 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
374
375 /// Struct representing one entry in the JS search index. These are all emitted
376 /// by hand to a large JS file at the end of cache-creation.
377 #[derive(Debug)]
378 struct IndexItem {
379     ty: ItemType,
380     name: String,
381     path: String,
382     desc: String,
383     parent: Option<DefId>,
384     parent_idx: Option<usize>,
385     search_type: Option<IndexItemFunctionType>,
386 }
387
388 impl ToJson for IndexItem {
389     fn to_json(&self) -> Json {
390         assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
391
392         let mut data = Vec::with_capacity(6);
393         data.push((self.ty as usize).to_json());
394         data.push(self.name.to_json());
395         data.push(self.path.to_json());
396         data.push(self.desc.to_json());
397         data.push(self.parent_idx.to_json());
398         data.push(self.search_type.to_json());
399
400         Json::Array(data)
401     }
402 }
403
404 /// A type used for the search index.
405 #[derive(Debug)]
406 struct Type {
407     name: Option<String>,
408     generics: Option<Vec<String>>,
409 }
410
411 impl ToJson for Type {
412     fn to_json(&self) -> Json {
413         match self.name {
414             Some(ref name) => {
415                 let mut data = BTreeMap::new();
416                 data.insert("n".to_owned(), name.to_json());
417                 if let Some(ref generics) = self.generics {
418                     data.insert("g".to_owned(), generics.to_json());
419                 }
420                 Json::Object(data)
421             },
422             None => Json::Null
423         }
424     }
425 }
426
427 /// Full type of functions/methods in the search index.
428 #[derive(Debug)]
429 struct IndexItemFunctionType {
430     inputs: Vec<Type>,
431     output: Option<Type>,
432 }
433
434 impl ToJson for IndexItemFunctionType {
435     fn to_json(&self) -> Json {
436         // If we couldn't figure out a type, just write `null`.
437         if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
438             Json::Null
439         } else {
440             let mut data = BTreeMap::new();
441             if !self.inputs.is_empty() {
442                 data.insert("i".to_owned(), self.inputs.to_json());
443             }
444             if let Some(ref output) = self.output {
445                 data.insert("o".to_owned(), output.to_json());
446             }
447             Json::Object(data)
448         }
449     }
450 }
451
452 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
453 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
454 thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> = RefCell::new(init_ids()));
455
456 fn init_ids() -> FxHashMap<String, usize> {
457     [
458      "main",
459      "search",
460      "help",
461      "TOC",
462      "render-detail",
463      "associated-types",
464      "associated-const",
465      "required-methods",
466      "provided-methods",
467      "implementors",
468      "synthetic-implementors",
469      "implementors-list",
470      "synthetic-implementors-list",
471      "methods",
472      "deref-methods",
473      "implementations",
474     ].into_iter().map(|id| (String::from(*id), 1)).collect()
475 }
476
477 /// This method resets the local table of used ID attributes. This is typically
478 /// used at the beginning of rendering an entire HTML page to reset from the
479 /// previous state (if any).
480 pub fn reset_ids(embedded: bool) {
481     USED_ID_MAP.with(|s| {
482         *s.borrow_mut() = if embedded {
483             init_ids()
484         } else {
485             FxHashMap()
486         };
487     });
488 }
489
490 pub fn derive_id(candidate: String) -> String {
491     USED_ID_MAP.with(|map| {
492         let id = match map.borrow_mut().get_mut(&candidate) {
493             None => candidate,
494             Some(a) => {
495                 let id = format!("{}-{}", candidate, *a);
496                 *a += 1;
497                 id
498             }
499         };
500
501         map.borrow_mut().insert(id.clone(), 1);
502         id
503     })
504 }
505
506 /// Generates the documentation for `crate` into the directory `dst`
507 pub fn run(mut krate: clean::Crate,
508            external_html: &ExternalHtml,
509            playground_url: Option<String>,
510            dst: PathBuf,
511            resource_suffix: String,
512            passes: FxHashSet<String>,
513            css_file_extension: Option<PathBuf>,
514            renderinfo: RenderInfo,
515            sort_modules_alphabetically: bool,
516            themes: Vec<PathBuf>) -> Result<(), Error> {
517     let src_root = match krate.src {
518         FileName::Real(ref p) => match p.parent() {
519             Some(p) => p.to_path_buf(),
520             None => PathBuf::new(),
521         },
522         _ => PathBuf::new(),
523     };
524     let mut scx = SharedContext {
525         src_root,
526         passes,
527         include_sources: true,
528         local_sources: FxHashMap(),
529         issue_tracker_base_url: None,
530         layout: layout::Layout {
531             logo: "".to_string(),
532             favicon: "".to_string(),
533             external_html: external_html.clone(),
534             krate: krate.name.clone(),
535         },
536         css_file_extension: css_file_extension.clone(),
537         created_dirs: RefCell::new(FxHashSet()),
538         sort_modules_alphabetically,
539         themes,
540         resource_suffix,
541     };
542
543     // If user passed in `--playground-url` arg, we fill in crate name here
544     if let Some(url) = playground_url {
545         markdown::PLAYGROUND.with(|slot| {
546             *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
547         });
548     }
549
550     // Crawl the crate attributes looking for attributes which control how we're
551     // going to emit HTML
552     if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
553         for attr in attrs.lists("doc") {
554             let name = attr.name().map(|s| s.as_str());
555             match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
556                 (Some("html_favicon_url"), Some(s)) => {
557                     scx.layout.favicon = s.to_string();
558                 }
559                 (Some("html_logo_url"), Some(s)) => {
560                     scx.layout.logo = s.to_string();
561                 }
562                 (Some("html_playground_url"), Some(s)) => {
563                     markdown::PLAYGROUND.with(|slot| {
564                         let name = krate.name.clone();
565                         *slot.borrow_mut() = Some((Some(name), s.to_string()));
566                     });
567                 }
568                 (Some("issue_tracker_base_url"), Some(s)) => {
569                     scx.issue_tracker_base_url = Some(s.to_string());
570                 }
571                 (Some("html_no_source"), None) if attr.is_word() => {
572                     scx.include_sources = false;
573                 }
574                 _ => {}
575             }
576         }
577     }
578     try_err!(fs::create_dir_all(&dst), &dst);
579     krate = render_sources(&dst, &mut scx, krate)?;
580     let cx = Context {
581         current: Vec::new(),
582         dst,
583         render_redirect_pages: false,
584         shared: Arc::new(scx),
585     };
586
587     // Crawl the crate to build various caches used for the output
588     let RenderInfo {
589         inlined: _,
590         external_paths,
591         external_typarams,
592         exact_paths,
593         deref_trait_did,
594         deref_mut_trait_did,
595         owned_box_did,
596     } = renderinfo;
597
598     let external_paths = external_paths.into_iter()
599         .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
600         .collect();
601
602     let mut cache = Cache {
603         impls: FxHashMap(),
604         external_paths,
605         exact_paths,
606         paths: FxHashMap(),
607         implementors: FxHashMap(),
608         stack: Vec::new(),
609         parent_stack: Vec::new(),
610         search_index: Vec::new(),
611         parent_is_trait_impl: false,
612         extern_locations: FxHashMap(),
613         primitive_locations: FxHashMap(),
614         stripped_mod: false,
615         access_levels: krate.access_levels.clone(),
616         crate_version: krate.version.take(),
617         orphan_impl_items: Vec::new(),
618         traits: mem::replace(&mut krate.external_traits, FxHashMap()),
619         deref_trait_did,
620         deref_mut_trait_did,
621         owned_box_did,
622         masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
623         typarams: external_typarams,
624         aliases: FxHashMap(),
625     };
626
627     // Cache where all our extern crates are located
628     for &(n, ref e) in &krate.externs {
629         let src_root = match e.src {
630             FileName::Real(ref p) => match p.parent() {
631                 Some(p) => p.to_path_buf(),
632                 None => PathBuf::new(),
633             },
634             _ => PathBuf::new(),
635         };
636         cache.extern_locations.insert(n, (e.name.clone(), src_root,
637                                           extern_location(e, &cx.dst)));
638
639         let did = DefId { krate: n, index: CRATE_DEF_INDEX };
640         cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
641     }
642
643     // Cache where all known primitives have their documentation located.
644     //
645     // Favor linking to as local extern as possible, so iterate all crates in
646     // reverse topological order.
647     for &(_, ref e) in krate.externs.iter().rev() {
648         for &(def_id, prim, _) in &e.primitives {
649             cache.primitive_locations.insert(prim, def_id);
650         }
651     }
652     for &(def_id, prim, _) in &krate.primitives {
653         cache.primitive_locations.insert(prim, def_id);
654     }
655
656     cache.stack.push(krate.name.clone());
657     krate = cache.fold_crate(krate);
658
659     // Build our search index
660     let index = build_index(&krate, &mut cache);
661
662     // Freeze the cache now that the index has been built. Put an Arc into TLS
663     // for future parallelization opportunities
664     let cache = Arc::new(cache);
665     CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
666     CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
667
668     write_shared(&cx, &krate, &*cache, index)?;
669
670     // And finally render the whole crate's documentation
671     cx.krate(krate)
672 }
673
674 /// Build the search index from the collected metadata
675 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
676     let mut nodeid_to_pathid = FxHashMap();
677     let mut crate_items = Vec::with_capacity(cache.search_index.len());
678     let mut crate_paths = Vec::<Json>::new();
679
680     let Cache { ref mut search_index,
681                 ref orphan_impl_items,
682                 ref mut paths, .. } = *cache;
683
684     // Attach all orphan items to the type's definition if the type
685     // has since been learned.
686     for &(did, ref item) in orphan_impl_items {
687         if let Some(&(ref fqp, _)) = paths.get(&did) {
688             search_index.push(IndexItem {
689                 ty: item.type_(),
690                 name: item.name.clone().unwrap(),
691                 path: fqp[..fqp.len() - 1].join("::"),
692                 desc: plain_summary_line(item.doc_value()),
693                 parent: Some(did),
694                 parent_idx: None,
695                 search_type: get_index_search_type(&item),
696             });
697         }
698     }
699
700     // Reduce `NodeId` in paths into smaller sequential numbers,
701     // and prune the paths that do not appear in the index.
702     let mut lastpath = String::new();
703     let mut lastpathid = 0usize;
704
705     for item in search_index {
706         item.parent_idx = item.parent.map(|nodeid| {
707             if nodeid_to_pathid.contains_key(&nodeid) {
708                 *nodeid_to_pathid.get(&nodeid).unwrap()
709             } else {
710                 let pathid = lastpathid;
711                 nodeid_to_pathid.insert(nodeid, pathid);
712                 lastpathid += 1;
713
714                 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
715                 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
716                 pathid
717             }
718         });
719
720         // Omit the parent path if it is same to that of the prior item.
721         if lastpath == item.path {
722             item.path.clear();
723         } else {
724             lastpath = item.path.clone();
725         }
726         crate_items.push(item.to_json());
727     }
728
729     let crate_doc = krate.module.as_ref().map(|module| {
730         plain_summary_line(module.doc_value())
731     }).unwrap_or(String::new());
732
733     let mut crate_data = BTreeMap::new();
734     crate_data.insert("doc".to_owned(), Json::String(crate_doc));
735     crate_data.insert("items".to_owned(), Json::Array(crate_items));
736     crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
737
738     // Collect the index into a string
739     format!("searchIndex[{}] = {};",
740             as_json(&krate.name),
741             Json::Object(crate_data))
742 }
743
744 fn write_shared(cx: &Context,
745                 krate: &clean::Crate,
746                 cache: &Cache,
747                 search_index: String) -> Result<(), Error> {
748     // Write out the shared files. Note that these are shared among all rustdoc
749     // docs placed in the output directory, so this needs to be a synchronized
750     // operation with respect to all other rustdocs running around.
751     let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
752
753     // Add all the static files. These may already exist, but we just
754     // overwrite them anyway to make sure that they're fresh and up-to-date.
755
756     write(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
757           include_bytes!("static/rustdoc.css"))?;
758     write(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
759           include_bytes!("static/settings.css"))?;
760
761     // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
762     // then we'll run over the "official" styles.
763     let mut themes: HashSet<String> = HashSet::new();
764
765     for entry in &cx.shared.themes {
766         let mut content = Vec::with_capacity(100000);
767
768         let mut f = try_err!(File::open(&entry), &entry);
769         try_err!(f.read_to_end(&mut content), &entry);
770         let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
771         let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
772         write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
773               content.as_slice())?;
774         themes.insert(theme.to_owned());
775     }
776
777     write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
778           include_bytes!("static/brush.svg"))?;
779     write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
780           include_bytes!("static/wheel.svg"))?;
781     write(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
782           include_bytes!("static/themes/light.css"))?;
783     themes.insert("light".to_owned());
784     write(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
785           include_bytes!("static/themes/dark.css"))?;
786     themes.insert("dark".to_owned());
787
788     let mut themes: Vec<&String> = themes.iter().collect();
789     themes.sort();
790     // To avoid theme switch latencies as much as possible, we put everything theme related
791     // at the beginning of the html files into another js file.
792     write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
793           format!(
794 r#"var themes = document.getElementById("theme-choices");
795 var themePicker = document.getElementById("theme-picker");
796
797 function switchThemeButtonState() {{
798     if (themes.style.display === "block") {{
799         themes.style.display = "none";
800         themePicker.style.borderBottomRightRadius = "3px";
801         themePicker.style.borderBottomLeftRadius = "3px";
802     }} else {{
803         themes.style.display = "block";
804         themePicker.style.borderBottomRightRadius = "0";
805         themePicker.style.borderBottomLeftRadius = "0";
806     }}
807 }};
808
809 function handleThemeButtonsBlur(e) {{
810     var active = document.activeElement;
811     var related = e.relatedTarget;
812
813     if (active.id !== "themePicker" &&
814         (!active.parentNode || active.parentNode.id !== "theme-choices") &&
815         (!related ||
816          (related.id !== "themePicker" &&
817           (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
818         switchThemeButtonState();
819     }}
820 }}
821
822 themePicker.onclick = switchThemeButtonState;
823 themePicker.onblur = handleThemeButtonsBlur;
824 [{}].forEach(function(item) {{
825     var but = document.createElement('button');
826     but.innerHTML = item;
827     but.onclick = function(el) {{
828         switchTheme(currentTheme, mainTheme, item);
829     }};
830     but.onblur = handleThemeButtonsBlur;
831     themes.appendChild(but);
832 }});"#,
833                  themes.iter()
834                        .map(|s| format!("\"{}\"", s))
835                        .collect::<Vec<String>>()
836                        .join(",")).as_bytes(),
837     )?;
838
839     write(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
840                       include_bytes!("static/main.js"))?;
841     write(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
842                       include_bytes!("static/settings.js"))?;
843
844     {
845         let mut data = format!("var resourcesSuffix = \"{}\";\n",
846                                cx.shared.resource_suffix).into_bytes();
847         data.extend_from_slice(include_bytes!("static/storage.js"));
848         write(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)), &data)?;
849     }
850
851     if let Some(ref css) = cx.shared.css_file_extension {
852         let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
853         try_err!(fs::copy(css, out), css);
854     }
855     write(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
856           include_bytes!("static/normalize.css"))?;
857     write(cx.dst.join("FiraSans-Regular.woff"),
858           include_bytes!("static/FiraSans-Regular.woff"))?;
859     write(cx.dst.join("FiraSans-Medium.woff"),
860           include_bytes!("static/FiraSans-Medium.woff"))?;
861     write(cx.dst.join("FiraSans-LICENSE.txt"),
862           include_bytes!("static/FiraSans-LICENSE.txt"))?;
863     write(cx.dst.join("Heuristica-Italic.woff"),
864           include_bytes!("static/Heuristica-Italic.woff"))?;
865     write(cx.dst.join("Heuristica-LICENSE.txt"),
866           include_bytes!("static/Heuristica-LICENSE.txt"))?;
867     write(cx.dst.join("SourceSerifPro-Regular.woff"),
868           include_bytes!("static/SourceSerifPro-Regular.woff"))?;
869     write(cx.dst.join("SourceSerifPro-Bold.woff"),
870           include_bytes!("static/SourceSerifPro-Bold.woff"))?;
871     write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
872           include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
873     write(cx.dst.join("SourceCodePro-Regular.woff"),
874           include_bytes!("static/SourceCodePro-Regular.woff"))?;
875     write(cx.dst.join("SourceCodePro-Semibold.woff"),
876           include_bytes!("static/SourceCodePro-Semibold.woff"))?;
877     write(cx.dst.join("SourceCodePro-LICENSE.txt"),
878           include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
879     write(cx.dst.join("LICENSE-MIT.txt"),
880           include_bytes!("static/LICENSE-MIT.txt"))?;
881     write(cx.dst.join("LICENSE-APACHE.txt"),
882           include_bytes!("static/LICENSE-APACHE.txt"))?;
883     write(cx.dst.join("COPYRIGHT.txt"),
884           include_bytes!("static/COPYRIGHT.txt"))?;
885
886     fn collect(path: &Path, krate: &str, key: &str) -> io::Result<Vec<String>> {
887         let mut ret = Vec::new();
888         if path.exists() {
889             for line in BufReader::new(File::open(path)?).lines() {
890                 let line = line?;
891                 if !line.starts_with(key) {
892                     continue;
893                 }
894                 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
895                     continue;
896                 }
897                 ret.push(line.to_string());
898             }
899         }
900         Ok(ret)
901     }
902
903     fn show_item(item: &IndexItem, krate: &str) -> String {
904         format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
905                 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
906                 if let Some(p) = item.parent_idx {
907                     format!(",'parent':{}", p)
908                 } else {
909                     String::new()
910                 })
911     }
912
913     let dst = cx.dst.join("aliases.js");
914     {
915         let mut all_aliases = try_err!(collect(&dst, &krate.name, "ALIASES"), &dst);
916         let mut w = try_err!(File::create(&dst), &dst);
917         let mut output = String::with_capacity(100);
918         for (alias, items) in &cache.aliases {
919             if items.is_empty() {
920                 continue
921             }
922             output.push_str(&format!("\"{}\":[{}],",
923                                      alias,
924                                      items.iter()
925                                           .map(|v| show_item(v, &krate.name))
926                                           .collect::<Vec<_>>()
927                                           .join(",")));
928         }
929         all_aliases.push(format!("ALIASES['{}'] = {{{}}};", krate.name, output));
930         all_aliases.sort();
931         try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
932         for aliases in &all_aliases {
933             try_err!(writeln!(&mut w, "{}", aliases), &dst);
934         }
935     }
936
937     // Update the search index
938     let dst = cx.dst.join("search-index.js");
939     let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
940     all_indexes.push(search_index);
941     // Sort the indexes by crate so the file will be generated identically even
942     // with rustdoc running in parallel.
943     all_indexes.sort();
944     let mut w = try_err!(File::create(&dst), &dst);
945     try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
946     for index in &all_indexes {
947         try_err!(writeln!(&mut w, "{}", *index), &dst);
948     }
949     try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
950
951     // Update the list of all implementors for traits
952     let dst = cx.dst.join("implementors");
953     for (&did, imps) in &cache.implementors {
954         // Private modules can leak through to this phase of rustdoc, which
955         // could contain implementations for otherwise private types. In some
956         // rare cases we could find an implementation for an item which wasn't
957         // indexed, so we just skip this step in that case.
958         //
959         // FIXME: this is a vague explanation for why this can't be a `get`, in
960         //        theory it should be...
961         let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
962             Some(p) => p,
963             None => match cache.external_paths.get(&did) {
964                 Some(p) => p,
965                 None => continue,
966             }
967         };
968
969         let mut have_impls = false;
970         let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
971         for imp in imps {
972             // If the trait and implementation are in the same crate, then
973             // there's no need to emit information about it (there's inlining
974             // going on). If they're in different crates then the crate defining
975             // the trait will be interested in our implementation.
976             if imp.impl_item.def_id.krate == did.krate { continue }
977             // If the implementation is from another crate then that crate
978             // should add it.
979             if !imp.impl_item.def_id.is_local() { continue }
980             have_impls = true;
981             write!(implementors, "{{text:{},synthetic:{},types:{}}},",
982                    as_json(&imp.inner_impl().to_string()),
983                    imp.inner_impl().synthetic,
984                    as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
985         }
986         implementors.push_str("];");
987
988         // Only create a js file if we have impls to add to it. If the trait is
989         // documented locally though we always create the file to avoid dead
990         // links.
991         if !have_impls && !cache.paths.contains_key(&did) {
992             continue;
993         }
994
995         let mut mydst = dst.clone();
996         for part in &remote_path[..remote_path.len() - 1] {
997             mydst.push(part);
998         }
999         try_err!(fs::create_dir_all(&mydst), &mydst);
1000         mydst.push(&format!("{}.{}.js",
1001                             remote_item_type.css_class(),
1002                             remote_path[remote_path.len() - 1]));
1003
1004         let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1005         all_implementors.push(implementors);
1006         // Sort the implementors by crate so the file will be generated
1007         // identically even with rustdoc running in parallel.
1008         all_implementors.sort();
1009
1010         let mut f = try_err!(File::create(&mydst), &mydst);
1011         try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1012         for implementor in &all_implementors {
1013             try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1014         }
1015         try_err!(writeln!(&mut f, "{}", r"
1016             if (window.register_implementors) {
1017                 window.register_implementors(implementors);
1018             } else {
1019                 window.pending_implementors = implementors;
1020             }
1021         "), &mydst);
1022         try_err!(writeln!(&mut f, r"}})()"), &mydst);
1023     }
1024     Ok(())
1025 }
1026
1027 fn render_sources(dst: &Path, scx: &mut SharedContext,
1028                   krate: clean::Crate) -> Result<clean::Crate, Error> {
1029     info!("emitting source files");
1030     let dst = dst.join("src").join(&krate.name);
1031     try_err!(fs::create_dir_all(&dst), &dst);
1032     let mut folder = SourceCollector {
1033         dst,
1034         scx,
1035     };
1036     Ok(folder.fold_crate(krate))
1037 }
1038
1039 /// Writes the entire contents of a string to a destination, not attempting to
1040 /// catch any errors.
1041 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1042     Ok(try_err!(fs::write(&dst, contents), &dst))
1043 }
1044
1045 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1046 /// things like ".." to components which preserve the "top down" hierarchy of a
1047 /// static HTML tree. Each component in the cleaned path will be passed as an
1048 /// argument to `f`. The very last component of the path (ie the file name) will
1049 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1050 // FIXME (#9639): The closure should deal with &[u8] instead of &str
1051 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
1052 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1053     F: FnMut(&str),
1054 {
1055     // make it relative, if possible
1056     let p = p.strip_prefix(src_root).unwrap_or(p);
1057
1058     let mut iter = p.components().peekable();
1059
1060     while let Some(c) = iter.next() {
1061         if !keep_filename && iter.peek().is_none() {
1062             break;
1063         }
1064
1065         match c {
1066             Component::ParentDir => f("up"),
1067             Component::Normal(c) => f(c.to_str().unwrap()),
1068             _ => continue,
1069         }
1070     }
1071 }
1072
1073 /// Attempts to find where an external crate is located, given that we're
1074 /// rendering in to the specified source destination.
1075 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
1076     // See if there's documentation generated into the local directory
1077     let local_location = dst.join(&e.name);
1078     if local_location.is_dir() {
1079         return Local;
1080     }
1081
1082     // Failing that, see if there's an attribute specifying where to find this
1083     // external crate
1084     e.attrs.lists("doc")
1085      .filter(|a| a.check_name("html_root_url"))
1086      .filter_map(|a| a.value_str())
1087      .map(|url| {
1088         let mut url = url.to_string();
1089         if !url.ends_with("/") {
1090             url.push('/')
1091         }
1092         Remote(url)
1093     }).next().unwrap_or(Unknown) // Well, at least we tried.
1094 }
1095
1096 impl<'a> DocFolder for SourceCollector<'a> {
1097     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1098         // If we're including source files, and we haven't seen this file yet,
1099         // then we need to render it out to the filesystem.
1100         if self.scx.include_sources
1101             // skip all invalid or macro spans
1102             && item.source.filename.is_real()
1103             // skip non-local items
1104             && item.def_id.is_local() {
1105
1106             // If it turns out that we couldn't read this file, then we probably
1107             // can't read any of the files (generating html output from json or
1108             // something like that), so just don't include sources for the
1109             // entire crate. The other option is maintaining this mapping on a
1110             // per-file basis, but that's probably not worth it...
1111             self.scx
1112                 .include_sources = match self.emit_source(&item.source.filename) {
1113                 Ok(()) => true,
1114                 Err(e) => {
1115                     println!("warning: source code was requested to be rendered, \
1116                               but processing `{}` had an error: {}",
1117                              item.source.filename, e);
1118                     println!("         skipping rendering of source code");
1119                     false
1120                 }
1121             };
1122         }
1123         self.fold_item_recur(item)
1124     }
1125 }
1126
1127 impl<'a> SourceCollector<'a> {
1128     /// Renders the given filename into its corresponding HTML source file.
1129     fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1130         let p = match *filename {
1131             FileName::Real(ref file) => file,
1132             _ => return Ok(()),
1133         };
1134         if self.scx.local_sources.contains_key(&**p) {
1135             // We've already emitted this source
1136             return Ok(());
1137         }
1138
1139         let contents = fs::read_to_string(&p)?;
1140
1141         // Remove the utf-8 BOM if any
1142         let contents = if contents.starts_with("\u{feff}") {
1143             &contents[3..]
1144         } else {
1145             &contents[..]
1146         };
1147
1148         // Create the intermediate directories
1149         let mut cur = self.dst.clone();
1150         let mut root_path = String::from("../../");
1151         let mut href = String::new();
1152         clean_srcpath(&self.scx.src_root, &p, false, |component| {
1153             cur.push(component);
1154             fs::create_dir_all(&cur).unwrap();
1155             root_path.push_str("../");
1156             href.push_str(component);
1157             href.push('/');
1158         });
1159         let mut fname = p.file_name()
1160                          .expect("source has no filename")
1161                          .to_os_string();
1162         fname.push(".html");
1163         cur.push(&fname);
1164         href.push_str(&fname.to_string_lossy());
1165
1166         let mut w = BufWriter::new(File::create(&cur)?);
1167         let title = format!("{} -- source", cur.file_name().unwrap()
1168                                                .to_string_lossy());
1169         let desc = format!("Source to the Rust file `{}`.", filename);
1170         let page = layout::Page {
1171             title: &title,
1172             css_class: "source",
1173             root_path: &root_path,
1174             description: &desc,
1175             keywords: BASIC_KEYWORDS,
1176             resource_suffix: &self.scx.resource_suffix,
1177         };
1178         layout::render(&mut w, &self.scx.layout,
1179                        &page, &(""), &Source(contents),
1180                        self.scx.css_file_extension.is_some(),
1181                        &self.scx.themes)?;
1182         w.flush()?;
1183         self.scx.local_sources.insert(p.clone(), href);
1184         Ok(())
1185     }
1186 }
1187
1188 impl DocFolder for Cache {
1189     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1190         // If this is a stripped module,
1191         // we don't want it or its children in the search index.
1192         let orig_stripped_mod = match item.inner {
1193             clean::StrippedItem(box clean::ModuleItem(..)) => {
1194                 mem::replace(&mut self.stripped_mod, true)
1195             }
1196             _ => self.stripped_mod,
1197         };
1198
1199         // If the impl is from a masked crate or references something from a
1200         // masked crate then remove it completely.
1201         if let clean::ImplItem(ref i) = item.inner {
1202             if self.masked_crates.contains(&item.def_id.krate) ||
1203                i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1204                i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1205                 return None;
1206             }
1207         }
1208
1209         // Register any generics to their corresponding string. This is used
1210         // when pretty-printing types.
1211         if let Some(generics) = item.inner.generics() {
1212             self.generics(generics);
1213         }
1214
1215         // Propagate a trait method's documentation to all implementors of the
1216         // trait.
1217         if let clean::TraitItem(ref t) = item.inner {
1218             self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1219         }
1220
1221         // Collect all the implementors of traits.
1222         if let clean::ImplItem(ref i) = item.inner {
1223             if let Some(did) = i.trait_.def_id() {
1224                 self.implementors.entry(did).or_insert(vec![]).push(Impl {
1225                     impl_item: item.clone(),
1226                 });
1227             }
1228         }
1229
1230         // Index this method for searching later on.
1231         if let Some(ref s) = item.name {
1232             let (parent, is_inherent_impl_item) = match item.inner {
1233                 clean::StrippedItem(..) => ((None, None), false),
1234                 clean::AssociatedConstItem(..) |
1235                 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1236                     // skip associated items in trait impls
1237                     ((None, None), false)
1238                 }
1239                 clean::AssociatedTypeItem(..) |
1240                 clean::TyMethodItem(..) |
1241                 clean::StructFieldItem(..) |
1242                 clean::VariantItem(..) => {
1243                     ((Some(*self.parent_stack.last().unwrap()),
1244                       Some(&self.stack[..self.stack.len() - 1])),
1245                      false)
1246                 }
1247                 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1248                     if self.parent_stack.is_empty() {
1249                         ((None, None), false)
1250                     } else {
1251                         let last = self.parent_stack.last().unwrap();
1252                         let did = *last;
1253                         let path = match self.paths.get(&did) {
1254                             // The current stack not necessarily has correlation
1255                             // for where the type was defined. On the other
1256                             // hand, `paths` always has the right
1257                             // information if present.
1258                             Some(&(ref fqp, ItemType::Trait)) |
1259                             Some(&(ref fqp, ItemType::Struct)) |
1260                             Some(&(ref fqp, ItemType::Union)) |
1261                             Some(&(ref fqp, ItemType::Enum)) =>
1262                                 Some(&fqp[..fqp.len() - 1]),
1263                             Some(..) => Some(&*self.stack),
1264                             None => None
1265                         };
1266                         ((Some(*last), path), true)
1267                     }
1268                 }
1269                 _ => ((None, Some(&*self.stack)), false)
1270             };
1271
1272             match parent {
1273                 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1274                     debug_assert!(!item.is_stripped());
1275
1276                     // A crate has a module at its root, containing all items,
1277                     // which should not be indexed. The crate-item itself is
1278                     // inserted later on when serializing the search-index.
1279                     if item.def_id.index != CRATE_DEF_INDEX {
1280                         self.search_index.push(IndexItem {
1281                             ty: item.type_(),
1282                             name: s.to_string(),
1283                             path: path.join("::").to_string(),
1284                             desc: plain_summary_line(item.doc_value()),
1285                             parent,
1286                             parent_idx: None,
1287                             search_type: get_index_search_type(&item),
1288                         });
1289                     }
1290                 }
1291                 (Some(parent), None) if is_inherent_impl_item => {
1292                     // We have a parent, but we don't know where they're
1293                     // defined yet. Wait for later to index this item.
1294                     self.orphan_impl_items.push((parent, item.clone()));
1295                 }
1296                 _ => {}
1297             }
1298         }
1299
1300         // Keep track of the fully qualified path for this item.
1301         let pushed = match item.name {
1302             Some(ref n) if !n.is_empty() => {
1303                 self.stack.push(n.to_string());
1304                 true
1305             }
1306             _ => false,
1307         };
1308
1309         match item.inner {
1310             clean::StructItem(..) | clean::EnumItem(..) |
1311             clean::TypedefItem(..) | clean::TraitItem(..) |
1312             clean::FunctionItem(..) | clean::ModuleItem(..) |
1313             clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1314             clean::ConstantItem(..) | clean::StaticItem(..) |
1315             clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1316             if !self.stripped_mod => {
1317                 // Re-exported items mean that the same id can show up twice
1318                 // in the rustdoc ast that we're looking at. We know,
1319                 // however, that a re-exported item doesn't show up in the
1320                 // `public_items` map, so we can skip inserting into the
1321                 // paths map if there was already an entry present and we're
1322                 // not a public item.
1323                 if !self.paths.contains_key(&item.def_id) ||
1324                    self.access_levels.is_public(item.def_id)
1325                 {
1326                     self.paths.insert(item.def_id,
1327                                       (self.stack.clone(), item.type_()));
1328                 }
1329                 self.add_aliases(&item);
1330             }
1331             // Link variants to their parent enum because pages aren't emitted
1332             // for each variant.
1333             clean::VariantItem(..) if !self.stripped_mod => {
1334                 let mut stack = self.stack.clone();
1335                 stack.pop();
1336                 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1337             }
1338
1339             clean::PrimitiveItem(..) if item.visibility.is_some() => {
1340                 self.add_aliases(&item);
1341                 self.paths.insert(item.def_id, (self.stack.clone(),
1342                                                 item.type_()));
1343             }
1344
1345             _ => {}
1346         }
1347
1348         // Maintain the parent stack
1349         let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1350         let parent_pushed = match item.inner {
1351             clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1352             clean::StructItem(..) | clean::UnionItem(..) => {
1353                 self.parent_stack.push(item.def_id);
1354                 self.parent_is_trait_impl = false;
1355                 true
1356             }
1357             clean::ImplItem(ref i) => {
1358                 self.parent_is_trait_impl = i.trait_.is_some();
1359                 match i.for_ {
1360                     clean::ResolvedPath{ did, .. } => {
1361                         self.parent_stack.push(did);
1362                         true
1363                     }
1364                     ref t => {
1365                         let prim_did = t.primitive_type().and_then(|t| {
1366                             self.primitive_locations.get(&t).cloned()
1367                         });
1368                         match prim_did {
1369                             Some(did) => {
1370                                 self.parent_stack.push(did);
1371                                 true
1372                             }
1373                             None => false,
1374                         }
1375                     }
1376                 }
1377             }
1378             _ => false
1379         };
1380
1381         // Once we've recursively found all the generics, hoard off all the
1382         // implementations elsewhere.
1383         let ret = self.fold_item_recur(item).and_then(|item| {
1384             if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1385                 // Figure out the id of this impl. This may map to a
1386                 // primitive rather than always to a struct/enum.
1387                 // Note: matching twice to restrict the lifetime of the `i` borrow.
1388                 let mut dids = FxHashSet();
1389                 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1390                     match i.for_ {
1391                         clean::ResolvedPath { did, .. } |
1392                         clean::BorrowedRef {
1393                             type_: box clean::ResolvedPath { did, .. }, ..
1394                         } => {
1395                             dids.insert(did);
1396                         }
1397                         ref t => {
1398                             let did = t.primitive_type().and_then(|t| {
1399                                 self.primitive_locations.get(&t).cloned()
1400                             });
1401
1402                             if let Some(did) = did {
1403                                 dids.insert(did);
1404                             }
1405                         }
1406                     }
1407
1408                     if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1409                         for bound in generics {
1410                             if let Some(did) = bound.def_id() {
1411                                 dids.insert(did);
1412                             }
1413                         }
1414                     }
1415                 } else {
1416                     unreachable!()
1417                 };
1418                 for did in dids {
1419                     self.impls.entry(did).or_insert(vec![]).push(Impl {
1420                         impl_item: item.clone(),
1421                     });
1422                 }
1423                 None
1424             } else {
1425                 Some(item)
1426             }
1427         });
1428
1429         if pushed { self.stack.pop().unwrap(); }
1430         if parent_pushed { self.parent_stack.pop().unwrap(); }
1431         self.stripped_mod = orig_stripped_mod;
1432         self.parent_is_trait_impl = orig_parent_is_trait_impl;
1433         ret
1434     }
1435 }
1436
1437 impl<'a> Cache {
1438     fn generics(&mut self, generics: &clean::Generics) {
1439         for param in &generics.params {
1440             if let clean::GenericParam::Type(ref typ) = *param {
1441                 self.typarams.insert(typ.did, typ.name.clone());
1442             }
1443         }
1444     }
1445
1446     fn add_aliases(&mut self, item: &clean::Item) {
1447         if item.def_id.index == CRATE_DEF_INDEX {
1448             return
1449         }
1450         if let Some(ref item_name) = item.name {
1451             let path = self.paths.get(&item.def_id)
1452                                  .map(|p| p.0[..p.0.len() - 1].join("::"))
1453                                  .unwrap_or("std".to_owned());
1454             for alias in item.attrs.lists("doc")
1455                                    .filter(|a| a.check_name("alias"))
1456                                    .filter_map(|a| a.value_str()
1457                                                     .map(|s| s.to_string().replace("\"", "")))
1458                                    .filter(|v| !v.is_empty())
1459                                    .collect::<FxHashSet<_>>()
1460                                    .into_iter() {
1461                 self.aliases.entry(alias)
1462                             .or_insert(Vec::with_capacity(1))
1463                             .push(IndexItem {
1464                                 ty: item.type_(),
1465                                 name: item_name.to_string(),
1466                                 path: path.clone(),
1467                                 desc: plain_summary_line(item.doc_value()),
1468                                 parent: None,
1469                                 parent_idx: None,
1470                                 search_type: get_index_search_type(&item),
1471                             });
1472             }
1473         }
1474     }
1475 }
1476
1477 #[derive(Debug, Eq, PartialEq, Hash)]
1478 struct ItemEntry {
1479     url: String,
1480     name: String,
1481 }
1482
1483 impl ItemEntry {
1484     fn new(mut url: String, name: String) -> ItemEntry {
1485         while url.starts_with('/') {
1486             url.remove(0);
1487         }
1488         ItemEntry {
1489             url,
1490             name,
1491         }
1492     }
1493 }
1494
1495 impl fmt::Display for ItemEntry {
1496     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1497         write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1498     }
1499 }
1500
1501 impl PartialOrd for ItemEntry {
1502     fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1503         Some(self.cmp(other))
1504     }
1505 }
1506
1507 impl Ord for ItemEntry {
1508     fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1509         self.name.cmp(&other.name)
1510     }
1511 }
1512
1513 #[derive(Debug)]
1514 struct AllTypes {
1515     structs: HashSet<ItemEntry>,
1516     enums: HashSet<ItemEntry>,
1517     unions: HashSet<ItemEntry>,
1518     primitives: HashSet<ItemEntry>,
1519     traits: HashSet<ItemEntry>,
1520     macros: HashSet<ItemEntry>,
1521     functions: HashSet<ItemEntry>,
1522     typedefs: HashSet<ItemEntry>,
1523     statics: HashSet<ItemEntry>,
1524     constants: HashSet<ItemEntry>,
1525 }
1526
1527 impl AllTypes {
1528     fn new() -> AllTypes {
1529         AllTypes {
1530             structs: HashSet::with_capacity(100),
1531             enums: HashSet::with_capacity(100),
1532             unions: HashSet::with_capacity(100),
1533             primitives: HashSet::with_capacity(26),
1534             traits: HashSet::with_capacity(100),
1535             macros: HashSet::with_capacity(100),
1536             functions: HashSet::with_capacity(100),
1537             typedefs: HashSet::with_capacity(100),
1538             statics: HashSet::with_capacity(100),
1539             constants: HashSet::with_capacity(100),
1540         }
1541     }
1542
1543     fn append(&mut self, item_name: String, item_type: &ItemType) {
1544         let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1545         if let Some(name) = url.pop() {
1546             let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1547             url.push(name);
1548             let name = url.join("::");
1549             match *item_type {
1550                 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1551                 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1552                 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1553                 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1554                 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1555                 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1556                 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1557                 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1558                 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1559                 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1560                 _ => true,
1561             };
1562         }
1563     }
1564 }
1565
1566 fn print_entries(f: &mut fmt::Formatter, e: &HashSet<ItemEntry>, title: &str,
1567                  class: &str) -> fmt::Result {
1568     if !e.is_empty() {
1569         let mut e: Vec<&ItemEntry> = e.iter().collect();
1570         e.sort();
1571         write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1572                title,
1573                Escape(title),
1574                class,
1575                e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1576     }
1577     Ok(())
1578 }
1579
1580 impl fmt::Display for AllTypes {
1581     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1582         write!(f,
1583 "<h1 class='fqn'>\
1584      <span class='in-band'>List of all items</span>\
1585      <span class='out-of-band'>\
1586          <span id='render-detail'>\
1587              <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1588                  [<span class='inner'>&#x2212;</span>]\
1589              </a>\
1590          </span>
1591      </span>
1592 </h1>")?;
1593         print_entries(f, &self.structs, "Structs", "structs")?;
1594         print_entries(f, &self.enums, "Enums", "enums")?;
1595         print_entries(f, &self.unions, "Unions", "unions")?;
1596         print_entries(f, &self.primitives, "Primitives", "primitives")?;
1597         print_entries(f, &self.traits, "Traits", "traits")?;
1598         print_entries(f, &self.macros, "Macros", "macros")?;
1599         print_entries(f, &self.functions, "Functions", "functions")?;
1600         print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1601         print_entries(f, &self.statics, "Statics", "statics")?;
1602         print_entries(f, &self.constants, "Constants", "constants")
1603     }
1604 }
1605
1606 #[derive(Debug)]
1607 struct Settings<'a> {
1608     // (id, explanation, default value)
1609     settings: Vec<(&'static str, &'static str, bool)>,
1610     root_path: &'a str,
1611     suffix: &'a str,
1612 }
1613
1614 impl<'a> Settings<'a> {
1615     pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1616         Settings {
1617             settings: vec![
1618                 ("item-declarations", "Auto-hide item declarations.", true),
1619                 ("item-attributes", "Auto-hide item attributes.", true),
1620                 ("go-to-only-result", "Directly go to item in search if there is only one result",
1621                  false),
1622             ],
1623             root_path,
1624             suffix,
1625         }
1626     }
1627 }
1628
1629 impl<'a> fmt::Display for Settings<'a> {
1630     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1631         write!(f,
1632 "<h1 class='fqn'>\
1633      <span class='in-band'>Rustdoc settings</span>\
1634 </h1>\
1635 <div class='settings'>{}</div>\
1636 <script src='{}settings{}.js'></script>",
1637                self.settings.iter()
1638                             .map(|(id, text, enabled)| {
1639                                 format!("<div class='setting-line'>\
1640                                              <label class='toggle'>\
1641                                                 <input type='checkbox' id='{}' {}>\
1642                                                 <span class='slider'></span>\
1643                                              </label>\
1644                                              <div>{}</div>\
1645                                          </div>", id, if *enabled { " checked" } else { "" }, text)
1646                             })
1647                             .collect::<String>(),
1648                self.root_path,
1649                self.suffix)
1650     }
1651 }
1652
1653 impl Context {
1654     /// String representation of how to get back to the root path of the 'doc/'
1655     /// folder in terms of a relative URL.
1656     fn root_path(&self) -> String {
1657         repeat("../").take(self.current.len()).collect::<String>()
1658     }
1659
1660     /// Recurse in the directory structure and change the "root path" to make
1661     /// sure it always points to the top (relatively).
1662     fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1663         F: FnOnce(&mut Context) -> T,
1664     {
1665         if s.is_empty() {
1666             panic!("Unexpected empty destination: {:?}", self.current);
1667         }
1668         let prev = self.dst.clone();
1669         self.dst.push(&s);
1670         self.current.push(s);
1671
1672         info!("Recursing into {}", self.dst.display());
1673
1674         let ret = f(self);
1675
1676         info!("Recursed; leaving {}", self.dst.display());
1677
1678         // Go back to where we were at
1679         self.dst = prev;
1680         self.current.pop().unwrap();
1681
1682         ret
1683     }
1684
1685     /// Main method for rendering a crate.
1686     ///
1687     /// This currently isn't parallelized, but it'd be pretty easy to add
1688     /// parallelization to this function.
1689     fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1690         let mut item = match krate.module.take() {
1691             Some(i) => i,
1692             None => return Ok(()),
1693         };
1694         let final_file = self.dst.join(&krate.name)
1695                                  .join("all.html");
1696         let settings_file = self.dst.join("settings.html");
1697
1698         let crate_name = krate.name.clone();
1699         item.name = Some(krate.name);
1700
1701         let mut all = AllTypes::new();
1702
1703         {
1704             // Render the crate documentation
1705             let mut work = vec![(self.clone(), item)];
1706
1707             while let Some((mut cx, item)) = work.pop() {
1708                 cx.item(item, &mut all, |cx, item| {
1709                     work.push((cx.clone(), item))
1710                 })?
1711             }
1712         }
1713
1714         let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
1715         let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1716         if !root_path.ends_with('/') {
1717             root_path.push('/');
1718         }
1719         let mut page = layout::Page {
1720             title: "List of all items in this crate",
1721             css_class: "mod",
1722             root_path: "../",
1723             description: "List of all items in this crate",
1724             keywords: BASIC_KEYWORDS,
1725             resource_suffix: &self.shared.resource_suffix,
1726         };
1727         let sidebar = if let Some(ref version) = cache().crate_version {
1728             format!("<p class='location'>Crate {}</p>\
1729                      <div class='block version'>\
1730                          <p>Version {}</p>\
1731                      </div>\
1732                      <a id='all-types' href='index.html'><p>Back to index</p></a>",
1733                     crate_name, version)
1734         } else {
1735             String::new()
1736         };
1737         try_err!(layout::render(&mut w, &self.shared.layout,
1738                                 &page, &sidebar, &all,
1739                                 self.shared.css_file_extension.is_some(),
1740                                 &self.shared.themes),
1741                  &final_file);
1742
1743         // Generating settings page.
1744         let settings = Settings::new("./", &self.shared.resource_suffix);
1745         page.title = "Rustdoc settings";
1746         page.description = "Settings of Rustdoc";
1747         page.root_path = "./";
1748
1749         let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
1750         let mut themes = self.shared.themes.clone();
1751         let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1752         themes.push(PathBuf::from("settings.css"));
1753         let mut layout = self.shared.layout.clone();
1754         layout.krate = String::new();
1755         layout.logo = String::new();
1756         layout.favicon = String::new();
1757         try_err!(layout::render(&mut w, &layout,
1758                                 &page, &sidebar, &settings,
1759                                 self.shared.css_file_extension.is_some(),
1760                                 &themes),
1761                  &settings_file);
1762
1763         Ok(())
1764     }
1765
1766     fn render_item(&self,
1767                    writer: &mut io::Write,
1768                    it: &clean::Item,
1769                    pushname: bool)
1770                    -> io::Result<()> {
1771         // A little unfortunate that this is done like this, but it sure
1772         // does make formatting *a lot* nicer.
1773         CURRENT_LOCATION_KEY.with(|slot| {
1774             *slot.borrow_mut() = self.current.clone();
1775         });
1776
1777         let mut title = if it.is_primitive() {
1778             // No need to include the namespace for primitive types
1779             String::new()
1780         } else {
1781             self.current.join("::")
1782         };
1783         if pushname {
1784             if !title.is_empty() {
1785                 title.push_str("::");
1786             }
1787             title.push_str(it.name.as_ref().unwrap());
1788         }
1789         title.push_str(" - Rust");
1790         let tyname = it.type_().css_class();
1791         let desc = if it.is_crate() {
1792             format!("API documentation for the Rust `{}` crate.",
1793                     self.shared.layout.krate)
1794         } else {
1795             format!("API documentation for the Rust `{}` {} in crate `{}`.",
1796                     it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1797         };
1798         let keywords = make_item_keywords(it);
1799         let page = layout::Page {
1800             css_class: tyname,
1801             root_path: &self.root_path(),
1802             title: &title,
1803             description: &desc,
1804             keywords: &keywords,
1805             resource_suffix: &self.shared.resource_suffix,
1806         };
1807
1808         reset_ids(true);
1809
1810         if !self.render_redirect_pages {
1811             layout::render(writer, &self.shared.layout, &page,
1812                            &Sidebar{ cx: self, item: it },
1813                            &Item{ cx: self, item: it },
1814                            self.shared.css_file_extension.is_some(),
1815                            &self.shared.themes)?;
1816         } else {
1817             let mut url = self.root_path();
1818             if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1819                 for name in &names[..names.len() - 1] {
1820                     url.push_str(name);
1821                     url.push_str("/");
1822                 }
1823                 url.push_str(&item_path(ty, names.last().unwrap()));
1824                 layout::redirect(writer, &url)?;
1825             }
1826         }
1827         Ok(())
1828     }
1829
1830     /// Non-parallelized version of rendering an item. This will take the input
1831     /// item, render its contents, and then invoke the specified closure with
1832     /// all sub-items which need to be rendered.
1833     ///
1834     /// The rendering driver uses this closure to queue up more work.
1835     fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
1836         where F: FnMut(&mut Context, clean::Item),
1837     {
1838         // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1839         // if they contain impls for public types. These modules can also
1840         // contain items such as publicly re-exported structures.
1841         //
1842         // External crates will provide links to these structures, so
1843         // these modules are recursed into, but not rendered normally
1844         // (a flag on the context).
1845         if !self.render_redirect_pages {
1846             self.render_redirect_pages = item.is_stripped();
1847         }
1848
1849         if item.is_mod() {
1850             // modules are special because they add a namespace. We also need to
1851             // recurse into the items of the module as well.
1852             let name = item.name.as_ref().unwrap().to_string();
1853             let mut item = Some(item);
1854             self.recurse(name, |this| {
1855                 let item = item.take().unwrap();
1856
1857                 let mut buf = Vec::new();
1858                 this.render_item(&mut buf, &item, false).unwrap();
1859                 // buf will be empty if the module is stripped and there is no redirect for it
1860                 if !buf.is_empty() {
1861                     try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1862                     let joint_dst = this.dst.join("index.html");
1863                     let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1864                     try_err!(dst.write_all(&buf), &joint_dst);
1865                 }
1866
1867                 let m = match item.inner {
1868                     clean::StrippedItem(box clean::ModuleItem(m)) |
1869                     clean::ModuleItem(m) => m,
1870                     _ => unreachable!()
1871                 };
1872
1873                 // Render sidebar-items.js used throughout this module.
1874                 if !this.render_redirect_pages {
1875                     let items = this.build_sidebar_items(&m);
1876                     let js_dst = this.dst.join("sidebar-items.js");
1877                     let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1878                     try_err!(write!(&mut js_out, "initSidebarItems({});",
1879                                     as_json(&items)), &js_dst);
1880                 }
1881
1882                 for item in m.items {
1883                     f(this, item);
1884                 }
1885
1886                 Ok(())
1887             })?;
1888         } else if item.name.is_some() {
1889             let mut buf = Vec::new();
1890             self.render_item(&mut buf, &item, true).unwrap();
1891             // buf will be empty if the item is stripped and there is no redirect for it
1892             if !buf.is_empty() {
1893                 let name = item.name.as_ref().unwrap();
1894                 let item_type = item.type_();
1895                 let file_name = &item_path(item_type, name);
1896                 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1897                 let joint_dst = self.dst.join(file_name);
1898                 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1899                 try_err!(dst.write_all(&buf), &joint_dst);
1900
1901                 if !self.render_redirect_pages {
1902                     all.append(full_path(self, &item), &item_type);
1903                 }
1904                 // Redirect from a sane URL using the namespace to Rustdoc's
1905                 // URL for the page.
1906                 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1907                 let redir_dst = self.dst.join(redir_name);
1908                 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1909                                                             .write(true)
1910                                                             .open(&redir_dst) {
1911                     let mut redirect_out = BufWriter::new(redirect_out);
1912                     try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1913                 }
1914
1915                 // If the item is a macro, redirect from the old macro URL (with !)
1916                 // to the new one (without).
1917                 // FIXME(#35705) remove this redirect.
1918                 if item_type == ItemType::Macro {
1919                     let redir_name = format!("{}.{}!.html", item_type, name);
1920                     let redir_dst = self.dst.join(redir_name);
1921                     let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1922                     let mut redirect_out = BufWriter::new(redirect_out);
1923                     try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1924                 }
1925             }
1926         }
1927         Ok(())
1928     }
1929
1930     fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1931         // BTreeMap instead of HashMap to get a sorted output
1932         let mut map = BTreeMap::new();
1933         for item in &m.items {
1934             if item.is_stripped() { continue }
1935
1936             let short = item.type_().css_class();
1937             let myname = match item.name {
1938                 None => continue,
1939                 Some(ref s) => s.to_string(),
1940             };
1941             let short = short.to_string();
1942             map.entry(short).or_insert(vec![])
1943                 .push((myname, Some(plain_summary_line(item.doc_value()))));
1944         }
1945
1946         if self.shared.sort_modules_alphabetically {
1947             for (_, items) in &mut map {
1948                 items.sort();
1949             }
1950         }
1951         map
1952     }
1953 }
1954
1955 impl<'a> Item<'a> {
1956     /// Generate a url appropriate for an `href` attribute back to the source of
1957     /// this item.
1958     ///
1959     /// The url generated, when clicked, will redirect the browser back to the
1960     /// original source code.
1961     ///
1962     /// If `None` is returned, then a source link couldn't be generated. This
1963     /// may happen, for example, with externally inlined items where the source
1964     /// of their crate documentation isn't known.
1965     fn src_href(&self) -> Option<String> {
1966         let mut root = self.cx.root_path();
1967
1968         let cache = cache();
1969         let mut path = String::new();
1970
1971         // We can safely ignore macros from other libraries
1972         let file = match self.item.source.filename {
1973             FileName::Real(ref path) => path,
1974             _ => return None,
1975         };
1976
1977         let (krate, path) = if self.item.def_id.is_local() {
1978             if let Some(path) = self.cx.shared.local_sources.get(file) {
1979                 (&self.cx.shared.layout.krate, path)
1980             } else {
1981                 return None;
1982             }
1983         } else {
1984             let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1985                 Some(&(ref name, ref src, Local)) => (name, src),
1986                 Some(&(ref name, ref src, Remote(ref s))) => {
1987                     root = s.to_string();
1988                     (name, src)
1989                 }
1990                 Some(&(_, _, Unknown)) | None => return None,
1991             };
1992
1993             clean_srcpath(&src_root, file, false, |component| {
1994                 path.push_str(component);
1995                 path.push('/');
1996             });
1997             let mut fname = file.file_name().expect("source has no filename")
1998                                 .to_os_string();
1999             fname.push(".html");
2000             path.push_str(&fname.to_string_lossy());
2001             (krate, &path)
2002         };
2003
2004         let lines = if self.item.source.loline == self.item.source.hiline {
2005             format!("{}", self.item.source.loline)
2006         } else {
2007             format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2008         };
2009         Some(format!("{root}src/{krate}/{path}#{lines}",
2010                      root = Escape(&root),
2011                      krate = krate,
2012                      path = path,
2013                      lines = lines))
2014     }
2015 }
2016
2017 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2018                          f: F) -> fmt::Result
2019 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2020     write!(w, "<div class=\"docblock type-decl\">")?;
2021     f(w)?;
2022     write!(w, "</div>")
2023 }
2024
2025 impl<'a> fmt::Display for Item<'a> {
2026     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2027         debug_assert!(!self.item.is_stripped());
2028         // Write the breadcrumb trail header for the top
2029         write!(fmt, "<h1 class='fqn'><span class='in-band'>")?;
2030         match self.item.inner {
2031             clean::ModuleItem(ref m) => if m.is_crate {
2032                     write!(fmt, "Crate ")?;
2033                 } else {
2034                     write!(fmt, "Module ")?;
2035                 },
2036             clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2037             clean::TraitItem(..) => write!(fmt, "Trait ")?,
2038             clean::StructItem(..) => write!(fmt, "Struct ")?,
2039             clean::UnionItem(..) => write!(fmt, "Union ")?,
2040             clean::EnumItem(..) => write!(fmt, "Enum ")?,
2041             clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2042             clean::MacroItem(..) => write!(fmt, "Macro ")?,
2043             clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2044             clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2045             clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2046             clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2047             _ => {
2048                 // We don't generate pages for any other type.
2049                 unreachable!();
2050             }
2051         }
2052         if !self.item.is_primitive() {
2053             let cur = &self.cx.current;
2054             let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2055             for (i, component) in cur.iter().enumerate().take(amt) {
2056                 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2057                        repeat("../").take(cur.len() - i - 1)
2058                                     .collect::<String>(),
2059                        component)?;
2060             }
2061         }
2062         write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2063                self.item.type_(), self.item.name.as_ref().unwrap())?;
2064
2065         write!(fmt, "</span>")?; // in-band
2066         write!(fmt, "<span class='out-of-band'>")?;
2067         if let Some(version) = self.item.stable_since() {
2068             write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2069                    version)?;
2070         }
2071         write!(fmt,
2072                "<span id='render-detail'>\
2073                    <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2074                       title=\"collapse all docs\">\
2075                        [<span class='inner'>&#x2212;</span>]\
2076                    </a>\
2077                </span>")?;
2078
2079         // Write `src` tag
2080         //
2081         // When this item is part of a `pub use` in a downstream crate, the
2082         // [src] link in the downstream documentation will actually come back to
2083         // this page, and this link will be auto-clicked. The `id` attribute is
2084         // used to find the link to auto-click.
2085         if self.cx.shared.include_sources && !self.item.is_primitive() {
2086             if let Some(l) = self.src_href() {
2087                 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2088                        l, "goto source code")?;
2089             }
2090         }
2091
2092         write!(fmt, "</span></h1>")?; // out-of-band
2093
2094         match self.item.inner {
2095             clean::ModuleItem(ref m) =>
2096                 item_module(fmt, self.cx, self.item, &m.items),
2097             clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2098                 item_function(fmt, self.cx, self.item, f),
2099             clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2100             clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2101             clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2102             clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2103             clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2104             clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2105             clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2106             clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2107                 item_static(fmt, self.cx, self.item, i),
2108             clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2109             clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2110             _ => {
2111                 // We don't generate pages for any other type.
2112                 unreachable!();
2113             }
2114         }
2115     }
2116 }
2117
2118 fn item_path(ty: ItemType, name: &str) -> String {
2119     match ty {
2120         ItemType::Module => format!("{}/index.html", name),
2121         _ => format!("{}.{}.html", ty.css_class(), name),
2122     }
2123 }
2124
2125 fn full_path(cx: &Context, item: &clean::Item) -> String {
2126     let mut s = cx.current.join("::");
2127     s.push_str("::");
2128     s.push_str(item.name.as_ref().unwrap());
2129     s
2130 }
2131
2132 fn shorter<'a>(s: Option<&'a str>) -> String {
2133     match s {
2134         Some(s) => s.lines()
2135             .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2136             .take_while(|line|{
2137             (*line).chars().any(|chr|{
2138                 !chr.is_whitespace()
2139             })
2140         }).collect::<Vec<_>>().join("\n"),
2141         None => "".to_string()
2142     }
2143 }
2144
2145 #[inline]
2146 fn plain_summary_line(s: Option<&str>) -> String {
2147     let line = shorter(s).replace("\n", " ");
2148     markdown::plain_summary_line(&line[..])
2149 }
2150
2151 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2152     if let Some(ref name) = item.name {
2153         info!("Documenting {}", name);
2154     }
2155     document_stability(w, cx, item)?;
2156     let prefix = render_assoc_const_value(item);
2157     document_full(w, item, cx, &prefix)?;
2158     Ok(())
2159 }
2160
2161 /// Render md_text as markdown.
2162 fn render_markdown(w: &mut fmt::Formatter,
2163                    md_text: &str,
2164                    links: Vec<(String, String)>,
2165                    prefix: &str,)
2166                    -> fmt::Result {
2167     write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
2168 }
2169
2170 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
2171                   prefix: &str) -> fmt::Result {
2172     if let Some(s) = item.doc_value() {
2173         let markdown = if s.contains('\n') {
2174             format!("{} [Read more]({})",
2175                     &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2176         } else {
2177             format!("{}", &plain_summary_line(Some(s)))
2178         };
2179         render_markdown(w, &markdown, item.links(), prefix)?;
2180     } else if !prefix.is_empty() {
2181         write!(w, "<div class='docblock'>{}</div>", prefix)?;
2182     }
2183     Ok(())
2184 }
2185
2186 fn render_assoc_const_value(item: &clean::Item) -> String {
2187     match item.inner {
2188         clean::AssociatedConstItem(ref ty, Some(ref default)) => {
2189             highlight::render_with_highlighting(
2190                 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
2191                 None,
2192                 None,
2193                 None,
2194                 None,
2195             )
2196         }
2197         _ => String::new(),
2198     }
2199 }
2200
2201 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2202                  cx: &Context, prefix: &str) -> fmt::Result {
2203     if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2204         debug!("Doc block: =====\n{}\n=====", s);
2205         render_markdown(w, &*s, item.links(), prefix)?;
2206     } else if !prefix.is_empty() {
2207         write!(w, "<div class='docblock'>{}</div>", prefix)?;
2208     }
2209     Ok(())
2210 }
2211
2212 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2213     let stabilities = short_stability(item, cx, true);
2214     if !stabilities.is_empty() {
2215         write!(w, "<div class='stability'>")?;
2216         for stability in stabilities {
2217             write!(w, "{}", stability)?;
2218         }
2219         write!(w, "</div>")?;
2220     }
2221     Ok(())
2222 }
2223
2224 fn name_key(name: &str) -> (&str, u64, usize) {
2225     // find number at end
2226     let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
2227
2228     // count leading zeroes
2229     let after_zeroes =
2230         name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2231
2232     // sort leading zeroes last
2233     let num_zeroes = after_zeroes - split;
2234
2235     match name[split..].parse() {
2236         Ok(n) => (&name[..split], n, num_zeroes),
2237         Err(_) => (name, 0, num_zeroes),
2238     }
2239 }
2240
2241 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2242                item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2243     document(w, cx, item)?;
2244
2245     let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2246
2247     // the order of item types in the listing
2248     fn reorder(ty: ItemType) -> u8 {
2249         match ty {
2250             ItemType::ExternCrate     => 0,
2251             ItemType::Import          => 1,
2252             ItemType::Primitive       => 2,
2253             ItemType::Module          => 3,
2254             ItemType::Macro           => 4,
2255             ItemType::Struct          => 5,
2256             ItemType::Enum            => 6,
2257             ItemType::Constant        => 7,
2258             ItemType::Static          => 8,
2259             ItemType::Trait           => 9,
2260             ItemType::Function        => 10,
2261             ItemType::Typedef         => 12,
2262             ItemType::Union           => 13,
2263             _                         => 14 + ty as u8,
2264         }
2265     }
2266
2267     fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2268         let ty1 = i1.type_();
2269         let ty2 = i2.type_();
2270         if ty1 != ty2 {
2271             return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2272         }
2273         let s1 = i1.stability.as_ref().map(|s| s.level);
2274         let s2 = i2.stability.as_ref().map(|s| s.level);
2275         match (s1, s2) {
2276             (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2277             (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2278             _ => {}
2279         }
2280         let lhs = i1.name.as_ref().map_or("", |s| &**s);
2281         let rhs = i2.name.as_ref().map_or("", |s| &**s);
2282         name_key(lhs).cmp(&name_key(rhs))
2283     }
2284
2285     if cx.shared.sort_modules_alphabetically {
2286         indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2287     }
2288     // This call is to remove re-export duplicates in cases such as:
2289     //
2290     // ```
2291     // pub mod foo {
2292     //     pub mod bar {
2293     //         pub trait Double { fn foo(); }
2294     //     }
2295     // }
2296     //
2297     // pub use foo::bar::*;
2298     // pub use foo::*;
2299     // ```
2300     //
2301     // `Double` will appear twice in the generated docs.
2302     //
2303     // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2304     // can be identical even if the elements are different (mostly in imports).
2305     // So in case this is an import, we keep everything by adding a "unique id"
2306     // (which is the position in the vector).
2307     indices.dedup_by_key(|i| (items[*i].def_id,
2308                               if items[*i].name.as_ref().is_some() {
2309                                   Some(full_path(cx, &items[*i]).clone())
2310                               } else {
2311                                   None
2312                               },
2313                               items[*i].type_(),
2314                               if items[*i].is_import() {
2315                                   *i
2316                               } else {
2317                                   0
2318                               }));
2319
2320     debug!("{:?}", indices);
2321     let mut curty = None;
2322     for &idx in &indices {
2323         let myitem = &items[idx];
2324         if myitem.is_stripped() {
2325             continue;
2326         }
2327
2328         let myty = Some(myitem.type_());
2329         if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2330             // Put `extern crate` and `use` re-exports in the same section.
2331             curty = myty;
2332         } else if myty != curty {
2333             if curty.is_some() {
2334                 write!(w, "</table>")?;
2335             }
2336             curty = myty;
2337             let (short, name) = match myty.unwrap() {
2338                 ItemType::ExternCrate |
2339                 ItemType::Import          => ("reexports", "Re-exports"),
2340                 ItemType::Module          => ("modules", "Modules"),
2341                 ItemType::Struct          => ("structs", "Structs"),
2342                 ItemType::Union           => ("unions", "Unions"),
2343                 ItemType::Enum            => ("enums", "Enums"),
2344                 ItemType::Function        => ("functions", "Functions"),
2345                 ItemType::Typedef         => ("types", "Type Definitions"),
2346                 ItemType::Static          => ("statics", "Statics"),
2347                 ItemType::Constant        => ("constants", "Constants"),
2348                 ItemType::Trait           => ("traits", "Traits"),
2349                 ItemType::Impl            => ("impls", "Implementations"),
2350                 ItemType::TyMethod        => ("tymethods", "Type Methods"),
2351                 ItemType::Method          => ("methods", "Methods"),
2352                 ItemType::StructField     => ("fields", "Struct Fields"),
2353                 ItemType::Variant         => ("variants", "Variants"),
2354                 ItemType::Macro           => ("macros", "Macros"),
2355                 ItemType::Primitive       => ("primitives", "Primitive Types"),
2356                 ItemType::AssociatedType  => ("associated-types", "Associated Types"),
2357                 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
2358                 ItemType::ForeignType     => ("foreign-types", "Foreign Types"),
2359             };
2360             write!(w, "<h2 id='{id}' class='section-header'>\
2361                        <a href=\"#{id}\">{name}</a></h2>\n<table>",
2362                    id = derive_id(short.to_owned()), name = name)?;
2363         }
2364
2365         match myitem.inner {
2366             clean::ExternCrateItem(ref name, ref src) => {
2367                 use html::format::HRef;
2368
2369                 match *src {
2370                     Some(ref src) => {
2371                         write!(w, "<tr><td><code>{}extern crate {} as {};",
2372                                VisSpace(&myitem.visibility),
2373                                HRef::new(myitem.def_id, src),
2374                                name)?
2375                     }
2376                     None => {
2377                         write!(w, "<tr><td><code>{}extern crate {};",
2378                                VisSpace(&myitem.visibility),
2379                                HRef::new(myitem.def_id, name))?
2380                     }
2381                 }
2382                 write!(w, "</code></td></tr>")?;
2383             }
2384
2385             clean::ImportItem(ref import) => {
2386                 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2387                        VisSpace(&myitem.visibility), *import)?;
2388             }
2389
2390             _ => {
2391                 if myitem.name.is_none() { continue }
2392
2393                 let stabilities = short_stability(myitem, cx, false);
2394
2395                 let stab_docs = if !stabilities.is_empty() {
2396                     stabilities.iter()
2397                                .map(|s| format!("[{}]", s))
2398                                .collect::<Vec<_>>()
2399                                .as_slice()
2400                                .join(" ")
2401                 } else {
2402                     String::new()
2403                 };
2404
2405                 let unsafety_flag = match myitem.inner {
2406                     clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2407                     if func.unsafety == hir::Unsafety::Unsafe => {
2408                         "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2409                     }
2410                     _ => "",
2411                 };
2412
2413                 let doc_value = myitem.doc_value().unwrap_or("");
2414                 write!(w, "
2415                        <tr class='{stab} module-item'>
2416                            <td><a class=\"{class}\" href=\"{href}\"
2417                                   title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2418                            <td class='docblock-short'>
2419                                {stab_docs} {docs}
2420                            </td>
2421                        </tr>",
2422                        name = *myitem.name.as_ref().unwrap(),
2423                        stab_docs = stab_docs,
2424                        docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2425                        class = myitem.type_(),
2426                        stab = myitem.stability_class().unwrap_or("".to_string()),
2427                        unsafety_flag = unsafety_flag,
2428                        href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2429                        title_type = myitem.type_(),
2430                        title = full_path(cx, myitem))?;
2431             }
2432         }
2433     }
2434
2435     if curty.is_some() {
2436         write!(w, "</table>")?;
2437     }
2438     Ok(())
2439 }
2440
2441 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2442     let mut stability = vec![];
2443
2444     if let Some(stab) = item.stability.as_ref() {
2445         let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2446             format!(": {}", stab.deprecated_reason)
2447         } else {
2448             String::new()
2449         };
2450         if !stab.deprecated_since.is_empty() {
2451             let since = if show_reason {
2452                 format!(" since {}", Escape(&stab.deprecated_since))
2453             } else {
2454                 String::new()
2455             };
2456             let text = if stability::deprecation_in_effect(&stab.deprecated_since) {
2457                 format!("Deprecated{}{}",
2458                         since,
2459                         MarkdownHtml(&deprecated_reason))
2460             } else {
2461                 format!("Deprecating in {}{}",
2462                         Escape(&stab.deprecated_since),
2463                         MarkdownHtml(&deprecated_reason))
2464             };
2465             stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2466         };
2467
2468         if stab.level == stability::Unstable {
2469             if show_reason {
2470                 let unstable_extra = match (!stab.feature.is_empty(),
2471                                             &cx.shared.issue_tracker_base_url,
2472                                             stab.issue) {
2473                     (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2474                         format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2475                                 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2476                     (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2477                         format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2478                                 issue_no),
2479                     (true, ..) =>
2480                         format!(" (<code>{}</code>)", Escape(&stab.feature)),
2481                     _ => String::new(),
2482                 };
2483                 if stab.unstable_reason.is_empty() {
2484                     stability.push(format!("<div class='stab unstable'>\
2485                                             <span class=microscope>🔬</span> \
2486                                             This is a nightly-only experimental API. {}\
2487                                             </div>",
2488                                            unstable_extra));
2489                 } else {
2490                     let text = format!("<summary><span class=microscope>🔬</span> \
2491                                         This is a nightly-only experimental API. {}\
2492                                         </summary>{}",
2493                                        unstable_extra,
2494                                        MarkdownHtml(&stab.unstable_reason));
2495                     stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2496                                    text));
2497                 }
2498             } else {
2499                 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2500             }
2501         };
2502     } else if let Some(depr) = item.deprecation.as_ref() {
2503         let note = if show_reason && !depr.note.is_empty() {
2504             format!(": {}", depr.note)
2505         } else {
2506             String::new()
2507         };
2508         let since = if show_reason && !depr.since.is_empty() {
2509             format!(" since {}", Escape(&depr.since))
2510         } else {
2511             String::new()
2512         };
2513
2514         let text = if stability::deprecation_in_effect(&depr.since) {
2515             format!("Deprecated{}{}",
2516                     since,
2517                     MarkdownHtml(&note))
2518         } else {
2519             format!("Deprecating in {}{}",
2520                     Escape(&depr.since),
2521                     MarkdownHtml(&note))
2522         };
2523         stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2524     }
2525
2526     if let Some(ref cfg) = item.attrs.cfg {
2527         stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2528             cfg.render_long_html()
2529         } else {
2530             cfg.render_short_html()
2531         }));
2532     }
2533
2534     stability
2535 }
2536
2537 struct Initializer<'a>(&'a str);
2538
2539 impl<'a> fmt::Display for Initializer<'a> {
2540     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2541         let Initializer(s) = *self;
2542         if s.is_empty() { return Ok(()); }
2543         write!(f, "<code> = </code>")?;
2544         write!(f, "<code>{}</code>", Escape(s))
2545     }
2546 }
2547
2548 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2549                  c: &clean::Constant) -> fmt::Result {
2550     write!(w, "<pre class='rust const'>")?;
2551     render_attributes(w, it)?;
2552     write!(w, "{vis}const \
2553                {name}: {typ}{init}</pre>",
2554            vis = VisSpace(&it.visibility),
2555            name = it.name.as_ref().unwrap(),
2556            typ = c.type_,
2557            init = Initializer(&c.expr))?;
2558     document(w, cx, it)
2559 }
2560
2561 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2562                s: &clean::Static) -> fmt::Result {
2563     write!(w, "<pre class='rust static'>")?;
2564     render_attributes(w, it)?;
2565     write!(w, "{vis}static {mutability}\
2566                {name}: {typ}{init}</pre>",
2567            vis = VisSpace(&it.visibility),
2568            mutability = MutableSpace(s.mutability),
2569            name = it.name.as_ref().unwrap(),
2570            typ = s.type_,
2571            init = Initializer(&s.expr))?;
2572     document(w, cx, it)
2573 }
2574
2575 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2576                  f: &clean::Function) -> fmt::Result {
2577     let name_len = format!("{}{}{}{:#}fn {}{:#}",
2578                            VisSpace(&it.visibility),
2579                            ConstnessSpace(f.constness),
2580                            UnsafetySpace(f.unsafety),
2581                            AbiSpace(f.abi),
2582                            it.name.as_ref().unwrap(),
2583                            f.generics).len();
2584     write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2585     render_attributes(w, it)?;
2586     write!(w,
2587            "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2588            vis = VisSpace(&it.visibility),
2589            constness = ConstnessSpace(f.constness),
2590            unsafety = UnsafetySpace(f.unsafety),
2591            abi = AbiSpace(f.abi),
2592            name = it.name.as_ref().unwrap(),
2593            generics = f.generics,
2594            where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2595            decl = Method {
2596               decl: &f.decl,
2597               name_len,
2598               indent: 0,
2599            })?;
2600     document(w, cx, it)
2601 }
2602
2603 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2604                       implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
2605     write!(w, "<li><table class='table-display'><tbody><tr><td><code>")?;
2606     // If there's already another implementor that has the same abbridged name, use the
2607     // full path, for example in `std::iter::ExactSizeIterator`
2608     let use_absolute = match implementor.inner_impl().for_ {
2609         clean::ResolvedPath { ref path, is_generic: false, .. } |
2610         clean::BorrowedRef {
2611             type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2612             ..
2613         } => implementor_dups[path.last_name()].1,
2614         _ => false,
2615     };
2616     fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2617     for it in &implementor.inner_impl().items {
2618         if let clean::TypedefItem(ref tydef, _) = it.inner {
2619             write!(w, "<span class=\"where fmt-newline\">  ")?;
2620             assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2621             write!(w, ";</span>")?;
2622         }
2623     }
2624     write!(w, "</code><td>")?;
2625     if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2626         write!(w, "<div class='out-of-band'>")?;
2627         write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2628                     l, "goto source code")?;
2629         write!(w, "</div>")?;
2630     }
2631     writeln!(w, "</td></tr></tbody></table></li>")?;
2632     Ok(())
2633 }
2634
2635 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2636                 traits: &[&&Impl],
2637                 containing_item: &clean::Item) -> fmt::Result {
2638     for i in traits {
2639         let did = i.trait_did().unwrap();
2640         let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2641         render_impl(w, cx, i, assoc_link,
2642                     RenderMode::Normal, containing_item.stable_since(), true)?;
2643     }
2644     Ok(())
2645 }
2646
2647 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2648               t: &clean::Trait) -> fmt::Result {
2649     let mut bounds = String::new();
2650     let mut bounds_plain = String::new();
2651     if !t.bounds.is_empty() {
2652         if !bounds.is_empty() {
2653             bounds.push(' ');
2654             bounds_plain.push(' ');
2655         }
2656         bounds.push_str(": ");
2657         bounds_plain.push_str(": ");
2658         for (i, p) in t.bounds.iter().enumerate() {
2659             if i > 0 {
2660                 bounds.push_str(" + ");
2661                 bounds_plain.push_str(" + ");
2662             }
2663             bounds.push_str(&format!("{}", *p));
2664             bounds_plain.push_str(&format!("{:#}", *p));
2665         }
2666     }
2667
2668     let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2669     let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2670     let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2671     let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2672
2673     // Output the trait definition
2674     wrap_into_docblock(w, |w| {
2675         write!(w, "<pre class='rust trait'>")?;
2676         render_attributes(w, it)?;
2677         write!(w, "{}{}{}trait {}{}{}",
2678                VisSpace(&it.visibility),
2679                UnsafetySpace(t.unsafety),
2680                if t.is_auto { "auto " } else { "" },
2681                it.name.as_ref().unwrap(),
2682                t.generics,
2683                bounds)?;
2684
2685         if !t.generics.where_predicates.is_empty() {
2686             write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2687         } else {
2688             write!(w, " ")?;
2689         }
2690
2691         if t.items.is_empty() {
2692             write!(w, "{{ }}")?;
2693         } else {
2694             // FIXME: we should be using a derived_id for the Anchors here
2695             write!(w, "{{\n")?;
2696             for t in &types {
2697                 write!(w, "    ")?;
2698                 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2699                 write!(w, ";\n")?;
2700             }
2701             if !types.is_empty() && !consts.is_empty() {
2702                 w.write_str("\n")?;
2703             }
2704             for t in &consts {
2705                 write!(w, "    ")?;
2706                 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2707                 write!(w, ";\n")?;
2708             }
2709             if !consts.is_empty() && !required.is_empty() {
2710                 w.write_str("\n")?;
2711             }
2712             for (pos, m) in required.iter().enumerate() {
2713                 write!(w, "    ")?;
2714                 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2715                 write!(w, ";\n")?;
2716
2717                 if pos < required.len() - 1 {
2718                    write!(w, "<div class='item-spacer'></div>")?;
2719                 }
2720             }
2721             if !required.is_empty() && !provided.is_empty() {
2722                 w.write_str("\n")?;
2723             }
2724             for (pos, m) in provided.iter().enumerate() {
2725                 write!(w, "    ")?;
2726                 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2727                 match m.inner {
2728                     clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2729                         write!(w, ",\n    {{ ... }}\n")?;
2730                     },
2731                     _ => {
2732                         write!(w, " {{ ... }}\n")?;
2733                     },
2734                 }
2735                 if pos < provided.len() - 1 {
2736                    write!(w, "<div class='item-spacer'></div>")?;
2737                 }
2738             }
2739             write!(w, "}}")?;
2740         }
2741         write!(w, "</pre>")
2742     })?;
2743
2744     // Trait documentation
2745     document(w, cx, it)?;
2746
2747     fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2748                   -> fmt::Result {
2749         let name = m.name.as_ref().unwrap();
2750         let item_type = m.type_();
2751         let id = derive_id(format!("{}.{}", item_type, name));
2752         let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2753         write!(w, "{extra}<h3 id='{id}' class='method'>\
2754                    <span id='{ns_id}' class='invisible'><code>",
2755                extra = render_spotlight_traits(m)?,
2756                id = id,
2757                ns_id = ns_id)?;
2758         render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2759         write!(w, "</code>")?;
2760         render_stability_since(w, m, t)?;
2761         write!(w, "</span></h3>")?;
2762         document(w, cx, m)?;
2763         Ok(())
2764     }
2765
2766     if !types.is_empty() {
2767         write!(w, "
2768             <h2 id='associated-types' class='small-section-header'>
2769               Associated Types<a href='#associated-types' class='anchor'></a>
2770             </h2>
2771             <div class='methods'>
2772         ")?;
2773         for t in &types {
2774             trait_item(w, cx, *t, it)?;
2775         }
2776         write!(w, "</div>")?;
2777     }
2778
2779     if !consts.is_empty() {
2780         write!(w, "
2781             <h2 id='associated-const' class='small-section-header'>
2782               Associated Constants<a href='#associated-const' class='anchor'></a>
2783             </h2>
2784             <div class='methods'>
2785         ")?;
2786         for t in &consts {
2787             trait_item(w, cx, *t, it)?;
2788         }
2789         write!(w, "</div>")?;
2790     }
2791
2792     // Output the documentation for each function individually
2793     if !required.is_empty() {
2794         write!(w, "
2795             <h2 id='required-methods' class='small-section-header'>
2796               Required Methods<a href='#required-methods' class='anchor'></a>
2797             </h2>
2798             <div class='methods'>
2799         ")?;
2800         for m in &required {
2801             trait_item(w, cx, *m, it)?;
2802         }
2803         write!(w, "</div>")?;
2804     }
2805     if !provided.is_empty() {
2806         write!(w, "
2807             <h2 id='provided-methods' class='small-section-header'>
2808               Provided Methods<a href='#provided-methods' class='anchor'></a>
2809             </h2>
2810             <div class='methods'>
2811         ")?;
2812         for m in &provided {
2813             trait_item(w, cx, *m, it)?;
2814         }
2815         write!(w, "</div>")?;
2816     }
2817
2818     // If there are methods directly on this trait object, render them here.
2819     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2820
2821     let cache = cache();
2822     let impl_header = "
2823         <h2 id='implementors' class='small-section-header'>
2824           Implementors<a href='#implementors' class='anchor'></a>
2825         </h2>
2826         <ul class='item-list' id='implementors-list'>
2827     ";
2828
2829     let synthetic_impl_header = "
2830         <h2 id='synthetic-implementors' class='small-section-header'>
2831           Auto implementors<a href='#synthetic-implementors' class='anchor'></a>
2832         </h2>
2833         <ul class='item-list' id='synthetic-implementors-list'>
2834     ";
2835
2836     let mut synthetic_types = Vec::new();
2837
2838     if let Some(implementors) = cache.implementors.get(&it.def_id) {
2839         // The DefId is for the first Type found with that name. The bool is
2840         // if any Types with the same name but different DefId have been found.
2841         let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2842         for implementor in implementors {
2843             match implementor.inner_impl().for_ {
2844                 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2845                 clean::BorrowedRef {
2846                     type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2847                     ..
2848                 } => {
2849                     let &mut (prev_did, ref mut has_duplicates) =
2850                         implementor_dups.entry(path.last_name()).or_insert((did, false));
2851                     if prev_did != did {
2852                         *has_duplicates = true;
2853                     }
2854                 }
2855                 _ => {}
2856             }
2857         }
2858
2859         let (local, foreign) = implementors.iter()
2860             .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2861                                          .map_or(true, |d| cache.paths.contains_key(&d)));
2862
2863
2864         let (synthetic, concrete) = local.iter()
2865             .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2866
2867
2868         if !foreign.is_empty() {
2869             write!(w, "
2870                 <h2 id='foreign-impls' class='small-section-header'>
2871                   Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2872                 </h2>
2873             ")?;
2874
2875             for implementor in foreign {
2876                 let assoc_link = AssocItemLink::GotoSource(
2877                     implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2878                 );
2879                 render_impl(w, cx, &implementor, assoc_link,
2880                             RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2881             }
2882         }
2883
2884         write!(w, "{}", impl_header)?;
2885         for implementor in concrete {
2886             render_implementor(cx, implementor, w, &implementor_dups)?;
2887         }
2888         write!(w, "</ul>")?;
2889
2890         if t.auto {
2891             write!(w, "{}", synthetic_impl_header)?;
2892             for implementor in synthetic {
2893                 synthetic_types.extend(
2894                     collect_paths_for_type(implementor.inner_impl().for_.clone())
2895                 );
2896                 render_implementor(cx, implementor, w, &implementor_dups)?;
2897             }
2898             write!(w, "</ul>")?;
2899         }
2900     } else {
2901         // even without any implementations to write in, we still want the heading and list, so the
2902         // implementors javascript file pulled in below has somewhere to write the impls into
2903         write!(w, "{}", impl_header)?;
2904         write!(w, "</ul>")?;
2905
2906         if t.auto {
2907             write!(w, "{}", synthetic_impl_header)?;
2908             write!(w, "</ul>")?;
2909         }
2910     }
2911     write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2912            as_json(&synthetic_types))?;
2913
2914     write!(w, r#"<script type="text/javascript" async
2915                          src="{root_path}/implementors/{path}/{ty}.{name}.js">
2916                  </script>"#,
2917            root_path = vec![".."; cx.current.len()].join("/"),
2918            path = if it.def_id.is_local() {
2919                cx.current.join("/")
2920            } else {
2921                let (ref path, _) = cache.external_paths[&it.def_id];
2922                path[..path.len() - 1].join("/")
2923            },
2924            ty = it.type_().css_class(),
2925            name = *it.name.as_ref().unwrap())?;
2926     Ok(())
2927 }
2928
2929 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2930     use html::item_type::ItemType::*;
2931
2932     let name = it.name.as_ref().unwrap();
2933     let ty = match it.type_() {
2934         Typedef | AssociatedType => AssociatedType,
2935         s@_ => s,
2936     };
2937
2938     let anchor = format!("#{}.{}", ty, name);
2939     match link {
2940         AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2941         AssocItemLink::Anchor(None) => anchor,
2942         AssocItemLink::GotoSource(did, _) => {
2943             href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2944         }
2945     }
2946 }
2947
2948 fn assoc_const(w: &mut fmt::Formatter,
2949                it: &clean::Item,
2950                ty: &clean::Type,
2951                _default: Option<&String>,
2952                link: AssocItemLink) -> fmt::Result {
2953     write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2954            VisSpace(&it.visibility),
2955            naive_assoc_href(it, link),
2956            it.name.as_ref().unwrap(),
2957            ty)?;
2958     Ok(())
2959 }
2960
2961 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2962                              bounds: &Vec<clean::TyParamBound>,
2963                              default: Option<&clean::Type>,
2964                              link: AssocItemLink) -> fmt::Result {
2965     write!(w, "type <a href='{}' class=\"type\">{}</a>",
2966            naive_assoc_href(it, link),
2967            it.name.as_ref().unwrap())?;
2968     if !bounds.is_empty() {
2969         write!(w, ": {}", TyParamBounds(bounds))?
2970     }
2971     if let Some(default) = default {
2972         write!(w, " = {}", default)?;
2973     }
2974     Ok(())
2975 }
2976
2977 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2978                                   ver: Option<&'a str>,
2979                                   containing_ver: Option<&'a str>) -> fmt::Result {
2980     if let Some(v) = ver {
2981         if containing_ver != ver && v.len() > 0 {
2982             write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2983                    v)?
2984         }
2985     }
2986     Ok(())
2987 }
2988
2989 fn render_stability_since(w: &mut fmt::Formatter,
2990                           item: &clean::Item,
2991                           containing_item: &clean::Item) -> fmt::Result {
2992     render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2993 }
2994
2995 fn render_assoc_item(w: &mut fmt::Formatter,
2996                      item: &clean::Item,
2997                      link: AssocItemLink,
2998                      parent: ItemType) -> fmt::Result {
2999     fn method(w: &mut fmt::Formatter,
3000               meth: &clean::Item,
3001               unsafety: hir::Unsafety,
3002               constness: hir::Constness,
3003               abi: abi::Abi,
3004               g: &clean::Generics,
3005               d: &clean::FnDecl,
3006               link: AssocItemLink,
3007               parent: ItemType)
3008               -> fmt::Result {
3009         let name = meth.name.as_ref().unwrap();
3010         let anchor = format!("#{}.{}", meth.type_(), name);
3011         let href = match link {
3012             AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3013             AssocItemLink::Anchor(None) => anchor,
3014             AssocItemLink::GotoSource(did, provided_methods) => {
3015                 // We're creating a link from an impl-item to the corresponding
3016                 // trait-item and need to map the anchored type accordingly.
3017                 let ty = if provided_methods.contains(name) {
3018                     ItemType::Method
3019                 } else {
3020                     ItemType::TyMethod
3021                 };
3022
3023                 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3024             }
3025         };
3026         let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
3027                                    VisSpace(&meth.visibility),
3028                                    ConstnessSpace(constness),
3029                                    UnsafetySpace(unsafety),
3030                                    AbiSpace(abi),
3031                                    name,
3032                                    *g).len();
3033         let (indent, end_newline) = if parent == ItemType::Trait {
3034             head_len += 4;
3035             (4, false)
3036         } else {
3037             (0, true)
3038         };
3039         write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3040                    {generics}{decl}{where_clause}",
3041                VisSpace(&meth.visibility),
3042                ConstnessSpace(constness),
3043                UnsafetySpace(unsafety),
3044                AbiSpace(abi),
3045                href = href,
3046                name = name,
3047                generics = *g,
3048                decl = Method {
3049                    decl: d,
3050                    name_len: head_len,
3051                    indent,
3052                },
3053                where_clause = WhereClause {
3054                    gens: g,
3055                    indent,
3056                    end_newline,
3057                })
3058     }
3059     match item.inner {
3060         clean::StrippedItem(..) => Ok(()),
3061         clean::TyMethodItem(ref m) => {
3062             method(w, item, m.unsafety, hir::Constness::NotConst,
3063                    m.abi, &m.generics, &m.decl, link, parent)
3064         }
3065         clean::MethodItem(ref m) => {
3066             method(w, item, m.unsafety, m.constness,
3067                    m.abi, &m.generics, &m.decl, link, parent)
3068         }
3069         clean::AssociatedConstItem(ref ty, ref default) => {
3070             assoc_const(w, item, ty, default.as_ref(), link)
3071         }
3072         clean::AssociatedTypeItem(ref bounds, ref default) => {
3073             assoc_type(w, item, bounds, default.as_ref(), link)
3074         }
3075         _ => panic!("render_assoc_item called on non-associated-item")
3076     }
3077 }
3078
3079 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3080                s: &clean::Struct) -> fmt::Result {
3081     wrap_into_docblock(w, |w| {
3082         write!(w, "<pre class='rust struct'>")?;
3083         render_attributes(w, it)?;
3084         render_struct(w,
3085                       it,
3086                       Some(&s.generics),
3087                       s.struct_type,
3088                       &s.fields,
3089                       "",
3090                       true)?;
3091         write!(w, "</pre>")
3092     })?;
3093
3094     document(w, cx, it)?;
3095     let mut fields = s.fields.iter().filter_map(|f| {
3096         match f.inner {
3097             clean::StructFieldItem(ref ty) => Some((f, ty)),
3098             _ => None,
3099         }
3100     }).peekable();
3101     if let doctree::Plain = s.struct_type {
3102         if fields.peek().is_some() {
3103             write!(w, "<h2 id='fields' class='fields small-section-header'>
3104                        Fields<a href='#fields' class='anchor'></a></h2>")?;
3105             for (field, ty) in fields {
3106                 let id = derive_id(format!("{}.{}",
3107                                            ItemType::StructField,
3108                                            field.name.as_ref().unwrap()));
3109                 let ns_id = derive_id(format!("{}.{}",
3110                                               field.name.as_ref().unwrap(),
3111                                               ItemType::StructField.name_space()));
3112                 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
3113                            <a href=\"#{id}\" class=\"anchor field\"></a>
3114                            <span id=\"{ns_id}\" class='invisible'>
3115                            <code>{name}: {ty}</code>
3116                            </span></span>",
3117                        item_type = ItemType::StructField,
3118                        id = id,
3119                        ns_id = ns_id,
3120                        name = field.name.as_ref().unwrap(),
3121                        ty = ty)?;
3122                 if let Some(stability_class) = field.stability_class() {
3123                     write!(w, "<span class='stab {stab}'></span>",
3124                         stab = stability_class)?;
3125                 }
3126                 document(w, cx, field)?;
3127             }
3128         }
3129     }
3130     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3131 }
3132
3133 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3134                s: &clean::Union) -> fmt::Result {
3135     wrap_into_docblock(w, |w| {
3136         write!(w, "<pre class='rust union'>")?;
3137         render_attributes(w, it)?;
3138         render_union(w,
3139                      it,
3140                      Some(&s.generics),
3141                      &s.fields,
3142                      "",
3143                      true)?;
3144         write!(w, "</pre>")
3145     })?;
3146
3147     document(w, cx, it)?;
3148     let mut fields = s.fields.iter().filter_map(|f| {
3149         match f.inner {
3150             clean::StructFieldItem(ref ty) => Some((f, ty)),
3151             _ => None,
3152         }
3153     }).peekable();
3154     if fields.peek().is_some() {
3155         write!(w, "<h2 id='fields' class='fields small-section-header'>
3156                    Fields<a href='#fields' class='anchor'></a></h2>")?;
3157         for (field, ty) in fields {
3158             let name = field.name.as_ref().expect("union field name");
3159             let id = format!("{}.{}", ItemType::StructField, name);
3160             write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3161                            <a href=\"#{id}\" class=\"anchor field\"></a>\
3162                            <span class='invisible'><code>{name}: {ty}</code></span>\
3163                        </span>",
3164                    id = id,
3165                    name = name,
3166                    shortty = ItemType::StructField,
3167                    ty = ty)?;
3168             if let Some(stability_class) = field.stability_class() {
3169                 write!(w, "<span class='stab {stab}'></span>",
3170                     stab = stability_class)?;
3171             }
3172             document(w, cx, field)?;
3173         }
3174     }
3175     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3176 }
3177
3178 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3179              e: &clean::Enum) -> fmt::Result {
3180     wrap_into_docblock(w, |w| {
3181         write!(w, "<pre class='rust enum'>")?;
3182         render_attributes(w, it)?;
3183         write!(w, "{}enum {}{}{}",
3184                VisSpace(&it.visibility),
3185                it.name.as_ref().unwrap(),
3186                e.generics,
3187                WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3188         if e.variants.is_empty() && !e.variants_stripped {
3189             write!(w, " {{}}")?;
3190         } else {
3191             write!(w, " {{\n")?;
3192             for v in &e.variants {
3193                 write!(w, "    ")?;
3194                 let name = v.name.as_ref().unwrap();
3195                 match v.inner {
3196                     clean::VariantItem(ref var) => {
3197                         match var.kind {
3198                             clean::VariantKind::CLike => write!(w, "{}", name)?,
3199                             clean::VariantKind::Tuple(ref tys) => {
3200                                 write!(w, "{}(", name)?;
3201                                 for (i, ty) in tys.iter().enumerate() {
3202                                     if i > 0 {
3203                                         write!(w, ",&nbsp;")?
3204                                     }
3205                                     write!(w, "{}", *ty)?;
3206                                 }
3207                                 write!(w, ")")?;
3208                             }
3209                             clean::VariantKind::Struct(ref s) => {
3210                                 render_struct(w,
3211                                               v,
3212                                               None,
3213                                               s.struct_type,
3214                                               &s.fields,
3215                                               "    ",
3216                                               false)?;
3217                             }
3218                         }
3219                     }
3220                     _ => unreachable!()
3221                 }
3222                 write!(w, ",\n")?;
3223             }
3224
3225             if e.variants_stripped {
3226                 write!(w, "    // some variants omitted\n")?;
3227             }
3228             write!(w, "}}")?;
3229         }
3230         write!(w, "</pre>")
3231     })?;
3232
3233     document(w, cx, it)?;
3234     if !e.variants.is_empty() {
3235         write!(w, "<h2 id='variants' class='variants small-section-header'>
3236                    Variants<a href='#variants' class='anchor'></a></h2>\n")?;
3237         for variant in &e.variants {
3238             let id = derive_id(format!("{}.{}",
3239                                        ItemType::Variant,
3240                                        variant.name.as_ref().unwrap()));
3241             let ns_id = derive_id(format!("{}.{}",
3242                                           variant.name.as_ref().unwrap(),
3243                                           ItemType::Variant.name_space()));
3244             write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3245                        <a href=\"#{id}\" class=\"anchor field\"></a>\
3246                        <span id='{ns_id}' class='invisible'><code>{name}",
3247                    id = id,
3248                    ns_id = ns_id,
3249                    name = variant.name.as_ref().unwrap())?;
3250             if let clean::VariantItem(ref var) = variant.inner {
3251                 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3252                     write!(w, "(")?;
3253                     for (i, ty) in tys.iter().enumerate() {
3254                         if i > 0 {
3255                             write!(w, ",&nbsp;")?;
3256                         }
3257                         write!(w, "{}", *ty)?;
3258                     }
3259                     write!(w, ")")?;
3260                 }
3261             }
3262             write!(w, "</code></span></span>")?;
3263             document(w, cx, variant)?;
3264
3265             use clean::{Variant, VariantKind};
3266             if let clean::VariantItem(Variant {
3267                 kind: VariantKind::Struct(ref s)
3268             }) = variant.inner {
3269                 let variant_id = derive_id(format!("{}.{}.fields",
3270                                                    ItemType::Variant,
3271                                                    variant.name.as_ref().unwrap()));
3272                 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
3273                        id = variant_id)?;
3274                 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
3275                            <table>", name = variant.name.as_ref().unwrap())?;
3276                 for field in &s.fields {
3277                     use clean::StructFieldItem;
3278                     if let StructFieldItem(ref ty) = field.inner {
3279                         let id = derive_id(format!("variant.{}.field.{}",
3280                                                    variant.name.as_ref().unwrap(),
3281                                                    field.name.as_ref().unwrap()));
3282                         let ns_id = derive_id(format!("{}.{}.{}.{}",
3283                                                       variant.name.as_ref().unwrap(),
3284                                                       ItemType::Variant.name_space(),
3285                                                       field.name.as_ref().unwrap(),
3286                                                       ItemType::StructField.name_space()));
3287                         write!(w, "<tr><td \
3288                                    id='{id}'>\
3289                                    <span id='{ns_id}' class='invisible'>\
3290                                    <code>{f}:&nbsp;{t}</code></span></td><td>",
3291                                id = id,
3292                                ns_id = ns_id,
3293                                f = field.name.as_ref().unwrap(),
3294                                t = *ty)?;
3295                         document(w, cx, field)?;
3296                         write!(w, "</td></tr>")?;
3297                     }
3298                 }
3299                 write!(w, "</table></span>")?;
3300             }
3301             render_stability_since(w, variant, it)?;
3302         }
3303     }
3304     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3305     Ok(())
3306 }
3307
3308 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3309     let name = attr.name();
3310
3311     if attr.is_word() {
3312         Some(format!("{}", name))
3313     } else if let Some(v) = attr.value_str() {
3314         Some(format!("{} = {:?}", name, v.as_str()))
3315     } else if let Some(values) = attr.meta_item_list() {
3316         let display: Vec<_> = values.iter().filter_map(|attr| {
3317             attr.meta_item().and_then(|mi| render_attribute(mi))
3318         }).collect();
3319
3320         if display.len() > 0 {
3321             Some(format!("{}({})", name, display.join(", ")))
3322         } else {
3323             None
3324         }
3325     } else {
3326         None
3327     }
3328 }
3329
3330 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3331     "export_name",
3332     "lang",
3333     "link_section",
3334     "must_use",
3335     "no_mangle",
3336     "repr",
3337     "unsafe_destructor_blind_to_params"
3338 ];
3339
3340 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3341     let mut attrs = String::new();
3342
3343     for attr in &it.attrs.other_attrs {
3344         let name = attr.name();
3345         if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3346             continue;
3347         }
3348         if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3349             attrs.push_str(&format!("#[{}]\n", s));
3350         }
3351     }
3352     if attrs.len() > 0 {
3353         write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3354     }
3355     Ok(())
3356 }
3357
3358 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3359                  g: Option<&clean::Generics>,
3360                  ty: doctree::StructType,
3361                  fields: &[clean::Item],
3362                  tab: &str,
3363                  structhead: bool) -> fmt::Result {
3364     write!(w, "{}{}{}",
3365            VisSpace(&it.visibility),
3366            if structhead {"struct "} else {""},
3367            it.name.as_ref().unwrap())?;
3368     if let Some(g) = g {
3369         write!(w, "{}", g)?
3370     }
3371     match ty {
3372         doctree::Plain => {
3373             if let Some(g) = g {
3374                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3375             }
3376             let mut has_visible_fields = false;
3377             write!(w, " {{")?;
3378             for field in fields {
3379                 if let clean::StructFieldItem(ref ty) = field.inner {
3380                     write!(w, "\n{}    {}{}: {},",
3381                            tab,
3382                            VisSpace(&field.visibility),
3383                            field.name.as_ref().unwrap(),
3384                            *ty)?;
3385                     has_visible_fields = true;
3386                 }
3387             }
3388
3389             if has_visible_fields {
3390                 if it.has_stripped_fields().unwrap() {
3391                     write!(w, "\n{}    // some fields omitted", tab)?;
3392                 }
3393                 write!(w, "\n{}", tab)?;
3394             } else if it.has_stripped_fields().unwrap() {
3395                 // If there are no visible fields we can just display
3396                 // `{ /* fields omitted */ }` to save space.
3397                 write!(w, " /* fields omitted */ ")?;
3398             }
3399             write!(w, "}}")?;
3400         }
3401         doctree::Tuple => {
3402             write!(w, "(")?;
3403             for (i, field) in fields.iter().enumerate() {
3404                 if i > 0 {
3405                     write!(w, ", ")?;
3406                 }
3407                 match field.inner {
3408                     clean::StrippedItem(box clean::StructFieldItem(..)) => {
3409                         write!(w, "_")?
3410                     }
3411                     clean::StructFieldItem(ref ty) => {
3412                         write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3413                     }
3414                     _ => unreachable!()
3415                 }
3416             }
3417             write!(w, ")")?;
3418             if let Some(g) = g {
3419                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3420             }
3421             write!(w, ";")?;
3422         }
3423         doctree::Unit => {
3424             // Needed for PhantomData.
3425             if let Some(g) = g {
3426                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3427             }
3428             write!(w, ";")?;
3429         }
3430     }
3431     Ok(())
3432 }
3433
3434 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3435                 g: Option<&clean::Generics>,
3436                 fields: &[clean::Item],
3437                 tab: &str,
3438                 structhead: bool) -> fmt::Result {
3439     write!(w, "{}{}{}",
3440            VisSpace(&it.visibility),
3441            if structhead {"union "} else {""},
3442            it.name.as_ref().unwrap())?;
3443     if let Some(g) = g {
3444         write!(w, "{}", g)?;
3445         write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3446     }
3447
3448     write!(w, " {{\n{}", tab)?;
3449     for field in fields {
3450         if let clean::StructFieldItem(ref ty) = field.inner {
3451             write!(w, "    {}{}: {},\n{}",
3452                    VisSpace(&field.visibility),
3453                    field.name.as_ref().unwrap(),
3454                    *ty,
3455                    tab)?;
3456         }
3457     }
3458
3459     if it.has_stripped_fields().unwrap() {
3460         write!(w, "    // some fields omitted\n{}", tab)?;
3461     }
3462     write!(w, "}}")?;
3463     Ok(())
3464 }
3465
3466 #[derive(Copy, Clone)]
3467 enum AssocItemLink<'a> {
3468     Anchor(Option<&'a str>),
3469     GotoSource(DefId, &'a FxHashSet<String>),
3470 }
3471
3472 impl<'a> AssocItemLink<'a> {
3473     fn anchor(&self, id: &'a String) -> Self {
3474         match *self {
3475             AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3476             ref other => *other,
3477         }
3478     }
3479 }
3480
3481 enum AssocItemRender<'a> {
3482     All,
3483     DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3484 }
3485
3486 #[derive(Copy, Clone, PartialEq)]
3487 enum RenderMode {
3488     Normal,
3489     ForDeref { mut_: bool },
3490 }
3491
3492 fn render_assoc_items(w: &mut fmt::Formatter,
3493                       cx: &Context,
3494                       containing_item: &clean::Item,
3495                       it: DefId,
3496                       what: AssocItemRender) -> fmt::Result {
3497     let c = cache();
3498     let v = match c.impls.get(&it) {
3499         Some(v) => v,
3500         None => return Ok(()),
3501     };
3502     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3503         i.inner_impl().trait_.is_none()
3504     });
3505     if !non_trait.is_empty() {
3506         let render_mode = match what {
3507             AssocItemRender::All => {
3508                 write!(w, "
3509                     <h2 id='methods' class='small-section-header'>
3510                       Methods<a href='#methods' class='anchor'></a>
3511                     </h2>
3512                 ")?;
3513                 RenderMode::Normal
3514             }
3515             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3516                 write!(w, "
3517                     <h2 id='deref-methods' class='small-section-header'>
3518                       Methods from {}&lt;Target = {}&gt;<a href='#deref-methods' class='anchor'></a>
3519                     </h2>
3520                 ", trait_, type_)?;
3521                 RenderMode::ForDeref { mut_: deref_mut_ }
3522             }
3523         };
3524         for i in &non_trait {
3525             render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3526                         containing_item.stable_since(), true)?;
3527         }
3528     }
3529     if let AssocItemRender::DerefFor { .. } = what {
3530         return Ok(());
3531     }
3532     if !traits.is_empty() {
3533         let deref_impl = traits.iter().find(|t| {
3534             t.inner_impl().trait_.def_id() == c.deref_trait_did
3535         });
3536         if let Some(impl_) = deref_impl {
3537             let has_deref_mut = traits.iter().find(|t| {
3538                 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3539             }).is_some();
3540             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3541         }
3542
3543         let (synthetic, concrete) = traits
3544             .iter()
3545             .partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
3546
3547         struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3548
3549         impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3550             fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3551                 render_impls(self.0, fmt, &self.1, self.2)
3552             }
3553         }
3554
3555         let impls = format!("{}", RendererStruct(cx, concrete, containing_item));
3556         if !impls.is_empty() {
3557             write!(w, "
3558                 <h2 id='implementations' class='small-section-header'>
3559                   Trait Implementations<a href='#implementations' class='anchor'></a>
3560                 </h2>
3561                 <div id='implementations-list'>{}</div>", impls)?;
3562         }
3563
3564         if !synthetic.is_empty() {
3565             write!(w, "
3566                 <h2 id='synthetic-implementations' class='small-section-header'>
3567                   Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
3568                 </h2>
3569                 <div id='synthetic-implementations-list'>
3570             ")?;
3571             render_impls(cx, w, &synthetic, containing_item)?;
3572             write!(w, "</div>")?;
3573         }
3574     }
3575     Ok(())
3576 }
3577
3578 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3579                         container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3580     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3581     let target = impl_.inner_impl().items.iter().filter_map(|item| {
3582         match item.inner {
3583             clean::TypedefItem(ref t, true) => Some(&t.type_),
3584             _ => None,
3585         }
3586     }).next().expect("Expected associated type binding");
3587     let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3588                                            deref_mut_: deref_mut };
3589     if let Some(did) = target.def_id() {
3590         render_assoc_items(w, cx, container_item, did, what)
3591     } else {
3592         if let Some(prim) = target.primitive_type() {
3593             if let Some(&did) = cache().primitive_locations.get(&prim) {
3594                 render_assoc_items(w, cx, container_item, did, what)?;
3595             }
3596         }
3597         Ok(())
3598     }
3599 }
3600
3601 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3602     let self_type_opt = match item.inner {
3603         clean::MethodItem(ref method) => method.decl.self_type(),
3604         clean::TyMethodItem(ref method) => method.decl.self_type(),
3605         _ => None
3606     };
3607
3608     if let Some(self_ty) = self_type_opt {
3609         let (by_mut_ref, by_box, by_value) = match self_ty {
3610             SelfTy::SelfBorrowed(_, mutability) |
3611             SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3612                 (mutability == Mutability::Mutable, false, false)
3613             },
3614             SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3615                 (false, Some(did) == cache().owned_box_did, false)
3616             },
3617             SelfTy::SelfValue => (false, false, true),
3618             _ => (false, false, false),
3619         };
3620
3621         (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3622     } else {
3623         false
3624     }
3625 }
3626
3627 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3628     let mut out = String::new();
3629
3630     match item.inner {
3631         clean::FunctionItem(clean::Function { ref decl, .. }) |
3632         clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3633         clean::MethodItem(clean::Method { ref decl, .. }) |
3634         clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3635             out = spotlight_decl(decl)?;
3636         }
3637         _ => {}
3638     }
3639
3640     Ok(out)
3641 }
3642
3643 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3644     let mut out = String::new();
3645     let mut trait_ = String::new();
3646
3647     if let Some(did) = decl.output.def_id() {
3648         let c = cache();
3649         if let Some(impls) = c.impls.get(&did) {
3650             for i in impls {
3651                 let impl_ = i.inner_impl();
3652                 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3653                     if out.is_empty() {
3654                         out.push_str(
3655                             &format!("<h3 class=\"important\">Important traits for {}</h3>\
3656                                       <code class=\"content\">",
3657                                      impl_.for_));
3658                         trait_.push_str(&format!("{}", impl_.for_));
3659                     }
3660
3661                     //use the "where" class here to make it small
3662                     out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3663                     let t_did = impl_.trait_.def_id().unwrap();
3664                     for it in &impl_.items {
3665                         if let clean::TypedefItem(ref tydef, _) = it.inner {
3666                             out.push_str("<span class=\"where fmt-newline\">    ");
3667                             assoc_type(&mut out, it, &vec![],
3668                                        Some(&tydef.type_),
3669                                        AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3670                             out.push_str(";</span>");
3671                         }
3672                     }
3673                 }
3674             }
3675         }
3676     }
3677
3678     if !out.is_empty() {
3679         out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3680                                     <span class='tooltiptext'>Important traits for {}</span></div>\
3681                                     <div class=\"content hidden\">",
3682                                    trait_));
3683         out.push_str("</code></div></div>");
3684     }
3685
3686     Ok(out)
3687 }
3688
3689 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3690                render_mode: RenderMode, outer_version: Option<&str>,
3691                show_def_docs: bool) -> fmt::Result {
3692     if render_mode == RenderMode::Normal {
3693         let id = derive_id(match i.inner_impl().trait_ {
3694             Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3695             None => "impl".to_string(),
3696         });
3697         write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
3698                    <tbody><tr><td><code>{}</code>",
3699                id, i.inner_impl())?;
3700         write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3701         write!(w, "</span></td><td><span class='out-of-band'>")?;
3702         let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3703         if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3704             write!(w, "<div class='ghost'></div>")?;
3705             render_stability_since_raw(w, since, outer_version)?;
3706             write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3707                    l, "goto source code")?;
3708         } else {
3709             render_stability_since_raw(w, since, outer_version)?;
3710         }
3711         write!(w, "</span></td></tr></tbody></table></h3>")?;
3712         if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3713             write!(w, "<div class='docblock'>{}</div>",
3714                    Markdown(&*dox, &i.impl_item.links()))?;
3715         }
3716     }
3717
3718     fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3719                      link: AssocItemLink, render_mode: RenderMode,
3720                      is_default_item: bool, outer_version: Option<&str>,
3721                      trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3722         let item_type = item.type_();
3723         let name = item.name.as_ref().unwrap();
3724
3725         let render_method_item: bool = match render_mode {
3726             RenderMode::Normal => true,
3727             RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3728         };
3729
3730         match item.inner {
3731             clean::MethodItem(clean::Method { ref decl, .. }) |
3732             clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3733                 // Only render when the method is not static or we allow static methods
3734                 if render_method_item {
3735                     let id = derive_id(format!("{}.{}", item_type, name));
3736                     let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3737                     write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3738                     write!(w, "{}", spotlight_decl(decl)?)?;
3739                     write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3740                     write!(w, "<table class='table-display'><tbody><tr><td><code>")?;
3741                     render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3742                     write!(w, "</code>")?;
3743                     if let Some(l) = (Item { cx, item }).src_href() {
3744                         write!(w, "</span></td><td><span class='out-of-band'>")?;
3745                         write!(w, "<div class='ghost'></div>")?;
3746                         render_stability_since_raw(w, item.stable_since(), outer_version)?;
3747                         write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3748                                l, "goto source code")?;
3749                     } else {
3750                         write!(w, "</td><td>")?;
3751                         render_stability_since_raw(w, item.stable_since(), outer_version)?;
3752                     }
3753                     write!(w, "</td></tr></tbody></table></span></h4>")?;
3754                 }
3755             }
3756             clean::TypedefItem(ref tydef, _) => {
3757                 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3758                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3759                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3760                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3761                 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3762                 write!(w, "</code></span></h4>\n")?;
3763             }
3764             clean::AssociatedConstItem(ref ty, ref default) => {
3765                 let id = derive_id(format!("{}.{}", item_type, name));
3766                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3767                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3768                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3769                 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3770                 write!(w, "</code></span></h4>\n")?;
3771             }
3772             clean::AssociatedTypeItem(ref bounds, ref default) => {
3773                 let id = derive_id(format!("{}.{}", item_type, name));
3774                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3775                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3776                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3777                 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3778                 write!(w, "</code></span></h4>\n")?;
3779             }
3780             clean::StrippedItem(..) => return Ok(()),
3781             _ => panic!("can't make docs for trait item with name {:?}", item.name)
3782         }
3783
3784         if render_method_item || render_mode == RenderMode::Normal {
3785             let prefix = render_assoc_const_value(item);
3786
3787             if !is_default_item {
3788                 if let Some(t) = trait_ {
3789                     // The trait item may have been stripped so we might not
3790                     // find any documentation or stability for it.
3791                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3792                         // We need the stability of the item from the trait
3793                         // because impls can't have a stability.
3794                         document_stability(w, cx, it)?;
3795                         if item.doc_value().is_some() {
3796                             document_full(w, item, cx, &prefix)?;
3797                         } else if show_def_docs {
3798                             // In case the item isn't documented,
3799                             // provide short documentation from the trait.
3800                             document_short(w, it, link, &prefix)?;
3801                         }
3802                     }
3803                 } else {
3804                     document_stability(w, cx, item)?;
3805                     if show_def_docs {
3806                         document_full(w, item, cx, &prefix)?;
3807                     }
3808                 }
3809             } else {
3810                 document_stability(w, cx, item)?;
3811                 if show_def_docs {
3812                     document_short(w, item, link, &prefix)?;
3813                 }
3814             }
3815         }
3816         Ok(())
3817     }
3818
3819     let traits = &cache().traits;
3820     let trait_ = i.trait_did().map(|did| &traits[&did]);
3821
3822     if !show_def_docs {
3823         write!(w, "<span class='docblock autohide'>")?;
3824     }
3825
3826     write!(w, "<div class='impl-items'>")?;
3827     for trait_item in &i.inner_impl().items {
3828         doc_impl_item(w, cx, trait_item, link, render_mode,
3829                       false, outer_version, trait_, show_def_docs)?;
3830     }
3831
3832     fn render_default_items(w: &mut fmt::Formatter,
3833                             cx: &Context,
3834                             t: &clean::Trait,
3835                             i: &clean::Impl,
3836                             render_mode: RenderMode,
3837                             outer_version: Option<&str>,
3838                             show_def_docs: bool) -> fmt::Result {
3839         for trait_item in &t.items {
3840             let n = trait_item.name.clone();
3841             if i.items.iter().find(|m| m.name == n).is_some() {
3842                 continue;
3843             }
3844             let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3845             let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3846
3847             doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3848                           outer_version, None, show_def_docs)?;
3849         }
3850         Ok(())
3851     }
3852
3853     // If we've implemented a trait, then also emit documentation for all
3854     // default items which weren't overridden in the implementation block.
3855     if let Some(t) = trait_ {
3856         render_default_items(w, cx, t, &i.inner_impl(),
3857                              render_mode, outer_version, show_def_docs)?;
3858     }
3859     write!(w, "</div>")?;
3860
3861     if !show_def_docs {
3862         write!(w, "</span>")?;
3863     }
3864
3865     Ok(())
3866 }
3867
3868 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3869                 t: &clean::Typedef) -> fmt::Result {
3870     write!(w, "<pre class='rust typedef'>")?;
3871     render_attributes(w, it)?;
3872     write!(w, "type {}{}{where_clause} = {type_};</pre>",
3873            it.name.as_ref().unwrap(),
3874            t.generics,
3875            where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3876            type_ = t.type_)?;
3877
3878     document(w, cx, it)?;
3879
3880     // Render any items associated directly to this alias, as otherwise they
3881     // won't be visible anywhere in the docs. It would be nice to also show
3882     // associated items from the aliased type (see discussion in #32077), but
3883     // we need #14072 to make sense of the generics.
3884     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3885 }
3886
3887 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3888     writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3889     render_attributes(w, it)?;
3890     write!(
3891         w,
3892         "    {}type {};\n}}</pre>",
3893         VisSpace(&it.visibility),
3894         it.name.as_ref().unwrap(),
3895     )?;
3896
3897     document(w, cx, it)?;
3898
3899     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3900 }
3901
3902 impl<'a> fmt::Display for Sidebar<'a> {
3903     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3904         let cx = self.cx;
3905         let it = self.item;
3906         let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3907
3908         if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3909             || it.is_enum() || it.is_mod() || it.is_typedef() {
3910             write!(fmt, "<p class='location'>{}{}</p>",
3911                 match it.inner {
3912                     clean::StructItem(..) => "Struct ",
3913                     clean::TraitItem(..) => "Trait ",
3914                     clean::PrimitiveItem(..) => "Primitive Type ",
3915                     clean::UnionItem(..) => "Union ",
3916                     clean::EnumItem(..) => "Enum ",
3917                     clean::TypedefItem(..) => "Type Definition ",
3918                     clean::ForeignTypeItem => "Foreign Type ",
3919                     clean::ModuleItem(..) => if it.is_crate() {
3920                         "Crate "
3921                     } else {
3922                         "Module "
3923                     },
3924                     _ => "",
3925                 },
3926                 it.name.as_ref().unwrap())?;
3927         }
3928
3929         if it.is_crate() {
3930             if let Some(ref version) = cache().crate_version {
3931                 write!(fmt,
3932                        "<div class='block version'>\
3933                         <p>Version {}</p>\
3934                         </div>
3935                         <a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3936                        version,
3937                        it.name.as_ref().unwrap())?;
3938             }
3939         }
3940
3941         write!(fmt, "<div class=\"sidebar-elems\">")?;
3942         match it.inner {
3943             clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3944             clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3945             clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3946             clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3947             clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3948             clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3949             clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3950             clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3951             _ => (),
3952         }
3953
3954         // The sidebar is designed to display sibling functions, modules and
3955         // other miscellaneous information. since there are lots of sibling
3956         // items (and that causes quadratic growth in large modules),
3957         // we refactor common parts into a shared JavaScript file per module.
3958         // still, we don't move everything into JS because we want to preserve
3959         // as much HTML as possible in order to allow non-JS-enabled browsers
3960         // to navigate the documentation (though slightly inefficiently).
3961
3962         write!(fmt, "<p class='location'>")?;
3963         for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3964             if i > 0 {
3965                 write!(fmt, "::<wbr>")?;
3966             }
3967             write!(fmt, "<a href='{}index.html'>{}</a>",
3968                    &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3969                    *name)?;
3970         }
3971         write!(fmt, "</p>")?;
3972
3973         // Sidebar refers to the enclosing module, not this module.
3974         let relpath = if it.is_mod() { "../" } else { "" };
3975         write!(fmt,
3976                "<script>window.sidebarCurrent = {{\
3977                    name: '{name}', \
3978                    ty: '{ty}', \
3979                    relpath: '{path}'\
3980                 }};</script>",
3981                name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3982                ty = it.type_().css_class(),
3983                path = relpath)?;
3984         if parentlen == 0 {
3985             // There is no sidebar-items.js beyond the crate root path
3986             // FIXME maybe dynamic crate loading can be merged here
3987         } else {
3988             write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3989                    path = relpath)?;
3990         }
3991         // Closes sidebar-elems div.
3992         write!(fmt, "</div>")?;
3993
3994         Ok(())
3995     }
3996 }
3997
3998 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3999     i.items.iter().filter_map(|item| {
4000         match item.name {
4001             // Maybe check with clean::Visibility::Public as well?
4002             Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4003                 if !for_deref || should_render_item(item, false) {
4004                     Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
4005                 } else {
4006                     None
4007                 }
4008             }
4009             _ => None,
4010         }
4011     }).collect::<Vec<_>>()
4012 }
4013
4014 // The point is to url encode any potential character from a type with genericity.
4015 fn small_url_encode(s: &str) -> String {
4016     s.replace("<", "%3C")
4017      .replace(">", "%3E")
4018      .replace(" ", "%20")
4019      .replace("?", "%3F")
4020      .replace("'", "%27")
4021      .replace("&", "%26")
4022      .replace(",", "%2C")
4023      .replace(":", "%3A")
4024      .replace(";", "%3B")
4025      .replace("[", "%5B")
4026      .replace("]", "%5D")
4027      .replace("\"", "%22")
4028 }
4029
4030 fn sidebar_assoc_items(it: &clean::Item) -> String {
4031     let mut out = String::new();
4032     let c = cache();
4033     if let Some(v) = c.impls.get(&it.def_id) {
4034         let ret = v.iter()
4035                    .filter(|i| i.inner_impl().trait_.is_none())
4036                    .flat_map(|i| get_methods(i.inner_impl(), false))
4037                    .collect::<String>();
4038         if !ret.is_empty() {
4039             out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4040                                    </a><div class=\"sidebar-links\">{}</div>", ret));
4041         }
4042
4043         if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4044             if let Some(impl_) = v.iter()
4045                                   .filter(|i| i.inner_impl().trait_.is_some())
4046                                   .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4047                 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4048                     match item.inner {
4049                         clean::TypedefItem(ref t, true) => Some(&t.type_),
4050                         _ => None,
4051                     }
4052                 }).next() {
4053                     let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4054                         c.primitive_locations.get(&prim).cloned()
4055                     })).and_then(|did| c.impls.get(&did));
4056                     if let Some(impls) = inner_impl {
4057                         out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4058                         out.push_str(&format!("Methods from {}&lt;Target={}&gt;",
4059                                               Escape(&format!("{:#}",
4060                                                      impl_.inner_impl().trait_.as_ref().unwrap())),
4061                                               Escape(&format!("{:#}", target))));
4062                         out.push_str("</a>");
4063                         let ret = impls.iter()
4064                                        .filter(|i| i.inner_impl().trait_.is_none())
4065                                        .flat_map(|i| get_methods(i.inner_impl(), true))
4066                                        .collect::<String>();
4067                         out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
4068                     }
4069                 }
4070             }
4071             let format_impls = |impls: Vec<&Impl>| {
4072                 let mut links = HashSet::new();
4073                 impls.iter()
4074                            .filter_map(|i| {
4075                                let is_negative_impl = is_negative_impl(i.inner_impl());
4076                                if let Some(ref i) = i.inner_impl().trait_ {
4077                                    let i_display = format!("{:#}", i);
4078                                    let out = Escape(&i_display);
4079                                    let encoded = small_url_encode(&format!("{:#}", i));
4080                                    let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4081                                                            encoded,
4082                                                            if is_negative_impl { "!" } else { "" },
4083                                                            out);
4084                                    if links.insert(generated.clone()) {
4085                                        Some(generated)
4086                                    } else {
4087                                        None
4088                                    }
4089                                } else {
4090                                    None
4091                                }
4092                            })
4093                            .collect::<String>()
4094             };
4095
4096             let (synthetic, concrete) = v
4097                 .iter()
4098                 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4099
4100             let concrete_format = format_impls(concrete);
4101             let synthetic_format = format_impls(synthetic);
4102
4103             if !concrete_format.is_empty() {
4104                 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4105                               Trait Implementations</a>");
4106                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4107             }
4108
4109             if !synthetic_format.is_empty() {
4110                 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4111                               Auto Trait Implementations</a>");
4112                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4113             }
4114         }
4115     }
4116
4117     out
4118 }
4119
4120 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4121                   s: &clean::Struct) -> fmt::Result {
4122     let mut sidebar = String::new();
4123     let fields = get_struct_fields_name(&s.fields);
4124
4125     if !fields.is_empty() {
4126         if let doctree::Plain = s.struct_type {
4127             sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4128                                        <div class=\"sidebar-links\">{}</div>", fields));
4129         }
4130     }
4131
4132     sidebar.push_str(&sidebar_assoc_items(it));
4133
4134     if !sidebar.is_empty() {
4135         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4136     }
4137     Ok(())
4138 }
4139
4140 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4141     match item.inner {
4142         clean::ItemEnum::ImplItem(ref i) => {
4143             if let Some(ref trait_) = i.trait_ {
4144                 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4145             } else {
4146                 None
4147             }
4148         },
4149         _ => None,
4150     }
4151 }
4152
4153 fn is_negative_impl(i: &clean::Impl) -> bool {
4154     i.polarity == Some(clean::ImplPolarity::Negative)
4155 }
4156
4157 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4158                  t: &clean::Trait) -> fmt::Result {
4159     let mut sidebar = String::new();
4160
4161     let types = t.items
4162                  .iter()
4163                  .filter_map(|m| {
4164                      match m.name {
4165                          Some(ref name) if m.is_associated_type() => {
4166                              Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4167                                           name=name))
4168                          }
4169                          _ => None,
4170                      }
4171                  })
4172                  .collect::<String>();
4173     let consts = t.items
4174                   .iter()
4175                   .filter_map(|m| {
4176                       match m.name {
4177                           Some(ref name) if m.is_associated_const() => {
4178                               Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4179                                            name=name))
4180                           }
4181                           _ => None,
4182                       }
4183                   })
4184                   .collect::<String>();
4185     let required = t.items
4186                     .iter()
4187                     .filter_map(|m| {
4188                         match m.name {
4189                             Some(ref name) if m.is_ty_method() => {
4190                                 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4191                                              name=name))
4192                             }
4193                             _ => None,
4194                         }
4195                     })
4196                     .collect::<String>();
4197     let provided = t.items
4198                     .iter()
4199                     .filter_map(|m| {
4200                         match m.name {
4201                             Some(ref name) if m.is_method() => {
4202                                 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
4203                             }
4204                             _ => None,
4205                         }
4206                     })
4207                     .collect::<String>();
4208
4209     if !types.is_empty() {
4210         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4211                                    Associated Types</a><div class=\"sidebar-links\">{}</div>",
4212                                   types));
4213     }
4214     if !consts.is_empty() {
4215         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4216                                    Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4217                                   consts));
4218     }
4219     if !required.is_empty() {
4220         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4221                                    Required Methods</a><div class=\"sidebar-links\">{}</div>",
4222                                   required));
4223     }
4224     if !provided.is_empty() {
4225         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4226                                    Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4227                                   provided));
4228     }
4229
4230     let c = cache();
4231
4232     if let Some(implementors) = c.implementors.get(&it.def_id) {
4233         let res = implementors.iter()
4234                               .filter(|i| i.inner_impl().for_.def_id()
4235                               .map_or(false, |d| !c.paths.contains_key(&d)))
4236                               .filter_map(|i| {
4237                                   match extract_for_impl_name(&i.impl_item) {
4238                                       Some((ref name, ref url)) => {
4239                                           Some(format!("<a href=\"#impl-{}\">{}</a>",
4240                                                       small_url_encode(url),
4241                                                       Escape(name)))
4242                                       }
4243                                       _ => None,
4244                                   }
4245                               })
4246                               .collect::<String>();
4247         if !res.is_empty() {
4248             sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4249                                        Implementations on Foreign Types</a><div \
4250                                        class=\"sidebar-links\">{}</div>",
4251                                       res));
4252         }
4253     }
4254
4255     sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4256     if t.auto {
4257         sidebar.push_str("<a class=\"sidebar-title\" \
4258                           href=\"#synthetic-implementors\">Auto Implementors</a>");
4259     }
4260
4261     sidebar.push_str(&sidebar_assoc_items(it));
4262
4263     write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4264 }
4265
4266 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4267                      _p: &clean::PrimitiveType) -> fmt::Result {
4268     let sidebar = sidebar_assoc_items(it);
4269
4270     if !sidebar.is_empty() {
4271         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4272     }
4273     Ok(())
4274 }
4275
4276 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4277                    _t: &clean::Typedef) -> fmt::Result {
4278     let sidebar = sidebar_assoc_items(it);
4279
4280     if !sidebar.is_empty() {
4281         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4282     }
4283     Ok(())
4284 }
4285
4286 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4287     fields.iter()
4288           .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4289               true
4290           } else {
4291               false
4292           })
4293           .filter_map(|f| match f.name {
4294               Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4295                                               {name}</a>", name=name)),
4296               _ => None,
4297           })
4298           .collect()
4299 }
4300
4301 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4302                  u: &clean::Union) -> fmt::Result {
4303     let mut sidebar = String::new();
4304     let fields = get_struct_fields_name(&u.fields);
4305
4306     if !fields.is_empty() {
4307         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4308                                    <div class=\"sidebar-links\">{}</div>", fields));
4309     }
4310
4311     sidebar.push_str(&sidebar_assoc_items(it));
4312
4313     if !sidebar.is_empty() {
4314         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4315     }
4316     Ok(())
4317 }
4318
4319 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4320                 e: &clean::Enum) -> fmt::Result {
4321     let mut sidebar = String::new();
4322
4323     let variants = e.variants.iter()
4324                              .filter_map(|v| match v.name {
4325                                  Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4326                                                                  </a>", name = name)),
4327                                  _ => None,
4328                              })
4329                              .collect::<String>();
4330     if !variants.is_empty() {
4331         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4332                                    <div class=\"sidebar-links\">{}</div>", variants));
4333     }
4334
4335     sidebar.push_str(&sidebar_assoc_items(it));
4336
4337     if !sidebar.is_empty() {
4338         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4339     }
4340     Ok(())
4341 }
4342
4343 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4344                   items: &[clean::Item]) -> fmt::Result {
4345     let mut sidebar = String::new();
4346
4347     if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4348                              it.type_() == ItemType::Import) {
4349         sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4350                                   id = "reexports",
4351                                   name = "Re-exports"));
4352     }
4353
4354     // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4355     // to print its headings
4356     for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4357                    ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4358                    ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4359                    ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4360                    ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4361         if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4362             let (short, name) = match myty {
4363                 ItemType::ExternCrate |
4364                 ItemType::Import          => ("reexports", "Re-exports"),
4365                 ItemType::Module          => ("modules", "Modules"),
4366                 ItemType::Struct          => ("structs", "Structs"),
4367                 ItemType::Union           => ("unions", "Unions"),
4368                 ItemType::Enum            => ("enums", "Enums"),
4369                 ItemType::Function        => ("functions", "Functions"),
4370                 ItemType::Typedef         => ("types", "Type Definitions"),
4371                 ItemType::Static          => ("statics", "Statics"),
4372                 ItemType::Constant        => ("constants", "Constants"),
4373                 ItemType::Trait           => ("traits", "Traits"),
4374                 ItemType::Impl            => ("impls", "Implementations"),
4375                 ItemType::TyMethod        => ("tymethods", "Type Methods"),
4376                 ItemType::Method          => ("methods", "Methods"),
4377                 ItemType::StructField     => ("fields", "Struct Fields"),
4378                 ItemType::Variant         => ("variants", "Variants"),
4379                 ItemType::Macro           => ("macros", "Macros"),
4380                 ItemType::Primitive       => ("primitives", "Primitive Types"),
4381                 ItemType::AssociatedType  => ("associated-types", "Associated Types"),
4382                 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4383                 ItemType::ForeignType     => ("foreign-types", "Foreign Types"),
4384             };
4385             sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4386                                       id = short,
4387                                       name = name));
4388         }
4389     }
4390
4391     if !sidebar.is_empty() {
4392         write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4393     }
4394     Ok(())
4395 }
4396
4397 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4398     let sidebar = sidebar_assoc_items(it);
4399     if !sidebar.is_empty() {
4400         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4401     }
4402     Ok(())
4403 }
4404
4405 impl<'a> fmt::Display for Source<'a> {
4406     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4407         let Source(s) = *self;
4408         let lines = s.lines().count();
4409         let mut cols = 0;
4410         let mut tmp = lines;
4411         while tmp > 0 {
4412             cols += 1;
4413             tmp /= 10;
4414         }
4415         write!(fmt, "<pre class=\"line-numbers\">")?;
4416         for i in 1..lines + 1 {
4417             write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4418         }
4419         write!(fmt, "</pre>")?;
4420         write!(fmt, "{}",
4421                highlight::render_with_highlighting(s, None, None, None, None))?;
4422         Ok(())
4423     }
4424 }
4425
4426 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4427               t: &clean::Macro) -> fmt::Result {
4428     wrap_into_docblock(w, |w| {
4429         w.write_str(&highlight::render_with_highlighting(&t.source,
4430                                                          Some("macro"),
4431                                                          None,
4432                                                          None,
4433                                                          None))
4434     })?;
4435     document(w, cx, it)
4436 }
4437
4438 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4439                   it: &clean::Item,
4440                   _p: &clean::PrimitiveType) -> fmt::Result {
4441     document(w, cx, it)?;
4442     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4443 }
4444
4445 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4446
4447 fn make_item_keywords(it: &clean::Item) -> String {
4448     format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4449 }
4450
4451 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4452     let decl = match item.inner {
4453         clean::FunctionItem(ref f) => &f.decl,
4454         clean::MethodItem(ref m) => &m.decl,
4455         clean::TyMethodItem(ref m) => &m.decl,
4456         _ => return None
4457     };
4458
4459     let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4460     let output = match decl.output {
4461         clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4462         _ => None
4463     };
4464
4465     Some(IndexItemFunctionType { inputs: inputs, output: output })
4466 }
4467
4468 fn get_index_type(clean_type: &clean::Type) -> Type {
4469     let t = Type {
4470         name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4471         generics: get_generics(clean_type),
4472     };
4473     t
4474 }
4475
4476 /// Returns a list of all paths used in the type.
4477 /// This is used to help deduplicate imported impls
4478 /// for reexported types. If any of the contained
4479 /// types are re-exported, we don't use the corresponding
4480 /// entry from the js file, as inlining will have already
4481 /// picked up the impl
4482 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4483     let mut out = Vec::new();
4484     let mut visited = FxHashSet();
4485     let mut work = VecDeque::new();
4486     let cache = cache();
4487
4488     work.push_back(first_ty);
4489
4490     while let Some(ty) = work.pop_front() {
4491         if !visited.insert(ty.clone()) {
4492             continue;
4493         }
4494
4495         match ty {
4496             clean::Type::ResolvedPath { did, .. } => {
4497                 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4498                 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4499
4500                 match fqp {
4501                     Some(path) => {
4502                         out.push(path.join("::"));
4503                     },
4504                     _ => {}
4505                 };
4506
4507             },
4508             clean::Type::Tuple(tys) => {
4509                 work.extend(tys.into_iter());
4510             },
4511             clean::Type::Slice(ty) => {
4512                 work.push_back(*ty);
4513             }
4514             clean::Type::Array(ty, _) => {
4515                 work.push_back(*ty);
4516             },
4517             clean::Type::Unique(ty) => {
4518                 work.push_back(*ty);
4519             },
4520             clean::Type::RawPointer(_, ty) => {
4521                 work.push_back(*ty);
4522             },
4523             clean::Type::BorrowedRef { type_, .. } => {
4524                 work.push_back(*type_);
4525             },
4526             clean::Type::QPath { self_type, trait_, .. } => {
4527                 work.push_back(*self_type);
4528                 work.push_back(*trait_);
4529             },
4530             _ => {}
4531         }
4532     };
4533     out
4534 }
4535
4536 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4537     match *clean_type {
4538         clean::ResolvedPath { ref path, .. } => {
4539             let segments = &path.segments;
4540             let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4541                 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4542                 clean_type, accept_generic
4543             ));
4544             Some(path_segment.name.clone())
4545         }
4546         clean::Generic(ref s) if accept_generic => Some(s.clone()),
4547         clean::Primitive(ref p) => Some(format!("{:?}", p)),
4548         clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4549         // FIXME: add all from clean::Type.
4550         _ => None
4551     }
4552 }
4553
4554 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4555     clean_type.generics()
4556               .and_then(|types| {
4557                   let r = types.iter()
4558                                .filter_map(|t| get_index_type_name(t, false))
4559                                .map(|s| s.to_ascii_lowercase())
4560                                .collect::<Vec<_>>();
4561                   if r.is_empty() {
4562                       None
4563                   } else {
4564                       Some(r)
4565                   }
4566               })
4567 }
4568
4569 pub fn cache() -> Arc<Cache> {
4570     CACHE_KEY.with(|c| c.borrow().clone())
4571 }
4572
4573 #[cfg(test)]
4574 #[test]
4575 fn test_unique_id() {
4576     let input = ["foo", "examples", "examples", "method.into_iter","examples",
4577                  "method.into_iter", "foo", "main", "search", "methods",
4578                  "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4579     let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4580                     "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4581                     "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4582
4583     let test = || {
4584         let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4585         assert_eq!(&actual[..], expected);
4586     };
4587     test();
4588     reset_ids(true);
4589     test();
4590 }
4591
4592 #[cfg(test)]
4593 #[test]
4594 fn test_name_key() {
4595     assert_eq!(name_key("0"), ("", 0, 1));
4596     assert_eq!(name_key("123"), ("", 123, 0));
4597     assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4598     assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4599     assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4600     assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4601     assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4602     assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4603 }
4604
4605 #[cfg(test)]
4606 #[test]
4607 fn test_name_sorting() {
4608     let names = ["Apple",
4609                  "Banana",
4610                  "Fruit", "Fruit0", "Fruit00",
4611                  "Fruit1", "Fruit01",
4612                  "Fruit2", "Fruit02",
4613                  "Fruit20",
4614                  "Fruit100",
4615                  "Pear"];
4616     let mut sorted = names.to_owned();
4617     sorted.sort_by_key(|&s| name_key(s));
4618     assert_eq!(names, sorted);
4619 }