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