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