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