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