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