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