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