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