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