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.
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.
11 //! Rustdoc's HTML Rendering module
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.
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
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).
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::*;
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;
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;
49 use std::path::{PathBuf, Path};
53 use externalfiles::ExternalHtml;
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::middle::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;
65 use clean::{self, SelfTy};
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::item_type::ItemType;
73 use html::markdown::{self, Markdown};
74 use html::{highlight, layout};
76 /// A pair of name and its optional document.
77 pub type NameDoc = (String, Option<String>);
79 /// Major driving force in all rustdoc rendering. This contains information
80 /// about where in the tree-like hierarchy rendering is occurring and controls
81 /// how the current page is being rendered.
83 /// It is intended that this context is a lightweight object which can be fairly
84 /// easily cloned because it is cloned per work-job (about once per item in the
88 /// Current hierarchy of components leading down to what's currently being
90 pub current: Vec<String>,
91 /// String representation of how to get back to the root path of the 'doc/'
92 /// folder in terms of a relative URL.
93 pub root_path: String,
94 /// The path to the crate root source minus the file name.
95 /// Used for simplifying paths to the highlighted source code files.
96 pub src_root: PathBuf,
97 /// The current destination folder of where HTML artifacts should be placed.
98 /// This changes as the context descends into the module hierarchy.
100 /// This describes the layout of each page, and is not modified after
101 /// creation of the context (contains info like the favicon and added html).
102 pub layout: layout::Layout,
103 /// This flag indicates whether [src] links should be generated or not. If
104 /// the source files are present in the html rendering, then this will be
106 pub include_sources: bool,
107 /// A flag, which when turned off, will render pages which redirect to the
108 /// real location of an item. This is used to allow external links to
109 /// publicly reused items to redirect to the right location.
110 pub render_redirect_pages: bool,
111 /// All the passes that were run on this crate.
112 pub passes: HashSet<String>,
113 /// The base-URL of the issue tracker for when an item has been tagged with
115 pub issue_tracker_base_url: Option<String>,
118 /// Indicates where an external crate can be found.
119 pub enum ExternalLocation {
120 /// Remote URL root of the external crate
122 /// This external crate can be found in the local doc/ folder
124 /// The external crate could not be found.
128 /// Metadata about an implementor of a trait.
129 pub struct Implementor {
131 pub stability: Option<clean::Stability>,
132 pub impl_: clean::Impl,
135 /// Metadata about implementations for a type.
138 pub impl_: clean::Impl,
139 pub dox: Option<String>,
140 pub stability: Option<clean::Stability>,
144 fn trait_did(&self) -> Option<DefId> {
145 self.impl_.trait_.as_ref().and_then(|tr| {
146 if let clean::ResolvedPath { did, .. } = *tr {Some(did)} else {None}
157 impl error::Error for Error {
158 fn description(&self) -> &str {
159 self.error.description()
163 impl Display for Error {
164 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
165 write!(f, "\"{}\": {}", self.file.display(), self.error)
170 pub fn new(e: io::Error, file: &Path) -> Error {
172 file: file.to_path_buf(),
178 macro_rules! try_err {
179 ($e:expr, $file:expr) => ({
182 Err(e) => return Err(Error::new(e, $file)),
187 /// This cache is used to store information about the `clean::Crate` being
188 /// rendered in order to provide more useful documentation. This contains
189 /// information like all implementors of a trait, all traits a type implements,
190 /// documentation for all known traits, etc.
192 /// This structure purposefully does not implement `Clone` because it's intended
193 /// to be a fairly large and expensive structure to clone. Instead this adheres
194 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
195 /// rendering threads.
198 /// Mapping of typaram ids to the name of the type parameter. This is used
199 /// when pretty-printing a type (so pretty printing doesn't have to
200 /// painfully maintain a context like this)
201 pub typarams: HashMap<DefId, String>,
203 /// Maps a type id to all known implementations for that type. This is only
204 /// recognized for intra-crate `ResolvedPath` types, and is used to print
205 /// out extra documentation on the page of an enum/struct.
207 /// The values of the map are a list of implementations and documentation
208 /// found on that implementation.
209 pub impls: HashMap<DefId, Vec<Impl>>,
211 /// Maintains a mapping of local crate node ids to the fully qualified name
212 /// and "short type description" of that node. This is used when generating
213 /// URLs when a type is being linked to. External paths are not located in
214 /// this map because the `External` type itself has all the information
216 pub paths: HashMap<DefId, (Vec<String>, ItemType)>,
218 /// Similar to `paths`, but only holds external paths. This is only used for
219 /// generating explicit hyperlinks to other crates.
220 pub external_paths: HashMap<DefId, Vec<String>>,
222 /// This map contains information about all known traits of this crate.
223 /// Implementations of a crate should inherit the documentation of the
224 /// parent trait if no extra documentation is specified, and default methods
225 /// should show up in documentation about trait implementations.
226 pub traits: HashMap<DefId, clean::Trait>,
228 /// When rendering traits, it's often useful to be able to list all
229 /// implementors of the trait, and this mapping is exactly, that: a mapping
230 /// of trait ids to the list of known implementors of the trait
231 pub implementors: HashMap<DefId, Vec<Implementor>>,
233 /// Cache of where external crate documentation can be found.
234 pub extern_locations: HashMap<ast::CrateNum, (String, ExternalLocation)>,
236 /// Cache of where documentation for primitives can be found.
237 pub primitive_locations: HashMap<clean::PrimitiveType, ast::CrateNum>,
239 /// Set of definitions which have been inlined from external crates.
240 pub inlined: HashSet<DefId>,
242 // Private fields only used when initially crawling a crate to build a cache
245 parent_stack: Vec<DefId>,
246 search_index: Vec<IndexItem>,
249 access_levels: AccessLevels<DefId>,
250 deref_trait_did: Option<DefId>,
252 // In rare case where a structure is defined in one module but implemented
253 // in another, if the implementing module is parsed before defining module,
254 // then the fully qualified name of the structure isn't presented in `paths`
255 // yet when its implementation methods are being indexed. Caches such methods
256 // and their parent id here and indexes them at the end of crate parsing.
257 orphan_methods: Vec<(DefId, clean::Item)>,
260 /// Helper struct to render all source code to HTML pages
261 struct SourceCollector<'a> {
264 /// Processed source-file paths
265 seen: HashSet<String>,
266 /// Root destination to place all HTML output into
270 /// Wrapper struct to render the source code of a file. This will do things like
271 /// adding line numbers to the left-hand side.
272 struct Source<'a>(&'a str);
274 // Helper structs for rendering items/sidebars and carrying along contextual
277 #[derive(Copy, Clone)]
280 item: &'a clean::Item,
283 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
285 /// Struct representing one entry in the JS search index. These are all emitted
286 /// by hand to a large JS file at the end of cache-creation.
292 parent: Option<DefId>,
293 parent_idx: Option<usize>,
294 search_type: Option<IndexItemFunctionType>,
297 impl ToJson for IndexItem {
298 fn to_json(&self) -> Json {
299 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
301 let mut data = Vec::with_capacity(6);
302 data.push((self.ty as usize).to_json());
303 data.push(self.name.to_json());
304 data.push(self.path.to_json());
305 data.push(self.desc.to_json());
306 data.push(self.parent_idx.to_json());
307 data.push(self.search_type.to_json());
313 /// A type used for the search index.
315 name: Option<String>,
318 impl ToJson for Type {
319 fn to_json(&self) -> Json {
322 let mut data = BTreeMap::new();
323 data.insert("name".to_owned(), name.to_json());
331 /// Full type of functions/methods in the search index.
332 struct IndexItemFunctionType {
337 impl ToJson for IndexItemFunctionType {
338 fn to_json(&self) -> Json {
339 // If we couldn't figure out a type, just write `null`.
340 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
343 let mut data = BTreeMap::new();
344 data.insert("inputs".to_owned(), self.inputs.to_json());
345 data.insert("output".to_owned(), self.output.to_json());
351 // TLS keys used to carry information around during rendering.
353 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
354 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
355 RefCell::new(Vec::new()));
356 thread_local!(static USED_ID_MAP: RefCell<HashMap<String, usize>> =
357 RefCell::new(init_ids()));
359 fn init_ids() -> HashMap<String, usize> {
375 "derived_implementations"
376 ].into_iter().map(|id| (String::from(*id), 1)).collect::<HashMap<_, _>>()
379 /// This method resets the local table of used ID attributes. This is typically
380 /// used at the beginning of rendering an entire HTML page to reset from the
381 /// previous state (if any).
383 USED_ID_MAP.with(|s| *s.borrow_mut() = init_ids());
386 pub fn derive_id(candidate: String) -> String {
387 USED_ID_MAP.with(|map| {
388 let id = match map.borrow_mut().get_mut(&candidate) {
391 let id = format!("{}-{}", candidate, *a);
397 map.borrow_mut().insert(id.clone(), 1);
402 /// Generates the documentation for `crate` into the directory `dst`
403 pub fn run(mut krate: clean::Crate,
404 external_html: &ExternalHtml,
406 passes: HashSet<String>) -> Result<(), Error> {
407 let src_root = match krate.src.parent() {
408 Some(p) => p.to_path_buf(),
409 None => PathBuf::new(),
411 let mut cx = Context {
416 root_path: String::new(),
417 layout: layout::Layout {
418 logo: "".to_string(),
419 favicon: "".to_string(),
420 external_html: external_html.clone(),
421 krate: krate.name.clone(),
422 playground_url: "".to_string(),
424 include_sources: true,
425 render_redirect_pages: false,
426 issue_tracker_base_url: None,
429 try_err!(mkdir(&cx.dst), &cx.dst);
431 // Crawl the crate attributes looking for attributes which control how we're
432 // going to emit HTML
433 let default: &[_] = &[];
434 match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(default)) {
438 clean::NameValue(ref x, ref s)
439 if "html_favicon_url" == *x => {
440 cx.layout.favicon = s.to_string();
442 clean::NameValue(ref x, ref s)
443 if "html_logo_url" == *x => {
444 cx.layout.logo = s.to_string();
446 clean::NameValue(ref x, ref s)
447 if "html_playground_url" == *x => {
448 cx.layout.playground_url = s.to_string();
449 markdown::PLAYGROUND_KRATE.with(|slot| {
450 if slot.borrow().is_none() {
451 let name = krate.name.clone();
452 *slot.borrow_mut() = Some(Some(name));
456 clean::NameValue(ref x, ref s)
457 if "issue_tracker_base_url" == *x => {
458 cx.issue_tracker_base_url = Some(s.to_string());
461 if "html_no_source" == *x => {
462 cx.include_sources = false;
471 // Crawl the crate to build various caches used for the output
472 let analysis = ::ANALYSISKEY.with(|a| a.clone());
473 let analysis = analysis.borrow();
474 let access_levels = analysis.as_ref().map(|a| a.access_levels.clone());
475 let access_levels = access_levels.unwrap_or(Default::default());
476 let paths: HashMap<DefId, (Vec<String>, ItemType)> =
477 analysis.as_ref().map(|a| {
478 let paths = a.external_paths.borrow_mut().take().unwrap();
479 paths.into_iter().map(|(k, (v, t))| (k, (v, ItemType::from_type_kind(t)))).collect()
480 }).unwrap_or(HashMap::new());
481 let mut cache = Cache {
482 impls: HashMap::new(),
483 external_paths: paths.iter().map(|(&k, v)| (k, v.0.clone()))
486 implementors: HashMap::new(),
488 parent_stack: Vec::new(),
489 search_index: Vec::new(),
490 extern_locations: HashMap::new(),
491 primitive_locations: HashMap::new(),
492 remove_priv: cx.passes.contains("strip-private"),
494 access_levels: access_levels,
495 orphan_methods: Vec::new(),
496 traits: mem::replace(&mut krate.external_traits, HashMap::new()),
497 deref_trait_did: analysis.as_ref().and_then(|a| a.deref_trait_did),
498 typarams: analysis.as_ref().map(|a| {
499 a.external_typarams.borrow_mut().take().unwrap()
500 }).unwrap_or(HashMap::new()),
501 inlined: analysis.as_ref().map(|a| {
502 a.inlined.borrow_mut().take().unwrap()
503 }).unwrap_or(HashSet::new()),
506 // Cache where all our extern crates are located
507 for &(n, ref e) in &krate.externs {
508 cache.extern_locations.insert(n, (e.name.clone(),
509 extern_location(e, &cx.dst)));
510 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
511 cache.paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
514 // Cache where all known primitives have their documentation located.
516 // Favor linking to as local extern as possible, so iterate all crates in
517 // reverse topological order.
518 for &(n, ref e) in krate.externs.iter().rev() {
519 for &prim in &e.primitives {
520 cache.primitive_locations.insert(prim, n);
523 for &prim in &krate.primitives {
524 cache.primitive_locations.insert(prim, LOCAL_CRATE);
527 cache.stack.push(krate.name.clone());
528 krate = cache.fold_crate(krate);
530 // Build our search index
531 let index = build_index(&krate, &mut cache);
533 // Freeze the cache now that the index has been built. Put an Arc into TLS
534 // for future parallelization opportunities
535 let cache = Arc::new(cache);
536 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
537 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
539 try!(write_shared(&cx, &krate, &*cache, index));
540 let krate = try!(render_sources(&mut cx, krate));
542 // And finally render the whole crate's documentation
546 /// Build the search index from the collected metadata
547 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
548 let mut nodeid_to_pathid = HashMap::new();
549 let mut crate_items = Vec::with_capacity(cache.search_index.len());
550 let mut crate_paths = Vec::<Json>::new();
552 let Cache { ref mut search_index,
554 ref mut paths, .. } = *cache;
556 // Attach all orphan methods to the type's definition if the type
557 // has since been learned.
558 for &(did, ref item) in orphan_methods {
559 match paths.get(&did) {
560 Some(&(ref fqp, _)) => {
561 // Needed to determine `self` type.
562 let parent_basename = Some(fqp[fqp.len() - 1].clone());
563 search_index.push(IndexItem {
565 name: item.name.clone().unwrap(),
566 path: fqp[..fqp.len() - 1].join("::"),
567 desc: Escape(&shorter(item.doc_value())).to_string(),
570 search_type: get_index_search_type(&item, parent_basename),
577 // Reduce `NodeId` in paths into smaller sequential numbers,
578 // and prune the paths that do not appear in the index.
579 let mut lastpath = String::new();
580 let mut lastpathid = 0usize;
582 for item in search_index {
583 item.parent_idx = item.parent.map(|nodeid| {
584 if nodeid_to_pathid.contains_key(&nodeid) {
585 *nodeid_to_pathid.get(&nodeid).unwrap()
587 let pathid = lastpathid;
588 nodeid_to_pathid.insert(nodeid, pathid);
591 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
592 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
597 // Omit the parent path if it is same to that of the prior item.
598 if lastpath == item.path {
601 lastpath = item.path.clone();
603 crate_items.push(item.to_json());
606 let crate_doc = krate.module.as_ref().map(|module| {
607 Escape(&shorter(module.doc_value())).to_string()
608 }).unwrap_or(String::new());
610 let mut crate_data = BTreeMap::new();
611 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
612 crate_data.insert("items".to_owned(), Json::Array(crate_items));
613 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
615 // Collect the index into a string
616 format!("searchIndex[{}] = {};",
617 as_json(&krate.name),
618 Json::Object(crate_data))
621 fn write_shared(cx: &Context,
622 krate: &clean::Crate,
624 search_index: String) -> Result<(), Error> {
625 // Write out the shared files. Note that these are shared among all rustdoc
626 // docs placed in the output directory, so this needs to be a synchronized
627 // operation with respect to all other rustdocs running around.
628 try_err!(mkdir(&cx.dst), &cx.dst);
629 let _lock = ::flock::Lock::new(&cx.dst.join(".lock"));
631 // Add all the static files. These may already exist, but we just
632 // overwrite them anyway to make sure that they're fresh and up-to-date.
633 try!(write(cx.dst.join("jquery.js"),
634 include_bytes!("static/jquery-2.1.4.min.js")));
635 try!(write(cx.dst.join("main.js"),
636 include_bytes!("static/main.js")));
637 try!(write(cx.dst.join("playpen.js"),
638 include_bytes!("static/playpen.js")));
639 try!(write(cx.dst.join("rustdoc.css"),
640 include_bytes!("static/rustdoc.css")));
641 try!(write(cx.dst.join("main.css"),
642 include_bytes!("static/styles/main.css")));
643 try!(write(cx.dst.join("normalize.css"),
644 include_bytes!("static/normalize.css")));
645 try!(write(cx.dst.join("FiraSans-Regular.woff"),
646 include_bytes!("static/FiraSans-Regular.woff")));
647 try!(write(cx.dst.join("FiraSans-Medium.woff"),
648 include_bytes!("static/FiraSans-Medium.woff")));
649 try!(write(cx.dst.join("FiraSans-LICENSE.txt"),
650 include_bytes!("static/FiraSans-LICENSE.txt")));
651 try!(write(cx.dst.join("Heuristica-Italic.woff"),
652 include_bytes!("static/Heuristica-Italic.woff")));
653 try!(write(cx.dst.join("Heuristica-LICENSE.txt"),
654 include_bytes!("static/Heuristica-LICENSE.txt")));
655 try!(write(cx.dst.join("SourceSerifPro-Regular.woff"),
656 include_bytes!("static/SourceSerifPro-Regular.woff")));
657 try!(write(cx.dst.join("SourceSerifPro-Bold.woff"),
658 include_bytes!("static/SourceSerifPro-Bold.woff")));
659 try!(write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
660 include_bytes!("static/SourceSerifPro-LICENSE.txt")));
661 try!(write(cx.dst.join("SourceCodePro-Regular.woff"),
662 include_bytes!("static/SourceCodePro-Regular.woff")));
663 try!(write(cx.dst.join("SourceCodePro-Semibold.woff"),
664 include_bytes!("static/SourceCodePro-Semibold.woff")));
665 try!(write(cx.dst.join("SourceCodePro-LICENSE.txt"),
666 include_bytes!("static/SourceCodePro-LICENSE.txt")));
667 try!(write(cx.dst.join("LICENSE-MIT.txt"),
668 include_bytes!("static/LICENSE-MIT.txt")));
669 try!(write(cx.dst.join("LICENSE-APACHE.txt"),
670 include_bytes!("static/LICENSE-APACHE.txt")));
671 try!(write(cx.dst.join("COPYRIGHT.txt"),
672 include_bytes!("static/COPYRIGHT.txt")));
674 fn collect(path: &Path, krate: &str,
675 key: &str) -> io::Result<Vec<String>> {
676 let mut ret = Vec::new();
678 for line in BufReader::new(try!(File::open(path))).lines() {
679 let line = try!(line);
680 if !line.starts_with(key) {
683 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
686 ret.push(line.to_string());
692 // Update the search index
693 let dst = cx.dst.join("search-index.js");
694 let all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
695 let mut w = try_err!(File::create(&dst), &dst);
696 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
697 try_err!(writeln!(&mut w, "{}", search_index), &dst);
698 for index in &all_indexes {
699 try_err!(writeln!(&mut w, "{}", *index), &dst);
701 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
703 // Update the list of all implementors for traits
704 let dst = cx.dst.join("implementors");
705 try_err!(mkdir(&dst), &dst);
706 for (&did, imps) in &cache.implementors {
707 // Private modules can leak through to this phase of rustdoc, which
708 // could contain implementations for otherwise private types. In some
709 // rare cases we could find an implementation for an item which wasn't
710 // indexed, so we just skip this step in that case.
712 // FIXME: this is a vague explanation for why this can't be a `get`, in
713 // theory it should be...
714 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
719 let mut mydst = dst.clone();
720 for part in &remote_path[..remote_path.len() - 1] {
722 try_err!(mkdir(&mydst), &mydst);
724 mydst.push(&format!("{}.{}.js",
725 remote_item_type.to_static_str(),
726 remote_path[remote_path.len() - 1]));
727 let all_implementors = try_err!(collect(&mydst, &krate.name,
731 try_err!(mkdir(mydst.parent().unwrap()),
732 &mydst.parent().unwrap().to_path_buf());
733 let mut f = BufWriter::new(try_err!(File::create(&mydst), &mydst));
734 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
736 for implementor in &all_implementors {
737 try_err!(write!(&mut f, "{}", *implementor), &mydst);
740 try_err!(write!(&mut f, r"implementors['{}'] = [", krate.name), &mydst);
742 // If the trait and implementation are in the same crate, then
743 // there's no need to emit information about it (there's inlining
744 // going on). If they're in different crates then the crate defining
745 // the trait will be interested in our implementation.
746 if imp.def_id.krate == did.krate { continue }
747 try_err!(write!(&mut f, r#""{}","#, imp.impl_), &mydst);
749 try_err!(writeln!(&mut f, r"];"), &mydst);
750 try_err!(writeln!(&mut f, "{}", r"
751 if (window.register_implementors) {
752 window.register_implementors(implementors);
754 window.pending_implementors = implementors;
757 try_err!(writeln!(&mut f, r"}})()"), &mydst);
762 fn render_sources(cx: &mut Context,
763 krate: clean::Crate) -> Result<clean::Crate, Error> {
764 info!("emitting source files");
765 let dst = cx.dst.join("src");
766 try_err!(mkdir(&dst), &dst);
767 let dst = dst.join(&krate.name);
768 try_err!(mkdir(&dst), &dst);
769 let mut folder = SourceCollector {
771 seen: HashSet::new(),
774 // skip all invalid spans
775 folder.seen.insert("".to_string());
776 Ok(folder.fold_crate(krate))
779 /// Writes the entire contents of a string to a destination, not attempting to
780 /// catch any errors.
781 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
782 Ok(try_err!(try_err!(File::create(&dst), &dst).write_all(contents), &dst))
785 /// Makes a directory on the filesystem, failing the thread if an error occurs and
786 /// skipping if the directory already exists.
787 fn mkdir(path: &Path) -> io::Result<()> {
795 /// Returns a documentation-level item type from the item.
796 fn shortty(item: &clean::Item) -> ItemType {
797 ItemType::from_item(item)
800 /// Takes a path to a source file and cleans the path to it. This canonicalizes
801 /// things like ".." to components which preserve the "top down" hierarchy of a
802 /// static HTML tree. Each component in the cleaned path will be passed as an
803 /// argument to `f`. The very last component of the path (ie the file name) will
804 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
805 // FIXME (#9639): The closure should deal with &[u8] instead of &str
806 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
807 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
810 // make it relative, if possible
811 let p = p.strip_prefix(src_root).unwrap_or(p);
813 let mut iter = p.iter().map(|x| x.to_str().unwrap()).peekable();
814 while let Some(c) = iter.next() {
815 if !keep_filename && iter.peek().is_none() {
827 /// Attempts to find where an external crate is located, given that we're
828 /// rendering in to the specified source destination.
829 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
830 // See if there's documentation generated into the local directory
831 let local_location = dst.join(&e.name);
832 if local_location.is_dir() {
836 // Failing that, see if there's an attribute specifying where to find this
838 for attr in &e.attrs {
840 clean::List(ref x, ref list) if "doc" == *x => {
843 clean::NameValue(ref x, ref s)
844 if "html_root_url" == *x => {
845 if s.ends_with("/") {
846 return Remote(s.to_string());
848 return Remote(format!("{}/", s));
858 // Well, at least we tried.
862 impl<'a> DocFolder for SourceCollector<'a> {
863 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
864 // If we're including source files, and we haven't seen this file yet,
865 // then we need to render it out to the filesystem
866 if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
868 // If it turns out that we couldn't read this file, then we probably
869 // can't read any of the files (generating html output from json or
870 // something like that), so just don't include sources for the
871 // entire crate. The other option is maintaining this mapping on a
872 // per-file basis, but that's probably not worth it...
874 .include_sources = match self.emit_source(&item.source .filename) {
877 println!("warning: source code was requested to be rendered, \
878 but processing `{}` had an error: {}",
879 item.source.filename, e);
880 println!(" skipping rendering of source code");
884 self.seen.insert(item.source.filename.clone());
887 self.fold_item_recur(item)
891 impl<'a> SourceCollector<'a> {
892 /// Renders the given filename into its corresponding HTML source file.
893 fn emit_source(&mut self, filename: &str) -> io::Result<()> {
894 let p = PathBuf::from(filename);
896 // If we couldn't open this file, then just returns because it
897 // probably means that it's some standard library macro thing and we
898 // can't have the source to it anyway.
899 let mut contents = Vec::new();
900 match File::open(&p).and_then(|mut f| f.read_to_end(&mut contents)) {
902 // macros from other libraries get special filenames which we can
904 Err(..) if filename.starts_with("<") &&
905 filename.ends_with("macros>") => return Ok(()),
906 Err(e) => return Err(e)
908 let contents = str::from_utf8(&contents).unwrap();
910 // Remove the utf-8 BOM if any
911 let contents = if contents.starts_with("\u{feff}") {
917 // Create the intermediate directories
918 let mut cur = self.dst.clone();
919 let mut root_path = String::from("../../");
920 clean_srcpath(&self.cx.src_root, &p, false, |component| {
922 mkdir(&cur).unwrap();
923 root_path.push_str("../");
926 let mut fname = p.file_name().expect("source has no filename")
929 cur.push(&fname[..]);
930 let mut w = BufWriter::new(try!(File::create(&cur)));
931 let title = format!("{} -- source", cur.file_name().unwrap()
933 let desc = format!("Source to the Rust file `{}`.", filename);
934 let page = layout::Page {
937 root_path: &root_path,
939 keywords: get_basic_keywords(),
941 try!(layout::render(&mut w, &self.cx.layout,
942 &page, &(""), &Source(contents)));
948 impl DocFolder for Cache {
949 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
950 // If this is a private module, we don't want it in the search index.
951 let orig_privmod = match item.inner {
952 clean::ModuleItem(..) => {
953 let prev = self.privmod;
954 self.privmod = prev || (self.remove_priv && item.visibility != Some(hir::Public));
960 // Register any generics to their corresponding string. This is used
961 // when pretty-printing types
963 clean::StructItem(ref s) => self.generics(&s.generics),
964 clean::EnumItem(ref e) => self.generics(&e.generics),
965 clean::FunctionItem(ref f) => self.generics(&f.generics),
966 clean::TypedefItem(ref t, _) => self.generics(&t.generics),
967 clean::TraitItem(ref t) => self.generics(&t.generics),
968 clean::ImplItem(ref i) => self.generics(&i.generics),
969 clean::TyMethodItem(ref i) => self.generics(&i.generics),
970 clean::MethodItem(ref i) => self.generics(&i.generics),
971 clean::ForeignFunctionItem(ref f) => self.generics(&f.generics),
975 // Propagate a trait methods' documentation to all implementors of the
977 if let clean::TraitItem(ref t) = item.inner {
978 self.traits.insert(item.def_id, t.clone());
981 // Collect all the implementors of traits.
982 if let clean::ImplItem(ref i) = item.inner {
984 Some(clean::ResolvedPath{ did, .. }) => {
985 self.implementors.entry(did).or_insert(vec![]).push(Implementor {
987 stability: item.stability.clone(),
991 Some(..) | None => {}
995 // Index this method for searching later on
996 if let Some(ref s) = item.name {
997 let (parent, is_method) = match item.inner {
998 clean::AssociatedTypeItem(..) |
999 clean::AssociatedConstItem(..) |
1000 clean::TyMethodItem(..) |
1001 clean::StructFieldItem(..) |
1002 clean::VariantItem(..) => {
1003 ((Some(*self.parent_stack.last().unwrap()),
1004 Some(&self.stack[..self.stack.len() - 1])),
1007 clean::MethodItem(..) => {
1008 if self.parent_stack.is_empty() {
1009 ((None, None), false)
1011 let last = self.parent_stack.last().unwrap();
1013 let path = match self.paths.get(&did) {
1014 Some(&(_, ItemType::Trait)) =>
1015 Some(&self.stack[..self.stack.len() - 1]),
1016 // The current stack not necessarily has correlation
1017 // for where the type was defined. On the other
1018 // hand, `paths` always has the right
1019 // information if present.
1020 Some(&(ref fqp, ItemType::Struct)) |
1021 Some(&(ref fqp, ItemType::Enum)) =>
1022 Some(&fqp[..fqp.len() - 1]),
1023 Some(..) => Some(&*self.stack),
1026 ((Some(*last), path), true)
1029 clean::TypedefItem(_, true) => {
1030 // skip associated types in impls
1031 ((None, None), false)
1033 _ => ((None, Some(&*self.stack)), false)
1035 let hidden_field = match item.inner {
1036 clean::StructFieldItem(clean::HiddenStructField) => true,
1041 (parent, Some(path)) if is_method || (!self.privmod && !hidden_field) => {
1042 // Needed to determine `self` type.
1043 let parent_basename = self.parent_stack.first().and_then(|parent| {
1044 match self.paths.get(parent) {
1045 Some(&(ref fqp, _)) => Some(fqp[fqp.len() - 1].clone()),
1050 if item.def_id.index != CRATE_DEF_INDEX {
1051 self.search_index.push(IndexItem {
1053 name: s.to_string(),
1054 path: path.join("::").to_string(),
1055 desc: Escape(&shorter(item.doc_value())).to_string(),
1058 search_type: get_index_search_type(&item, parent_basename),
1062 (Some(parent), None) if is_method || (!self.privmod && !hidden_field)=> {
1063 if parent.is_local() {
1064 // We have a parent, but we don't know where they're
1065 // defined yet. Wait for later to index this item.
1066 self.orphan_methods.push((parent, item.clone()))
1073 // Keep track of the fully qualified path for this item.
1074 let pushed = if item.name.is_some() {
1075 let n = item.name.as_ref().unwrap();
1077 self.stack.push(n.to_string());
1082 clean::StructItem(..) | clean::EnumItem(..) |
1083 clean::TypedefItem(..) | clean::TraitItem(..) |
1084 clean::FunctionItem(..) | clean::ModuleItem(..) |
1085 clean::ForeignFunctionItem(..) if !self.privmod => {
1086 // Reexported items mean that the same id can show up twice
1087 // in the rustdoc ast that we're looking at. We know,
1088 // however, that a reexported item doesn't show up in the
1089 // `public_items` map, so we can skip inserting into the
1090 // paths map if there was already an entry present and we're
1091 // not a public item.
1093 !self.paths.contains_key(&item.def_id) ||
1094 !item.def_id.is_local() ||
1095 self.access_levels.is_public(item.def_id)
1097 self.paths.insert(item.def_id,
1098 (self.stack.clone(), shortty(&item)));
1101 // link variants to their parent enum because pages aren't emitted
1103 clean::VariantItem(..) if !self.privmod => {
1104 let mut stack = self.stack.clone();
1106 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1109 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1110 self.paths.insert(item.def_id, (self.stack.clone(),
1117 // Maintain the parent stack
1118 let parent_pushed = match item.inner {
1119 clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
1120 self.parent_stack.push(item.def_id);
1123 clean::ImplItem(ref i) => {
1125 clean::ResolvedPath{ did, .. } => {
1126 self.parent_stack.push(did);
1130 match t.primitive_type() {
1132 let did = DefId::local(prim.to_def_index());
1133 self.parent_stack.push(did);
1144 // Once we've recursively found all the generics, then hoard off all the
1145 // implementations elsewhere
1146 let ret = match self.fold_item_recur(item) {
1149 clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
1150 // extract relevant documentation for this impl
1151 let dox = match attrs.into_iter().find(|a| {
1153 clean::NameValue(ref x, _)
1160 Some(clean::NameValue(_, dox)) => Some(dox),
1161 Some(..) | None => None,
1164 // Figure out the id of this impl. This may map to a
1165 // primitive rather than always to a struct/enum.
1166 let did = match i.for_ {
1167 clean::ResolvedPath { did, .. } |
1168 clean::BorrowedRef {
1169 type_: box clean::ResolvedPath { did, .. }, ..
1175 t.primitive_type().and_then(|t| {
1176 self.primitive_locations.get(&t).map(|n| {
1177 let id = t.to_def_index();
1178 DefId { krate: *n, index: id }
1184 if let Some(did) = did {
1185 self.impls.entry(did).or_insert(vec![]).push(Impl {
1188 stability: item.stability.clone(),
1201 if pushed { self.stack.pop().unwrap(); }
1202 if parent_pushed { self.parent_stack.pop().unwrap(); }
1203 self.privmod = orig_privmod;
1209 fn generics(&mut self, generics: &clean::Generics) {
1210 for typ in &generics.type_params {
1211 self.typarams.insert(typ.did, typ.name.clone());
1217 /// Recurse in the directory structure and change the "root path" to make
1218 /// sure it always points to the top (relatively)
1219 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1220 F: FnOnce(&mut Context) -> T,
1223 panic!("Unexpected empty destination: {:?}", self.current);
1225 let prev = self.dst.clone();
1227 self.root_path.push_str("../");
1228 self.current.push(s);
1230 info!("Recursing into {}", self.dst.display());
1232 mkdir(&self.dst).unwrap();
1235 info!("Recursed; leaving {}", self.dst.display());
1237 // Go back to where we were at
1239 let len = self.root_path.len();
1240 self.root_path.truncate(len - 3);
1241 self.current.pop().unwrap();
1246 /// Main method for rendering a crate.
1248 /// This currently isn't parallelized, but it'd be pretty easy to add
1249 /// parallelization to this function.
1250 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1251 let mut item = match krate.module.take() {
1253 None => return Ok(())
1255 item.name = Some(krate.name);
1257 // render the crate documentation
1258 let mut work = vec!((self, item));
1261 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
1262 work.push((cx.clone(), item));
1271 /// Non-parallelized version of rendering an item. This will take the input
1272 /// item, render its contents, and then invoke the specified closure with
1273 /// all sub-items which need to be rendered.
1275 /// The rendering driver uses this closure to queue up more work.
1276 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1277 F: FnMut(&mut Context, clean::Item),
1279 fn render(w: File, cx: &Context, it: &clean::Item,
1280 pushname: bool) -> io::Result<()> {
1281 // A little unfortunate that this is done like this, but it sure
1282 // does make formatting *a lot* nicer.
1283 CURRENT_LOCATION_KEY.with(|slot| {
1284 *slot.borrow_mut() = cx.current.clone();
1287 let mut title = cx.current.join("::");
1289 if !title.is_empty() {
1290 title.push_str("::");
1292 title.push_str(it.name.as_ref().unwrap());
1294 title.push_str(" - Rust");
1295 let tyname = shortty(it).to_static_str();
1296 let is_crate = match it.inner {
1297 clean::ModuleItem(clean::Module { items: _, is_crate: true }) => true,
1300 let desc = if is_crate {
1301 format!("API documentation for the Rust `{}` crate.",
1304 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1305 it.name.as_ref().unwrap(), tyname, cx.layout.krate)
1307 let keywords = make_item_keywords(it);
1308 let page = layout::Page {
1310 root_path: &cx.root_path,
1313 keywords: &keywords,
1318 // We have a huge number of calls to write, so try to alleviate some
1319 // of the pain by using a buffered writer instead of invoking the
1320 // write syscall all the time.
1321 let mut writer = BufWriter::new(w);
1322 if !cx.render_redirect_pages {
1323 try!(layout::render(&mut writer, &cx.layout, &page,
1324 &Sidebar{ cx: cx, item: it },
1325 &Item{ cx: cx, item: it }));
1327 let mut url = repeat("../").take(cx.current.len())
1328 .collect::<String>();
1329 match cache().paths.get(&it.def_id) {
1330 Some(&(ref names, _)) => {
1331 for name in &names[..names.len() - 1] {
1335 url.push_str(&item_path(it));
1336 try!(layout::redirect(&mut writer, &url));
1344 // Private modules may survive the strip-private pass if they
1345 // contain impls for public types. These modules can also
1346 // contain items such as publicly reexported structures.
1348 // External crates will provide links to these structures, so
1349 // these modules are recursed into, but not rendered normally (a
1350 // flag on the context).
1351 if !self.render_redirect_pages {
1352 self.render_redirect_pages = self.ignore_private_item(&item);
1356 // modules are special because they add a namespace. We also need to
1357 // recurse into the items of the module as well.
1358 clean::ModuleItem(..) => {
1359 let name = item.name.as_ref().unwrap().to_string();
1360 let mut item = Some(item);
1361 self.recurse(name, |this| {
1362 let item = item.take().unwrap();
1363 let joint_dst = this.dst.join("index.html");
1364 let dst = try_err!(File::create(&joint_dst), &joint_dst);
1365 try_err!(render(dst, this, &item, false), &joint_dst);
1367 let m = match item.inner {
1368 clean::ModuleItem(m) => m,
1372 // render sidebar-items.js used throughout this module
1374 let items = this.build_sidebar_items(&m);
1375 let js_dst = this.dst.join("sidebar-items.js");
1376 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1377 try_err!(write!(&mut js_out, "initSidebarItems({});",
1378 as_json(&items)), &js_dst);
1381 for item in m.items {
1388 // Things which don't have names (like impls) don't get special
1389 // pages dedicated to them.
1390 _ if item.name.is_some() => {
1391 let joint_dst = self.dst.join(&item_path(&item));
1393 let dst = try_err!(File::create(&joint_dst), &joint_dst);
1394 try_err!(render(dst, self, &item, true), &joint_dst);
1402 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1403 // BTreeMap instead of HashMap to get a sorted output
1404 let mut map = BTreeMap::new();
1405 for item in &m.items {
1406 if self.ignore_private_item(item) { continue }
1408 let short = shortty(item).to_static_str();
1409 let myname = match item.name {
1411 Some(ref s) => s.to_string(),
1413 let short = short.to_string();
1414 map.entry(short).or_insert(vec![])
1415 .push((myname, Some(plain_summary_line(item.doc_value()))));
1418 for (_, items) in &mut map {
1424 fn ignore_private_item(&self, it: &clean::Item) -> bool {
1426 clean::ModuleItem(ref m) => {
1427 (m.items.is_empty() &&
1428 it.doc_value().is_none() &&
1429 it.visibility != Some(hir::Public)) ||
1430 (self.passes.contains("strip-private") && it.visibility != Some(hir::Public))
1432 clean::PrimitiveItem(..) => it.visibility != Some(hir::Public),
1439 fn ismodule(&self) -> bool {
1440 match self.item.inner {
1441 clean::ModuleItem(..) => true, _ => false
1445 /// Generate a url appropriate for an `href` attribute back to the source of
1448 /// The url generated, when clicked, will redirect the browser back to the
1449 /// original source code.
1451 /// If `None` is returned, then a source link couldn't be generated. This
1452 /// may happen, for example, with externally inlined items where the source
1453 /// of their crate documentation isn't known.
1454 fn href(&self, cx: &Context) -> Option<String> {
1455 let href = if self.item.source.loline == self.item.source.hiline {
1456 format!("{}", self.item.source.loline)
1458 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1461 // First check to see if this is an imported macro source. In this case
1462 // we need to handle it specially as cross-crate inlined macros have...
1464 let imported_macro_from = match self.item.inner {
1465 clean::MacroItem(ref m) => m.imported_from.as_ref(),
1468 if let Some(krate) = imported_macro_from {
1469 let cache = cache();
1470 let root = cache.extern_locations.values().find(|&&(ref n, _)| {
1473 let root = match root {
1474 Some(&Remote(ref s)) => s.to_string(),
1475 Some(&Local) => self.cx.root_path.clone(),
1476 None | Some(&Unknown) => return None,
1478 Some(format!("{root}/{krate}/macro.{name}.html?gotomacrosrc=1",
1481 name = self.item.name.as_ref().unwrap()))
1483 // If this item is part of the local crate, then we're guaranteed to
1484 // know the span, so we plow forward and generate a proper url. The url
1485 // has anchors for the line numbers that we're linking to.
1486 } else if self.item.def_id.is_local() {
1487 let mut path = Vec::new();
1488 clean_srcpath(&cx.src_root, Path::new(&self.item.source.filename),
1490 path.push(component.to_string());
1492 // If the span points into an external macro the
1493 // source-file will be bogus, i.e `<foo macros>`
1494 if Path::new(&self.item.source.filename).is_file() {
1495 Some(format!("{root}src/{krate}/{path}.html#{href}",
1496 root = self.cx.root_path,
1497 krate = self.cx.layout.krate,
1498 path = path.join("/"),
1504 // If this item is not part of the local crate, then things get a little
1505 // trickier. We don't actually know the span of the external item, but
1506 // we know that the documentation on the other end knows the span!
1508 // In this case, we generate a link to the *documentation* for this type
1509 // in the original crate. There's an extra URL parameter which says that
1510 // we want to go somewhere else, and the JS on the destination page will
1511 // pick it up and instantly redirect the browser to the source code.
1513 // If we don't know where the external documentation for this crate is
1514 // located, then we return `None`.
1516 let cache = cache();
1517 let path = &cache.external_paths[&self.item.def_id];
1518 let root = match cache.extern_locations[&self.item.def_id.krate] {
1519 (_, Remote(ref s)) => s.to_string(),
1520 (_, Local) => self.cx.root_path.clone(),
1521 (_, Unknown) => return None,
1523 Some(format!("{root}{path}/{file}?gotosrc={goto}",
1525 path = path[..path.len() - 1].join("/"),
1526 file = item_path(self.item),
1527 goto = self.item.def_id.index.as_usize()))
1533 impl<'a> fmt::Display for Item<'a> {
1534 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1535 // Write the breadcrumb trail header for the top
1536 try!(write!(fmt, "\n<h1 class='fqn'><span class='in-band'>"));
1537 match self.item.inner {
1538 clean::ModuleItem(ref m) => if m.is_crate {
1539 try!(write!(fmt, "Crate "));
1541 try!(write!(fmt, "Module "));
1543 clean::FunctionItem(..) => try!(write!(fmt, "Function ")),
1544 clean::TraitItem(..) => try!(write!(fmt, "Trait ")),
1545 clean::StructItem(..) => try!(write!(fmt, "Struct ")),
1546 clean::EnumItem(..) => try!(write!(fmt, "Enum ")),
1547 clean::PrimitiveItem(..) => try!(write!(fmt, "Primitive Type ")),
1550 let is_primitive = match self.item.inner {
1551 clean::PrimitiveItem(..) => true,
1555 let cur = &self.cx.current;
1556 let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
1557 for (i, component) in cur.iter().enumerate().take(amt) {
1558 try!(write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1559 repeat("../").take(cur.len() - i - 1)
1560 .collect::<String>(),
1564 try!(write!(fmt, "<a class='{}' href=''>{}</a>",
1565 shortty(self.item), self.item.name.as_ref().unwrap()));
1567 try!(write!(fmt, "</span>")); // in-band
1568 try!(write!(fmt, "<span class='out-of-band'>"));
1570 r##"<span id='render-detail'>
1571 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1572 [<span class='inner'>−</span>]
1578 // When this item is part of a `pub use` in a downstream crate, the
1579 // [src] link in the downstream documentation will actually come back to
1580 // this page, and this link will be auto-clicked. The `id` attribute is
1581 // used to find the link to auto-click.
1582 if self.cx.include_sources && !is_primitive {
1583 match self.href(self.cx) {
1585 try!(write!(fmt, "<a id='src-{}' class='srclink' \
1586 href='{}' title='{}'>[src]</a>",
1587 self.item.def_id.index.as_usize(), l, "goto source code"));
1593 try!(write!(fmt, "</span>")); // out-of-band
1595 try!(write!(fmt, "</h1>\n"));
1597 match self.item.inner {
1598 clean::ModuleItem(ref m) => {
1599 item_module(fmt, self.cx, self.item, &m.items)
1601 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1602 item_function(fmt, self.cx, self.item, f),
1603 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1604 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1605 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1606 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1607 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1608 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1609 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1610 item_static(fmt, self.cx, self.item, i),
1611 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1617 fn item_path(item: &clean::Item) -> String {
1619 clean::ModuleItem(..) => {
1620 format!("{}/index.html", item.name.as_ref().unwrap())
1623 format!("{}.{}.html",
1624 shortty(item).to_static_str(),
1625 *item.name.as_ref().unwrap())
1630 fn full_path(cx: &Context, item: &clean::Item) -> String {
1631 let mut s = cx.current.join("::");
1633 s.push_str(item.name.as_ref().unwrap());
1637 fn shorter<'a>(s: Option<&'a str>) -> String {
1639 Some(s) => s.lines().take_while(|line|{
1640 (*line).chars().any(|chr|{
1641 !chr.is_whitespace()
1643 }).collect::<Vec<_>>().join("\n"),
1644 None => "".to_string()
1649 fn plain_summary_line(s: Option<&str>) -> String {
1650 let md = markdown::plain_summary_line(s.unwrap_or(""));
1651 shorter(Some(&md)).replace("\n", " ")
1654 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1655 if let Some(s) = short_stability(item, cx, true) {
1656 try!(write!(w, "<div class='stability'>{}</div>", s));
1658 if let Some(s) = item.doc_value() {
1659 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1664 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1665 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1666 try!(document(w, cx, item));
1668 let mut indices = (0..items.len()).filter(|i| {
1669 !cx.ignore_private_item(&items[*i])
1670 }).collect::<Vec<usize>>();
1672 // the order of item types in the listing
1673 fn reorder(ty: ItemType) -> u8 {
1675 ItemType::ExternCrate => 0,
1676 ItemType::Import => 1,
1677 ItemType::Primitive => 2,
1678 ItemType::Module => 3,
1679 ItemType::Macro => 4,
1680 ItemType::Struct => 5,
1681 ItemType::Enum => 6,
1682 ItemType::Constant => 7,
1683 ItemType::Static => 8,
1684 ItemType::Trait => 9,
1685 ItemType::Function => 10,
1686 ItemType::Typedef => 12,
1691 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1692 let ty1 = shortty(i1);
1693 let ty2 = shortty(i2);
1695 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1697 let s1 = i1.stability.as_ref().map(|s| s.level);
1698 let s2 = i2.stability.as_ref().map(|s| s.level);
1700 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1701 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1704 i1.name.cmp(&i2.name)
1707 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1709 debug!("{:?}", indices);
1710 let mut curty = None;
1711 for &idx in &indices {
1712 let myitem = &items[idx];
1714 let myty = Some(shortty(myitem));
1715 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1716 // Put `extern crate` and `use` re-exports in the same section.
1718 } else if myty != curty {
1719 if curty.is_some() {
1720 try!(write!(w, "</table>"));
1723 let (short, name) = match myty.unwrap() {
1724 ItemType::ExternCrate |
1725 ItemType::Import => ("reexports", "Reexports"),
1726 ItemType::Module => ("modules", "Modules"),
1727 ItemType::Struct => ("structs", "Structs"),
1728 ItemType::Enum => ("enums", "Enums"),
1729 ItemType::Function => ("functions", "Functions"),
1730 ItemType::Typedef => ("types", "Type Definitions"),
1731 ItemType::Static => ("statics", "Statics"),
1732 ItemType::Constant => ("constants", "Constants"),
1733 ItemType::Trait => ("traits", "Traits"),
1734 ItemType::Impl => ("impls", "Implementations"),
1735 ItemType::TyMethod => ("tymethods", "Type Methods"),
1736 ItemType::Method => ("methods", "Methods"),
1737 ItemType::StructField => ("fields", "Struct Fields"),
1738 ItemType::Variant => ("variants", "Variants"),
1739 ItemType::Macro => ("macros", "Macros"),
1740 ItemType::Primitive => ("primitives", "Primitive Types"),
1741 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1742 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1744 try!(write!(w, "<h2 id='{id}' class='section-header'>\
1745 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1746 id = derive_id(short.to_owned()), name = name));
1749 match myitem.inner {
1750 clean::ExternCrateItem(ref name, ref src) => {
1753 try!(write!(w, "<tr><td><code>{}extern crate {} as {};",
1754 VisSpace(myitem.visibility),
1759 try!(write!(w, "<tr><td><code>{}extern crate {};",
1760 VisSpace(myitem.visibility), name))
1763 try!(write!(w, "</code></td></tr>"));
1766 clean::ImportItem(ref import) => {
1767 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1768 VisSpace(myitem.visibility), *import));
1772 if myitem.name.is_none() { continue }
1773 let stab_docs = if let Some(s) = short_stability(myitem, cx, false) {
1778 let doc_value = myitem.doc_value().unwrap_or("");
1780 <tr class='{stab} module-item'>
1781 <td><a class='{class}' href='{href}'
1782 title='{title}'>{name}</a></td>
1783 <td class='docblock short'>
1788 name = *myitem.name.as_ref().unwrap(),
1789 stab_docs = stab_docs,
1790 docs = shorter(Some(&Markdown(doc_value).to_string())),
1791 class = shortty(myitem),
1792 stab = myitem.stability_class(),
1793 href = item_path(myitem),
1794 title = full_path(cx, myitem)));
1799 write!(w, "</table>")
1802 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Option<String> {
1803 let mut result = item.stability.as_ref().and_then(|stab| {
1804 let reason = if show_reason && !stab.reason.is_empty() {
1805 format!(": {}", stab.reason)
1809 let text = if !stab.deprecated_since.is_empty() {
1810 let since = if show_reason {
1811 format!(" since {}", Escape(&stab.deprecated_since))
1815 format!("Deprecated{}{}", since, Markdown(&reason))
1816 } else if stab.level == stability::Unstable {
1817 let unstable_extra = if show_reason {
1818 match (!stab.feature.is_empty(), &cx.issue_tracker_base_url, stab.issue) {
1819 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1820 format!(" (<code>{}</code> <a href=\"{}{}\">#{}</a>)",
1821 Escape(&stab.feature), tracker_url, issue_no, issue_no),
1822 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1823 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
1826 format!(" (<code>{}</code>)", Escape(&stab.feature)),
1832 format!("Unstable{}{}", unstable_extra, Markdown(&reason))
1836 Some(format!("<em class='stab {}'>{}</em>",
1837 item.stability_class(), text))
1840 if result.is_none() {
1841 result = item.deprecation.as_ref().and_then(|depr| {
1842 let note = if show_reason && !depr.note.is_empty() {
1843 format!(": {}", depr.note)
1847 let since = if show_reason && !depr.since.is_empty() {
1848 format!(" since {}", Escape(&depr.since))
1853 let text = format!("Deprecated{}{}", since, Markdown(¬e));
1854 Some(format!("<em class='stab deprecated'>{}</em>", text))
1861 struct Initializer<'a>(&'a str);
1863 impl<'a> fmt::Display for Initializer<'a> {
1864 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1865 let Initializer(s) = *self;
1866 if s.is_empty() { return Ok(()); }
1867 try!(write!(f, "<code> = </code>"));
1868 write!(f, "<code>{}</code>", s)
1872 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1873 c: &clean::Constant) -> fmt::Result {
1874 try!(write!(w, "<pre class='rust const'>{vis}const \
1875 {name}: {typ}{init}</pre>",
1876 vis = VisSpace(it.visibility),
1877 name = it.name.as_ref().unwrap(),
1879 init = Initializer(&c.expr)));
1883 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1884 s: &clean::Static) -> fmt::Result {
1885 try!(write!(w, "<pre class='rust static'>{vis}static {mutability}\
1886 {name}: {typ}{init}</pre>",
1887 vis = VisSpace(it.visibility),
1888 mutability = MutableSpace(s.mutability),
1889 name = it.name.as_ref().unwrap(),
1891 init = Initializer(&s.expr)));
1895 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1896 f: &clean::Function) -> fmt::Result {
1897 let vis_constness = match get_unstable_features_setting() {
1898 UnstableFeatures::Allow => f.constness,
1899 _ => hir::Constness::NotConst
1901 try!(write!(w, "<pre class='rust fn'>{vis}{constness}{unsafety}{abi}fn \
1902 {name}{generics}{decl}{where_clause}</pre>",
1903 vis = VisSpace(it.visibility),
1904 constness = ConstnessSpace(vis_constness),
1905 unsafety = UnsafetySpace(f.unsafety),
1906 abi = AbiSpace(f.abi),
1907 name = it.name.as_ref().unwrap(),
1908 generics = f.generics,
1909 where_clause = WhereClause(&f.generics),
1911 try!(render_stability_since_raw(w, it.stable_since(), None));
1915 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1916 t: &clean::Trait) -> fmt::Result {
1917 let mut bounds = String::new();
1918 if !t.bounds.is_empty() {
1919 if !bounds.is_empty() {
1922 bounds.push_str(": ");
1923 for (i, p) in t.bounds.iter().enumerate() {
1924 if i > 0 { bounds.push_str(" + "); }
1925 bounds.push_str(&format!("{}", *p));
1929 // Output the trait definition
1930 try!(write!(w, "<pre class='rust trait'>{}{}trait {}{}{}{} ",
1931 VisSpace(it.visibility),
1932 UnsafetySpace(t.unsafety),
1933 it.name.as_ref().unwrap(),
1936 WhereClause(&t.generics)));
1938 let types = t.items.iter().filter(|m| {
1939 match m.inner { clean::AssociatedTypeItem(..) => true, _ => false }
1940 }).collect::<Vec<_>>();
1941 let consts = t.items.iter().filter(|m| {
1942 match m.inner { clean::AssociatedConstItem(..) => true, _ => false }
1943 }).collect::<Vec<_>>();
1944 let required = t.items.iter().filter(|m| {
1945 match m.inner { clean::TyMethodItem(_) => true, _ => false }
1946 }).collect::<Vec<_>>();
1947 let provided = t.items.iter().filter(|m| {
1948 match m.inner { clean::MethodItem(_) => true, _ => false }
1949 }).collect::<Vec<_>>();
1951 if t.items.is_empty() {
1952 try!(write!(w, "{{ }}"));
1954 try!(write!(w, "{{\n"));
1956 try!(write!(w, " "));
1957 try!(render_assoc_item(w, t, AssocItemLink::Anchor));
1958 try!(write!(w, ";\n"));
1960 if !types.is_empty() && !consts.is_empty() {
1961 try!(w.write_str("\n"));
1964 try!(write!(w, " "));
1965 try!(render_assoc_item(w, t, AssocItemLink::Anchor));
1966 try!(write!(w, ";\n"));
1968 if !consts.is_empty() && !required.is_empty() {
1969 try!(w.write_str("\n"));
1971 for m in &required {
1972 try!(write!(w, " "));
1973 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1974 try!(write!(w, ";\n"));
1976 if !required.is_empty() && !provided.is_empty() {
1977 try!(w.write_str("\n"));
1979 for m in &provided {
1980 try!(write!(w, " "));
1981 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1982 try!(write!(w, " {{ ... }}\n"));
1984 try!(write!(w, "}}"));
1986 try!(write!(w, "</pre>"));
1988 // Trait documentation
1989 try!(document(w, cx, it));
1991 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
1993 let name = m.name.as_ref().unwrap();
1994 let id = derive_id(format!("{}.{}", shortty(m), name));
1995 try!(write!(w, "<h3 id='{id}' class='method stab {stab}'><code>",
1997 stab = m.stability_class()));
1998 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1999 try!(write!(w, "</code>"));
2000 try!(render_stability_since(w, m, t));
2001 try!(write!(w, "</h3>"));
2002 try!(document(w, cx, m));
2006 if !types.is_empty() {
2008 <h2 id='associated-types'>Associated Types</h2>
2009 <div class='methods'>
2012 try!(trait_item(w, cx, *t, it));
2014 try!(write!(w, "</div>"));
2017 if !consts.is_empty() {
2019 <h2 id='associated-const'>Associated Constants</h2>
2020 <div class='methods'>
2023 try!(trait_item(w, cx, *t, it));
2025 try!(write!(w, "</div>"));
2028 // Output the documentation for each function individually
2029 if !required.is_empty() {
2031 <h2 id='required-methods'>Required Methods</h2>
2032 <div class='methods'>
2034 for m in &required {
2035 try!(trait_item(w, cx, *m, it));
2037 try!(write!(w, "</div>"));
2039 if !provided.is_empty() {
2041 <h2 id='provided-methods'>Provided Methods</h2>
2042 <div class='methods'>
2044 for m in &provided {
2045 try!(trait_item(w, cx, *m, it));
2047 try!(write!(w, "</div>"));
2050 // If there are methods directly on this trait object, render them here.
2051 try!(render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All));
2053 let cache = cache();
2055 <h2 id='implementors'>Implementors</h2>
2056 <ul class='item-list' id='implementors-list'>
2058 match cache.implementors.get(&it.def_id) {
2059 Some(implementors) => {
2060 for i in implementors {
2061 try!(writeln!(w, "<li><code>{}</code></li>", i.impl_));
2066 try!(write!(w, "</ul>"));
2067 try!(write!(w, r#"<script type="text/javascript" async
2068 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2070 root_path = vec![".."; cx.current.len()].join("/"),
2071 path = if it.def_id.is_local() {
2072 cx.current.join("/")
2074 let path = &cache.external_paths[&it.def_id];
2075 path[..path.len() - 1].join("/")
2077 ty = shortty(it).to_static_str(),
2078 name = *it.name.as_ref().unwrap()));
2082 fn assoc_const(w: &mut fmt::Formatter, it: &clean::Item,
2083 ty: &clean::Type, default: Option<&String>)
2085 try!(write!(w, "const {}", it.name.as_ref().unwrap()));
2086 try!(write!(w, ": {}", ty));
2087 if let Some(default) = default {
2088 try!(write!(w, " = {}", default));
2093 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
2094 bounds: &Vec<clean::TyParamBound>,
2095 default: &Option<clean::Type>)
2097 try!(write!(w, "type {}", it.name.as_ref().unwrap()));
2098 if !bounds.is_empty() {
2099 try!(write!(w, ": {}", TyParamBounds(bounds)))
2101 if let Some(ref default) = *default {
2102 try!(write!(w, " = {}", default));
2107 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2108 ver: Option<&'a str>,
2109 containing_ver: Option<&'a str>) -> fmt::Result {
2110 if containing_ver != ver {
2114 try!(write!(w, "<span class=\"since\">{}</span>",
2124 fn render_stability_since(w: &mut fmt::Formatter,
2126 containing_item: &clean::Item) -> fmt::Result {
2127 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2130 fn render_assoc_item(w: &mut fmt::Formatter, meth: &clean::Item,
2131 link: AssocItemLink) -> fmt::Result {
2132 fn method(w: &mut fmt::Formatter,
2134 unsafety: hir::Unsafety,
2135 constness: hir::Constness,
2137 g: &clean::Generics,
2138 selfty: &clean::SelfTy,
2140 link: AssocItemLink)
2142 use syntax::abi::Abi;
2144 let name = it.name.as_ref().unwrap();
2145 let anchor = format!("#{}.{}", shortty(it), name);
2146 let href = match link {
2147 AssocItemLink::Anchor => anchor,
2148 AssocItemLink::GotoSource(did) => {
2149 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2152 let vis_constness = match get_unstable_features_setting() {
2153 UnstableFeatures::Allow => constness,
2154 _ => hir::Constness::NotConst
2156 write!(w, "{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2157 {generics}{decl}{where_clause}",
2158 ConstnessSpace(vis_constness),
2159 UnsafetySpace(unsafety),
2161 Abi::Rust => String::new(),
2162 a => format!("extern {} ", a.to_string())
2167 decl = Method(selfty, d),
2168 where_clause = WhereClause(g))
2171 clean::TyMethodItem(ref m) => {
2172 method(w, meth, m.unsafety, hir::Constness::NotConst,
2173 m.abi, &m.generics, &m.self_, &m.decl, link)
2175 clean::MethodItem(ref m) => {
2176 method(w, meth, m.unsafety, m.constness,
2177 m.abi, &m.generics, &m.self_, &m.decl,
2180 clean::AssociatedConstItem(ref ty, ref default) => {
2181 assoc_const(w, meth, ty, default.as_ref())
2183 clean::AssociatedTypeItem(ref bounds, ref default) => {
2184 assoc_type(w, meth, bounds, default)
2186 _ => panic!("render_assoc_item called on non-associated-item")
2190 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2191 s: &clean::Struct) -> fmt::Result {
2192 try!(write!(w, "<pre class='rust struct'>"));
2193 try!(render_attributes(w, it));
2194 try!(render_struct(w,
2201 try!(write!(w, "</pre>"));
2202 try!(render_stability_since_raw(w, it.stable_since(), None));
2204 try!(document(w, cx, it));
2205 let mut fields = s.fields.iter().filter(|f| {
2207 clean::StructFieldItem(clean::HiddenStructField) => false,
2208 clean::StructFieldItem(clean::TypedStructField(..)) => true,
2212 if let doctree::Plain = s.struct_type {
2213 if fields.peek().is_some() {
2214 try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
2215 for field in fields {
2216 try!(write!(w, "<tr class='stab {stab}'>
2217 <td id='structfield.{name}'>\
2218 <code>{name}</code></td><td>",
2219 stab = field.stability_class(),
2220 name = field.name.as_ref().unwrap()));
2221 try!(document(w, cx, field));
2222 try!(write!(w, "</td></tr>"));
2224 try!(write!(w, "</table>"));
2227 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2230 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2231 e: &clean::Enum) -> fmt::Result {
2232 try!(write!(w, "<pre class='rust enum'>"));
2233 try!(render_attributes(w, it));
2234 try!(write!(w, "{}enum {}{}{}",
2235 VisSpace(it.visibility),
2236 it.name.as_ref().unwrap(),
2238 WhereClause(&e.generics)));
2239 if e.variants.is_empty() && !e.variants_stripped {
2240 try!(write!(w, " {{}}"));
2242 try!(write!(w, " {{\n"));
2243 for v in &e.variants {
2244 try!(write!(w, " "));
2245 let name = v.name.as_ref().unwrap();
2247 clean::VariantItem(ref var) => {
2249 clean::CLikeVariant => try!(write!(w, "{}", name)),
2250 clean::TupleVariant(ref tys) => {
2251 try!(write!(w, "{}(", name));
2252 for (i, ty) in tys.iter().enumerate() {
2254 try!(write!(w, ", "))
2256 try!(write!(w, "{}", *ty));
2258 try!(write!(w, ")"));
2260 clean::StructVariant(ref s) => {
2261 try!(render_struct(w,
2273 try!(write!(w, ",\n"));
2276 if e.variants_stripped {
2277 try!(write!(w, " // some variants omitted\n"));
2279 try!(write!(w, "}}"));
2281 try!(write!(w, "</pre>"));
2282 try!(render_stability_since_raw(w, it.stable_since(), None));
2284 try!(document(w, cx, it));
2285 if !e.variants.is_empty() {
2286 try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table class='variants_table'>"));
2287 for variant in &e.variants {
2288 try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
2289 name = variant.name.as_ref().unwrap()));
2290 try!(document(w, cx, variant));
2291 match variant.inner {
2292 clean::VariantItem(ref var) => {
2294 clean::StructVariant(ref s) => {
2295 let fields = s.fields.iter().filter(|f| {
2297 clean::StructFieldItem(ref t) => match *t {
2298 clean::HiddenStructField => false,
2299 clean::TypedStructField(..) => true,
2304 try!(write!(w, "<h3 class='fields'>Fields</h3>\n
2306 for field in fields {
2307 try!(write!(w, "<tr><td \
2308 id='variant.{v}.field.{f}'>\
2309 <code>{f}</code></td><td>",
2310 v = variant.name.as_ref().unwrap(),
2311 f = field.name.as_ref().unwrap()));
2312 try!(document(w, cx, field));
2313 try!(write!(w, "</td></tr>"));
2315 try!(write!(w, "</table>"));
2322 try!(write!(w, "</td><td>"));
2323 try!(render_stability_since(w, variant, it));
2324 try!(write!(w, "</td></tr>"));
2326 try!(write!(w, "</table>"));
2329 try!(render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All));
2333 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2334 for attr in &it.attrs {
2336 clean::Word(ref s) if *s == "must_use" => {
2337 try!(write!(w, "#[{}]\n", s));
2339 clean::NameValue(ref k, ref v) if *k == "must_use" => {
2340 try!(write!(w, "#[{} = \"{}\"]\n", k, v));
2348 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2349 g: Option<&clean::Generics>,
2350 ty: doctree::StructType,
2351 fields: &[clean::Item],
2353 structhead: bool) -> fmt::Result {
2354 try!(write!(w, "{}{}{}",
2355 VisSpace(it.visibility),
2356 if structhead {"struct "} else {""},
2357 it.name.as_ref().unwrap()));
2359 Some(g) => try!(write!(w, "{}{}", *g, WhereClause(g))),
2364 try!(write!(w, " {{\n{}", tab));
2365 let mut fields_stripped = false;
2366 for field in fields {
2368 clean::StructFieldItem(clean::HiddenStructField) => {
2369 fields_stripped = true;
2371 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
2372 try!(write!(w, " {}{}: {},\n{}",
2373 VisSpace(field.visibility),
2374 field.name.as_ref().unwrap(),
2378 _ => unreachable!(),
2382 if fields_stripped {
2383 try!(write!(w, " // some fields omitted\n{}", tab));
2385 try!(write!(w, "}}"));
2387 doctree::Tuple | doctree::Newtype => {
2388 try!(write!(w, "("));
2389 for (i, field) in fields.iter().enumerate() {
2391 try!(write!(w, ", "));
2394 clean::StructFieldItem(clean::HiddenStructField) => {
2395 try!(write!(w, "_"))
2397 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
2398 try!(write!(w, "{}{}", VisSpace(field.visibility), *ty))
2403 try!(write!(w, ");"));
2406 try!(write!(w, ";"));
2412 #[derive(Copy, Clone)]
2413 enum AssocItemLink {
2418 enum AssocItemRender<'a> {
2420 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type },
2423 fn render_assoc_items(w: &mut fmt::Formatter,
2425 containing_item: &clean::Item,
2427 what: AssocItemRender) -> fmt::Result {
2429 let v = match c.impls.get(&it) {
2431 None => return Ok(()),
2433 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
2434 i.impl_.trait_.is_none()
2436 if !non_trait.is_empty() {
2437 let render_header = match what {
2438 AssocItemRender::All => {
2439 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
2442 AssocItemRender::DerefFor { trait_, type_ } => {
2443 try!(write!(w, "<h2 id='deref-methods'>Methods from \
2444 {}<Target={}></h2>", trait_, type_));
2448 for i in &non_trait {
2449 try!(render_impl(w, cx, i, AssocItemLink::Anchor, render_header,
2450 containing_item.stable_since()));
2453 if let AssocItemRender::DerefFor { .. } = what {
2456 if !traits.is_empty() {
2457 let deref_impl = traits.iter().find(|t| {
2458 match *t.impl_.trait_.as_ref().unwrap() {
2459 clean::ResolvedPath { did, .. } => {
2460 Some(did) == c.deref_trait_did
2465 if let Some(impl_) = deref_impl {
2466 try!(render_deref_methods(w, cx, impl_, containing_item));
2468 try!(write!(w, "<h2 id='implementations'>Trait \
2469 Implementations</h2>"));
2470 let (derived, manual): (Vec<_>, Vec<&Impl>) = traits.iter().partition(|i| {
2474 let did = i.trait_did().unwrap();
2475 try!(render_impl(w, cx, i, AssocItemLink::GotoSource(did), true,
2476 containing_item.stable_since()));
2478 if !derived.is_empty() {
2479 try!(write!(w, "<h3 id='derived_implementations'>\
2480 Derived Implementations \
2483 let did = i.trait_did().unwrap();
2484 try!(render_impl(w, cx, i, AssocItemLink::GotoSource(did), true,
2485 containing_item.stable_since()));
2492 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
2493 container_item: &clean::Item) -> fmt::Result {
2494 let deref_type = impl_.impl_.trait_.as_ref().unwrap();
2495 let target = impl_.impl_.items.iter().filter_map(|item| {
2497 clean::TypedefItem(ref t, true) => Some(&t.type_),
2500 }).next().expect("Expected associated type binding");
2501 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target };
2503 clean::ResolvedPath { did, .. } => render_assoc_items(w, cx, container_item, did, what),
2505 if let Some(prim) = target.primitive_type() {
2506 if let Some(c) = cache().primitive_locations.get(&prim) {
2507 let did = DefId { krate: *c, index: prim.to_def_index() };
2508 try!(render_assoc_items(w, cx, container_item, did, what));
2516 // Render_header is false when we are rendering a `Deref` impl and true
2517 // otherwise. If render_header is false, we will avoid rendering static
2518 // methods, since they are not accessible for the type implementing `Deref`
2519 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
2520 render_header: bool, outer_version: Option<&str>) -> fmt::Result {
2522 try!(write!(w, "<h3 class='impl'><code>{}</code>", i.impl_));
2523 let since = i.stability.as_ref().map(|s| &s.since[..]);
2524 try!(render_stability_since_raw(w, since, outer_version));
2525 try!(write!(w, "</h3>"));
2526 if let Some(ref dox) = i.dox {
2527 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(dox)));
2531 fn doctraititem(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2532 link: AssocItemLink, render_static: bool,
2533 outer_version: Option<&str>) -> fmt::Result {
2534 let name = item.name.as_ref().unwrap();
2536 clean::MethodItem(..) | clean::TyMethodItem(..) => {
2537 // Only render when the method is not static or we allow static methods
2538 if !is_static_method(item) || render_static {
2539 let id = derive_id(format!("method.{}", name));
2540 try!(write!(w, "<h4 id='{}' class='{}'>", id, shortty(item)));
2541 try!(render_stability_since_raw(w, item.stable_since(), outer_version));
2542 try!(write!(w, "<code>"));
2543 try!(render_assoc_item(w, item, link));
2544 try!(write!(w, "</code></h4>\n"));
2547 clean::TypedefItem(ref tydef, _) => {
2548 let id = derive_id(format!("associatedtype.{}", name));
2549 try!(write!(w, "<h4 id='{}' class='{}'><code>", id, shortty(item)));
2550 try!(write!(w, "type {} = {}", name, tydef.type_));
2551 try!(write!(w, "</code></h4>\n"));
2553 clean::AssociatedConstItem(ref ty, ref default) => {
2554 let id = derive_id(format!("associatedconstant.{}", name));
2555 try!(write!(w, "<h4 id='{}' class='{}'><code>", id, shortty(item)));
2556 try!(assoc_const(w, item, ty, default.as_ref()));
2557 try!(write!(w, "</code></h4>\n"));
2559 clean::ConstantItem(ref c) => {
2560 let id = derive_id(format!("associatedconstant.{}", name));
2561 try!(write!(w, "<h4 id='{}' class='{}'><code>", id, shortty(item)));
2562 try!(assoc_const(w, item, &c.type_, Some(&c.expr)));
2563 try!(write!(w, "</code></h4>\n"));
2565 clean::AssociatedTypeItem(ref bounds, ref default) => {
2566 let id = derive_id(format!("associatedtype.{}", name));
2567 try!(write!(w, "<h4 id='{}' class='{}'><code>", id, shortty(item)));
2568 try!(assoc_type(w, item, bounds, default));
2569 try!(write!(w, "</code></h4>\n"));
2571 _ => panic!("can't make docs for trait item with name {:?}", item.name)
2574 return if let AssocItemLink::Anchor = link {
2575 if is_static_method(item) && !render_static {
2578 document(w, cx, item)
2584 fn is_static_method(item: &clean::Item) -> bool {
2586 clean::MethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
2587 clean::TyMethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
2593 try!(write!(w, "<div class='impl-items'>"));
2594 for trait_item in &i.impl_.items {
2595 try!(doctraititem(w, cx, trait_item, link, render_header, outer_version));
2598 fn render_default_items(w: &mut fmt::Formatter,
2603 render_static: bool,
2604 outer_version: Option<&str>) -> fmt::Result {
2605 for trait_item in &t.items {
2606 let n = trait_item.name.clone();
2607 match i.items.iter().find(|m| { m.name == n }) {
2608 Some(..) => continue,
2612 try!(doctraititem(w, cx, trait_item, AssocItemLink::GotoSource(did), render_static,
2618 // If we've implemented a trait, then also emit documentation for all
2619 // default methods which weren't overridden in the implementation block.
2620 // FIXME: this also needs to be done for associated types, whenever defaults
2622 if let Some(clean::ResolvedPath { did, .. }) = i.impl_.trait_ {
2623 if let Some(t) = cache().traits.get(&did) {
2624 try!(render_default_items(w, cx, did, t, &i.impl_, render_header, outer_version));
2628 try!(write!(w, "</div>"));
2632 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2633 t: &clean::Typedef) -> fmt::Result {
2634 try!(write!(w, "<pre class='rust typedef'>type {}{}{where_clause} = {type_};</pre>",
2635 it.name.as_ref().unwrap(),
2637 where_clause = WhereClause(&t.generics),
2643 impl<'a> fmt::Display for Sidebar<'a> {
2644 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2647 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
2649 // the sidebar is designed to display sibling functions, modules and
2650 // other miscellaneous informations. since there are lots of sibling
2651 // items (and that causes quadratic growth in large modules),
2652 // we refactor common parts into a shared JavaScript file per module.
2653 // still, we don't move everything into JS because we want to preserve
2654 // as much HTML as possible in order to allow non-JS-enabled browsers
2655 // to navigate the documentation (though slightly inefficiently).
2657 try!(write!(fmt, "<p class='location'>"));
2658 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
2660 try!(write!(fmt, "::<wbr>"));
2662 try!(write!(fmt, "<a href='{}index.html'>{}</a>",
2663 &cx.root_path[..(cx.current.len() - i - 1) * 3],
2666 try!(write!(fmt, "</p>"));
2668 // sidebar refers to the enclosing module, not this module
2669 let relpath = if shortty(it) == ItemType::Module { "../" } else { "" };
2671 "<script>window.sidebarCurrent = {{\
2676 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
2677 ty = shortty(it).to_static_str(),
2680 // there is no sidebar-items.js beyond the crate root path
2681 // FIXME maybe dynamic crate loading can be merged here
2683 try!(write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
2691 impl<'a> fmt::Display for Source<'a> {
2692 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2693 let Source(s) = *self;
2694 let lines = s.lines().count();
2696 let mut tmp = lines;
2701 try!(write!(fmt, "<pre class=\"line-numbers\">"));
2702 for i in 1..lines + 1 {
2703 try!(write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols));
2705 try!(write!(fmt, "</pre>"));
2706 try!(write!(fmt, "{}", highlight::highlight(s, None, None)));
2711 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2712 t: &clean::Macro) -> fmt::Result {
2713 try!(w.write_str(&highlight::highlight(&t.source,
2716 try!(render_stability_since_raw(w, it.stable_since(), None));
2720 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
2722 _p: &clean::PrimitiveType) -> fmt::Result {
2723 try!(document(w, cx, it));
2724 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2727 fn get_basic_keywords() -> &'static str {
2728 "rust, rustlang, rust-lang"
2731 fn make_item_keywords(it: &clean::Item) -> String {
2732 format!("{}, {}", get_basic_keywords(), it.name.as_ref().unwrap())
2735 fn get_index_search_type(item: &clean::Item,
2736 parent: Option<String>) -> Option<IndexItemFunctionType> {
2737 let decl = match item.inner {
2738 clean::FunctionItem(ref f) => &f.decl,
2739 clean::MethodItem(ref m) => &m.decl,
2740 clean::TyMethodItem(ref m) => &m.decl,
2744 let mut inputs = Vec::new();
2746 // Consider `self` an argument as well.
2747 if let Some(name) = parent {
2748 inputs.push(Type { name: Some(name.to_ascii_lowercase()) });
2751 inputs.extend(&mut decl.inputs.values.iter().map(|arg| {
2752 get_index_type(&arg.type_)
2755 let output = match decl.output {
2756 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
2760 Some(IndexItemFunctionType { inputs: inputs, output: output })
2763 fn get_index_type(clean_type: &clean::Type) -> Type {
2764 Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
2767 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
2769 clean::ResolvedPath { ref path, .. } => {
2770 let segments = &path.segments;
2771 Some(segments[segments.len() - 1].name.clone())
2773 clean::Generic(ref s) => Some(s.clone()),
2774 clean::Primitive(ref p) => Some(format!("{:?}", p)),
2775 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
2776 // FIXME: add all from clean::Type.
2781 pub fn cache() -> Arc<Cache> {
2782 CACHE_KEY.with(|c| c.borrow().clone())
2787 fn test_unique_id() {
2788 let input = ["foo", "examples", "examples", "method.into_iter","examples",
2789 "method.into_iter", "foo", "main", "search", "methods",
2790 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
2791 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
2792 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
2793 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
2796 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
2797 assert_eq!(&actual[..], expected);