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