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::{self, ToJson};
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 search_type: Option<IndexItemFunctionType>,
296 /// A type used for the search index.
298 name: Option<String>,
301 impl fmt::Display for Type {
302 /// Formats type as {name: $name}.
303 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
304 // Wrapping struct fmt should never call us when self.name is None,
305 // but just to be safe we write `null` in that case.
307 Some(ref n) => write!(f, "{{\"name\":\"{}\"}}", n),
308 None => write!(f, "null")
313 /// Full type of functions/methods in the search index.
314 struct IndexItemFunctionType {
319 impl fmt::Display for IndexItemFunctionType {
320 /// Formats a full fn type as a JSON {inputs: [Type], outputs: Type/null}.
321 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
322 // If we couldn't figure out a type, just write `null`.
323 if self.inputs.iter().any(|ref i| i.name.is_none()) ||
324 (self.output.is_some() && self.output.as_ref().unwrap().name.is_none()) {
325 return write!(f, "null")
328 let inputs: Vec<String> = self.inputs.iter().map(|ref t| {
331 try!(write!(f, "{{\"inputs\":[{}],\"output\":", inputs.join(",")));
334 Some(ref t) => try!(write!(f, "{}", t)),
335 None => try!(write!(f, "null"))
338 Ok(try!(write!(f, "}}")))
342 // TLS keys used to carry information around during rendering.
344 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
345 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
346 RefCell::new(Vec::new()));
347 thread_local!(static USED_ID_MAP: RefCell<HashMap<String, usize>> =
348 RefCell::new(init_ids()));
350 fn init_ids() -> HashMap<String, usize> {
366 "derived_implementations"
367 ].into_iter().map(|id| (String::from(*id), 1)).collect::<HashMap<_, _>>()
370 /// This method resets the local table of used ID attributes. This is typically
371 /// used at the beginning of rendering an entire HTML page to reset from the
372 /// previous state (if any).
374 USED_ID_MAP.with(|s| *s.borrow_mut() = init_ids());
377 pub fn derive_id(candidate: String) -> String {
378 USED_ID_MAP.with(|map| {
379 let id = match map.borrow_mut().get_mut(&candidate) {
382 let id = format!("{}-{}", candidate, *a);
388 map.borrow_mut().insert(id.clone(), 1);
393 /// Generates the documentation for `crate` into the directory `dst`
394 pub fn run(mut krate: clean::Crate,
395 external_html: &ExternalHtml,
397 passes: HashSet<String>) -> Result<(), Error> {
398 let src_root = match krate.src.parent() {
399 Some(p) => p.to_path_buf(),
400 None => PathBuf::new(),
402 let mut cx = Context {
407 root_path: String::new(),
408 layout: layout::Layout {
409 logo: "".to_string(),
410 favicon: "".to_string(),
411 external_html: external_html.clone(),
412 krate: krate.name.clone(),
413 playground_url: "".to_string(),
415 include_sources: true,
416 render_redirect_pages: false,
417 issue_tracker_base_url: None,
420 try_err!(mkdir(&cx.dst), &cx.dst);
422 // Crawl the crate attributes looking for attributes which control how we're
423 // going to emit HTML
424 let default: &[_] = &[];
425 match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(default)) {
429 clean::NameValue(ref x, ref s)
430 if "html_favicon_url" == *x => {
431 cx.layout.favicon = s.to_string();
433 clean::NameValue(ref x, ref s)
434 if "html_logo_url" == *x => {
435 cx.layout.logo = s.to_string();
437 clean::NameValue(ref x, ref s)
438 if "html_playground_url" == *x => {
439 cx.layout.playground_url = s.to_string();
440 markdown::PLAYGROUND_KRATE.with(|slot| {
441 if slot.borrow().is_none() {
442 let name = krate.name.clone();
443 *slot.borrow_mut() = Some(Some(name));
447 clean::NameValue(ref x, ref s)
448 if "issue_tracker_base_url" == *x => {
449 cx.issue_tracker_base_url = Some(s.to_string());
452 if "html_no_source" == *x => {
453 cx.include_sources = false;
462 // Crawl the crate to build various caches used for the output
463 let analysis = ::ANALYSISKEY.with(|a| a.clone());
464 let analysis = analysis.borrow();
465 let access_levels = analysis.as_ref().map(|a| a.access_levels.clone());
466 let access_levels = access_levels.unwrap_or(Default::default());
467 let paths: HashMap<DefId, (Vec<String>, ItemType)> =
468 analysis.as_ref().map(|a| {
469 let paths = a.external_paths.borrow_mut().take().unwrap();
470 paths.into_iter().map(|(k, (v, t))| (k, (v, ItemType::from_type_kind(t)))).collect()
471 }).unwrap_or(HashMap::new());
472 let mut cache = Cache {
473 impls: HashMap::new(),
474 external_paths: paths.iter().map(|(&k, v)| (k, v.0.clone()))
477 implementors: HashMap::new(),
479 parent_stack: Vec::new(),
480 search_index: Vec::new(),
481 extern_locations: HashMap::new(),
482 primitive_locations: HashMap::new(),
483 remove_priv: cx.passes.contains("strip-private"),
485 access_levels: access_levels,
486 orphan_methods: Vec::new(),
487 traits: mem::replace(&mut krate.external_traits, HashMap::new()),
488 deref_trait_did: analysis.as_ref().and_then(|a| a.deref_trait_did),
489 typarams: analysis.as_ref().map(|a| {
490 a.external_typarams.borrow_mut().take().unwrap()
491 }).unwrap_or(HashMap::new()),
492 inlined: analysis.as_ref().map(|a| {
493 a.inlined.borrow_mut().take().unwrap()
494 }).unwrap_or(HashSet::new()),
497 // Cache where all our extern crates are located
498 for &(n, ref e) in &krate.externs {
499 cache.extern_locations.insert(n, (e.name.clone(),
500 extern_location(e, &cx.dst)));
501 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
502 cache.paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
505 // Cache where all known primitives have their documentation located.
507 // Favor linking to as local extern as possible, so iterate all crates in
508 // reverse topological order.
509 for &(n, ref e) in krate.externs.iter().rev() {
510 for &prim in &e.primitives {
511 cache.primitive_locations.insert(prim, n);
514 for &prim in &krate.primitives {
515 cache.primitive_locations.insert(prim, LOCAL_CRATE);
518 cache.stack.push(krate.name.clone());
519 krate = cache.fold_crate(krate);
521 // Build our search index
522 let index = build_index(&krate, &mut cache);
524 // Freeze the cache now that the index has been built. Put an Arc into TLS
525 // for future parallelization opportunities
526 let cache = Arc::new(cache);
527 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
528 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
530 try!(write_shared(&cx, &krate, &*cache, index));
531 let krate = try!(render_sources(&mut cx, krate));
533 // And finally render the whole crate's documentation
537 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
538 // Build the search index from the collected metadata
539 let mut nodeid_to_pathid = HashMap::new();
540 let mut pathid_to_nodeid = Vec::new();
542 let Cache { ref mut search_index,
544 ref mut paths, .. } = *cache;
546 // Attach all orphan methods to the type's definition if the type
547 // has since been learned.
548 for &(did, ref item) in orphan_methods {
549 match paths.get(&did) {
550 Some(&(ref fqp, _)) => {
551 // Needed to determine `self` type.
552 let parent_basename = Some(fqp[fqp.len() - 1].clone());
553 search_index.push(IndexItem {
555 name: item.name.clone().unwrap(),
556 path: fqp[..fqp.len() - 1].join("::"),
557 desc: shorter(item.doc_value()),
559 search_type: get_index_search_type(&item, parent_basename),
566 // Reduce `NodeId` in paths into smaller sequential numbers,
567 // and prune the paths that do not appear in the index.
568 for item in search_index.iter() {
571 if !nodeid_to_pathid.contains_key(&nodeid) {
572 let pathid = pathid_to_nodeid.len();
573 nodeid_to_pathid.insert(nodeid, pathid);
574 pathid_to_nodeid.push(nodeid);
580 assert_eq!(nodeid_to_pathid.len(), pathid_to_nodeid.len());
583 // Collect the index into a string
584 let mut w = io::Cursor::new(Vec::new());
585 write!(&mut w, r#"searchIndex['{}'] = {{"items":["#, krate.name).unwrap();
587 let mut lastpath = "".to_string();
588 for (i, item) in cache.search_index.iter().enumerate() {
589 // Omit the path if it is same to that of the prior item.
591 if lastpath == item.path {
594 lastpath = item.path.to_string();
599 write!(&mut w, ",").unwrap();
601 write!(&mut w, r#"[{},"{}","{}",{}"#,
602 item.ty as usize, item.name, path,
603 item.desc.to_json().to_string()).unwrap();
606 let pathid = *nodeid_to_pathid.get(&nodeid).unwrap();
607 write!(&mut w, ",{}", pathid).unwrap();
609 None => write!(&mut w, ",null").unwrap()
611 match item.search_type {
612 Some(ref t) => write!(&mut w, ",{}", t).unwrap(),
613 None => write!(&mut w, ",null").unwrap()
615 write!(&mut w, "]").unwrap();
618 write!(&mut w, r#"],"paths":["#).unwrap();
620 for (i, &did) in pathid_to_nodeid.iter().enumerate() {
621 let &(ref fqp, short) = cache.paths.get(&did).unwrap();
623 write!(&mut w, ",").unwrap();
625 write!(&mut w, r#"[{},"{}"]"#,
626 short as usize, *fqp.last().unwrap()).unwrap();
629 write!(&mut w, "]}};").unwrap();
631 String::from_utf8(w.into_inner()).unwrap()
634 fn write_shared(cx: &Context,
635 krate: &clean::Crate,
637 search_index: String) -> Result<(), Error> {
638 // Write out the shared files. Note that these are shared among all rustdoc
639 // docs placed in the output directory, so this needs to be a synchronized
640 // operation with respect to all other rustdocs running around.
641 try_err!(mkdir(&cx.dst), &cx.dst);
642 let _lock = ::flock::Lock::new(&cx.dst.join(".lock"));
644 // Add all the static files. These may already exist, but we just
645 // overwrite them anyway to make sure that they're fresh and up-to-date.
646 try!(write(cx.dst.join("jquery.js"),
647 include_bytes!("static/jquery-2.1.4.min.js")));
648 try!(write(cx.dst.join("main.js"),
649 include_bytes!("static/main.js")));
650 try!(write(cx.dst.join("playpen.js"),
651 include_bytes!("static/playpen.js")));
652 try!(write(cx.dst.join("rustdoc.css"),
653 include_bytes!("static/rustdoc.css")));
654 try!(write(cx.dst.join("main.css"),
655 include_bytes!("static/styles/main.css")));
656 try!(write(cx.dst.join("normalize.css"),
657 include_bytes!("static/normalize.css")));
658 try!(write(cx.dst.join("FiraSans-Regular.woff"),
659 include_bytes!("static/FiraSans-Regular.woff")));
660 try!(write(cx.dst.join("FiraSans-Medium.woff"),
661 include_bytes!("static/FiraSans-Medium.woff")));
662 try!(write(cx.dst.join("FiraSans-LICENSE.txt"),
663 include_bytes!("static/FiraSans-LICENSE.txt")));
664 try!(write(cx.dst.join("Heuristica-Italic.woff"),
665 include_bytes!("static/Heuristica-Italic.woff")));
666 try!(write(cx.dst.join("Heuristica-LICENSE.txt"),
667 include_bytes!("static/Heuristica-LICENSE.txt")));
668 try!(write(cx.dst.join("SourceSerifPro-Regular.woff"),
669 include_bytes!("static/SourceSerifPro-Regular.woff")));
670 try!(write(cx.dst.join("SourceSerifPro-Bold.woff"),
671 include_bytes!("static/SourceSerifPro-Bold.woff")));
672 try!(write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
673 include_bytes!("static/SourceSerifPro-LICENSE.txt")));
674 try!(write(cx.dst.join("SourceCodePro-Regular.woff"),
675 include_bytes!("static/SourceCodePro-Regular.woff")));
676 try!(write(cx.dst.join("SourceCodePro-Semibold.woff"),
677 include_bytes!("static/SourceCodePro-Semibold.woff")));
678 try!(write(cx.dst.join("SourceCodePro-LICENSE.txt"),
679 include_bytes!("static/SourceCodePro-LICENSE.txt")));
680 try!(write(cx.dst.join("LICENSE-MIT.txt"),
681 include_bytes!("static/LICENSE-MIT.txt")));
682 try!(write(cx.dst.join("LICENSE-APACHE.txt"),
683 include_bytes!("static/LICENSE-APACHE.txt")));
684 try!(write(cx.dst.join("COPYRIGHT.txt"),
685 include_bytes!("static/COPYRIGHT.txt")));
687 fn collect(path: &Path, krate: &str,
688 key: &str) -> io::Result<Vec<String>> {
689 let mut ret = Vec::new();
691 for line in BufReader::new(try!(File::open(path))).lines() {
692 let line = try!(line);
693 if !line.starts_with(key) {
696 if line.starts_with(&format!("{}['{}']", key, krate)) {
699 ret.push(line.to_string());
705 // Update the search index
706 let dst = cx.dst.join("search-index.js");
707 let all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
708 let mut w = try_err!(File::create(&dst), &dst);
709 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
710 try_err!(writeln!(&mut w, "{}", search_index), &dst);
711 for index in &all_indexes {
712 try_err!(writeln!(&mut w, "{}", *index), &dst);
714 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
716 // Update the list of all implementors for traits
717 let dst = cx.dst.join("implementors");
718 try_err!(mkdir(&dst), &dst);
719 for (&did, imps) in &cache.implementors {
720 // Private modules can leak through to this phase of rustdoc, which
721 // could contain implementations for otherwise private types. In some
722 // rare cases we could find an implementation for an item which wasn't
723 // indexed, so we just skip this step in that case.
725 // FIXME: this is a vague explanation for why this can't be a `get`, in
726 // theory it should be...
727 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
732 let mut mydst = dst.clone();
733 for part in &remote_path[..remote_path.len() - 1] {
735 try_err!(mkdir(&mydst), &mydst);
737 mydst.push(&format!("{}.{}.js",
738 remote_item_type.to_static_str(),
739 remote_path[remote_path.len() - 1]));
740 let all_implementors = try_err!(collect(&mydst, &krate.name,
744 try_err!(mkdir(mydst.parent().unwrap()),
745 &mydst.parent().unwrap().to_path_buf());
746 let mut f = BufWriter::new(try_err!(File::create(&mydst), &mydst));
747 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
749 for implementor in &all_implementors {
750 try_err!(write!(&mut f, "{}", *implementor), &mydst);
753 try_err!(write!(&mut f, r"implementors['{}'] = [", krate.name), &mydst);
755 // If the trait and implementation are in the same crate, then
756 // there's no need to emit information about it (there's inlining
757 // going on). If they're in different crates then the crate defining
758 // the trait will be interested in our implementation.
759 if imp.def_id.krate == did.krate { continue }
760 try_err!(write!(&mut f, r#""{}","#, imp.impl_), &mydst);
762 try_err!(writeln!(&mut f, r"];"), &mydst);
763 try_err!(writeln!(&mut f, "{}", r"
764 if (window.register_implementors) {
765 window.register_implementors(implementors);
767 window.pending_implementors = implementors;
770 try_err!(writeln!(&mut f, r"}})()"), &mydst);
775 fn render_sources(cx: &mut Context,
776 krate: clean::Crate) -> Result<clean::Crate, Error> {
777 info!("emitting source files");
778 let dst = cx.dst.join("src");
779 try_err!(mkdir(&dst), &dst);
780 let dst = dst.join(&krate.name);
781 try_err!(mkdir(&dst), &dst);
782 let mut folder = SourceCollector {
784 seen: HashSet::new(),
787 // skip all invalid spans
788 folder.seen.insert("".to_string());
789 Ok(folder.fold_crate(krate))
792 /// Writes the entire contents of a string to a destination, not attempting to
793 /// catch any errors.
794 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
795 Ok(try_err!(try_err!(File::create(&dst), &dst).write_all(contents), &dst))
798 /// Makes a directory on the filesystem, failing the thread if an error occurs and
799 /// skipping if the directory already exists.
800 fn mkdir(path: &Path) -> io::Result<()> {
808 /// Returns a documentation-level item type from the item.
809 fn shortty(item: &clean::Item) -> ItemType {
810 ItemType::from_item(item)
813 /// Takes a path to a source file and cleans the path to it. This canonicalizes
814 /// things like ".." to components which preserve the "top down" hierarchy of a
815 /// static HTML tree. Each component in the cleaned path will be passed as an
816 /// argument to `f`. The very last component of the path (ie the file name) will
817 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
818 // FIXME (#9639): The closure should deal with &[u8] instead of &str
819 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
820 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
823 // make it relative, if possible
824 let p = p.strip_prefix(src_root).unwrap_or(p);
826 let mut iter = p.iter().map(|x| x.to_str().unwrap()).peekable();
827 while let Some(c) = iter.next() {
828 if !keep_filename && iter.peek().is_none() {
840 /// Attempts to find where an external crate is located, given that we're
841 /// rendering in to the specified source destination.
842 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
843 // See if there's documentation generated into the local directory
844 let local_location = dst.join(&e.name);
845 if local_location.is_dir() {
849 // Failing that, see if there's an attribute specifying where to find this
851 for attr in &e.attrs {
853 clean::List(ref x, ref list) if "doc" == *x => {
856 clean::NameValue(ref x, ref s)
857 if "html_root_url" == *x => {
858 if s.ends_with("/") {
859 return Remote(s.to_string());
861 return Remote(format!("{}/", s));
871 // Well, at least we tried.
875 impl<'a> DocFolder for SourceCollector<'a> {
876 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
877 // If we're including source files, and we haven't seen this file yet,
878 // then we need to render it out to the filesystem
879 if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
881 // If it turns out that we couldn't read this file, then we probably
882 // can't read any of the files (generating html output from json or
883 // something like that), so just don't include sources for the
884 // entire crate. The other option is maintaining this mapping on a
885 // per-file basis, but that's probably not worth it...
887 .include_sources = match self.emit_source(&item.source .filename) {
890 println!("warning: source code was requested to be rendered, \
891 but processing `{}` had an error: {}",
892 item.source.filename, e);
893 println!(" skipping rendering of source code");
897 self.seen.insert(item.source.filename.clone());
900 self.fold_item_recur(item)
904 impl<'a> SourceCollector<'a> {
905 /// Renders the given filename into its corresponding HTML source file.
906 fn emit_source(&mut self, filename: &str) -> io::Result<()> {
907 let p = PathBuf::from(filename);
909 // If we couldn't open this file, then just returns because it
910 // probably means that it's some standard library macro thing and we
911 // can't have the source to it anyway.
912 let mut contents = Vec::new();
913 match File::open(&p).and_then(|mut f| f.read_to_end(&mut contents)) {
915 // macros from other libraries get special filenames which we can
917 Err(..) if filename.starts_with("<") &&
918 filename.ends_with("macros>") => return Ok(()),
919 Err(e) => return Err(e)
921 let contents = str::from_utf8(&contents).unwrap();
923 // Remove the utf-8 BOM if any
924 let contents = if contents.starts_with("\u{feff}") {
930 // Create the intermediate directories
931 let mut cur = self.dst.clone();
932 let mut root_path = String::from("../../");
933 clean_srcpath(&self.cx.src_root, &p, false, |component| {
935 mkdir(&cur).unwrap();
936 root_path.push_str("../");
939 let mut fname = p.file_name().expect("source has no filename")
942 cur.push(&fname[..]);
943 let mut w = BufWriter::new(try!(File::create(&cur)));
944 let title = format!("{} -- source", cur.file_name().unwrap()
946 let desc = format!("Source to the Rust file `{}`.", filename);
947 let page = layout::Page {
950 root_path: &root_path,
952 keywords: get_basic_keywords(),
954 try!(layout::render(&mut w, &self.cx.layout,
955 &page, &(""), &Source(contents)));
961 impl DocFolder for Cache {
962 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
963 // If this is a private module, we don't want it in the search index.
964 let orig_privmod = match item.inner {
965 clean::ModuleItem(..) => {
966 let prev = self.privmod;
967 self.privmod = prev || (self.remove_priv && item.visibility != Some(hir::Public));
973 // Register any generics to their corresponding string. This is used
974 // when pretty-printing types
976 clean::StructItem(ref s) => self.generics(&s.generics),
977 clean::EnumItem(ref e) => self.generics(&e.generics),
978 clean::FunctionItem(ref f) => self.generics(&f.generics),
979 clean::TypedefItem(ref t, _) => self.generics(&t.generics),
980 clean::TraitItem(ref t) => self.generics(&t.generics),
981 clean::ImplItem(ref i) => self.generics(&i.generics),
982 clean::TyMethodItem(ref i) => self.generics(&i.generics),
983 clean::MethodItem(ref i) => self.generics(&i.generics),
984 clean::ForeignFunctionItem(ref f) => self.generics(&f.generics),
988 // Propagate a trait methods' documentation to all implementors of the
990 if let clean::TraitItem(ref t) = item.inner {
991 self.traits.insert(item.def_id, t.clone());
994 // Collect all the implementors of traits.
995 if let clean::ImplItem(ref i) = item.inner {
997 Some(clean::ResolvedPath{ did, .. }) => {
998 self.implementors.entry(did).or_insert(vec![]).push(Implementor {
1000 stability: item.stability.clone(),
1004 Some(..) | None => {}
1008 // Index this method for searching later on
1009 if let Some(ref s) = item.name {
1010 let (parent, is_method) = match item.inner {
1011 clean::AssociatedTypeItem(..) |
1012 clean::AssociatedConstItem(..) |
1013 clean::TyMethodItem(..) |
1014 clean::StructFieldItem(..) |
1015 clean::VariantItem(..) => {
1016 ((Some(*self.parent_stack.last().unwrap()),
1017 Some(&self.stack[..self.stack.len() - 1])),
1020 clean::MethodItem(..) => {
1021 if self.parent_stack.is_empty() {
1022 ((None, None), false)
1024 let last = self.parent_stack.last().unwrap();
1026 let path = match self.paths.get(&did) {
1027 Some(&(_, ItemType::Trait)) =>
1028 Some(&self.stack[..self.stack.len() - 1]),
1029 // The current stack not necessarily has correlation
1030 // for where the type was defined. On the other
1031 // hand, `paths` always has the right
1032 // information if present.
1033 Some(&(ref fqp, ItemType::Struct)) |
1034 Some(&(ref fqp, ItemType::Enum)) =>
1035 Some(&fqp[..fqp.len() - 1]),
1036 Some(..) => Some(&*self.stack),
1039 ((Some(*last), path), true)
1042 clean::TypedefItem(_, true) => {
1043 // skip associated types in impls
1044 ((None, None), false)
1046 _ => ((None, Some(&*self.stack)), false)
1048 let hidden_field = match item.inner {
1049 clean::StructFieldItem(clean::HiddenStructField) => true,
1054 (parent, Some(path)) if is_method || (!self.privmod && !hidden_field) => {
1055 // Needed to determine `self` type.
1056 let parent_basename = self.parent_stack.first().and_then(|parent| {
1057 match self.paths.get(parent) {
1058 Some(&(ref fqp, _)) => Some(fqp[fqp.len() - 1].clone()),
1063 if item.def_id.index != CRATE_DEF_INDEX {
1064 self.search_index.push(IndexItem {
1066 name: s.to_string(),
1067 path: path.join("::").to_string(),
1068 desc: shorter(item.doc_value()),
1070 search_type: get_index_search_type(&item, parent_basename),
1074 (Some(parent), None) if is_method || (!self.privmod && !hidden_field)=> {
1075 if parent.is_local() {
1076 // We have a parent, but we don't know where they're
1077 // defined yet. Wait for later to index this item.
1078 self.orphan_methods.push((parent, item.clone()))
1085 // Keep track of the fully qualified path for this item.
1086 let pushed = if item.name.is_some() {
1087 let n = item.name.as_ref().unwrap();
1089 self.stack.push(n.to_string());
1094 clean::StructItem(..) | clean::EnumItem(..) |
1095 clean::TypedefItem(..) | clean::TraitItem(..) |
1096 clean::FunctionItem(..) | clean::ModuleItem(..) |
1097 clean::ForeignFunctionItem(..) if !self.privmod => {
1098 // Reexported items mean that the same id can show up twice
1099 // in the rustdoc ast that we're looking at. We know,
1100 // however, that a reexported item doesn't show up in the
1101 // `public_items` map, so we can skip inserting into the
1102 // paths map if there was already an entry present and we're
1103 // not a public item.
1105 !self.paths.contains_key(&item.def_id) ||
1106 !item.def_id.is_local() ||
1107 self.access_levels.is_public(item.def_id)
1109 self.paths.insert(item.def_id,
1110 (self.stack.clone(), shortty(&item)));
1113 // link variants to their parent enum because pages aren't emitted
1115 clean::VariantItem(..) if !self.privmod => {
1116 let mut stack = self.stack.clone();
1118 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1121 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1122 self.paths.insert(item.def_id, (self.stack.clone(),
1129 // Maintain the parent stack
1130 let parent_pushed = match item.inner {
1131 clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
1132 self.parent_stack.push(item.def_id);
1135 clean::ImplItem(ref i) => {
1137 clean::ResolvedPath{ did, .. } => {
1138 self.parent_stack.push(did);
1142 match t.primitive_type() {
1144 let did = DefId::local(prim.to_def_index());
1145 self.parent_stack.push(did);
1156 // Once we've recursively found all the generics, then hoard off all the
1157 // implementations elsewhere
1158 let ret = match self.fold_item_recur(item) {
1161 clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
1162 // extract relevant documentation for this impl
1163 let dox = match attrs.into_iter().find(|a| {
1165 clean::NameValue(ref x, _)
1172 Some(clean::NameValue(_, dox)) => Some(dox),
1173 Some(..) | None => None,
1176 // Figure out the id of this impl. This may map to a
1177 // primitive rather than always to a struct/enum.
1178 let did = match i.for_ {
1179 clean::ResolvedPath { did, .. } |
1180 clean::BorrowedRef {
1181 type_: box clean::ResolvedPath { did, .. }, ..
1187 t.primitive_type().and_then(|t| {
1188 self.primitive_locations.get(&t).map(|n| {
1189 let id = t.to_def_index();
1190 DefId { krate: *n, index: id }
1196 if let Some(did) = did {
1197 self.impls.entry(did).or_insert(vec![]).push(Impl {
1200 stability: item.stability.clone(),
1213 if pushed { self.stack.pop().unwrap(); }
1214 if parent_pushed { self.parent_stack.pop().unwrap(); }
1215 self.privmod = orig_privmod;
1221 fn generics(&mut self, generics: &clean::Generics) {
1222 for typ in &generics.type_params {
1223 self.typarams.insert(typ.did, typ.name.clone());
1229 /// Recurse in the directory structure and change the "root path" to make
1230 /// sure it always points to the top (relatively)
1231 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1232 F: FnOnce(&mut Context) -> T,
1235 panic!("Unexpected empty destination: {:?}", self.current);
1237 let prev = self.dst.clone();
1239 self.root_path.push_str("../");
1240 self.current.push(s);
1242 info!("Recursing into {}", self.dst.display());
1244 mkdir(&self.dst).unwrap();
1247 info!("Recursed; leaving {}", self.dst.display());
1249 // Go back to where we were at
1251 let len = self.root_path.len();
1252 self.root_path.truncate(len - 3);
1253 self.current.pop().unwrap();
1258 /// Main method for rendering a crate.
1260 /// This currently isn't parallelized, but it'd be pretty easy to add
1261 /// parallelization to this function.
1262 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1263 let mut item = match krate.module.take() {
1265 None => return Ok(())
1267 item.name = Some(krate.name);
1269 // render the crate documentation
1270 let mut work = vec!((self, item));
1273 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
1274 work.push((cx.clone(), item));
1283 /// Non-parallelized version of rendering an item. This will take the input
1284 /// item, render its contents, and then invoke the specified closure with
1285 /// all sub-items which need to be rendered.
1287 /// The rendering driver uses this closure to queue up more work.
1288 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1289 F: FnMut(&mut Context, clean::Item),
1291 fn render(w: File, cx: &Context, it: &clean::Item,
1292 pushname: bool) -> io::Result<()> {
1293 // A little unfortunate that this is done like this, but it sure
1294 // does make formatting *a lot* nicer.
1295 CURRENT_LOCATION_KEY.with(|slot| {
1296 *slot.borrow_mut() = cx.current.clone();
1299 let mut title = cx.current.join("::");
1301 if !title.is_empty() {
1302 title.push_str("::");
1304 title.push_str(it.name.as_ref().unwrap());
1306 title.push_str(" - Rust");
1307 let tyname = shortty(it).to_static_str();
1308 let is_crate = match it.inner {
1309 clean::ModuleItem(clean::Module { items: _, is_crate: true }) => true,
1312 let desc = if is_crate {
1313 format!("API documentation for the Rust `{}` crate.",
1316 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1317 it.name.as_ref().unwrap(), tyname, cx.layout.krate)
1319 let keywords = make_item_keywords(it);
1320 let page = layout::Page {
1322 root_path: &cx.root_path,
1325 keywords: &keywords,
1330 // We have a huge number of calls to write, so try to alleviate some
1331 // of the pain by using a buffered writer instead of invoking the
1332 // write syscall all the time.
1333 let mut writer = BufWriter::new(w);
1334 if !cx.render_redirect_pages {
1335 try!(layout::render(&mut writer, &cx.layout, &page,
1336 &Sidebar{ cx: cx, item: it },
1337 &Item{ cx: cx, item: it }));
1339 let mut url = repeat("../").take(cx.current.len())
1340 .collect::<String>();
1341 match cache().paths.get(&it.def_id) {
1342 Some(&(ref names, _)) => {
1343 for name in &names[..names.len() - 1] {
1347 url.push_str(&item_path(it));
1348 try!(layout::redirect(&mut writer, &url));
1356 // Private modules may survive the strip-private pass if they
1357 // contain impls for public types. These modules can also
1358 // contain items such as publicly reexported structures.
1360 // External crates will provide links to these structures, so
1361 // these modules are recursed into, but not rendered normally (a
1362 // flag on the context).
1363 if !self.render_redirect_pages {
1364 self.render_redirect_pages = self.ignore_private_item(&item);
1368 // modules are special because they add a namespace. We also need to
1369 // recurse into the items of the module as well.
1370 clean::ModuleItem(..) => {
1371 let name = item.name.as_ref().unwrap().to_string();
1372 let mut item = Some(item);
1373 self.recurse(name, |this| {
1374 let item = item.take().unwrap();
1375 let joint_dst = this.dst.join("index.html");
1376 let dst = try_err!(File::create(&joint_dst), &joint_dst);
1377 try_err!(render(dst, this, &item, false), &joint_dst);
1379 let m = match item.inner {
1380 clean::ModuleItem(m) => m,
1384 // render sidebar-items.js used throughout this module
1386 let items = this.build_sidebar_items(&m);
1387 let js_dst = this.dst.join("sidebar-items.js");
1388 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1389 try_err!(write!(&mut js_out, "initSidebarItems({});",
1390 json::as_json(&items)), &js_dst);
1393 for item in m.items {
1400 // Things which don't have names (like impls) don't get special
1401 // pages dedicated to them.
1402 _ if item.name.is_some() => {
1403 let joint_dst = self.dst.join(&item_path(&item));
1405 let dst = try_err!(File::create(&joint_dst), &joint_dst);
1406 try_err!(render(dst, self, &item, true), &joint_dst);
1414 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1415 // BTreeMap instead of HashMap to get a sorted output
1416 let mut map = BTreeMap::new();
1417 for item in &m.items {
1418 if self.ignore_private_item(item) { continue }
1420 let short = shortty(item).to_static_str();
1421 let myname = match item.name {
1423 Some(ref s) => s.to_string(),
1425 let short = short.to_string();
1426 map.entry(short).or_insert(vec![])
1427 .push((myname, Some(plain_summary_line(item.doc_value()))));
1430 for (_, items) in &mut map {
1436 fn ignore_private_item(&self, it: &clean::Item) -> bool {
1438 clean::ModuleItem(ref m) => {
1439 (m.items.is_empty() &&
1440 it.doc_value().is_none() &&
1441 it.visibility != Some(hir::Public)) ||
1442 (self.passes.contains("strip-private") && it.visibility != Some(hir::Public))
1444 clean::PrimitiveItem(..) => it.visibility != Some(hir::Public),
1451 fn ismodule(&self) -> bool {
1452 match self.item.inner {
1453 clean::ModuleItem(..) => true, _ => false
1457 /// Generate a url appropriate for an `href` attribute back to the source of
1460 /// The url generated, when clicked, will redirect the browser back to the
1461 /// original source code.
1463 /// If `None` is returned, then a source link couldn't be generated. This
1464 /// may happen, for example, with externally inlined items where the source
1465 /// of their crate documentation isn't known.
1466 fn href(&self, cx: &Context) -> Option<String> {
1467 let href = if self.item.source.loline == self.item.source.hiline {
1468 format!("{}", self.item.source.loline)
1470 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1473 // First check to see if this is an imported macro source. In this case
1474 // we need to handle it specially as cross-crate inlined macros have...
1476 let imported_macro_from = match self.item.inner {
1477 clean::MacroItem(ref m) => m.imported_from.as_ref(),
1480 if let Some(krate) = imported_macro_from {
1481 let cache = cache();
1482 let root = cache.extern_locations.values().find(|&&(ref n, _)| {
1485 let root = match root {
1486 Some(&Remote(ref s)) => s.to_string(),
1487 Some(&Local) => self.cx.root_path.clone(),
1488 None | Some(&Unknown) => return None,
1490 Some(format!("{root}/{krate}/macro.{name}.html?gotomacrosrc=1",
1493 name = self.item.name.as_ref().unwrap()))
1495 // If this item is part of the local crate, then we're guaranteed to
1496 // know the span, so we plow forward and generate a proper url. The url
1497 // has anchors for the line numbers that we're linking to.
1498 } else if self.item.def_id.is_local() {
1499 let mut path = Vec::new();
1500 clean_srcpath(&cx.src_root, Path::new(&self.item.source.filename),
1502 path.push(component.to_string());
1504 Some(format!("{root}src/{krate}/{path}.html#{href}",
1505 root = self.cx.root_path,
1506 krate = self.cx.layout.krate,
1507 path = path.join("/"),
1510 // If this item is not part of the local crate, then things get a little
1511 // trickier. We don't actually know the span of the external item, but
1512 // we know that the documentation on the other end knows the span!
1514 // In this case, we generate a link to the *documentation* for this type
1515 // in the original crate. There's an extra URL parameter which says that
1516 // we want to go somewhere else, and the JS on the destination page will
1517 // pick it up and instantly redirect the browser to the source code.
1519 // If we don't know where the external documentation for this crate is
1520 // located, then we return `None`.
1522 let cache = cache();
1523 let path = &cache.external_paths[&self.item.def_id];
1524 let root = match cache.extern_locations[&self.item.def_id.krate] {
1525 (_, Remote(ref s)) => s.to_string(),
1526 (_, Local) => self.cx.root_path.clone(),
1527 (_, Unknown) => return None,
1529 Some(format!("{root}{path}/{file}?gotosrc={goto}",
1531 path = path[..path.len() - 1].join("/"),
1532 file = item_path(self.item),
1533 goto = self.item.def_id.index.as_usize()))
1539 impl<'a> fmt::Display for Item<'a> {
1540 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1541 // Write the breadcrumb trail header for the top
1542 try!(write!(fmt, "\n<h1 class='fqn'><span class='in-band'>"));
1543 match self.item.inner {
1544 clean::ModuleItem(ref m) => if m.is_crate {
1545 try!(write!(fmt, "Crate "));
1547 try!(write!(fmt, "Module "));
1549 clean::FunctionItem(..) => try!(write!(fmt, "Function ")),
1550 clean::TraitItem(..) => try!(write!(fmt, "Trait ")),
1551 clean::StructItem(..) => try!(write!(fmt, "Struct ")),
1552 clean::EnumItem(..) => try!(write!(fmt, "Enum ")),
1553 clean::PrimitiveItem(..) => try!(write!(fmt, "Primitive Type ")),
1556 let is_primitive = match self.item.inner {
1557 clean::PrimitiveItem(..) => true,
1561 let cur = &self.cx.current;
1562 let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
1563 for (i, component) in cur.iter().enumerate().take(amt) {
1564 try!(write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1565 repeat("../").take(cur.len() - i - 1)
1566 .collect::<String>(),
1570 try!(write!(fmt, "<a class='{}' href=''>{}</a>",
1571 shortty(self.item), self.item.name.as_ref().unwrap()));
1573 try!(write!(fmt, "</span>")); // in-band
1574 try!(write!(fmt, "<span class='out-of-band'>"));
1576 r##"<span id='render-detail'>
1577 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1578 [<span class='inner'>−</span>]
1584 // When this item is part of a `pub use` in a downstream crate, the
1585 // [src] link in the downstream documentation will actually come back to
1586 // this page, and this link will be auto-clicked. The `id` attribute is
1587 // used to find the link to auto-click.
1588 if self.cx.include_sources && !is_primitive {
1589 match self.href(self.cx) {
1591 try!(write!(fmt, "<a id='src-{}' class='srclink' \
1592 href='{}' title='{}'>[src]</a>",
1593 self.item.def_id.index.as_usize(), l, "goto source code"));
1599 try!(write!(fmt, "</span>")); // out-of-band
1601 try!(write!(fmt, "</h1>\n"));
1603 match self.item.inner {
1604 clean::ModuleItem(ref m) => {
1605 item_module(fmt, self.cx, self.item, &m.items)
1607 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1608 item_function(fmt, self.cx, self.item, f),
1609 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1610 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1611 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1612 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1613 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1614 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1615 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1616 item_static(fmt, self.cx, self.item, i),
1617 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1623 fn item_path(item: &clean::Item) -> String {
1625 clean::ModuleItem(..) => {
1626 format!("{}/index.html", item.name.as_ref().unwrap())
1629 format!("{}.{}.html",
1630 shortty(item).to_static_str(),
1631 *item.name.as_ref().unwrap())
1636 fn full_path(cx: &Context, item: &clean::Item) -> String {
1637 let mut s = cx.current.join("::");
1639 s.push_str(item.name.as_ref().unwrap());
1643 fn shorter<'a>(s: Option<&'a str>) -> String {
1645 Some(s) => s.lines().take_while(|line|{
1646 (*line).chars().any(|chr|{
1647 !chr.is_whitespace()
1649 }).collect::<Vec<_>>().join("\n"),
1650 None => "".to_string()
1655 fn plain_summary_line(s: Option<&str>) -> String {
1656 let line = shorter(s).replace("\n", " ");
1657 markdown::plain_summary_line(&line[..])
1660 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1661 if let Some(s) = short_stability(item, cx, true) {
1662 try!(write!(w, "<div class='stability'>{}</div>", s));
1664 if let Some(s) = item.doc_value() {
1665 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1670 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1671 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1672 try!(document(w, cx, item));
1674 let mut indices = (0..items.len()).filter(|i| {
1675 !cx.ignore_private_item(&items[*i])
1676 }).collect::<Vec<usize>>();
1678 // the order of item types in the listing
1679 fn reorder(ty: ItemType) -> u8 {
1681 ItemType::ExternCrate => 0,
1682 ItemType::Import => 1,
1683 ItemType::Primitive => 2,
1684 ItemType::Module => 3,
1685 ItemType::Macro => 4,
1686 ItemType::Struct => 5,
1687 ItemType::Enum => 6,
1688 ItemType::Constant => 7,
1689 ItemType::Static => 8,
1690 ItemType::Trait => 9,
1691 ItemType::Function => 10,
1692 ItemType::Typedef => 12,
1697 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1698 let ty1 = shortty(i1);
1699 let ty2 = shortty(i2);
1701 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1703 let s1 = i1.stability.as_ref().map(|s| s.level);
1704 let s2 = i2.stability.as_ref().map(|s| s.level);
1706 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1707 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1710 i1.name.cmp(&i2.name)
1713 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1715 debug!("{:?}", indices);
1716 let mut curty = None;
1717 for &idx in &indices {
1718 let myitem = &items[idx];
1720 let myty = Some(shortty(myitem));
1721 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1722 // Put `extern crate` and `use` re-exports in the same section.
1724 } else if myty != curty {
1725 if curty.is_some() {
1726 try!(write!(w, "</table>"));
1729 let (short, name) = match myty.unwrap() {
1730 ItemType::ExternCrate |
1731 ItemType::Import => ("reexports", "Reexports"),
1732 ItemType::Module => ("modules", "Modules"),
1733 ItemType::Struct => ("structs", "Structs"),
1734 ItemType::Enum => ("enums", "Enums"),
1735 ItemType::Function => ("functions", "Functions"),
1736 ItemType::Typedef => ("types", "Type Definitions"),
1737 ItemType::Static => ("statics", "Statics"),
1738 ItemType::Constant => ("constants", "Constants"),
1739 ItemType::Trait => ("traits", "Traits"),
1740 ItemType::Impl => ("impls", "Implementations"),
1741 ItemType::TyMethod => ("tymethods", "Type Methods"),
1742 ItemType::Method => ("methods", "Methods"),
1743 ItemType::StructField => ("fields", "Struct Fields"),
1744 ItemType::Variant => ("variants", "Variants"),
1745 ItemType::Macro => ("macros", "Macros"),
1746 ItemType::Primitive => ("primitives", "Primitive Types"),
1747 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1748 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1750 try!(write!(w, "<h2 id='{id}' class='section-header'>\
1751 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1752 id = derive_id(short.to_owned()), name = name));
1755 match myitem.inner {
1756 clean::ExternCrateItem(ref name, ref src) => {
1759 try!(write!(w, "<tr><td><code>{}extern crate {} as {};",
1760 VisSpace(myitem.visibility),
1765 try!(write!(w, "<tr><td><code>{}extern crate {};",
1766 VisSpace(myitem.visibility), name))
1769 try!(write!(w, "</code></td></tr>"));
1772 clean::ImportItem(ref import) => {
1773 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1774 VisSpace(myitem.visibility), *import));
1778 if myitem.name.is_none() { continue }
1779 let stab_docs = if let Some(s) = short_stability(myitem, cx, false) {
1785 <tr class='{stab} module-item'>
1786 <td><a class='{class}' href='{href}'
1787 title='{title}'>{name}</a></td>
1788 <td class='docblock short'>
1793 name = *myitem.name.as_ref().unwrap(),
1794 stab_docs = stab_docs,
1795 docs = Markdown(&shorter(myitem.doc_value())),
1796 class = shortty(myitem),
1797 stab = myitem.stability_class(),
1798 href = item_path(myitem),
1799 title = full_path(cx, myitem)));
1804 write!(w, "</table>")
1807 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Option<String> {
1808 let mut result = item.stability.as_ref().and_then(|stab| {
1809 let reason = if show_reason && !stab.reason.is_empty() {
1810 format!(": {}", stab.reason)
1814 let text = if !stab.deprecated_since.is_empty() {
1815 let since = if show_reason {
1816 format!(" since {}", Escape(&stab.deprecated_since))
1820 format!("Deprecated{}{}", since, Markdown(&reason))
1821 } else if stab.level == stability::Unstable {
1822 let unstable_extra = if show_reason {
1823 match (!stab.feature.is_empty(), &cx.issue_tracker_base_url, stab.issue) {
1824 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1825 format!(" (<code>{}</code> <a href=\"{}{}\">#{}</a>)",
1826 Escape(&stab.feature), tracker_url, issue_no, issue_no),
1827 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1828 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
1831 format!(" (<code>{}</code>)", Escape(&stab.feature)),
1837 format!("Unstable{}{}", unstable_extra, Markdown(&reason))
1841 Some(format!("<em class='stab {}'>{}</em>",
1842 item.stability_class(), text))
1845 if result.is_none() {
1846 result = item.deprecation.as_ref().and_then(|depr| {
1847 let note = if show_reason && !depr.note.is_empty() {
1848 format!(": {}", depr.note)
1852 let since = if show_reason && !depr.since.is_empty() {
1853 format!(" since {}", Escape(&depr.since))
1858 let text = format!("Deprecated{}{}", since, Markdown(¬e));
1859 Some(format!("<em class='stab deprecated'>{}</em>", text))
1866 struct Initializer<'a>(&'a str);
1868 impl<'a> fmt::Display for Initializer<'a> {
1869 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1870 let Initializer(s) = *self;
1871 if s.is_empty() { return Ok(()); }
1872 try!(write!(f, "<code> = </code>"));
1873 write!(f, "<code>{}</code>", s)
1877 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1878 c: &clean::Constant) -> fmt::Result {
1879 try!(write!(w, "<pre class='rust const'>{vis}const \
1880 {name}: {typ}{init}</pre>",
1881 vis = VisSpace(it.visibility),
1882 name = it.name.as_ref().unwrap(),
1884 init = Initializer(&c.expr)));
1888 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1889 s: &clean::Static) -> fmt::Result {
1890 try!(write!(w, "<pre class='rust static'>{vis}static {mutability}\
1891 {name}: {typ}{init}</pre>",
1892 vis = VisSpace(it.visibility),
1893 mutability = MutableSpace(s.mutability),
1894 name = it.name.as_ref().unwrap(),
1896 init = Initializer(&s.expr)));
1900 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1901 f: &clean::Function) -> fmt::Result {
1902 let vis_constness = match get_unstable_features_setting() {
1903 UnstableFeatures::Allow => f.constness,
1904 _ => hir::Constness::NotConst
1906 try!(write!(w, "<pre class='rust fn'>{vis}{constness}{unsafety}{abi}fn \
1907 {name}{generics}{decl}{where_clause}</pre>",
1908 vis = VisSpace(it.visibility),
1909 constness = ConstnessSpace(vis_constness),
1910 unsafety = UnsafetySpace(f.unsafety),
1911 abi = AbiSpace(f.abi),
1912 name = it.name.as_ref().unwrap(),
1913 generics = f.generics,
1914 where_clause = WhereClause(&f.generics),
1919 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1920 t: &clean::Trait) -> fmt::Result {
1921 let mut bounds = String::new();
1922 if !t.bounds.is_empty() {
1923 if !bounds.is_empty() {
1926 bounds.push_str(": ");
1927 for (i, p) in t.bounds.iter().enumerate() {
1928 if i > 0 { bounds.push_str(" + "); }
1929 bounds.push_str(&format!("{}", *p));
1933 // Output the trait definition
1934 try!(write!(w, "<pre class='rust trait'>{}{}trait {}{}{}{} ",
1935 VisSpace(it.visibility),
1936 UnsafetySpace(t.unsafety),
1937 it.name.as_ref().unwrap(),
1940 WhereClause(&t.generics)));
1942 let types = t.items.iter().filter(|m| {
1943 match m.inner { clean::AssociatedTypeItem(..) => true, _ => false }
1944 }).collect::<Vec<_>>();
1945 let consts = t.items.iter().filter(|m| {
1946 match m.inner { clean::AssociatedConstItem(..) => true, _ => false }
1947 }).collect::<Vec<_>>();
1948 let required = t.items.iter().filter(|m| {
1949 match m.inner { clean::TyMethodItem(_) => true, _ => false }
1950 }).collect::<Vec<_>>();
1951 let provided = t.items.iter().filter(|m| {
1952 match m.inner { clean::MethodItem(_) => true, _ => false }
1953 }).collect::<Vec<_>>();
1955 if t.items.is_empty() {
1956 try!(write!(w, "{{ }}"));
1958 try!(write!(w, "{{\n"));
1960 try!(write!(w, " "));
1961 try!(render_assoc_item(w, t, AssocItemLink::Anchor));
1962 try!(write!(w, ";\n"));
1964 if !types.is_empty() && !consts.is_empty() {
1965 try!(w.write_str("\n"));
1968 try!(write!(w, " "));
1969 try!(render_assoc_item(w, t, AssocItemLink::Anchor));
1970 try!(write!(w, ";\n"));
1972 if !consts.is_empty() && !required.is_empty() {
1973 try!(w.write_str("\n"));
1975 for m in &required {
1976 try!(write!(w, " "));
1977 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1978 try!(write!(w, ";\n"));
1980 if !required.is_empty() && !provided.is_empty() {
1981 try!(w.write_str("\n"));
1983 for m in &provided {
1984 try!(write!(w, " "));
1985 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1986 try!(write!(w, " {{ ... }}\n"));
1988 try!(write!(w, "}}"));
1990 try!(write!(w, "</pre>"));
1992 // Trait documentation
1993 try!(document(w, cx, it));
1995 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item)
1997 let name = m.name.as_ref().unwrap();
1998 let id = derive_id(format!("{}.{}", shortty(m), name));
1999 try!(write!(w, "<h3 id='{id}' class='method stab {stab}'><code>",
2001 stab = m.stability_class()));
2002 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
2003 try!(write!(w, "</code></h3>"));
2004 try!(document(w, cx, m));
2008 if !types.is_empty() {
2010 <h2 id='associated-types'>Associated Types</h2>
2011 <div class='methods'>
2014 try!(trait_item(w, cx, *t));
2016 try!(write!(w, "</div>"));
2019 if !consts.is_empty() {
2021 <h2 id='associated-const'>Associated Constants</h2>
2022 <div class='methods'>
2025 try!(trait_item(w, cx, *t));
2027 try!(write!(w, "</div>"));
2030 // Output the documentation for each function individually
2031 if !required.is_empty() {
2033 <h2 id='required-methods'>Required Methods</h2>
2034 <div class='methods'>
2036 for m in &required {
2037 try!(trait_item(w, cx, *m));
2039 try!(write!(w, "</div>"));
2041 if !provided.is_empty() {
2043 <h2 id='provided-methods'>Provided Methods</h2>
2044 <div class='methods'>
2046 for m in &provided {
2047 try!(trait_item(w, cx, *m));
2049 try!(write!(w, "</div>"));
2052 // If there are methods directly on this trait object, render them here.
2053 try!(render_assoc_items(w, cx, it.def_id, AssocItemRender::All));
2055 let cache = cache();
2057 <h2 id='implementors'>Implementors</h2>
2058 <ul class='item-list' id='implementors-list'>
2060 match cache.implementors.get(&it.def_id) {
2061 Some(implementors) => {
2062 for i in implementors {
2063 try!(writeln!(w, "<li><code>{}</code></li>", i.impl_));
2068 try!(write!(w, "</ul>"));
2069 try!(write!(w, r#"<script type="text/javascript" async
2070 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2072 root_path = vec![".."; cx.current.len()].join("/"),
2073 path = if it.def_id.is_local() {
2074 cx.current.join("/")
2076 let path = &cache.external_paths[&it.def_id];
2077 path[..path.len() - 1].join("/")
2079 ty = shortty(it).to_static_str(),
2080 name = *it.name.as_ref().unwrap()));
2084 fn assoc_const(w: &mut fmt::Formatter, it: &clean::Item,
2085 ty: &clean::Type, default: Option<&String>)
2087 try!(write!(w, "const {}", it.name.as_ref().unwrap()));
2088 try!(write!(w, ": {}", ty));
2089 if let Some(default) = default {
2090 try!(write!(w, " = {}", default));
2095 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
2096 bounds: &Vec<clean::TyParamBound>,
2097 default: &Option<clean::Type>)
2099 try!(write!(w, "type {}", it.name.as_ref().unwrap()));
2100 if !bounds.is_empty() {
2101 try!(write!(w, ": {}", TyParamBounds(bounds)))
2103 if let Some(ref default) = *default {
2104 try!(write!(w, " = {}", default));
2109 fn render_assoc_item(w: &mut fmt::Formatter, meth: &clean::Item,
2110 link: AssocItemLink) -> fmt::Result {
2111 fn method(w: &mut fmt::Formatter,
2113 unsafety: hir::Unsafety,
2114 constness: hir::Constness,
2116 g: &clean::Generics,
2117 selfty: &clean::SelfTy,
2119 link: AssocItemLink)
2121 use syntax::abi::Abi;
2123 let name = it.name.as_ref().unwrap();
2124 let anchor = format!("#{}.{}", shortty(it), name);
2125 let href = match link {
2126 AssocItemLink::Anchor => anchor,
2127 AssocItemLink::GotoSource(did) => {
2128 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2131 let vis_constness = match get_unstable_features_setting() {
2132 UnstableFeatures::Allow => constness,
2133 _ => hir::Constness::NotConst
2135 write!(w, "{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2136 {generics}{decl}{where_clause}",
2137 ConstnessSpace(vis_constness),
2138 UnsafetySpace(unsafety),
2140 Abi::Rust => String::new(),
2141 a => format!("extern {} ", a.to_string())
2146 decl = Method(selfty, d),
2147 where_clause = WhereClause(g))
2150 clean::TyMethodItem(ref m) => {
2151 method(w, meth, m.unsafety, hir::Constness::NotConst,
2152 m.abi, &m.generics, &m.self_, &m.decl, link)
2154 clean::MethodItem(ref m) => {
2155 method(w, meth, m.unsafety, m.constness,
2156 m.abi, &m.generics, &m.self_, &m.decl,
2159 clean::AssociatedConstItem(ref ty, ref default) => {
2160 assoc_const(w, meth, ty, default.as_ref())
2162 clean::AssociatedTypeItem(ref bounds, ref default) => {
2163 assoc_type(w, meth, bounds, default)
2165 _ => panic!("render_assoc_item called on non-associated-item")
2169 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2170 s: &clean::Struct) -> fmt::Result {
2171 try!(write!(w, "<pre class='rust struct'>"));
2172 try!(render_attributes(w, it));
2173 try!(render_struct(w,
2180 try!(write!(w, "</pre>"));
2182 try!(document(w, cx, it));
2183 let mut fields = s.fields.iter().filter(|f| {
2185 clean::StructFieldItem(clean::HiddenStructField) => false,
2186 clean::StructFieldItem(clean::TypedStructField(..)) => true,
2190 if let doctree::Plain = s.struct_type {
2191 if fields.peek().is_some() {
2192 try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
2193 for field in fields {
2194 try!(write!(w, "<tr class='stab {stab}'>
2195 <td id='structfield.{name}'>\
2196 <code>{name}</code></td><td>",
2197 stab = field.stability_class(),
2198 name = field.name.as_ref().unwrap()));
2199 try!(document(w, cx, field));
2200 try!(write!(w, "</td></tr>"));
2202 try!(write!(w, "</table>"));
2205 render_assoc_items(w, cx, it.def_id, AssocItemRender::All)
2208 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2209 e: &clean::Enum) -> fmt::Result {
2210 try!(write!(w, "<pre class='rust enum'>"));
2211 try!(render_attributes(w, it));
2212 try!(write!(w, "{}enum {}{}{}",
2213 VisSpace(it.visibility),
2214 it.name.as_ref().unwrap(),
2216 WhereClause(&e.generics)));
2217 if e.variants.is_empty() && !e.variants_stripped {
2218 try!(write!(w, " {{}}"));
2220 try!(write!(w, " {{\n"));
2221 for v in &e.variants {
2222 try!(write!(w, " "));
2223 let name = v.name.as_ref().unwrap();
2225 clean::VariantItem(ref var) => {
2227 clean::CLikeVariant => try!(write!(w, "{}", name)),
2228 clean::TupleVariant(ref tys) => {
2229 try!(write!(w, "{}(", name));
2230 for (i, ty) in tys.iter().enumerate() {
2232 try!(write!(w, ", "))
2234 try!(write!(w, "{}", *ty));
2236 try!(write!(w, ")"));
2238 clean::StructVariant(ref s) => {
2239 try!(render_struct(w,
2251 try!(write!(w, ",\n"));
2254 if e.variants_stripped {
2255 try!(write!(w, " // some variants omitted\n"));
2257 try!(write!(w, "}}"));
2259 try!(write!(w, "</pre>"));
2261 try!(document(w, cx, it));
2262 if !e.variants.is_empty() {
2263 try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
2264 for variant in &e.variants {
2265 try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
2266 name = variant.name.as_ref().unwrap()));
2267 try!(document(w, cx, variant));
2268 match variant.inner {
2269 clean::VariantItem(ref var) => {
2271 clean::StructVariant(ref s) => {
2272 let fields = s.fields.iter().filter(|f| {
2274 clean::StructFieldItem(ref t) => match *t {
2275 clean::HiddenStructField => false,
2276 clean::TypedStructField(..) => true,
2281 try!(write!(w, "<h3 class='fields'>Fields</h3>\n
2283 for field in fields {
2284 try!(write!(w, "<tr><td \
2285 id='variant.{v}.field.{f}'>\
2286 <code>{f}</code></td><td>",
2287 v = variant.name.as_ref().unwrap(),
2288 f = field.name.as_ref().unwrap()));
2289 try!(document(w, cx, field));
2290 try!(write!(w, "</td></tr>"));
2292 try!(write!(w, "</table>"));
2299 try!(write!(w, "</td></tr>"));
2301 try!(write!(w, "</table>"));
2304 try!(render_assoc_items(w, cx, it.def_id, AssocItemRender::All));
2308 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2309 for attr in &it.attrs {
2311 clean::Word(ref s) if *s == "must_use" => {
2312 try!(write!(w, "#[{}]\n", s));
2314 clean::NameValue(ref k, ref v) if *k == "must_use" => {
2315 try!(write!(w, "#[{} = \"{}\"]\n", k, v));
2323 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2324 g: Option<&clean::Generics>,
2325 ty: doctree::StructType,
2326 fields: &[clean::Item],
2328 structhead: bool) -> fmt::Result {
2329 try!(write!(w, "{}{}{}",
2330 VisSpace(it.visibility),
2331 if structhead {"struct "} else {""},
2332 it.name.as_ref().unwrap()));
2334 Some(g) => try!(write!(w, "{}{}", *g, WhereClause(g))),
2339 try!(write!(w, " {{\n{}", tab));
2340 let mut fields_stripped = false;
2341 for field in fields {
2343 clean::StructFieldItem(clean::HiddenStructField) => {
2344 fields_stripped = true;
2346 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
2347 try!(write!(w, " {}{}: {},\n{}",
2348 VisSpace(field.visibility),
2349 field.name.as_ref().unwrap(),
2353 _ => unreachable!(),
2357 if fields_stripped {
2358 try!(write!(w, " // some fields omitted\n{}", tab));
2360 try!(write!(w, "}}"));
2362 doctree::Tuple | doctree::Newtype => {
2363 try!(write!(w, "("));
2364 for (i, field) in fields.iter().enumerate() {
2366 try!(write!(w, ", "));
2369 clean::StructFieldItem(clean::HiddenStructField) => {
2370 try!(write!(w, "_"))
2372 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
2373 try!(write!(w, "{}{}", VisSpace(field.visibility), *ty))
2378 try!(write!(w, ");"));
2381 try!(write!(w, ";"));
2387 #[derive(Copy, Clone)]
2388 enum AssocItemLink {
2393 enum AssocItemRender<'a> {
2395 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type },
2398 fn render_assoc_items(w: &mut fmt::Formatter,
2401 what: AssocItemRender) -> fmt::Result {
2403 let v = match c.impls.get(&it) {
2405 None => return Ok(()),
2407 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
2408 i.impl_.trait_.is_none()
2410 if !non_trait.is_empty() {
2411 let render_header = match what {
2412 AssocItemRender::All => {
2413 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
2416 AssocItemRender::DerefFor { trait_, type_ } => {
2417 try!(write!(w, "<h2 id='deref-methods'>Methods from \
2418 {}<Target={}></h2>", trait_, type_));
2422 for i in &non_trait {
2423 try!(render_impl(w, cx, i, AssocItemLink::Anchor, render_header));
2426 if let AssocItemRender::DerefFor { .. } = what {
2429 if !traits.is_empty() {
2430 let deref_impl = traits.iter().find(|t| {
2431 match *t.impl_.trait_.as_ref().unwrap() {
2432 clean::ResolvedPath { did, .. } => {
2433 Some(did) == c.deref_trait_did
2438 if let Some(impl_) = deref_impl {
2439 try!(render_deref_methods(w, cx, impl_));
2441 try!(write!(w, "<h2 id='implementations'>Trait \
2442 Implementations</h2>"));
2443 let (derived, manual): (Vec<_>, Vec<&Impl>) = traits.iter().partition(|i| {
2447 let did = i.trait_did().unwrap();
2448 try!(render_impl(w, cx, i, AssocItemLink::GotoSource(did), true));
2450 if !derived.is_empty() {
2451 try!(write!(w, "<h3 id='derived_implementations'>\
2452 Derived Implementations \
2455 let did = i.trait_did().unwrap();
2456 try!(render_impl(w, cx, i, AssocItemLink::GotoSource(did), true));
2463 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl) -> fmt::Result {
2464 let deref_type = impl_.impl_.trait_.as_ref().unwrap();
2465 let target = impl_.impl_.items.iter().filter_map(|item| {
2467 clean::TypedefItem(ref t, true) => Some(&t.type_),
2470 }).next().expect("Expected associated type binding");
2471 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target };
2473 clean::ResolvedPath { did, .. } => render_assoc_items(w, cx, did, what),
2475 if let Some(prim) = target.primitive_type() {
2476 if let Some(c) = cache().primitive_locations.get(&prim) {
2477 let did = DefId { krate: *c, index: prim.to_def_index() };
2478 try!(render_assoc_items(w, cx, did, what));
2486 // Render_header is false when we are rendering a `Deref` impl and true
2487 // otherwise. If render_header is false, we will avoid rendering static
2488 // methods, since they are not accessible for the type implementing `Deref`
2489 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
2490 render_header: bool) -> fmt::Result {
2492 try!(write!(w, "<h3 class='impl'><code>{}</code></h3>", i.impl_));
2493 if let Some(ref dox) = i.dox {
2494 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(dox)));
2498 fn doctraititem(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2499 link: AssocItemLink, render_static: bool) -> fmt::Result {
2500 let name = item.name.as_ref().unwrap();
2502 clean::MethodItem(..) | clean::TyMethodItem(..) => {
2503 // Only render when the method is not static or we allow static methods
2504 if !is_static_method(item) || render_static {
2505 let id = derive_id(format!("method.{}", name));
2506 try!(write!(w, "<h4 id='{}' class='{}'><code>", id, shortty(item)));
2507 try!(render_assoc_item(w, item, link));
2508 try!(write!(w, "</code></h4>\n"));
2511 clean::TypedefItem(ref tydef, _) => {
2512 let id = derive_id(format!("assoc_type.{}", name));
2513 try!(write!(w, "<h4 id='{}' class='{}'><code>", id, shortty(item)));
2514 try!(write!(w, "type {} = {}", name, tydef.type_));
2515 try!(write!(w, "</code></h4>\n"));
2517 clean::AssociatedConstItem(ref ty, ref default) => {
2518 let id = derive_id(format!("assoc_const.{}", name));
2519 try!(write!(w, "<h4 id='{}' class='{}'><code>", id, shortty(item)));
2520 try!(assoc_const(w, item, ty, default.as_ref()));
2521 try!(write!(w, "</code></h4>\n"));
2523 clean::ConstantItem(ref c) => {
2524 let id = derive_id(format!("assoc_const.{}", name));
2525 try!(write!(w, "<h4 id='{}' class='{}'><code>", id, shortty(item)));
2526 try!(assoc_const(w, item, &c.type_, Some(&c.expr)));
2527 try!(write!(w, "</code></h4>\n"));
2529 clean::AssociatedTypeItem(ref bounds, ref default) => {
2530 let id = derive_id(format!("assoc_type.{}", name));
2531 try!(write!(w, "<h4 id='{}' class='{}'><code>", id, shortty(item)));
2532 try!(assoc_type(w, item, bounds, default));
2533 try!(write!(w, "</code></h4>\n"));
2535 _ => panic!("can't make docs for trait item with name {:?}", item.name)
2538 return if let AssocItemLink::Anchor = link {
2539 if is_static_method(item) && !render_static {
2542 document(w, cx, item)
2548 fn is_static_method(item: &clean::Item) -> bool {
2550 clean::MethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
2551 clean::TyMethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
2557 try!(write!(w, "<div class='impl-items'>"));
2558 for trait_item in &i.impl_.items {
2559 try!(doctraititem(w, cx, trait_item, link, render_header));
2562 fn render_default_items(w: &mut fmt::Formatter,
2567 render_static: bool) -> fmt::Result {
2568 for trait_item in &t.items {
2569 let n = trait_item.name.clone();
2570 match i.items.iter().find(|m| { m.name == n }) {
2571 Some(..) => continue,
2575 try!(doctraititem(w, cx, trait_item, AssocItemLink::GotoSource(did), render_static));
2580 // If we've implemented a trait, then also emit documentation for all
2581 // default methods which weren't overridden in the implementation block.
2582 // FIXME: this also needs to be done for associated types, whenever defaults
2584 if let Some(clean::ResolvedPath { did, .. }) = i.impl_.trait_ {
2585 if let Some(t) = cache().traits.get(&did) {
2586 try!(render_default_items(w, cx, did, t, &i.impl_, render_header));
2590 try!(write!(w, "</div>"));
2594 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2595 t: &clean::Typedef) -> fmt::Result {
2596 try!(write!(w, "<pre class='rust typedef'>type {}{}{where_clause} = {type_};</pre>",
2597 it.name.as_ref().unwrap(),
2599 where_clause = WhereClause(&t.generics),
2605 impl<'a> fmt::Display for Sidebar<'a> {
2606 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2609 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
2611 // the sidebar is designed to display sibling functions, modules and
2612 // other miscellaneous informations. since there are lots of sibling
2613 // items (and that causes quadratic growth in large modules),
2614 // we refactor common parts into a shared JavaScript file per module.
2615 // still, we don't move everything into JS because we want to preserve
2616 // as much HTML as possible in order to allow non-JS-enabled browsers
2617 // to navigate the documentation (though slightly inefficiently).
2619 try!(write!(fmt, "<p class='location'>"));
2620 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
2622 try!(write!(fmt, "::<wbr>"));
2624 try!(write!(fmt, "<a href='{}index.html'>{}</a>",
2625 &cx.root_path[..(cx.current.len() - i - 1) * 3],
2628 try!(write!(fmt, "</p>"));
2630 // sidebar refers to the enclosing module, not this module
2631 let relpath = if shortty(it) == ItemType::Module { "../" } else { "" };
2633 "<script>window.sidebarCurrent = {{\
2638 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
2639 ty = shortty(it).to_static_str(),
2642 // there is no sidebar-items.js beyond the crate root path
2643 // FIXME maybe dynamic crate loading can be merged here
2645 try!(write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
2653 impl<'a> fmt::Display for Source<'a> {
2654 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2655 let Source(s) = *self;
2656 let lines = s.lines().count();
2658 let mut tmp = lines;
2663 try!(write!(fmt, "<pre class=\"line-numbers\">"));
2664 for i in 1..lines + 1 {
2665 try!(write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols));
2667 try!(write!(fmt, "</pre>"));
2668 try!(write!(fmt, "{}", highlight::highlight(s, None, None)));
2673 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2674 t: &clean::Macro) -> fmt::Result {
2675 try!(w.write_str(&highlight::highlight(&t.source,
2681 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
2683 _p: &clean::PrimitiveType) -> fmt::Result {
2684 try!(document(w, cx, it));
2685 render_assoc_items(w, cx, it.def_id, AssocItemRender::All)
2688 fn get_basic_keywords() -> &'static str {
2689 "rust, rustlang, rust-lang"
2692 fn make_item_keywords(it: &clean::Item) -> String {
2693 format!("{}, {}", get_basic_keywords(), it.name.as_ref().unwrap())
2696 fn get_index_search_type(item: &clean::Item,
2697 parent: Option<String>) -> Option<IndexItemFunctionType> {
2698 let decl = match item.inner {
2699 clean::FunctionItem(ref f) => &f.decl,
2700 clean::MethodItem(ref m) => &m.decl,
2701 clean::TyMethodItem(ref m) => &m.decl,
2705 let mut inputs = Vec::new();
2707 // Consider `self` an argument as well.
2708 if let Some(name) = parent {
2709 inputs.push(Type { name: Some(name.to_ascii_lowercase()) });
2712 inputs.extend(&mut decl.inputs.values.iter().map(|arg| {
2713 get_index_type(&arg.type_)
2716 let output = match decl.output {
2717 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
2721 Some(IndexItemFunctionType { inputs: inputs, output: output })
2724 fn get_index_type(clean_type: &clean::Type) -> Type {
2725 Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
2728 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
2730 clean::ResolvedPath { ref path, .. } => {
2731 let segments = &path.segments;
2732 Some(segments[segments.len() - 1].name.clone())
2734 clean::Generic(ref s) => Some(s.clone()),
2735 clean::Primitive(ref p) => Some(format!("{:?}", p)),
2736 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
2737 // FIXME: add all from clean::Type.
2742 pub fn cache() -> Arc<Cache> {
2743 CACHE_KEY.with(|c| c.borrow().clone())
2748 fn test_unique_id() {
2749 let input = ["foo", "examples", "examples", "method.into_iter","examples",
2750 "method.into_iter", "foo", "main", "search", "methods",
2751 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
2752 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
2753 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
2754 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
2757 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
2758 assert_eq!(&actual[..], expected);