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