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