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