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