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