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