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