]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render.rs
Auto merge of #58151 - ljedrz:HirIdify_rustc, r=Zoxc
[rust.git] / src / librustdoc / html / render.rs
1 //! Rustdoc's HTML Rendering module
2 //!
3 //! This modules contains the bulk of the logic necessary for rendering a
4 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
5 //! rendering process is largely driven by the `format!` syntax extension to
6 //! perform all I/O into files and streams.
7 //!
8 //! The rendering process is largely driven by the `Context` and `Cache`
9 //! structures. The cache is pre-populated by crawling the crate in question,
10 //! and then it is shared among the various rendering threads. The cache is meant
11 //! to be a fairly large structure not implementing `Clone` (because it's shared
12 //! among threads). The context, however, should be a lightweight structure. This
13 //! is cloned per-thread and contains information about what is currently being
14 //! rendered.
15 //!
16 //! In order to speed up rendering (mostly because of markdown rendering), the
17 //! rendering process has been parallelized. This parallelization is only
18 //! exposed through the `crate` method on the context, and then also from the
19 //! fact that the shared cache is stored in TLS (and must be accessed as such).
20 //!
21 //! In addition to rendering the crate itself, this module is also responsible
22 //! for creating the corresponding search index and source file renderings.
23 //! These threads are not parallelized (they haven't been a bottleneck yet), and
24 //! both occur before the crate is rendered.
25
26 pub use self::ExternalLocation::*;
27
28 use std::borrow::Cow;
29 use std::cell::RefCell;
30 use std::cmp::Ordering;
31 use std::collections::{BTreeMap, VecDeque};
32 use std::default::Default;
33 use std::error;
34 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
35 use std::ffi::OsStr;
36 use std::fs::{self, File, OpenOptions};
37 use std::io::prelude::*;
38 use std::io::{self, BufWriter, BufReader};
39 use std::mem;
40 use std::path::{PathBuf, Path, Component};
41 use std::str;
42 use std::sync::Arc;
43 use std::rc::Rc;
44
45 use errors;
46 use serialize::json::{ToJson, Json, as_json};
47 use syntax::ast;
48 use syntax::ext::base::MacroKind;
49 use syntax::source_map::FileName;
50 use syntax::feature_gate::UnstableFeatures;
51 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
52 use rustc::middle::privacy::AccessLevels;
53 use rustc::middle::stability;
54 use rustc::hir;
55 use rustc::util::nodemap::{FxHashMap, FxHashSet};
56 use rustc_data_structures::flock;
57
58 use clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
59 use config::RenderOptions;
60 use doctree;
61 use fold::DocFolder;
62 use html::escape::Escape;
63 use html::format::{AsyncSpace, ConstnessSpace};
64 use html::format::{GenericBounds, WhereClause, href, AbiSpace};
65 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
66 use html::format::fmt_impl_for_trait_page;
67 use html::item_type::ItemType;
68 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
69 use html::{highlight, layout, static_files};
70
71 use minifier;
72
73 /// A pair of name and its optional document.
74 pub type NameDoc = (String, Option<String>);
75
76 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 whether 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 node ids 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 def ids 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 /// Build 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 }
1840
1841 impl AllTypes {
1842     fn new() -> AllTypes {
1843         let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1844         AllTypes {
1845             structs: new_set(100),
1846             enums: new_set(100),
1847             unions: new_set(100),
1848             primitives: new_set(26),
1849             traits: new_set(100),
1850             macros: new_set(100),
1851             functions: new_set(100),
1852             typedefs: new_set(100),
1853             existentials: new_set(100),
1854             statics: new_set(100),
1855             constants: new_set(100),
1856             keywords: new_set(100),
1857             attributes: new_set(100),
1858             derives: new_set(100),
1859         }
1860     }
1861
1862     fn append(&mut self, item_name: String, item_type: &ItemType) {
1863         let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1864         if let Some(name) = url.pop() {
1865             let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1866             url.push(name);
1867             let name = url.join("::");
1868             match *item_type {
1869                 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1870                 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1871                 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1872                 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1873                 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1874                 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1875                 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1876                 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1877                 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1878                 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1879                 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1880                 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1881                 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1882                 _ => true,
1883             };
1884         }
1885     }
1886 }
1887
1888 fn print_entries(f: &mut fmt::Formatter, e: &FxHashSet<ItemEntry>, title: &str,
1889                  class: &str) -> fmt::Result {
1890     if !e.is_empty() {
1891         let mut e: Vec<&ItemEntry> = e.iter().collect();
1892         e.sort();
1893         write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1894                title,
1895                Escape(title),
1896                class,
1897                e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1898     }
1899     Ok(())
1900 }
1901
1902 impl fmt::Display for AllTypes {
1903     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1904         write!(f,
1905 "<h1 class='fqn'>\
1906      <span class='out-of-band'>\
1907          <span id='render-detail'>\
1908              <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1909                  [<span class='inner'>&#x2212;</span>]\
1910              </a>\
1911          </span>
1912      </span>
1913      <span class='in-band'>List of all items</span>\
1914 </h1>")?;
1915         print_entries(f, &self.structs, "Structs", "structs")?;
1916         print_entries(f, &self.enums, "Enums", "enums")?;
1917         print_entries(f, &self.unions, "Unions", "unions")?;
1918         print_entries(f, &self.primitives, "Primitives", "primitives")?;
1919         print_entries(f, &self.traits, "Traits", "traits")?;
1920         print_entries(f, &self.macros, "Macros", "macros")?;
1921         print_entries(f, &self.attributes, "Attribute Macros", "attributes")?;
1922         print_entries(f, &self.derives, "Derive Macros", "derives")?;
1923         print_entries(f, &self.functions, "Functions", "functions")?;
1924         print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1925         print_entries(f, &self.existentials, "Existentials", "existentials")?;
1926         print_entries(f, &self.statics, "Statics", "statics")?;
1927         print_entries(f, &self.constants, "Constants", "constants")
1928     }
1929 }
1930
1931 #[derive(Debug)]
1932 struct Settings<'a> {
1933     // (id, explanation, default value)
1934     settings: Vec<(&'static str, &'static str, bool)>,
1935     root_path: &'a str,
1936     suffix: &'a str,
1937 }
1938
1939 impl<'a> Settings<'a> {
1940     pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1941         Settings {
1942             settings: vec![
1943                 ("item-declarations", "Auto-hide item declarations.", true),
1944                 ("item-attributes", "Auto-hide item attributes.", true),
1945                 ("trait-implementations", "Auto-hide trait implementations documentation",
1946                  true),
1947                 ("method-docs", "Auto-hide item methods' documentation", false),
1948                 ("go-to-only-result", "Directly go to item in search if there is only one result",
1949                  false),
1950                 ("line-numbers", "Show line numbers on code examples", false),
1951             ],
1952             root_path,
1953             suffix,
1954         }
1955     }
1956 }
1957
1958 impl<'a> fmt::Display for Settings<'a> {
1959     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1960         write!(f,
1961 "<h1 class='fqn'>\
1962      <span class='in-band'>Rustdoc settings</span>\
1963 </h1>\
1964 <div class='settings'>{}</div>\
1965 <script src='{}settings{}.js'></script>",
1966                self.settings.iter()
1967                             .map(|(id, text, enabled)| {
1968                                 format!("<div class='setting-line'>\
1969                                              <label class='toggle'>\
1970                                                 <input type='checkbox' id='{}' {}>\
1971                                                 <span class='slider'></span>\
1972                                              </label>\
1973                                              <div>{}</div>\
1974                                          </div>", id, if *enabled { " checked" } else { "" }, text)
1975                             })
1976                             .collect::<String>(),
1977                self.root_path,
1978                self.suffix)
1979     }
1980 }
1981
1982 impl Context {
1983     fn derive_id(&self, id: String) -> String {
1984         let mut map = self.id_map.borrow_mut();
1985         map.derive(id)
1986     }
1987
1988     /// String representation of how to get back to the root path of the 'doc/'
1989     /// folder in terms of a relative URL.
1990     fn root_path(&self) -> String {
1991         "../".repeat(self.current.len())
1992     }
1993
1994     /// Recurse in the directory structure and change the "root path" to make
1995     /// sure it always points to the top (relatively).
1996     fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1997         F: FnOnce(&mut Context) -> T,
1998     {
1999         if s.is_empty() {
2000             panic!("Unexpected empty destination: {:?}", self.current);
2001         }
2002         let prev = self.dst.clone();
2003         self.dst.push(&s);
2004         self.current.push(s);
2005
2006         info!("Recursing into {}", self.dst.display());
2007
2008         let ret = f(self);
2009
2010         info!("Recursed; leaving {}", self.dst.display());
2011
2012         // Go back to where we were at
2013         self.dst = prev;
2014         self.current.pop().unwrap();
2015
2016         ret
2017     }
2018
2019     /// Main method for rendering a crate.
2020     ///
2021     /// This currently isn't parallelized, but it'd be pretty easy to add
2022     /// parallelization to this function.
2023     fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
2024         let mut item = match krate.module.take() {
2025             Some(i) => i,
2026             None => return Ok(()),
2027         };
2028         let final_file = self.dst.join(&krate.name)
2029                                  .join("all.html");
2030         let settings_file = self.dst.join("settings.html");
2031
2032         let crate_name = krate.name.clone();
2033         item.name = Some(krate.name);
2034
2035         let mut all = AllTypes::new();
2036
2037         {
2038             // Render the crate documentation
2039             let mut work = vec![(self.clone(), item)];
2040
2041             while let Some((mut cx, item)) = work.pop() {
2042                 cx.item(item, &mut all, |cx, item| {
2043                     work.push((cx.clone(), item))
2044                 })?
2045             }
2046         }
2047
2048         let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
2049         let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
2050         if !root_path.ends_with('/') {
2051             root_path.push('/');
2052         }
2053         let mut page = layout::Page {
2054             title: "List of all items in this crate",
2055             css_class: "mod",
2056             root_path: "../",
2057             static_root_path: self.shared.static_root_path.deref(),
2058             description: "List of all items in this crate",
2059             keywords: BASIC_KEYWORDS,
2060             resource_suffix: &self.shared.resource_suffix,
2061             extra_scripts: &[],
2062             static_extra_scripts: &[],
2063         };
2064         let sidebar = if let Some(ref version) = cache().crate_version {
2065             format!("<p class='location'>Crate {}</p>\
2066                      <div class='block version'>\
2067                          <p>Version {}</p>\
2068                      </div>\
2069                      <a id='all-types' href='index.html'><p>Back to index</p></a>",
2070                     crate_name, version)
2071         } else {
2072             String::new()
2073         };
2074         try_err!(layout::render(&mut w, &self.shared.layout,
2075                                 &page, &sidebar, &all,
2076                                 self.shared.css_file_extension.is_some(),
2077                                 &self.shared.themes,
2078                                 self.shared.generate_search_filter),
2079                  &final_file);
2080
2081         // Generating settings page.
2082         let settings = Settings::new("./", &self.shared.resource_suffix);
2083         page.title = "Rustdoc settings";
2084         page.description = "Settings of Rustdoc";
2085         page.root_path = "./";
2086
2087         let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
2088         let mut themes = self.shared.themes.clone();
2089         let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
2090         themes.push(PathBuf::from("settings.css"));
2091         let layout = self.shared.layout.clone();
2092         try_err!(layout::render(&mut w, &layout,
2093                                 &page, &sidebar, &settings,
2094                                 self.shared.css_file_extension.is_some(),
2095                                 &themes,
2096                                 self.shared.generate_search_filter),
2097                  &settings_file);
2098
2099         Ok(())
2100     }
2101
2102     fn render_item(&self,
2103                    writer: &mut dyn io::Write,
2104                    it: &clean::Item,
2105                    pushname: bool)
2106                    -> io::Result<()> {
2107         // A little unfortunate that this is done like this, but it sure
2108         // does make formatting *a lot* nicer.
2109         CURRENT_LOCATION_KEY.with(|slot| {
2110             *slot.borrow_mut() = self.current.clone();
2111         });
2112
2113         let mut title = if it.is_primitive() || it.is_keyword() {
2114             // No need to include the namespace for primitive types and keywords
2115             String::new()
2116         } else {
2117             self.current.join("::")
2118         };
2119         if pushname {
2120             if !title.is_empty() {
2121                 title.push_str("::");
2122             }
2123             title.push_str(it.name.as_ref().unwrap());
2124         }
2125         title.push_str(" - Rust");
2126         let tyname = it.type_().css_class();
2127         let desc = if it.is_crate() {
2128             format!("API documentation for the Rust `{}` crate.",
2129                     self.shared.layout.krate)
2130         } else {
2131             format!("API documentation for the Rust `{}` {} in crate `{}`.",
2132                     it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
2133         };
2134         let keywords = make_item_keywords(it);
2135         let page = layout::Page {
2136             css_class: tyname,
2137             root_path: &self.root_path(),
2138             static_root_path: self.shared.static_root_path.deref(),
2139             title: &title,
2140             description: &desc,
2141             keywords: &keywords,
2142             resource_suffix: &self.shared.resource_suffix,
2143             extra_scripts: &[],
2144             static_extra_scripts: &[],
2145         };
2146
2147         {
2148             self.id_map.borrow_mut().reset();
2149             self.id_map.borrow_mut().populate(initial_ids());
2150         }
2151
2152         if !self.render_redirect_pages {
2153             layout::render(writer, &self.shared.layout, &page,
2154                            &Sidebar{ cx: self, item: it },
2155                            &Item{ cx: self, item: it },
2156                            self.shared.css_file_extension.is_some(),
2157                            &self.shared.themes,
2158                            self.shared.generate_search_filter)?;
2159         } else {
2160             let mut url = self.root_path();
2161             if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
2162                 for name in &names[..names.len() - 1] {
2163                     url.push_str(name);
2164                     url.push_str("/");
2165                 }
2166                 url.push_str(&item_path(ty, names.last().unwrap()));
2167                 layout::redirect(writer, &url)?;
2168             }
2169         }
2170         Ok(())
2171     }
2172
2173     /// Non-parallelized version of rendering an item. This will take the input
2174     /// item, render its contents, and then invoke the specified closure with
2175     /// all sub-items which need to be rendered.
2176     ///
2177     /// The rendering driver uses this closure to queue up more work.
2178     fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
2179         where F: FnMut(&mut Context, clean::Item),
2180     {
2181         // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
2182         // if they contain impls for public types. These modules can also
2183         // contain items such as publicly re-exported structures.
2184         //
2185         // External crates will provide links to these structures, so
2186         // these modules are recursed into, but not rendered normally
2187         // (a flag on the context).
2188         if !self.render_redirect_pages {
2189             self.render_redirect_pages = item.is_stripped();
2190         }
2191
2192         if item.is_mod() {
2193             // modules are special because they add a namespace. We also need to
2194             // recurse into the items of the module as well.
2195             let name = item.name.as_ref().unwrap().to_string();
2196             let mut item = Some(item);
2197             self.recurse(name, |this| {
2198                 let item = item.take().unwrap();
2199
2200                 let mut buf = Vec::new();
2201                 this.render_item(&mut buf, &item, false).unwrap();
2202                 // buf will be empty if the module is stripped and there is no redirect for it
2203                 if !buf.is_empty() {
2204                     try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
2205                     let joint_dst = this.dst.join("index.html");
2206                     try_err!(fs::write(&joint_dst, buf), &joint_dst);
2207                 }
2208
2209                 let m = match item.inner {
2210                     clean::StrippedItem(box clean::ModuleItem(m)) |
2211                     clean::ModuleItem(m) => m,
2212                     _ => unreachable!()
2213                 };
2214
2215                 // Render sidebar-items.js used throughout this module.
2216                 if !this.render_redirect_pages {
2217                     let items = this.build_sidebar_items(&m);
2218                     let js_dst = this.dst.join("sidebar-items.js");
2219                     let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
2220                     try_err!(write!(&mut js_out, "initSidebarItems({});",
2221                                     as_json(&items)), &js_dst);
2222                 }
2223
2224                 for item in m.items {
2225                     f(this, item);
2226                 }
2227
2228                 Ok(())
2229             })?;
2230         } else if item.name.is_some() {
2231             let mut buf = Vec::new();
2232             self.render_item(&mut buf, &item, true).unwrap();
2233             // buf will be empty if the item is stripped and there is no redirect for it
2234             if !buf.is_empty() {
2235                 let name = item.name.as_ref().unwrap();
2236                 let item_type = item.type_();
2237                 let file_name = &item_path(item_type, name);
2238                 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
2239                 let joint_dst = self.dst.join(file_name);
2240                 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2241
2242                 if !self.render_redirect_pages {
2243                     all.append(full_path(self, &item), &item_type);
2244                 }
2245                 // Redirect from a sane URL using the namespace to Rustdoc's
2246                 // URL for the page.
2247                 let redir_name = format!("{}.{}.html", name, item_type.name_space());
2248                 let redir_dst = self.dst.join(redir_name);
2249                 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
2250                                                             .write(true)
2251                                                             .open(&redir_dst) {
2252                     let mut redirect_out = BufWriter::new(redirect_out);
2253                     try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2254                 }
2255
2256                 // If the item is a macro, redirect from the old macro URL (with !)
2257                 // to the new one (without).
2258                 if item_type == ItemType::Macro {
2259                     let redir_name = format!("{}.{}!.html", item_type, name);
2260                     let redir_dst = self.dst.join(redir_name);
2261                     let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
2262                     let mut redirect_out = BufWriter::new(redirect_out);
2263                     try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2264                 }
2265             }
2266         }
2267         Ok(())
2268     }
2269
2270     fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
2271         // BTreeMap instead of HashMap to get a sorted output
2272         let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
2273         for item in &m.items {
2274             if item.is_stripped() { continue }
2275
2276             let short = item.type_().css_class();
2277             let myname = match item.name {
2278                 None => continue,
2279                 Some(ref s) => s.to_string(),
2280             };
2281             let short = short.to_string();
2282             map.entry(short).or_default()
2283                 .push((myname, Some(plain_summary_line(item.doc_value()))));
2284         }
2285
2286         if self.shared.sort_modules_alphabetically {
2287             for (_, items) in &mut map {
2288                 items.sort();
2289             }
2290         }
2291         map
2292     }
2293 }
2294
2295 impl<'a> Item<'a> {
2296     /// Generate a url appropriate for an `href` attribute back to the source of
2297     /// this item.
2298     ///
2299     /// The url generated, when clicked, will redirect the browser back to the
2300     /// original source code.
2301     ///
2302     /// If `None` is returned, then a source link couldn't be generated. This
2303     /// may happen, for example, with externally inlined items where the source
2304     /// of their crate documentation isn't known.
2305     fn src_href(&self) -> Option<String> {
2306         let mut root = self.cx.root_path();
2307
2308         let cache = cache();
2309         let mut path = String::new();
2310
2311         // We can safely ignore macros from other libraries
2312         let file = match self.item.source.filename {
2313             FileName::Real(ref path) => path,
2314             _ => return None,
2315         };
2316
2317         let (krate, path) = if self.item.def_id.is_local() {
2318             if let Some(path) = self.cx.shared.local_sources.get(file) {
2319                 (&self.cx.shared.layout.krate, path)
2320             } else {
2321                 return None;
2322             }
2323         } else {
2324             let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? {
2325                 (ref name, ref src, Local) => (name, src),
2326                 (ref name, ref src, Remote(ref s)) => {
2327                     root = s.to_string();
2328                     (name, src)
2329                 }
2330                 (_, _, Unknown) => return None,
2331             };
2332
2333             clean_srcpath(&src_root, file, false, |component| {
2334                 path.push_str(&component.to_string_lossy());
2335                 path.push('/');
2336             });
2337             let mut fname = file.file_name().expect("source has no filename")
2338                                 .to_os_string();
2339             fname.push(".html");
2340             path.push_str(&fname.to_string_lossy());
2341             (krate, &path)
2342         };
2343
2344         let lines = if self.item.source.loline == self.item.source.hiline {
2345             self.item.source.loline.to_string()
2346         } else {
2347             format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2348         };
2349         Some(format!("{root}src/{krate}/{path}#{lines}",
2350                      root = Escape(&root),
2351                      krate = krate,
2352                      path = path,
2353                      lines = lines))
2354     }
2355 }
2356
2357 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2358                          f: F) -> fmt::Result
2359 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2360     write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2361     f(w)?;
2362     write!(w, "</div>")
2363 }
2364
2365 impl<'a> fmt::Display for Item<'a> {
2366     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2367         debug_assert!(!self.item.is_stripped());
2368         // Write the breadcrumb trail header for the top
2369         write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2370         if let Some(version) = self.item.stable_since() {
2371             write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2372                    version)?;
2373         }
2374         write!(fmt,
2375                "<span id='render-detail'>\
2376                    <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2377                       title=\"collapse all docs\">\
2378                        [<span class='inner'>&#x2212;</span>]\
2379                    </a>\
2380                </span>")?;
2381
2382         // Write `src` tag
2383         //
2384         // When this item is part of a `pub use` in a downstream crate, the
2385         // [src] link in the downstream documentation will actually come back to
2386         // this page, and this link will be auto-clicked. The `id` attribute is
2387         // used to find the link to auto-click.
2388         if self.cx.shared.include_sources && !self.item.is_primitive() {
2389             if let Some(l) = self.src_href() {
2390                 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2391                        l, "goto source code")?;
2392             }
2393         }
2394
2395         write!(fmt, "</span>")?; // out-of-band
2396         write!(fmt, "<span class='in-band'>")?;
2397         match self.item.inner {
2398             clean::ModuleItem(ref m) => if m.is_crate {
2399                     write!(fmt, "Crate ")?;
2400                 } else {
2401                     write!(fmt, "Module ")?;
2402                 },
2403             clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2404             clean::TraitItem(..) => write!(fmt, "Trait ")?,
2405             clean::StructItem(..) => write!(fmt, "Struct ")?,
2406             clean::UnionItem(..) => write!(fmt, "Union ")?,
2407             clean::EnumItem(..) => write!(fmt, "Enum ")?,
2408             clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2409             clean::MacroItem(..) => write!(fmt, "Macro ")?,
2410             clean::ProcMacroItem(ref mac) => match mac.kind {
2411                 MacroKind::Bang => write!(fmt, "Macro ")?,
2412                 MacroKind::Attr => write!(fmt, "Attribute Macro ")?,
2413                 MacroKind::Derive => write!(fmt, "Derive Macro ")?,
2414                 MacroKind::ProcMacroStub => unreachable!(),
2415             }
2416             clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2417             clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2418             clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2419             clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2420             clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2421             clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2422             _ => {
2423                 // We don't generate pages for any other type.
2424                 unreachable!();
2425             }
2426         }
2427         if !self.item.is_primitive() && !self.item.is_keyword() {
2428             let cur = &self.cx.current;
2429             let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2430             for (i, component) in cur.iter().enumerate().take(amt) {
2431                 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2432                        "../".repeat(cur.len() - i - 1),
2433                        component)?;
2434             }
2435         }
2436         write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2437                self.item.type_(), self.item.name.as_ref().unwrap())?;
2438
2439         write!(fmt, "</span></h1>")?; // in-band
2440
2441         match self.item.inner {
2442             clean::ModuleItem(ref m) =>
2443                 item_module(fmt, self.cx, self.item, &m.items),
2444             clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2445                 item_function(fmt, self.cx, self.item, f),
2446             clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2447             clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2448             clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2449             clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2450             clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2451             clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2452             clean::ProcMacroItem(ref m) => item_proc_macro(fmt, self.cx, self.item, m),
2453             clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2454             clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2455                 item_static(fmt, self.cx, self.item, i),
2456             clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2457             clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2458             clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2459             clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2460             _ => {
2461                 // We don't generate pages for any other type.
2462                 unreachable!();
2463             }
2464         }
2465     }
2466 }
2467
2468 fn item_path(ty: ItemType, name: &str) -> String {
2469     match ty {
2470         ItemType::Module => format!("{}index.html", SlashChecker(name)),
2471         _ => format!("{}.{}.html", ty.css_class(), name),
2472     }
2473 }
2474
2475 fn full_path(cx: &Context, item: &clean::Item) -> String {
2476     let mut s = cx.current.join("::");
2477     s.push_str("::");
2478     s.push_str(item.name.as_ref().unwrap());
2479     s
2480 }
2481
2482 fn shorter<'a>(s: Option<&'a str>) -> String {
2483     match s {
2484         Some(s) => s.lines()
2485             .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2486             .take_while(|line|{
2487             (*line).chars().any(|chr|{
2488                 !chr.is_whitespace()
2489             })
2490         }).collect::<Vec<_>>().join("\n"),
2491         None => String::new()
2492     }
2493 }
2494
2495 #[inline]
2496 fn plain_summary_line(s: Option<&str>) -> String {
2497     let line = shorter(s).replace("\n", " ");
2498     markdown::plain_summary_line_full(&line[..], false)
2499 }
2500
2501 #[inline]
2502 fn plain_summary_line_short(s: Option<&str>) -> String {
2503     let line = shorter(s).replace("\n", " ");
2504     markdown::plain_summary_line_full(&line[..], true)
2505 }
2506
2507 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2508     if let Some(ref name) = item.name {
2509         info!("Documenting {}", name);
2510     }
2511     document_stability(w, cx, item, false)?;
2512     document_full(w, item, cx, "", false)?;
2513     Ok(())
2514 }
2515
2516 /// Render md_text as markdown.
2517 fn render_markdown(w: &mut fmt::Formatter,
2518                    cx: &Context,
2519                    md_text: &str,
2520                    links: Vec<(String, String)>,
2521                    prefix: &str,
2522                    is_hidden: bool)
2523                    -> fmt::Result {
2524     let mut ids = cx.id_map.borrow_mut();
2525     write!(w, "<div class='docblock{}'>{}{}</div>",
2526            if is_hidden { " hidden" } else { "" },
2527            prefix,
2528            Markdown(md_text, &links, RefCell::new(&mut ids),
2529            cx.codes))
2530 }
2531
2532 fn document_short(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item, link: AssocItemLink,
2533                   prefix: &str, is_hidden: bool) -> fmt::Result {
2534     if let Some(s) = item.doc_value() {
2535         let markdown = if s.contains('\n') {
2536             format!("{} [Read more]({})",
2537                     &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2538         } else {
2539             plain_summary_line(Some(s))
2540         };
2541         render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden)?;
2542     } else if !prefix.is_empty() {
2543         write!(w, "<div class='docblock{}'>{}</div>",
2544                if is_hidden { " hidden" } else { "" },
2545                prefix)?;
2546     }
2547     Ok(())
2548 }
2549
2550 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2551                  cx: &Context, prefix: &str, is_hidden: bool) -> fmt::Result {
2552     if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2553         debug!("Doc block: =====\n{}\n=====", s);
2554         render_markdown(w, cx, &*s, item.links(), prefix, is_hidden)?;
2555     } else if !prefix.is_empty() {
2556         write!(w, "<div class='docblock{}'>{}</div>",
2557                if is_hidden { " hidden" } else { "" },
2558                prefix)?;
2559     }
2560     Ok(())
2561 }
2562
2563 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2564                       is_hidden: bool) -> fmt::Result {
2565     let stabilities = short_stability(item, cx);
2566     if !stabilities.is_empty() {
2567         write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" })?;
2568         for stability in stabilities {
2569             write!(w, "{}", stability)?;
2570         }
2571         write!(w, "</div>")?;
2572     }
2573     Ok(())
2574 }
2575
2576 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2577     if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2578 }
2579
2580 fn document_non_exhaustive(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
2581     if item.is_non_exhaustive() {
2582         write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2583             if item.is_struct() { "struct" } else if item.is_enum() { "enum" } else { "type" }
2584         })?;
2585
2586         if item.is_struct() {
2587             write!(w, "Non-exhaustive structs could have additional fields added in future. \
2588                        Therefore, non-exhaustive structs cannot be constructed in external crates \
2589                        using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2590                        matched against without a wildcard <code>..</code>; and \
2591                        struct update syntax will not work.")?;
2592         } else if item.is_enum() {
2593             write!(w, "Non-exhaustive enums could have additional variants added in future. \
2594                        Therefore, when matching against variants of non-exhaustive enums, an \
2595                        extra wildcard arm must be added to account for any future variants.")?;
2596         } else {
2597             write!(w, "This type will require a wildcard arm in any match statements or \
2598                        constructors.")?;
2599         }
2600
2601         write!(w, "</div>")?;
2602     }
2603
2604     Ok(())
2605 }
2606
2607 fn name_key(name: &str) -> (&str, u64, usize) {
2608     let end = name.bytes()
2609         .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
2610
2611     // find number at end
2612     let split = name[0..end].bytes()
2613         .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
2614
2615     // count leading zeroes
2616     let after_zeroes =
2617         name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2618
2619     // sort leading zeroes last
2620     let num_zeroes = after_zeroes - split;
2621
2622     match name[split..end].parse() {
2623         Ok(n) => (&name[..split], n, num_zeroes),
2624         Err(_) => (name, 0, num_zeroes),
2625     }
2626 }
2627
2628 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2629                item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2630     document(w, cx, item)?;
2631
2632     let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2633
2634     // the order of item types in the listing
2635     fn reorder(ty: ItemType) -> u8 {
2636         match ty {
2637             ItemType::ExternCrate     => 0,
2638             ItemType::Import          => 1,
2639             ItemType::Primitive       => 2,
2640             ItemType::Module          => 3,
2641             ItemType::Macro           => 4,
2642             ItemType::Struct          => 5,
2643             ItemType::Enum            => 6,
2644             ItemType::Constant        => 7,
2645             ItemType::Static          => 8,
2646             ItemType::Trait           => 9,
2647             ItemType::Function        => 10,
2648             ItemType::Typedef         => 12,
2649             ItemType::Union           => 13,
2650             _                         => 14 + ty as u8,
2651         }
2652     }
2653
2654     fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2655         let ty1 = i1.type_();
2656         let ty2 = i2.type_();
2657         if ty1 != ty2 {
2658             return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2659         }
2660         let s1 = i1.stability.as_ref().map(|s| s.level);
2661         let s2 = i2.stability.as_ref().map(|s| s.level);
2662         match (s1, s2) {
2663             (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2664             (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2665             _ => {}
2666         }
2667         let lhs = i1.name.as_ref().map_or("", |s| &**s);
2668         let rhs = i2.name.as_ref().map_or("", |s| &**s);
2669         name_key(lhs).cmp(&name_key(rhs))
2670     }
2671
2672     if cx.shared.sort_modules_alphabetically {
2673         indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2674     }
2675     // This call is to remove re-export duplicates in cases such as:
2676     //
2677     // ```
2678     // pub mod foo {
2679     //     pub mod bar {
2680     //         pub trait Double { fn foo(); }
2681     //     }
2682     // }
2683     //
2684     // pub use foo::bar::*;
2685     // pub use foo::*;
2686     // ```
2687     //
2688     // `Double` will appear twice in the generated docs.
2689     //
2690     // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2691     // can be identical even if the elements are different (mostly in imports).
2692     // So in case this is an import, we keep everything by adding a "unique id"
2693     // (which is the position in the vector).
2694     indices.dedup_by_key(|i| (items[*i].def_id,
2695                               if items[*i].name.as_ref().is_some() {
2696                                   Some(full_path(cx, &items[*i]))
2697                               } else {
2698                                   None
2699                               },
2700                               items[*i].type_(),
2701                               if items[*i].is_import() {
2702                                   *i
2703                               } else {
2704                                   0
2705                               }));
2706
2707     debug!("{:?}", indices);
2708     let mut curty = None;
2709     for &idx in &indices {
2710         let myitem = &items[idx];
2711         if myitem.is_stripped() {
2712             continue;
2713         }
2714
2715         let myty = Some(myitem.type_());
2716         if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2717             // Put `extern crate` and `use` re-exports in the same section.
2718             curty = myty;
2719         } else if myty != curty {
2720             if curty.is_some() {
2721                 write!(w, "</table>")?;
2722             }
2723             curty = myty;
2724             let (short, name) = item_ty_to_strs(&myty.unwrap());
2725             write!(w, "<h2 id='{id}' class='section-header'>\
2726                        <a href=\"#{id}\">{name}</a></h2>\n<table>",
2727                    id = cx.derive_id(short.to_owned()), name = name)?;
2728         }
2729
2730         match myitem.inner {
2731             clean::ExternCrateItem(ref name, ref src) => {
2732                 use html::format::HRef;
2733
2734                 match *src {
2735                     Some(ref src) => {
2736                         write!(w, "<tr><td><code>{}extern crate {} as {};",
2737                                VisSpace(&myitem.visibility),
2738                                HRef::new(myitem.def_id, src),
2739                                name)?
2740                     }
2741                     None => {
2742                         write!(w, "<tr><td><code>{}extern crate {};",
2743                                VisSpace(&myitem.visibility),
2744                                HRef::new(myitem.def_id, name))?
2745                     }
2746                 }
2747                 write!(w, "</code></td></tr>")?;
2748             }
2749
2750             clean::ImportItem(ref import) => {
2751                 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2752                        VisSpace(&myitem.visibility), *import)?;
2753             }
2754
2755             _ => {
2756                 if myitem.name.is_none() { continue }
2757
2758                 let unsafety_flag = match myitem.inner {
2759                     clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2760                     if func.header.unsafety == hir::Unsafety::Unsafe => {
2761                         "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2762                     }
2763                     _ => "",
2764                 };
2765
2766                 let stab = myitem.stability_class();
2767                 let add = if stab.is_some() {
2768                     " "
2769                 } else {
2770                     ""
2771                 };
2772
2773                 let doc_value = myitem.doc_value().unwrap_or("");
2774                 write!(w, "\
2775                        <tr class='{stab}{add}module-item'>\
2776                            <td><a class=\"{class}\" href=\"{href}\" \
2777                                   title='{title}'>{name}</a>{unsafety_flag}</td>\
2778                            <td class='docblock-short'>{stab_tags}{docs}\
2779                            </td>\
2780                        </tr>",
2781                        name = *myitem.name.as_ref().unwrap(),
2782                        stab_tags = stability_tags(myitem),
2783                        docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2784                        class = myitem.type_(),
2785                        add = add,
2786                        stab = stab.unwrap_or_else(|| String::new()),
2787                        unsafety_flag = unsafety_flag,
2788                        href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2789                        title = [full_path(cx, myitem), myitem.type_().to_string()]
2790                                 .iter()
2791                                 .filter_map(|s| if !s.is_empty() {
2792                                     Some(s.as_str())
2793                                 } else {
2794                                     None
2795                                 })
2796                                 .collect::<Vec<_>>()
2797                                 .join(" "),
2798                       )?;
2799             }
2800         }
2801     }
2802
2803     if curty.is_some() {
2804         write!(w, "</table>")?;
2805     }
2806     Ok(())
2807 }
2808
2809 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2810 /// module level.
2811 fn stability_tags(item: &clean::Item) -> String {
2812     let mut tags = String::new();
2813
2814     fn tag_html(class: &str, contents: &str) -> String {
2815         format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2816     }
2817
2818     // The trailing space after each tag is to space it properly against the rest of the docs.
2819     if item.deprecation().is_some() {
2820         tags += &tag_html("deprecated", "Deprecated");
2821     }
2822
2823     if let Some(stab) = item
2824         .stability
2825         .as_ref()
2826         .filter(|s| s.level == stability::Unstable)
2827     {
2828         if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2829             tags += &tag_html("internal", "Internal");
2830         } else {
2831             tags += &tag_html("unstable", "Experimental");
2832         }
2833     }
2834
2835     if let Some(ref cfg) = item.attrs.cfg {
2836         tags += &tag_html("portability", &cfg.render_short_html());
2837     }
2838
2839     tags
2840 }
2841
2842 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2843 /// documentation.
2844 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2845     let mut stability = vec![];
2846     let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2847
2848     if let Some(Deprecation { since, note }) = &item.deprecation() {
2849         let mut message = if let Some(since) = since {
2850             if stability::deprecation_in_effect(since) {
2851                 format!("Deprecated since {}", Escape(since))
2852             } else {
2853                 format!("Deprecating in {}", Escape(since))
2854             }
2855         } else {
2856             String::from("Deprecated")
2857         };
2858
2859         if let Some(note) = note {
2860             let mut ids = cx.id_map.borrow_mut();
2861             let html = MarkdownHtml(&note, RefCell::new(&mut ids), error_codes);
2862             message.push_str(&format!(": {}", html));
2863         }
2864         stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2865     }
2866
2867     if let Some(stab) = item
2868         .stability
2869         .as_ref()
2870         .filter(|stab| stab.level == stability::Unstable)
2871     {
2872         let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2873
2874         let mut message = if is_rustc_private {
2875             "<span class='emoji'>⚙️</span> This is an internal compiler API."
2876         } else {
2877             "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2878         }
2879         .to_owned();
2880
2881         if let Some(feature) = stab.feature.as_ref() {
2882             let mut feature = format!("<code>{}</code>", Escape(&feature));
2883             if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2884                 feature.push_str(&format!(
2885                     "&nbsp;<a href=\"{url}{issue}\">#{issue}</a>",
2886                     url = url,
2887                     issue = issue
2888                 ));
2889             }
2890
2891             message.push_str(&format!(" ({})", feature));
2892         }
2893
2894         if let Some(unstable_reason) = &stab.unstable_reason {
2895             // Provide a more informative message than the compiler help.
2896             let unstable_reason = if is_rustc_private {
2897                 "This crate is being loaded from the sysroot, a permanently unstable location \
2898                 for private compiler dependencies. It is not intended for general use. Prefer \
2899                 using a public version of this crate from \
2900                 [crates.io](https://crates.io) via [`Cargo.toml`]\
2901                 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2902             } else {
2903                 unstable_reason
2904             };
2905
2906             let mut ids = cx.id_map.borrow_mut();
2907             message = format!(
2908                 "<details><summary>{}</summary>{}</details>",
2909                 message,
2910                 MarkdownHtml(&unstable_reason, RefCell::new(&mut ids), error_codes)
2911             );
2912         }
2913
2914         let class = if is_rustc_private {
2915             "internal"
2916         } else {
2917             "unstable"
2918         };
2919         stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2920     }
2921
2922     if let Some(ref cfg) = item.attrs.cfg {
2923         stability.push(format!(
2924             "<div class='stab portability'>{}</div>",
2925             cfg.render_long_html()
2926         ));
2927     }
2928
2929     stability
2930 }
2931
2932 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2933                  c: &clean::Constant) -> fmt::Result {
2934     write!(w, "<pre class='rust const'>")?;
2935     render_attributes(w, it)?;
2936     write!(w, "{vis}const \
2937                {name}: {typ}</pre>",
2938            vis = VisSpace(&it.visibility),
2939            name = it.name.as_ref().unwrap(),
2940            typ = c.type_)?;
2941     document(w, cx, it)
2942 }
2943
2944 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2945                s: &clean::Static) -> fmt::Result {
2946     write!(w, "<pre class='rust static'>")?;
2947     render_attributes(w, it)?;
2948     write!(w, "{vis}static {mutability}\
2949                {name}: {typ}</pre>",
2950            vis = VisSpace(&it.visibility),
2951            mutability = MutableSpace(s.mutability),
2952            name = it.name.as_ref().unwrap(),
2953            typ = s.type_)?;
2954     document(w, cx, it)
2955 }
2956
2957 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2958                  f: &clean::Function) -> fmt::Result {
2959     let name_len = format!("{}{}{}{}{:#}fn {}{:#}",
2960                            VisSpace(&it.visibility),
2961                            ConstnessSpace(f.header.constness),
2962                            UnsafetySpace(f.header.unsafety),
2963                            AsyncSpace(f.header.asyncness),
2964                            AbiSpace(f.header.abi),
2965                            it.name.as_ref().unwrap(),
2966                            f.generics).len();
2967     write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2968     render_attributes(w, it)?;
2969     write!(w,
2970            "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2971            {name}{generics}{decl}{where_clause}</pre>",
2972            vis = VisSpace(&it.visibility),
2973            constness = ConstnessSpace(f.header.constness),
2974            unsafety = UnsafetySpace(f.header.unsafety),
2975            asyncness = AsyncSpace(f.header.asyncness),
2976            abi = AbiSpace(f.header.abi),
2977            name = it.name.as_ref().unwrap(),
2978            generics = f.generics,
2979            where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2980            decl = Method {
2981               decl: &f.decl,
2982               name_len,
2983               indent: 0,
2984            })?;
2985     document(w, cx, it)
2986 }
2987
2988 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2989                       implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
2990     // If there's already another implementor that has the same abbridged name, use the
2991     // full path, for example in `std::iter::ExactSizeIterator`
2992     let use_absolute = match implementor.inner_impl().for_ {
2993         clean::ResolvedPath { ref path, is_generic: false, .. } |
2994         clean::BorrowedRef {
2995             type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2996             ..
2997         } => implementor_dups[path.last_name()].1,
2998         _ => false,
2999     };
3000     render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
3001                 implementor.impl_item.stable_since(), false, Some(use_absolute))?;
3002     Ok(())
3003 }
3004
3005 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
3006                 traits: &[&&Impl],
3007                 containing_item: &clean::Item) -> fmt::Result {
3008     for i in traits {
3009         let did = i.trait_did().unwrap();
3010         let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3011         render_impl(w, cx, i, assoc_link,
3012                     RenderMode::Normal, containing_item.stable_since(), true, None)?;
3013     }
3014     Ok(())
3015 }
3016
3017 fn bounds(t_bounds: &[clean::GenericBound]) -> String {
3018     let mut bounds = String::new();
3019     let mut bounds_plain = String::new();
3020     if !t_bounds.is_empty() {
3021         if !bounds.is_empty() {
3022             bounds.push(' ');
3023             bounds_plain.push(' ');
3024         }
3025         bounds.push_str(": ");
3026         bounds_plain.push_str(": ");
3027         for (i, p) in t_bounds.iter().enumerate() {
3028             if i > 0 {
3029                 bounds.push_str(" + ");
3030                 bounds_plain.push_str(" + ");
3031             }
3032             bounds.push_str(&(*p).to_string());
3033             bounds_plain.push_str(&format!("{:#}", *p));
3034         }
3035     }
3036     bounds
3037 }
3038
3039 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
3040     let lhs = format!("{}", lhs.inner_impl());
3041     let rhs = format!("{}", rhs.inner_impl());
3042
3043     // lhs and rhs are formatted as HTML, which may be unnecessary
3044     name_key(&lhs).cmp(&name_key(&rhs))
3045 }
3046
3047 fn item_trait(
3048     w: &mut fmt::Formatter,
3049     cx: &Context,
3050     it: &clean::Item,
3051     t: &clean::Trait,
3052 ) -> fmt::Result {
3053     let bounds = bounds(&t.bounds);
3054     let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
3055     let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
3056     let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
3057     let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
3058
3059     // Output the trait definition
3060     wrap_into_docblock(w, |w| {
3061         write!(w, "<pre class='rust trait'>")?;
3062         render_attributes(w, it)?;
3063         write!(w, "{}{}{}trait {}{}{}",
3064                VisSpace(&it.visibility),
3065                UnsafetySpace(t.unsafety),
3066                if t.is_auto { "auto " } else { "" },
3067                it.name.as_ref().unwrap(),
3068                t.generics,
3069                bounds)?;
3070
3071         if !t.generics.where_predicates.is_empty() {
3072             write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
3073         } else {
3074             write!(w, " ")?;
3075         }
3076
3077         if t.items.is_empty() {
3078             write!(w, "{{ }}")?;
3079         } else {
3080             // FIXME: we should be using a derived_id for the Anchors here
3081             write!(w, "{{\n")?;
3082             for t in &types {
3083                 write!(w, "    ")?;
3084                 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3085                 write!(w, ";\n")?;
3086             }
3087             if !types.is_empty() && !consts.is_empty() {
3088                 w.write_str("\n")?;
3089             }
3090             for t in &consts {
3091                 write!(w, "    ")?;
3092                 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3093                 write!(w, ";\n")?;
3094             }
3095             if !consts.is_empty() && !required.is_empty() {
3096                 w.write_str("\n")?;
3097             }
3098             for (pos, m) in required.iter().enumerate() {
3099                 write!(w, "    ")?;
3100                 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3101                 write!(w, ";\n")?;
3102
3103                 if pos < required.len() - 1 {
3104                    write!(w, "<div class='item-spacer'></div>")?;
3105                 }
3106             }
3107             if !required.is_empty() && !provided.is_empty() {
3108                 w.write_str("\n")?;
3109             }
3110             for (pos, m) in provided.iter().enumerate() {
3111                 write!(w, "    ")?;
3112                 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3113                 match m.inner {
3114                     clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
3115                         write!(w, ",\n    {{ ... }}\n")?;
3116                     },
3117                     _ => {
3118                         write!(w, " {{ ... }}\n")?;
3119                     },
3120                 }
3121                 if pos < provided.len() - 1 {
3122                    write!(w, "<div class='item-spacer'></div>")?;
3123                 }
3124             }
3125             write!(w, "}}")?;
3126         }
3127         write!(w, "</pre>")
3128     })?;
3129
3130     // Trait documentation
3131     document(w, cx, it)?;
3132
3133     fn write_small_section_header(
3134         w: &mut fmt::Formatter,
3135         id: &str,
3136         title: &str,
3137         extra_content: &str,
3138     ) -> fmt::Result {
3139         write!(w, "
3140             <h2 id='{0}' class='small-section-header'>\
3141               {1}<a href='#{0}' class='anchor'></a>\
3142             </h2>{2}", id, title, extra_content)
3143     }
3144
3145     fn write_loading_content(w: &mut fmt::Formatter, extra_content: &str) -> fmt::Result {
3146         write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
3147     }
3148
3149     fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
3150                   -> fmt::Result {
3151         let name = m.name.as_ref().unwrap();
3152         let item_type = m.type_();
3153         let id = cx.derive_id(format!("{}.{}", item_type, name));
3154         let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3155         write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
3156                extra = render_spotlight_traits(m)?,
3157                id = id,
3158                ns_id = ns_id)?;
3159         render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
3160         write!(w, "</code>")?;
3161         render_stability_since(w, m, t)?;
3162         write!(w, "</h3>")?;
3163         document(w, cx, m)?;
3164         Ok(())
3165     }
3166
3167     if !types.is_empty() {
3168         write_small_section_header(w, "associated-types", "Associated Types",
3169                                    "<div class='methods'>")?;
3170         for t in &types {
3171             trait_item(w, cx, *t, it)?;
3172         }
3173         write_loading_content(w, "</div>")?;
3174     }
3175
3176     if !consts.is_empty() {
3177         write_small_section_header(w, "associated-const", "Associated Constants",
3178                                    "<div class='methods'>")?;
3179         for t in &consts {
3180             trait_item(w, cx, *t, it)?;
3181         }
3182         write_loading_content(w, "</div>")?;
3183     }
3184
3185     // Output the documentation for each function individually
3186     if !required.is_empty() {
3187         write_small_section_header(w, "required-methods", "Required methods",
3188                                    "<div class='methods'>")?;
3189         for m in &required {
3190             trait_item(w, cx, *m, it)?;
3191         }
3192         write_loading_content(w, "</div>")?;
3193     }
3194     if !provided.is_empty() {
3195         write_small_section_header(w, "provided-methods", "Provided methods",
3196                                    "<div class='methods'>")?;
3197         for m in &provided {
3198             trait_item(w, cx, *m, it)?;
3199         }
3200         write_loading_content(w, "</div>")?;
3201     }
3202
3203     // If there are methods directly on this trait object, render them here.
3204     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3205
3206     let cache = cache();
3207
3208     let mut synthetic_types = Vec::new();
3209
3210     if let Some(implementors) = cache.implementors.get(&it.def_id) {
3211         // The DefId is for the first Type found with that name. The bool is
3212         // if any Types with the same name but different DefId have been found.
3213         let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
3214         for implementor in implementors {
3215             match implementor.inner_impl().for_ {
3216                 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
3217                 clean::BorrowedRef {
3218                     type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
3219                     ..
3220                 } => {
3221                     let &mut (prev_did, ref mut has_duplicates) =
3222                         implementor_dups.entry(path.last_name()).or_insert((did, false));
3223                     if prev_did != did {
3224                         *has_duplicates = true;
3225                     }
3226                 }
3227                 _ => {}
3228             }
3229         }
3230
3231         let (local, foreign) = implementors.iter()
3232             .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
3233                                          .map_or(true, |d| cache.paths.contains_key(&d)));
3234
3235
3236         let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
3237             .partition(|i| i.inner_impl().synthetic);
3238
3239         synthetic.sort_by(compare_impl);
3240         concrete.sort_by(compare_impl);
3241
3242         if !foreign.is_empty() {
3243             write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
3244
3245             for implementor in foreign {
3246                 let assoc_link = AssocItemLink::GotoSource(
3247                     implementor.impl_item.def_id,
3248                     &implementor.inner_impl().provided_trait_methods
3249                 );
3250                 render_impl(w, cx, &implementor, assoc_link,
3251                             RenderMode::Normal, implementor.impl_item.stable_since(), false,
3252                             None)?;
3253             }
3254             write_loading_content(w, "")?;
3255         }
3256
3257         write_small_section_header(w, "implementors", "Implementors",
3258                                    "<div class='item-list' id='implementors-list'>")?;
3259         for implementor in concrete {
3260             render_implementor(cx, implementor, w, &implementor_dups)?;
3261         }
3262         write_loading_content(w, "</div>")?;
3263
3264         if t.auto {
3265             write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3266                                        "<div class='item-list' id='synthetic-implementors-list'>")?;
3267             for implementor in synthetic {
3268                 synthetic_types.extend(
3269                     collect_paths_for_type(implementor.inner_impl().for_.clone())
3270                 );
3271                 render_implementor(cx, implementor, w, &implementor_dups)?;
3272             }
3273             write_loading_content(w, "</div>")?;
3274         }
3275     } else {
3276         // even without any implementations to write in, we still want the heading and list, so the
3277         // implementors javascript file pulled in below has somewhere to write the impls into
3278         write_small_section_header(w, "implementors", "Implementors",
3279                                    "<div class='item-list' id='implementors-list'>")?;
3280         write_loading_content(w, "</div>")?;
3281
3282         if t.auto {
3283             write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3284                                        "<div class='item-list' id='synthetic-implementors-list'>")?;
3285             write_loading_content(w, "</div>")?;
3286         }
3287     }
3288     write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
3289            as_json(&synthetic_types))?;
3290
3291     write!(w, r#"<script type="text/javascript" async
3292                          src="{root_path}/implementors/{path}/{ty}.{name}.js">
3293                  </script>"#,
3294            root_path = vec![".."; cx.current.len()].join("/"),
3295            path = if it.def_id.is_local() {
3296                cx.current.join("/")
3297            } else {
3298                let (ref path, _) = cache.external_paths[&it.def_id];
3299                path[..path.len() - 1].join("/")
3300            },
3301            ty = it.type_().css_class(),
3302            name = *it.name.as_ref().unwrap())?;
3303     Ok(())
3304 }
3305
3306 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
3307     use html::item_type::ItemType::*;
3308
3309     let name = it.name.as_ref().unwrap();
3310     let ty = match it.type_() {
3311         Typedef | AssociatedType => AssociatedType,
3312         s@_ => s,
3313     };
3314
3315     let anchor = format!("#{}.{}", ty, name);
3316     match link {
3317         AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3318         AssocItemLink::Anchor(None) => anchor,
3319         AssocItemLink::GotoSource(did, _) => {
3320             href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
3321         }
3322     }
3323 }
3324
3325 fn assoc_const(w: &mut fmt::Formatter,
3326                it: &clean::Item,
3327                ty: &clean::Type,
3328                _default: Option<&String>,
3329                link: AssocItemLink) -> fmt::Result {
3330     write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
3331            VisSpace(&it.visibility),
3332            naive_assoc_href(it, link),
3333            it.name.as_ref().unwrap(),
3334            ty)?;
3335     Ok(())
3336 }
3337
3338 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3339                              bounds: &[clean::GenericBound],
3340                              default: Option<&clean::Type>,
3341                              link: AssocItemLink) -> fmt::Result {
3342     write!(w, "type <a href='{}' class=\"type\">{}</a>",
3343            naive_assoc_href(it, link),
3344            it.name.as_ref().unwrap())?;
3345     if !bounds.is_empty() {
3346         write!(w, ": {}", GenericBounds(bounds))?
3347     }
3348     if let Some(default) = default {
3349         write!(w, " = {}", default)?;
3350     }
3351     Ok(())
3352 }
3353
3354 fn render_stability_since_raw<'a, T: fmt::Write>(
3355     w: &mut T,
3356     ver: Option<&'a str>,
3357     containing_ver: Option<&'a str>,
3358 ) -> fmt::Result {
3359     if let Some(v) = ver {
3360         if containing_ver != ver && v.len() > 0 {
3361             write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>", v)?
3362         }
3363     }
3364     Ok(())
3365 }
3366
3367 fn render_stability_since(w: &mut fmt::Formatter,
3368                           item: &clean::Item,
3369                           containing_item: &clean::Item) -> fmt::Result {
3370     render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3371 }
3372
3373 fn render_assoc_item(w: &mut fmt::Formatter,
3374                      item: &clean::Item,
3375                      link: AssocItemLink,
3376                      parent: ItemType) -> fmt::Result {
3377     fn method(w: &mut fmt::Formatter,
3378               meth: &clean::Item,
3379               header: hir::FnHeader,
3380               g: &clean::Generics,
3381               d: &clean::FnDecl,
3382               link: AssocItemLink,
3383               parent: ItemType)
3384               -> fmt::Result {
3385         let name = meth.name.as_ref().unwrap();
3386         let anchor = format!("#{}.{}", meth.type_(), name);
3387         let href = match link {
3388             AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3389             AssocItemLink::Anchor(None) => anchor,
3390             AssocItemLink::GotoSource(did, provided_methods) => {
3391                 // We're creating a link from an impl-item to the corresponding
3392                 // trait-item and need to map the anchored type accordingly.
3393                 let ty = if provided_methods.contains(name) {
3394                     ItemType::Method
3395                 } else {
3396                     ItemType::TyMethod
3397                 };
3398
3399                 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3400             }
3401         };
3402         let mut head_len = format!("{}{}{}{}{:#}fn {}{:#}",
3403                                    VisSpace(&meth.visibility),
3404                                    ConstnessSpace(header.constness),
3405                                    UnsafetySpace(header.unsafety),
3406                                    AsyncSpace(header.asyncness),
3407                                    AbiSpace(header.abi),
3408                                    name,
3409                                    *g).len();
3410         let (indent, end_newline) = if parent == ItemType::Trait {
3411             head_len += 4;
3412             (4, false)
3413         } else {
3414             (0, true)
3415         };
3416         render_attributes(w, meth)?;
3417         write!(w, "{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3418                    {generics}{decl}{where_clause}",
3419                VisSpace(&meth.visibility),
3420                ConstnessSpace(header.constness),
3421                UnsafetySpace(header.unsafety),
3422                AsyncSpace(header.asyncness),
3423                AbiSpace(header.abi),
3424                href = href,
3425                name = name,
3426                generics = *g,
3427                decl = Method {
3428                    decl: d,
3429                    name_len: head_len,
3430                    indent,
3431                },
3432                where_clause = WhereClause {
3433                    gens: g,
3434                    indent,
3435                    end_newline,
3436                })
3437     }
3438     match item.inner {
3439         clean::StrippedItem(..) => Ok(()),
3440         clean::TyMethodItem(ref m) => {
3441             method(w, item, m.header, &m.generics, &m.decl, link, parent)
3442         }
3443         clean::MethodItem(ref m) => {
3444             method(w, item, m.header, &m.generics, &m.decl, link, parent)
3445         }
3446         clean::AssociatedConstItem(ref ty, ref default) => {
3447             assoc_const(w, item, ty, default.as_ref(), link)
3448         }
3449         clean::AssociatedTypeItem(ref bounds, ref default) => {
3450             assoc_type(w, item, bounds, default.as_ref(), link)
3451         }
3452         _ => panic!("render_assoc_item called on non-associated-item")
3453     }
3454 }
3455
3456 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3457                s: &clean::Struct) -> fmt::Result {
3458     wrap_into_docblock(w, |w| {
3459         write!(w, "<pre class='rust struct'>")?;
3460         render_attributes(w, it)?;
3461         render_struct(w,
3462                       it,
3463                       Some(&s.generics),
3464                       s.struct_type,
3465                       &s.fields,
3466                       "",
3467                       true)?;
3468         write!(w, "</pre>")
3469     })?;
3470
3471     document(w, cx, it)?;
3472     let mut fields = s.fields.iter().filter_map(|f| {
3473         match f.inner {
3474             clean::StructFieldItem(ref ty) => Some((f, ty)),
3475             _ => None,
3476         }
3477     }).peekable();
3478     if let doctree::Plain = s.struct_type {
3479         if fields.peek().is_some() {
3480             write!(w, "<h2 id='fields' class='fields small-section-header'>
3481                        Fields{}<a href='#fields' class='anchor'></a></h2>",
3482                        document_non_exhaustive_header(it))?;
3483             document_non_exhaustive(w, it)?;
3484             for (field, ty) in fields {
3485                 let id = cx.derive_id(format!("{}.{}",
3486                                            ItemType::StructField,
3487                                            field.name.as_ref().unwrap()));
3488                 let ns_id = cx.derive_id(format!("{}.{}",
3489                                               field.name.as_ref().unwrap(),
3490                                               ItemType::StructField.name_space()));
3491                 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3492                            <a href=\"#{id}\" class=\"anchor field\"></a>\
3493                            <code id=\"{ns_id}\">{name}: {ty}</code>\
3494                            </span>",
3495                        item_type = ItemType::StructField,
3496                        id = id,
3497                        ns_id = ns_id,
3498                        name = field.name.as_ref().unwrap(),
3499                        ty = ty)?;
3500                 document(w, cx, field)?;
3501             }
3502         }
3503     }
3504     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3505 }
3506
3507 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3508                s: &clean::Union) -> fmt::Result {
3509     wrap_into_docblock(w, |w| {
3510         write!(w, "<pre class='rust union'>")?;
3511         render_attributes(w, it)?;
3512         render_union(w,
3513                      it,
3514                      Some(&s.generics),
3515                      &s.fields,
3516                      "",
3517                      true)?;
3518         write!(w, "</pre>")
3519     })?;
3520
3521     document(w, cx, it)?;
3522     let mut fields = s.fields.iter().filter_map(|f| {
3523         match f.inner {
3524             clean::StructFieldItem(ref ty) => Some((f, ty)),
3525             _ => None,
3526         }
3527     }).peekable();
3528     if fields.peek().is_some() {
3529         write!(w, "<h2 id='fields' class='fields small-section-header'>
3530                    Fields<a href='#fields' class='anchor'></a></h2>")?;
3531         for (field, ty) in fields {
3532             let name = field.name.as_ref().expect("union field name");
3533             let id = format!("{}.{}", ItemType::StructField, name);
3534             write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3535                            <a href=\"#{id}\" class=\"anchor field\"></a>\
3536                            <code>{name}: {ty}</code>\
3537                        </span>",
3538                    id = id,
3539                    name = name,
3540                    shortty = ItemType::StructField,
3541                    ty = ty)?;
3542             if let Some(stability_class) = field.stability_class() {
3543                 write!(w, "<span class='stab {stab}'></span>",
3544                     stab = stability_class)?;
3545             }
3546             document(w, cx, field)?;
3547         }
3548     }
3549     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3550 }
3551
3552 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3553              e: &clean::Enum) -> fmt::Result {
3554     wrap_into_docblock(w, |w| {
3555         write!(w, "<pre class='rust enum'>")?;
3556         render_attributes(w, it)?;
3557         write!(w, "{}enum {}{}{}",
3558                VisSpace(&it.visibility),
3559                it.name.as_ref().unwrap(),
3560                e.generics,
3561                WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3562         if e.variants.is_empty() && !e.variants_stripped {
3563             write!(w, " {{}}")?;
3564         } else {
3565             write!(w, " {{\n")?;
3566             for v in &e.variants {
3567                 write!(w, "    ")?;
3568                 let name = v.name.as_ref().unwrap();
3569                 match v.inner {
3570                     clean::VariantItem(ref var) => {
3571                         match var.kind {
3572                             clean::VariantKind::CLike => write!(w, "{}", name)?,
3573                             clean::VariantKind::Tuple(ref tys) => {
3574                                 write!(w, "{}(", name)?;
3575                                 for (i, ty) in tys.iter().enumerate() {
3576                                     if i > 0 {
3577                                         write!(w, ",&nbsp;")?
3578                                     }
3579                                     write!(w, "{}", *ty)?;
3580                                 }
3581                                 write!(w, ")")?;
3582                             }
3583                             clean::VariantKind::Struct(ref s) => {
3584                                 render_struct(w,
3585                                               v,
3586                                               None,
3587                                               s.struct_type,
3588                                               &s.fields,
3589                                               "    ",
3590                                               false)?;
3591                             }
3592                         }
3593                     }
3594                     _ => unreachable!()
3595                 }
3596                 write!(w, ",\n")?;
3597             }
3598
3599             if e.variants_stripped {
3600                 write!(w, "    // some variants omitted\n")?;
3601             }
3602             write!(w, "}}")?;
3603         }
3604         write!(w, "</pre>")
3605     })?;
3606
3607     document(w, cx, it)?;
3608     if !e.variants.is_empty() {
3609         write!(w, "<h2 id='variants' class='variants small-section-header'>
3610                    Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3611                    document_non_exhaustive_header(it))?;
3612         document_non_exhaustive(w, it)?;
3613         for variant in &e.variants {
3614             let id = cx.derive_id(format!("{}.{}",
3615                                        ItemType::Variant,
3616                                        variant.name.as_ref().unwrap()));
3617             let ns_id = cx.derive_id(format!("{}.{}",
3618                                           variant.name.as_ref().unwrap(),
3619                                           ItemType::Variant.name_space()));
3620             write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3621                        <a href=\"#{id}\" class=\"anchor field\"></a>\
3622                        <code id='{ns_id}'>{name}",
3623                    id = id,
3624                    ns_id = ns_id,
3625                    name = variant.name.as_ref().unwrap())?;
3626             if let clean::VariantItem(ref var) = variant.inner {
3627                 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3628                     write!(w, "(")?;
3629                     for (i, ty) in tys.iter().enumerate() {
3630                         if i > 0 {
3631                             write!(w, ",&nbsp;")?;
3632                         }
3633                         write!(w, "{}", *ty)?;
3634                     }
3635                     write!(w, ")")?;
3636                 }
3637             }
3638             write!(w, "</code></span>")?;
3639             document(w, cx, variant)?;
3640
3641             use clean::{Variant, VariantKind};
3642             if let clean::VariantItem(Variant {
3643                 kind: VariantKind::Struct(ref s)
3644             }) = variant.inner {
3645                 let variant_id = cx.derive_id(format!("{}.{}.fields",
3646                                                    ItemType::Variant,
3647                                                    variant.name.as_ref().unwrap()));
3648                 write!(w, "<span class='autohide sub-variant' id='{id}'>",
3649                        id = variant_id)?;
3650                 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
3651                        name = variant.name.as_ref().unwrap())?;
3652                 for field in &s.fields {
3653                     use clean::StructFieldItem;
3654                     if let StructFieldItem(ref ty) = field.inner {
3655                         let id = cx.derive_id(format!("variant.{}.field.{}",
3656                                                    variant.name.as_ref().unwrap(),
3657                                                    field.name.as_ref().unwrap()));
3658                         let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3659                                                       variant.name.as_ref().unwrap(),
3660                                                       ItemType::Variant.name_space(),
3661                                                       field.name.as_ref().unwrap(),
3662                                                       ItemType::StructField.name_space()));
3663                         write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3664                                    <a href=\"#{id}\" class=\"anchor field\"></a>\
3665                                    <code id='{ns_id}'>{f}:&nbsp;{t}\
3666                                    </code></span>",
3667                                id = id,
3668                                ns_id = ns_id,
3669                                f = field.name.as_ref().unwrap(),
3670                                t = *ty)?;
3671                         document(w, cx, field)?;
3672                     }
3673                 }
3674                 write!(w, "</div></span>")?;
3675             }
3676             render_stability_since(w, variant, it)?;
3677         }
3678     }
3679     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3680     Ok(())
3681 }
3682
3683 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3684     let name = attr.name();
3685
3686     if attr.is_word() {
3687         Some(name.to_string())
3688     } else if let Some(v) = attr.value_str() {
3689         Some(format!("{} = {:?}", name, v.as_str()))
3690     } else if let Some(values) = attr.meta_item_list() {
3691         let display: Vec<_> = values.iter().filter_map(|attr| {
3692             attr.meta_item().and_then(|mi| render_attribute(mi))
3693         }).collect();
3694
3695         if display.len() > 0 {
3696             Some(format!("{}({})", name, display.join(", ")))
3697         } else {
3698             None
3699         }
3700     } else {
3701         None
3702     }
3703 }
3704
3705 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3706     "export_name",
3707     "lang",
3708     "link_section",
3709     "must_use",
3710     "no_mangle",
3711     "repr",
3712     "unsafe_destructor_blind_to_params",
3713     "non_exhaustive"
3714 ];
3715
3716 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3717     let mut attrs = String::new();
3718
3719     for attr in &it.attrs.other_attrs {
3720         let name = attr.name();
3721         if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3722             continue;
3723         }
3724         if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3725             attrs.push_str(&format!("#[{}]\n", s));
3726         }
3727     }
3728     if attrs.len() > 0 {
3729         write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3730     }
3731     Ok(())
3732 }
3733
3734 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3735                  g: Option<&clean::Generics>,
3736                  ty: doctree::StructType,
3737                  fields: &[clean::Item],
3738                  tab: &str,
3739                  structhead: bool) -> fmt::Result {
3740     write!(w, "{}{}{}",
3741            VisSpace(&it.visibility),
3742            if structhead {"struct "} else {""},
3743            it.name.as_ref().unwrap())?;
3744     if let Some(g) = g {
3745         write!(w, "{}", g)?
3746     }
3747     match ty {
3748         doctree::Plain => {
3749             if let Some(g) = g {
3750                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3751             }
3752             let mut has_visible_fields = false;
3753             write!(w, " {{")?;
3754             for field in fields {
3755                 if let clean::StructFieldItem(ref ty) = field.inner {
3756                     write!(w, "\n{}    {}{}: {},",
3757                            tab,
3758                            VisSpace(&field.visibility),
3759                            field.name.as_ref().unwrap(),
3760                            *ty)?;
3761                     has_visible_fields = true;
3762                 }
3763             }
3764
3765             if has_visible_fields {
3766                 if it.has_stripped_fields().unwrap() {
3767                     write!(w, "\n{}    // some fields omitted", tab)?;
3768                 }
3769                 write!(w, "\n{}", tab)?;
3770             } else if it.has_stripped_fields().unwrap() {
3771                 // If there are no visible fields we can just display
3772                 // `{ /* fields omitted */ }` to save space.
3773                 write!(w, " /* fields omitted */ ")?;
3774             }
3775             write!(w, "}}")?;
3776         }
3777         doctree::Tuple => {
3778             write!(w, "(")?;
3779             for (i, field) in fields.iter().enumerate() {
3780                 if i > 0 {
3781                     write!(w, ", ")?;
3782                 }
3783                 match field.inner {
3784                     clean::StrippedItem(box clean::StructFieldItem(..)) => {
3785                         write!(w, "_")?
3786                     }
3787                     clean::StructFieldItem(ref ty) => {
3788                         write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3789                     }
3790                     _ => unreachable!()
3791                 }
3792             }
3793             write!(w, ")")?;
3794             if let Some(g) = g {
3795                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3796             }
3797             write!(w, ";")?;
3798         }
3799         doctree::Unit => {
3800             // Needed for PhantomData.
3801             if let Some(g) = g {
3802                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3803             }
3804             write!(w, ";")?;
3805         }
3806     }
3807     Ok(())
3808 }
3809
3810 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3811                 g: Option<&clean::Generics>,
3812                 fields: &[clean::Item],
3813                 tab: &str,
3814                 structhead: bool) -> fmt::Result {
3815     write!(w, "{}{}{}",
3816            VisSpace(&it.visibility),
3817            if structhead {"union "} else {""},
3818            it.name.as_ref().unwrap())?;
3819     if let Some(g) = g {
3820         write!(w, "{}", g)?;
3821         write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3822     }
3823
3824     write!(w, " {{\n{}", tab)?;
3825     for field in fields {
3826         if let clean::StructFieldItem(ref ty) = field.inner {
3827             write!(w, "    {}{}: {},\n{}",
3828                    VisSpace(&field.visibility),
3829                    field.name.as_ref().unwrap(),
3830                    *ty,
3831                    tab)?;
3832         }
3833     }
3834
3835     if it.has_stripped_fields().unwrap() {
3836         write!(w, "    // some fields omitted\n{}", tab)?;
3837     }
3838     write!(w, "}}")?;
3839     Ok(())
3840 }
3841
3842 #[derive(Copy, Clone)]
3843 enum AssocItemLink<'a> {
3844     Anchor(Option<&'a str>),
3845     GotoSource(DefId, &'a FxHashSet<String>),
3846 }
3847
3848 impl<'a> AssocItemLink<'a> {
3849     fn anchor(&self, id: &'a String) -> Self {
3850         match *self {
3851             AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3852             ref other => *other,
3853         }
3854     }
3855 }
3856
3857 enum AssocItemRender<'a> {
3858     All,
3859     DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3860 }
3861
3862 #[derive(Copy, Clone, PartialEq)]
3863 enum RenderMode {
3864     Normal,
3865     ForDeref { mut_: bool },
3866 }
3867
3868 fn render_assoc_items(w: &mut fmt::Formatter,
3869                       cx: &Context,
3870                       containing_item: &clean::Item,
3871                       it: DefId,
3872                       what: AssocItemRender) -> fmt::Result {
3873     let c = cache();
3874     let v = match c.impls.get(&it) {
3875         Some(v) => v,
3876         None => return Ok(()),
3877     };
3878     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3879         i.inner_impl().trait_.is_none()
3880     });
3881     if !non_trait.is_empty() {
3882         let render_mode = match what {
3883             AssocItemRender::All => {
3884                 write!(w, "\
3885                     <h2 id='methods' class='small-section-header'>\
3886                       Methods<a href='#methods' class='anchor'></a>\
3887                     </h2>\
3888                 ")?;
3889                 RenderMode::Normal
3890             }
3891             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3892                 write!(w, "\
3893                     <h2 id='deref-methods' class='small-section-header'>\
3894                       Methods from {}&lt;Target = {}&gt;\
3895                       <a href='#deref-methods' class='anchor'></a>\
3896                     </h2>\
3897                 ", trait_, type_)?;
3898                 RenderMode::ForDeref { mut_: deref_mut_ }
3899             }
3900         };
3901         for i in &non_trait {
3902             render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3903                         containing_item.stable_since(), true, None)?;
3904         }
3905     }
3906     if let AssocItemRender::DerefFor { .. } = what {
3907         return Ok(());
3908     }
3909     if !traits.is_empty() {
3910         let deref_impl = traits.iter().find(|t| {
3911             t.inner_impl().trait_.def_id() == c.deref_trait_did
3912         });
3913         if let Some(impl_) = deref_impl {
3914             let has_deref_mut = traits.iter().find(|t| {
3915                 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3916             }).is_some();
3917             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3918         }
3919
3920         let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3921             .iter()
3922             .partition(|t| t.inner_impl().synthetic);
3923         let (blanket_impl, concrete) = concrete
3924             .into_iter()
3925             .partition(|t| t.inner_impl().blanket_impl.is_some());
3926
3927         struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3928
3929         impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3930             fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3931                 render_impls(self.0, fmt, &self.1, self.2)
3932             }
3933         }
3934
3935         let impls = RendererStruct(cx, concrete, containing_item).to_string();
3936         if !impls.is_empty() {
3937             write!(w, "\
3938                 <h2 id='implementations' class='small-section-header'>\
3939                   Trait Implementations<a href='#implementations' class='anchor'></a>\
3940                 </h2>\
3941                 <div id='implementations-list'>{}</div>", impls)?;
3942         }
3943
3944         if !synthetic.is_empty() {
3945             write!(w, "\
3946                 <h2 id='synthetic-implementations' class='small-section-header'>\
3947                   Auto Trait Implementations\
3948                   <a href='#synthetic-implementations' class='anchor'></a>\
3949                 </h2>\
3950                 <div id='synthetic-implementations-list'>\
3951             ")?;
3952             render_impls(cx, w, &synthetic, containing_item)?;
3953             write!(w, "</div>")?;
3954         }
3955
3956         if !blanket_impl.is_empty() {
3957             write!(w, "\
3958                 <h2 id='blanket-implementations' class='small-section-header'>\
3959                   Blanket Implementations\
3960                   <a href='#blanket-implementations' class='anchor'></a>\
3961                 </h2>\
3962                 <div id='blanket-implementations-list'>\
3963             ")?;
3964             render_impls(cx, w, &blanket_impl, containing_item)?;
3965             write!(w, "</div>")?;
3966         }
3967     }
3968     Ok(())
3969 }
3970
3971 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3972                         container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3973     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3974     let target = impl_.inner_impl().items.iter().filter_map(|item| {
3975         match item.inner {
3976             clean::TypedefItem(ref t, true) => Some(&t.type_),
3977             _ => None,
3978         }
3979     }).next().expect("Expected associated type binding");
3980     let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3981                                            deref_mut_: deref_mut };
3982     if let Some(did) = target.def_id() {
3983         render_assoc_items(w, cx, container_item, did, what)
3984     } else {
3985         if let Some(prim) = target.primitive_type() {
3986             if let Some(&did) = cache().primitive_locations.get(&prim) {
3987                 render_assoc_items(w, cx, container_item, did, what)?;
3988             }
3989         }
3990         Ok(())
3991     }
3992 }
3993
3994 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3995     let self_type_opt = match item.inner {
3996         clean::MethodItem(ref method) => method.decl.self_type(),
3997         clean::TyMethodItem(ref method) => method.decl.self_type(),
3998         _ => None
3999     };
4000
4001     if let Some(self_ty) = self_type_opt {
4002         let (by_mut_ref, by_box, by_value) = match self_ty {
4003             SelfTy::SelfBorrowed(_, mutability) |
4004             SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
4005                 (mutability == Mutability::Mutable, false, false)
4006             },
4007             SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
4008                 (false, Some(did) == cache().owned_box_did, false)
4009             },
4010             SelfTy::SelfValue => (false, false, true),
4011             _ => (false, false, false),
4012         };
4013
4014         (deref_mut_ || !by_mut_ref) && !by_box && !by_value
4015     } else {
4016         false
4017     }
4018 }
4019
4020 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
4021     let mut out = String::new();
4022
4023     match item.inner {
4024         clean::FunctionItem(clean::Function { ref decl, .. }) |
4025         clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
4026         clean::MethodItem(clean::Method { ref decl, .. }) |
4027         clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
4028             out = spotlight_decl(decl)?;
4029         }
4030         _ => {}
4031     }
4032
4033     Ok(out)
4034 }
4035
4036 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
4037     let mut out = String::new();
4038     let mut trait_ = String::new();
4039
4040     if let Some(did) = decl.output.def_id() {
4041         let c = cache();
4042         if let Some(impls) = c.impls.get(&did) {
4043             for i in impls {
4044                 let impl_ = i.inner_impl();
4045                 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
4046                     if out.is_empty() {
4047                         out.push_str(
4048                             &format!("<h3 class=\"important\">Important traits for {}</h3>\
4049                                       <code class=\"content\">",
4050                                      impl_.for_));
4051                         trait_.push_str(&impl_.for_.to_string());
4052                     }
4053
4054                     //use the "where" class here to make it small
4055                     out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
4056                     let t_did = impl_.trait_.def_id().unwrap();
4057                     for it in &impl_.items {
4058                         if let clean::TypedefItem(ref tydef, _) = it.inner {
4059                             out.push_str("<span class=\"where fmt-newline\">    ");
4060                             assoc_type(&mut out, it, &[],
4061                                        Some(&tydef.type_),
4062                                        AssocItemLink::GotoSource(t_did, &FxHashSet::default()))?;
4063                             out.push_str(";</span>");
4064                         }
4065                     }
4066                 }
4067             }
4068         }
4069     }
4070
4071     if !out.is_empty() {
4072         out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
4073                                     <span class='tooltiptext'>Important traits for {}</span></div>\
4074                                     <div class=\"content hidden\">",
4075                                    trait_));
4076         out.push_str("</code></div></div>");
4077     }
4078
4079     Ok(out)
4080 }
4081
4082 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
4083                render_mode: RenderMode, outer_version: Option<&str>,
4084                show_def_docs: bool, use_absolute: Option<bool>) -> fmt::Result {
4085     if render_mode == RenderMode::Normal {
4086         let id = cx.derive_id(match i.inner_impl().trait_ {
4087             Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
4088             None => "impl".to_string(),
4089         });
4090         if let Some(use_absolute) = use_absolute {
4091             write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id)?;
4092             fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
4093             if show_def_docs {
4094                 for it in &i.inner_impl().items {
4095                     if let clean::TypedefItem(ref tydef, _) = it.inner {
4096                         write!(w, "<span class=\"where fmt-newline\">  ")?;
4097                         assoc_type(w, it, &vec![], Some(&tydef.type_),
4098                                    AssocItemLink::Anchor(None))?;
4099                         write!(w, ";</span>")?;
4100                     }
4101                 }
4102             }
4103             write!(w, "</code>")?;
4104         } else {
4105             write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
4106                 id, i.inner_impl()
4107             )?;
4108         }
4109         write!(w, "<a href='#{}' class='anchor'></a>", id)?;
4110         let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
4111         render_stability_since_raw(w, since, outer_version)?;
4112         if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
4113             write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4114                    l, "goto source code")?;
4115         }
4116         write!(w, "</h3>")?;
4117         if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
4118             let mut ids = cx.id_map.borrow_mut();
4119             write!(w, "<div class='docblock'>{}</div>",
4120                    Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids), cx.codes))?;
4121         }
4122     }
4123
4124     fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
4125                      link: AssocItemLink, render_mode: RenderMode,
4126                      is_default_item: bool, outer_version: Option<&str>,
4127                      trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
4128         let item_type = item.type_();
4129         let name = item.name.as_ref().unwrap();
4130
4131         let render_method_item: bool = match render_mode {
4132             RenderMode::Normal => true,
4133             RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
4134         };
4135
4136         let (is_hidden, extra_class) = if trait_.is_none() ||
4137                                           item.doc_value().is_some() ||
4138                                           item.inner.is_associated() {
4139             (false, "")
4140         } else {
4141             (true, " hidden")
4142         };
4143         match item.inner {
4144             clean::MethodItem(clean::Method { ref decl, .. }) |
4145             clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
4146                 // Only render when the method is not static or we allow static methods
4147                 if render_method_item {
4148                     let id = cx.derive_id(format!("{}.{}", item_type, name));
4149                     let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4150                     write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4151                     write!(w, "{}", spotlight_decl(decl)?)?;
4152                     write!(w, "<code id='{}'>", ns_id)?;
4153                     render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
4154                     write!(w, "</code>")?;
4155                     render_stability_since_raw(w, item.stable_since(), outer_version)?;
4156                     if let Some(l) = (Item { cx, item }).src_href() {
4157                         write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4158                                l, "goto source code")?;
4159                     }
4160                     write!(w, "</h4>")?;
4161                 }
4162             }
4163             clean::TypedefItem(ref tydef, _) => {
4164                 let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, name));
4165                 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4166                 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4167                 write!(w, "<code id='{}'>", ns_id)?;
4168                 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
4169                 write!(w, "</code></h4>")?;
4170             }
4171             clean::AssociatedConstItem(ref ty, ref default) => {
4172                 let id = cx.derive_id(format!("{}.{}", item_type, name));
4173                 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4174                 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4175                 write!(w, "<code id='{}'>", ns_id)?;
4176                 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
4177                 write!(w, "</code>")?;
4178                 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4179                 if let Some(l) = (Item { cx, item }).src_href() {
4180                     write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4181                             l, "goto source code")?;
4182                 }
4183                 write!(w, "</h4>")?;
4184             }
4185             clean::AssociatedTypeItem(ref bounds, ref default) => {
4186                 let id = cx.derive_id(format!("{}.{}", item_type, name));
4187                 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4188                 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4189                 write!(w, "<code id='{}'>", ns_id)?;
4190                 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
4191                 write!(w, "</code></h4>")?;
4192             }
4193             clean::StrippedItem(..) => return Ok(()),
4194             _ => panic!("can't make docs for trait item with name {:?}", item.name)
4195         }
4196
4197         if render_method_item || render_mode == RenderMode::Normal {
4198             if !is_default_item {
4199                 if let Some(t) = trait_ {
4200                     // The trait item may have been stripped so we might not
4201                     // find any documentation or stability for it.
4202                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
4203                         // We need the stability of the item from the trait
4204                         // because impls can't have a stability.
4205                         document_stability(w, cx, it, is_hidden)?;
4206                         if item.doc_value().is_some() {
4207                             document_full(w, item, cx, "", is_hidden)?;
4208                         } else if show_def_docs {
4209                             // In case the item isn't documented,
4210                             // provide short documentation from the trait.
4211                             document_short(w, cx, it, link, "", is_hidden)?;
4212                         }
4213                     }
4214                 } else {
4215                     document_stability(w, cx, item, is_hidden)?;
4216                     if show_def_docs {
4217                         document_full(w, item, cx, "", is_hidden)?;
4218                     }
4219                 }
4220             } else {
4221                 document_stability(w, cx, item, is_hidden)?;
4222                 if show_def_docs {
4223                     document_short(w, cx, item, link, "", is_hidden)?;
4224                 }
4225             }
4226         }
4227         Ok(())
4228     }
4229
4230     let traits = &cache().traits;
4231     let trait_ = i.trait_did().map(|did| &traits[&did]);
4232
4233     write!(w, "<div class='impl-items'>")?;
4234     for trait_item in &i.inner_impl().items {
4235         doc_impl_item(w, cx, trait_item, link, render_mode,
4236                       false, outer_version, trait_, show_def_docs)?;
4237     }
4238
4239     fn render_default_items(w: &mut fmt::Formatter,
4240                             cx: &Context,
4241                             t: &clean::Trait,
4242                             i: &clean::Impl,
4243                             render_mode: RenderMode,
4244                             outer_version: Option<&str>,
4245                             show_def_docs: bool) -> fmt::Result {
4246         for trait_item in &t.items {
4247             let n = trait_item.name.clone();
4248             if i.items.iter().find(|m| m.name == n).is_some() {
4249                 continue;
4250             }
4251             let did = i.trait_.as_ref().unwrap().def_id().unwrap();
4252             let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4253
4254             doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
4255                           outer_version, None, show_def_docs)?;
4256         }
4257         Ok(())
4258     }
4259
4260     // If we've implemented a trait, then also emit documentation for all
4261     // default items which weren't overridden in the implementation block.
4262     if let Some(t) = trait_ {
4263         render_default_items(w, cx, t, &i.inner_impl(),
4264                              render_mode, outer_version, show_def_docs)?;
4265     }
4266     write!(w, "</div>")?;
4267
4268     Ok(())
4269 }
4270
4271 fn item_existential(
4272     w: &mut fmt::Formatter,
4273     cx: &Context,
4274     it: &clean::Item,
4275     t: &clean::Existential,
4276 ) -> fmt::Result {
4277     write!(w, "<pre class='rust existential'>")?;
4278     render_attributes(w, it)?;
4279     write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
4280            it.name.as_ref().unwrap(),
4281            t.generics,
4282            where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4283            bounds = bounds(&t.bounds))?;
4284
4285     document(w, cx, it)?;
4286
4287     // Render any items associated directly to this alias, as otherwise they
4288     // won't be visible anywhere in the docs. It would be nice to also show
4289     // associated items from the aliased type (see discussion in #32077), but
4290     // we need #14072 to make sense of the generics.
4291     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4292 }
4293
4294 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4295                 t: &clean::Typedef) -> fmt::Result {
4296     write!(w, "<pre class='rust typedef'>")?;
4297     render_attributes(w, it)?;
4298     write!(w, "type {}{}{where_clause} = {type_};</pre>",
4299            it.name.as_ref().unwrap(),
4300            t.generics,
4301            where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4302            type_ = t.type_)?;
4303
4304     document(w, cx, it)?;
4305
4306     // Render any items associated directly to this alias, as otherwise they
4307     // won't be visible anywhere in the docs. It would be nice to also show
4308     // associated items from the aliased type (see discussion in #32077), but
4309     // we need #14072 to make sense of the generics.
4310     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4311 }
4312
4313 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
4314     writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
4315     render_attributes(w, it)?;
4316     write!(
4317         w,
4318         "    {}type {};\n}}</pre>",
4319         VisSpace(&it.visibility),
4320         it.name.as_ref().unwrap(),
4321     )?;
4322
4323     document(w, cx, it)?;
4324
4325     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4326 }
4327
4328 impl<'a> fmt::Display for Sidebar<'a> {
4329     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4330         let cx = self.cx;
4331         let it = self.item;
4332         let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4333
4334         if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4335             || it.is_enum() || it.is_mod() || it.is_typedef() {
4336             write!(fmt, "<p class='location'>{}{}</p>",
4337                 match it.inner {
4338                     clean::StructItem(..) => "Struct ",
4339                     clean::TraitItem(..) => "Trait ",
4340                     clean::PrimitiveItem(..) => "Primitive Type ",
4341                     clean::UnionItem(..) => "Union ",
4342                     clean::EnumItem(..) => "Enum ",
4343                     clean::TypedefItem(..) => "Type Definition ",
4344                     clean::ForeignTypeItem => "Foreign Type ",
4345                     clean::ModuleItem(..) => if it.is_crate() {
4346                         "Crate "
4347                     } else {
4348                         "Module "
4349                     },
4350                     _ => "",
4351                 },
4352                 it.name.as_ref().unwrap())?;
4353         }
4354
4355         if it.is_crate() {
4356             if let Some(ref version) = cache().crate_version {
4357                 write!(fmt,
4358                        "<div class='block version'>\
4359                         <p>Version {}</p>\
4360                         </div>",
4361                        version)?;
4362             }
4363         }
4364
4365         write!(fmt, "<div class=\"sidebar-elems\">")?;
4366         if it.is_crate() {
4367             write!(fmt, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4368                    it.name.as_ref().expect("crates always have a name"))?;
4369         }
4370         match it.inner {
4371             clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4372             clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4373             clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4374             clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4375             clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4376             clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4377             clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4378             clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4379             _ => (),
4380         }
4381
4382         // The sidebar is designed to display sibling functions, modules and
4383         // other miscellaneous information. since there are lots of sibling
4384         // items (and that causes quadratic growth in large modules),
4385         // we refactor common parts into a shared JavaScript file per module.
4386         // still, we don't move everything into JS because we want to preserve
4387         // as much HTML as possible in order to allow non-JS-enabled browsers
4388         // to navigate the documentation (though slightly inefficiently).
4389
4390         write!(fmt, "<p class='location'>")?;
4391         for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4392             if i > 0 {
4393                 write!(fmt, "::<wbr>")?;
4394             }
4395             write!(fmt, "<a href='{}index.html'>{}</a>",
4396                    &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4397                    *name)?;
4398         }
4399         write!(fmt, "</p>")?;
4400
4401         // Sidebar refers to the enclosing module, not this module.
4402         let relpath = if it.is_mod() { "../" } else { "" };
4403         write!(fmt,
4404                "<script>window.sidebarCurrent = {{\
4405                    name: '{name}', \
4406                    ty: '{ty}', \
4407                    relpath: '{path}'\
4408                 }};</script>",
4409                name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4410                ty = it.type_().css_class(),
4411                path = relpath)?;
4412         if parentlen == 0 {
4413             // There is no sidebar-items.js beyond the crate root path
4414             // FIXME maybe dynamic crate loading can be merged here
4415         } else {
4416             write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4417                    path = relpath)?;
4418         }
4419         // Closes sidebar-elems div.
4420         write!(fmt, "</div>")?;
4421
4422         Ok(())
4423     }
4424 }
4425
4426 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4427     if used_links.insert(url.clone()) {
4428         return url;
4429     }
4430     let mut add = 1;
4431     while used_links.insert(format!("{}-{}", url, add)) == false {
4432         add += 1;
4433     }
4434     format!("{}-{}", url, add)
4435 }
4436
4437 fn get_methods(
4438     i: &clean::Impl,
4439     for_deref: bool,
4440     used_links: &mut FxHashSet<String>,
4441 ) -> Vec<String> {
4442     i.items.iter().filter_map(|item| {
4443         match item.name {
4444             // Maybe check with clean::Visibility::Public as well?
4445             Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4446                 if !for_deref || should_render_item(item, false) {
4447                     Some(format!("<a href=\"#{}\">{}</a>",
4448                                  get_next_url(used_links, format!("method.{}", name)),
4449                                  name))
4450                 } else {
4451                     None
4452                 }
4453             }
4454             _ => None,
4455         }
4456     }).collect::<Vec<_>>()
4457 }
4458
4459 // The point is to url encode any potential character from a type with genericity.
4460 fn small_url_encode(s: &str) -> String {
4461     s.replace("<", "%3C")
4462      .replace(">", "%3E")
4463      .replace(" ", "%20")
4464      .replace("?", "%3F")
4465      .replace("'", "%27")
4466      .replace("&", "%26")
4467      .replace(",", "%2C")
4468      .replace(":", "%3A")
4469      .replace(";", "%3B")
4470      .replace("[", "%5B")
4471      .replace("]", "%5D")
4472      .replace("\"", "%22")
4473 }
4474
4475 fn sidebar_assoc_items(it: &clean::Item) -> String {
4476     let mut out = String::new();
4477     let c = cache();
4478     if let Some(v) = c.impls.get(&it.def_id) {
4479         let mut used_links = FxHashSet::default();
4480
4481         {
4482             let used_links_bor = Rc::new(RefCell::new(&mut used_links));
4483             let mut ret = v.iter()
4484                            .filter(|i| i.inner_impl().trait_.is_none())
4485                            .flat_map(move |i| get_methods(i.inner_impl(),
4486                                                           false,
4487                                                           &mut used_links_bor.borrow_mut()))
4488                            .collect::<Vec<_>>();
4489             // We want links' order to be reproducible so we don't use unstable sort.
4490             ret.sort();
4491             if !ret.is_empty() {
4492                 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4493                                        </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
4494             }
4495         }
4496
4497         if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4498             if let Some(impl_) = v.iter()
4499                                   .filter(|i| i.inner_impl().trait_.is_some())
4500                                   .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4501                 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4502                     match item.inner {
4503                         clean::TypedefItem(ref t, true) => Some(&t.type_),
4504                         _ => None,
4505                     }
4506                 }).next() {
4507                     let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4508                         c.primitive_locations.get(&prim).cloned()
4509                     })).and_then(|did| c.impls.get(&did));
4510                     if let Some(impls) = inner_impl {
4511                         out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4512                         out.push_str(&format!("Methods from {}&lt;Target={}&gt;",
4513                                               Escape(&format!("{:#}",
4514                                                      impl_.inner_impl().trait_.as_ref().unwrap())),
4515                                               Escape(&format!("{:#}", target))));
4516                         out.push_str("</a>");
4517                         let mut ret = impls.iter()
4518                                            .filter(|i| i.inner_impl().trait_.is_none())
4519                                            .flat_map(|i| get_methods(i.inner_impl(),
4520                                                                      true,
4521                                                                      &mut used_links))
4522                                            .collect::<Vec<_>>();
4523                         // We want links' order to be reproducible so we don't use unstable sort.
4524                         ret.sort();
4525                         if !ret.is_empty() {
4526                             out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
4527                                                   ret.join("")));
4528                         }
4529                     }
4530                 }
4531             }
4532             let format_impls = |impls: Vec<&Impl>| {
4533                 let mut links = FxHashSet::default();
4534
4535                 let mut ret = impls.iter()
4536                     .filter_map(|i| {
4537                         let is_negative_impl = is_negative_impl(i.inner_impl());
4538                         if let Some(ref i) = i.inner_impl().trait_ {
4539                             let i_display = format!("{:#}", i);
4540                             let out = Escape(&i_display);
4541                             let encoded = small_url_encode(&format!("{:#}", i));
4542                             let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4543                                                     encoded,
4544                                                     if is_negative_impl { "!" } else { "" },
4545                                                     out);
4546                             if links.insert(generated.clone()) {
4547                                 Some(generated)
4548                             } else {
4549                                 None
4550                             }
4551                         } else {
4552                             None
4553                         }
4554                     })
4555                     .collect::<Vec<String>>();
4556                 ret.sort();
4557                 ret.join("")
4558             };
4559
4560             let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4561                 .iter()
4562                 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4563             let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4564                 .into_iter()
4565                 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4566
4567             let concrete_format = format_impls(concrete);
4568             let synthetic_format = format_impls(synthetic);
4569             let blanket_format = format_impls(blanket_impl);
4570
4571             if !concrete_format.is_empty() {
4572                 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4573                               Trait Implementations</a>");
4574                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4575             }
4576
4577             if !synthetic_format.is_empty() {
4578                 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4579                               Auto Trait Implementations</a>");
4580                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4581             }
4582
4583             if !blanket_format.is_empty() {
4584                 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4585                               Blanket Implementations</a>");
4586                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4587             }
4588         }
4589     }
4590
4591     out
4592 }
4593
4594 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4595                   s: &clean::Struct) -> fmt::Result {
4596     let mut sidebar = String::new();
4597     let fields = get_struct_fields_name(&s.fields);
4598
4599     if !fields.is_empty() {
4600         if let doctree::Plain = s.struct_type {
4601             sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4602                                        <div class=\"sidebar-links\">{}</div>", fields));
4603         }
4604     }
4605
4606     sidebar.push_str(&sidebar_assoc_items(it));
4607
4608     if !sidebar.is_empty() {
4609         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4610     }
4611     Ok(())
4612 }
4613
4614 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4615     match item.inner {
4616         clean::ItemEnum::ImplItem(ref i) => {
4617             if let Some(ref trait_) = i.trait_ {
4618                 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4619             } else {
4620                 None
4621             }
4622         },
4623         _ => None,
4624     }
4625 }
4626
4627 fn is_negative_impl(i: &clean::Impl) -> bool {
4628     i.polarity == Some(clean::ImplPolarity::Negative)
4629 }
4630
4631 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4632                  t: &clean::Trait) -> fmt::Result {
4633     let mut sidebar = String::new();
4634
4635     let types = t.items
4636                  .iter()
4637                  .filter_map(|m| {
4638                      match m.name {
4639                          Some(ref name) if m.is_associated_type() => {
4640                              Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4641                                           name=name))
4642                          }
4643                          _ => None,
4644                      }
4645                  })
4646                  .collect::<String>();
4647     let consts = t.items
4648                   .iter()
4649                   .filter_map(|m| {
4650                       match m.name {
4651                           Some(ref name) if m.is_associated_const() => {
4652                               Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4653                                            name=name))
4654                           }
4655                           _ => None,
4656                       }
4657                   })
4658                   .collect::<String>();
4659     let mut required = t.items
4660                         .iter()
4661                         .filter_map(|m| {
4662                             match m.name {
4663                                 Some(ref name) if m.is_ty_method() => {
4664                                     Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4665                                                  name=name))
4666                                 }
4667                                 _ => None,
4668                             }
4669                         })
4670                         .collect::<Vec<String>>();
4671     let mut provided = t.items
4672                         .iter()
4673                         .filter_map(|m| {
4674                             match m.name {
4675                                 Some(ref name) if m.is_method() => {
4676                                     Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4677                                 }
4678                                 _ => None,
4679                             }
4680                         })
4681                         .collect::<Vec<String>>();
4682
4683     if !types.is_empty() {
4684         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4685                                    Associated Types</a><div class=\"sidebar-links\">{}</div>",
4686                                   types));
4687     }
4688     if !consts.is_empty() {
4689         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4690                                    Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4691                                   consts));
4692     }
4693     if !required.is_empty() {
4694         required.sort();
4695         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4696                                    Required Methods</a><div class=\"sidebar-links\">{}</div>",
4697                                   required.join("")));
4698     }
4699     if !provided.is_empty() {
4700         provided.sort();
4701         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4702                                    Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4703                                   provided.join("")));
4704     }
4705
4706     let c = cache();
4707
4708     if let Some(implementors) = c.implementors.get(&it.def_id) {
4709         let mut res = implementors.iter()
4710                                   .filter(|i| i.inner_impl().for_.def_id()
4711                                   .map_or(false, |d| !c.paths.contains_key(&d)))
4712                                   .filter_map(|i| {
4713                                       match extract_for_impl_name(&i.impl_item) {
4714                                           Some((ref name, ref url)) => {
4715                                               Some(format!("<a href=\"#impl-{}\">{}</a>",
4716                                                           small_url_encode(url),
4717                                                           Escape(name)))
4718                                           }
4719                                           _ => None,
4720                                       }
4721                                   })
4722                                   .collect::<Vec<String>>();
4723         if !res.is_empty() {
4724             res.sort();
4725             sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4726                                        Implementations on Foreign Types</a><div \
4727                                        class=\"sidebar-links\">{}</div>",
4728                                       res.join("")));
4729         }
4730     }
4731
4732     sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4733     if t.auto {
4734         sidebar.push_str("<a class=\"sidebar-title\" \
4735                           href=\"#synthetic-implementors\">Auto Implementors</a>");
4736     }
4737
4738     sidebar.push_str(&sidebar_assoc_items(it));
4739
4740     write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4741 }
4742
4743 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4744                      _p: &clean::PrimitiveType) -> fmt::Result {
4745     let sidebar = sidebar_assoc_items(it);
4746
4747     if !sidebar.is_empty() {
4748         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4749     }
4750     Ok(())
4751 }
4752
4753 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4754                    _t: &clean::Typedef) -> fmt::Result {
4755     let sidebar = sidebar_assoc_items(it);
4756
4757     if !sidebar.is_empty() {
4758         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4759     }
4760     Ok(())
4761 }
4762
4763 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4764     fields.iter()
4765           .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4766               true
4767           } else {
4768               false
4769           })
4770           .filter_map(|f| match f.name {
4771               Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4772                                               {name}</a>", name=name)),
4773               _ => None,
4774           })
4775           .collect()
4776 }
4777
4778 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4779                  u: &clean::Union) -> fmt::Result {
4780     let mut sidebar = String::new();
4781     let fields = get_struct_fields_name(&u.fields);
4782
4783     if !fields.is_empty() {
4784         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4785                                    <div class=\"sidebar-links\">{}</div>", fields));
4786     }
4787
4788     sidebar.push_str(&sidebar_assoc_items(it));
4789
4790     if !sidebar.is_empty() {
4791         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4792     }
4793     Ok(())
4794 }
4795
4796 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4797                 e: &clean::Enum) -> fmt::Result {
4798     let mut sidebar = String::new();
4799
4800     let variants = e.variants.iter()
4801                              .filter_map(|v| match v.name {
4802                                  Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4803                                                                  </a>", name = name)),
4804                                  _ => None,
4805                              })
4806                              .collect::<String>();
4807     if !variants.is_empty() {
4808         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4809                                    <div class=\"sidebar-links\">{}</div>", variants));
4810     }
4811
4812     sidebar.push_str(&sidebar_assoc_items(it));
4813
4814     if !sidebar.is_empty() {
4815         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4816     }
4817     Ok(())
4818 }
4819
4820 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4821     match *ty {
4822         ItemType::ExternCrate |
4823         ItemType::Import          => ("reexports", "Re-exports"),
4824         ItemType::Module          => ("modules", "Modules"),
4825         ItemType::Struct          => ("structs", "Structs"),
4826         ItemType::Union           => ("unions", "Unions"),
4827         ItemType::Enum            => ("enums", "Enums"),
4828         ItemType::Function        => ("functions", "Functions"),
4829         ItemType::Typedef         => ("types", "Type Definitions"),
4830         ItemType::Static          => ("statics", "Statics"),
4831         ItemType::Constant        => ("constants", "Constants"),
4832         ItemType::Trait           => ("traits", "Traits"),
4833         ItemType::Impl            => ("impls", "Implementations"),
4834         ItemType::TyMethod        => ("tymethods", "Type Methods"),
4835         ItemType::Method          => ("methods", "Methods"),
4836         ItemType::StructField     => ("fields", "Struct Fields"),
4837         ItemType::Variant         => ("variants", "Variants"),
4838         ItemType::Macro           => ("macros", "Macros"),
4839         ItemType::Primitive       => ("primitives", "Primitive Types"),
4840         ItemType::AssociatedType  => ("associated-types", "Associated Types"),
4841         ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4842         ItemType::ForeignType     => ("foreign-types", "Foreign Types"),
4843         ItemType::Keyword         => ("keywords", "Keywords"),
4844         ItemType::Existential     => ("existentials", "Existentials"),
4845         ItemType::ProcAttribute   => ("attributes", "Attribute Macros"),
4846         ItemType::ProcDerive      => ("derives", "Derive Macros"),
4847     }
4848 }
4849
4850 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4851                   items: &[clean::Item]) -> fmt::Result {
4852     let mut sidebar = String::new();
4853
4854     if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4855                              it.type_() == ItemType::Import) {
4856         sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4857                                   id = "reexports",
4858                                   name = "Re-exports"));
4859     }
4860
4861     // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4862     // to print its headings
4863     for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4864                    ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4865                    ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4866                    ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4867                    ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4868         if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4869             let (short, name) = item_ty_to_strs(&myty);
4870             sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4871                                       id = short,
4872                                       name = name));
4873         }
4874     }
4875
4876     if !sidebar.is_empty() {
4877         write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4878     }
4879     Ok(())
4880 }
4881
4882 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4883     let sidebar = sidebar_assoc_items(it);
4884     if !sidebar.is_empty() {
4885         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4886     }
4887     Ok(())
4888 }
4889
4890 impl<'a> fmt::Display for Source<'a> {
4891     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4892         let Source(s) = *self;
4893         let lines = s.lines().count();
4894         let mut cols = 0;
4895         let mut tmp = lines;
4896         while tmp > 0 {
4897             cols += 1;
4898             tmp /= 10;
4899         }
4900         write!(fmt, "<pre class=\"line-numbers\">")?;
4901         for i in 1..=lines {
4902             write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4903         }
4904         write!(fmt, "</pre>")?;
4905         write!(fmt, "{}",
4906                highlight::render_with_highlighting(s, None, None, None))?;
4907         Ok(())
4908     }
4909 }
4910
4911 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4912               t: &clean::Macro) -> fmt::Result {
4913     wrap_into_docblock(w, |w| {
4914         w.write_str(&highlight::render_with_highlighting(&t.source,
4915                                                          Some("macro"),
4916                                                          None,
4917                                                          None))
4918     })?;
4919     document(w, cx, it)
4920 }
4921
4922 fn item_proc_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, m: &clean::ProcMacro)
4923     -> fmt::Result
4924 {
4925     let name = it.name.as_ref().expect("proc-macros always have names");
4926     match m.kind {
4927         MacroKind::Bang => {
4928             write!(w, "<pre class='rust macro'>")?;
4929             write!(w, "{}!() {{ /* proc-macro */ }}", name)?;
4930             write!(w, "</pre>")?;
4931         }
4932         MacroKind::Attr => {
4933             write!(w, "<pre class='rust attr'>")?;
4934             write!(w, "#[{}]", name)?;
4935             write!(w, "</pre>")?;
4936         }
4937         MacroKind::Derive => {
4938             write!(w, "<pre class='rust derive'>")?;
4939             write!(w, "#[derive({})]", name)?;
4940             if !m.helpers.is_empty() {
4941                 writeln!(w, "\n{{")?;
4942                 writeln!(w, "    // Attributes available to this derive:")?;
4943                 for attr in &m.helpers {
4944                     writeln!(w, "    #[{}]", attr)?;
4945                 }
4946                 write!(w, "}}")?;
4947             }
4948             write!(w, "</pre>")?;
4949         }
4950         _ => {}
4951     }
4952     document(w, cx, it)
4953 }
4954
4955 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4956                   it: &clean::Item,
4957                   _p: &clean::PrimitiveType) -> fmt::Result {
4958     document(w, cx, it)?;
4959     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4960 }
4961
4962 fn item_keyword(w: &mut fmt::Formatter, cx: &Context,
4963                 it: &clean::Item,
4964                 _p: &str) -> fmt::Result {
4965     document(w, cx, it)
4966 }
4967
4968 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4969
4970 fn make_item_keywords(it: &clean::Item) -> String {
4971     format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4972 }
4973
4974 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4975     let decl = match item.inner {
4976         clean::FunctionItem(ref f) => &f.decl,
4977         clean::MethodItem(ref m) => &m.decl,
4978         clean::TyMethodItem(ref m) => &m.decl,
4979         _ => return None
4980     };
4981
4982     let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4983     let output = match decl.output {
4984         clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4985         _ => None
4986     };
4987
4988     Some(IndexItemFunctionType { inputs: inputs, output: output })
4989 }
4990
4991 fn get_index_type(clean_type: &clean::Type) -> Type {
4992     let t = Type {
4993         name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4994         generics: get_generics(clean_type),
4995     };
4996     t
4997 }
4998
4999 /// Returns a list of all paths used in the type.
5000 /// This is used to help deduplicate imported impls
5001 /// for reexported types. If any of the contained
5002 /// types are re-exported, we don't use the corresponding
5003 /// entry from the js file, as inlining will have already
5004 /// picked up the impl
5005 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
5006     let mut out = Vec::new();
5007     let mut visited = FxHashSet::default();
5008     let mut work = VecDeque::new();
5009     let cache = cache();
5010
5011     work.push_back(first_ty);
5012
5013     while let Some(ty) = work.pop_front() {
5014         if !visited.insert(ty.clone()) {
5015             continue;
5016         }
5017
5018         match ty {
5019             clean::Type::ResolvedPath { did, .. } => {
5020                 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
5021                 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
5022
5023                 match fqp {
5024                     Some(path) => {
5025                         out.push(path.join("::"));
5026                     },
5027                     _ => {}
5028                 };
5029
5030             },
5031             clean::Type::Tuple(tys) => {
5032                 work.extend(tys.into_iter());
5033             },
5034             clean::Type::Slice(ty) => {
5035                 work.push_back(*ty);
5036             }
5037             clean::Type::Array(ty, _) => {
5038                 work.push_back(*ty);
5039             },
5040             clean::Type::Unique(ty) => {
5041                 work.push_back(*ty);
5042             },
5043             clean::Type::RawPointer(_, ty) => {
5044                 work.push_back(*ty);
5045             },
5046             clean::Type::BorrowedRef { type_, .. } => {
5047                 work.push_back(*type_);
5048             },
5049             clean::Type::QPath { self_type, trait_, .. } => {
5050                 work.push_back(*self_type);
5051                 work.push_back(*trait_);
5052             },
5053             _ => {}
5054         }
5055     };
5056     out
5057 }
5058
5059 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
5060     match *clean_type {
5061         clean::ResolvedPath { ref path, .. } => {
5062             let segments = &path.segments;
5063             let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
5064                 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
5065                 clean_type, accept_generic
5066             ));
5067             Some(path_segment.name.clone())
5068         }
5069         clean::Generic(ref s) if accept_generic => Some(s.clone()),
5070         clean::Primitive(ref p) => Some(format!("{:?}", p)),
5071         clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
5072         // FIXME: add all from clean::Type.
5073         _ => None
5074     }
5075 }
5076
5077 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
5078     clean_type.generics()
5079               .and_then(|types| {
5080                   let r = types.iter()
5081                                .filter_map(|t| get_index_type_name(t, false))
5082                                .map(|s| s.to_ascii_lowercase())
5083                                .collect::<Vec<_>>();
5084                   if r.is_empty() {
5085                       None
5086                   } else {
5087                       Some(r)
5088                   }
5089               })
5090 }
5091
5092 pub fn cache() -> Arc<Cache> {
5093     CACHE_KEY.with(|c| c.borrow().clone())
5094 }
5095
5096 #[cfg(test)]
5097 #[test]
5098 fn test_name_key() {
5099     assert_eq!(name_key("0"), ("", 0, 1));
5100     assert_eq!(name_key("123"), ("", 123, 0));
5101     assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
5102     assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
5103     assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
5104     assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
5105     assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
5106     assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
5107 }
5108
5109 #[cfg(test)]
5110 #[test]
5111 fn test_name_sorting() {
5112     let names = ["Apple",
5113                  "Banana",
5114                  "Fruit", "Fruit0", "Fruit00",
5115                  "Fruit1", "Fruit01",
5116                  "Fruit2", "Fruit02",
5117                  "Fruit20",
5118                  "Fruit30x",
5119                  "Fruit100",
5120                  "Pear"];
5121     let mut sorted = names.to_owned();
5122     sorted.sort_by_key(|&s| name_key(s));
5123     assert_eq!(names, sorted);
5124 }