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