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