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