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