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::fs::{self, File};
44 use std::io::prelude::*;
45 use std::io::{self, BufWriter, BufReader};
46 use std::iter::repeat;
48 use std::path::{PathBuf, Path};
52 use externalfiles::ExternalHtml;
54 use serialize::json::{self, ToJson};
55 use syntax::{abi, ast, attr};
56 use rustc::metadata::cstore::LOCAL_CRATE;
57 use rustc::middle::def_id::DefId;
58 use rustc::util::nodemap::DefIdSet;
61 use clean::{self, SelfTy};
64 use html::escape::Escape;
65 use html::format::{ConstnessSpace};
66 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
67 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
68 use html::item_type::ItemType;
69 use html::markdown::{self, Markdown};
70 use html::{highlight, layout};
72 /// A pair of name and its optional document.
73 pub type NameDoc = (String, Option<String>);
75 /// Major driving force in all rustdoc rendering. This contains information
76 /// about where in the tree-like hierarchy rendering is occurring and controls
77 /// how the current page is being rendered.
79 /// It is intended that this context is a lightweight object which can be fairly
80 /// easily cloned because it is cloned per work-job (about once per item in the
84 /// Current hierarchy of components leading down to what's currently being
86 pub current: Vec<String>,
87 /// String representation of how to get back to the root path of the 'doc/'
88 /// folder in terms of a relative URL.
89 pub root_path: String,
90 /// The path to the crate root source minus the file name.
91 /// Used for simplifying paths to the highlighted source code files.
92 pub src_root: PathBuf,
93 /// The current destination folder of where HTML artifacts should be placed.
94 /// This changes as the context descends into the module hierarchy.
96 /// This describes the layout of each page, and is not modified after
97 /// creation of the context (contains info like the favicon and added html).
98 pub layout: layout::Layout,
99 /// This flag indicates whether [src] links should be generated or not. If
100 /// the source files are present in the html rendering, then this will be
102 pub include_sources: bool,
103 /// A flag, which when turned off, will render pages which redirect to the
104 /// real location of an item. This is used to allow external links to
105 /// publicly reused items to redirect to the right location.
106 pub render_redirect_pages: bool,
107 /// All the passes that were run on this crate.
108 pub passes: HashSet<String>,
109 /// The base-URL of the issue tracker for when an item has been tagged with
111 pub issue_tracker_base_url: Option<String>,
114 /// Indicates where an external crate can be found.
115 pub enum ExternalLocation {
116 /// Remote URL root of the external crate
118 /// This external crate can be found in the local doc/ folder
120 /// The external crate could not be found.
124 /// Metadata about an implementor of a trait.
125 pub struct Implementor {
127 pub stability: Option<clean::Stability>,
128 pub impl_: clean::Impl,
131 /// Metadata about implementations for a type.
134 pub impl_: clean::Impl,
135 pub dox: Option<String>,
136 pub stability: Option<clean::Stability>,
140 fn trait_did(&self) -> Option<DefId> {
141 self.impl_.trait_.as_ref().and_then(|tr| {
142 if let clean::ResolvedPath { did, .. } = *tr {Some(did)} else {None}
147 /// This cache is used to store information about the `clean::Crate` being
148 /// rendered in order to provide more useful documentation. This contains
149 /// information like all implementors of a trait, all traits a type implements,
150 /// documentation for all known traits, etc.
152 /// This structure purposefully does not implement `Clone` because it's intended
153 /// to be a fairly large and expensive structure to clone. Instead this adheres
154 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
155 /// rendering threads.
158 /// Mapping of typaram ids to the name of the type parameter. This is used
159 /// when pretty-printing a type (so pretty printing doesn't have to
160 /// painfully maintain a context like this)
161 pub typarams: HashMap<DefId, String>,
163 /// Maps a type id to all known implementations for that type. This is only
164 /// recognized for intra-crate `ResolvedPath` types, and is used to print
165 /// out extra documentation on the page of an enum/struct.
167 /// The values of the map are a list of implementations and documentation
168 /// found on that implementation.
169 pub impls: HashMap<DefId, Vec<Impl>>,
171 /// Maintains a mapping of local crate node ids to the fully qualified name
172 /// and "short type description" of that node. This is used when generating
173 /// URLs when a type is being linked to. External paths are not located in
174 /// this map because the `External` type itself has all the information
176 pub paths: HashMap<DefId, (Vec<String>, ItemType)>,
178 /// Similar to `paths`, but only holds external paths. This is only used for
179 /// generating explicit hyperlinks to other crates.
180 pub external_paths: HashMap<DefId, Vec<String>>,
182 /// This map contains information about all known traits of this crate.
183 /// Implementations of a crate should inherit the documentation of the
184 /// parent trait if no extra documentation is specified, and default methods
185 /// should show up in documentation about trait implementations.
186 pub traits: HashMap<DefId, clean::Trait>,
188 /// When rendering traits, it's often useful to be able to list all
189 /// implementors of the trait, and this mapping is exactly, that: a mapping
190 /// of trait ids to the list of known implementors of the trait
191 pub implementors: HashMap<DefId, Vec<Implementor>>,
193 /// Cache of where external crate documentation can be found.
194 pub extern_locations: HashMap<ast::CrateNum, (String, ExternalLocation)>,
196 /// Cache of where documentation for primitives can be found.
197 pub primitive_locations: HashMap<clean::PrimitiveType, ast::CrateNum>,
199 /// Set of definitions which have been inlined from external crates.
200 pub inlined: HashSet<DefId>,
202 // Private fields only used when initially crawling a crate to build a cache
205 parent_stack: Vec<DefId>,
206 search_index: Vec<IndexItem>,
209 public_items: DefIdSet,
210 deref_trait_did: Option<DefId>,
212 // In rare case where a structure is defined in one module but implemented
213 // in another, if the implementing module is parsed before defining module,
214 // then the fully qualified name of the structure isn't presented in `paths`
215 // yet when its implementation methods are being indexed. Caches such methods
216 // and their parent id here and indexes them at the end of crate parsing.
217 orphan_methods: Vec<(DefId, clean::Item)>,
220 /// Helper struct to render all source code to HTML pages
221 struct SourceCollector<'a> {
224 /// Processed source-file paths
225 seen: HashSet<String>,
226 /// Root destination to place all HTML output into
230 /// Wrapper struct to render the source code of a file. This will do things like
231 /// adding line numbers to the left-hand side.
232 struct Source<'a>(&'a str);
234 // Helper structs for rendering items/sidebars and carrying along contextual
237 #[derive(Copy, Clone)]
240 item: &'a clean::Item,
243 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
245 /// Struct representing one entry in the JS search index. These are all emitted
246 /// by hand to a large JS file at the end of cache-creation.
252 parent: Option<DefId>,
253 search_type: Option<IndexItemFunctionType>,
256 /// A type used for the search index.
258 name: Option<String>,
261 impl fmt::Display for Type {
262 /// Formats type as {name: $name}.
263 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
264 // Wrapping struct fmt should never call us when self.name is None,
265 // but just to be safe we write `null` in that case.
267 Some(ref n) => write!(f, "{{\"name\":\"{}\"}}", n),
268 None => write!(f, "null")
273 /// Full type of functions/methods in the search index.
274 struct IndexItemFunctionType {
279 impl fmt::Display for IndexItemFunctionType {
280 /// Formats a full fn type as a JSON {inputs: [Type], outputs: Type/null}.
281 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
282 // If we couldn't figure out a type, just write `null`.
283 if self.inputs.iter().any(|ref i| i.name.is_none()) ||
284 (self.output.is_some() && self.output.as_ref().unwrap().name.is_none()) {
285 return write!(f, "null")
288 let inputs: Vec<String> = self.inputs.iter().map(|ref t| {
291 try!(write!(f, "{{\"inputs\":[{}],\"output\":", inputs.join(",")));
294 Some(ref t) => try!(write!(f, "{}", t)),
295 None => try!(write!(f, "null"))
298 Ok(try!(write!(f, "}}")))
302 // TLS keys used to carry information around during rendering.
304 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
305 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
306 RefCell::new(Vec::new()));
308 /// Generates the documentation for `crate` into the directory `dst`
309 pub fn run(mut krate: clean::Crate,
310 external_html: &ExternalHtml,
312 passes: HashSet<String>) -> io::Result<()> {
313 let src_root = match krate.src.parent() {
314 Some(p) => p.to_path_buf(),
315 None => PathBuf::new(),
317 let mut cx = Context {
322 root_path: String::new(),
323 layout: layout::Layout {
324 logo: "".to_string(),
325 favicon: "".to_string(),
326 external_html: external_html.clone(),
327 krate: krate.name.clone(),
328 playground_url: "".to_string(),
330 include_sources: true,
331 render_redirect_pages: false,
332 issue_tracker_base_url: None,
335 try!(mkdir(&cx.dst));
337 // Crawl the crate attributes looking for attributes which control how we're
338 // going to emit HTML
339 let default: &[_] = &[];
340 match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(default)) {
344 clean::NameValue(ref x, ref s)
345 if "html_favicon_url" == *x => {
346 cx.layout.favicon = s.to_string();
348 clean::NameValue(ref x, ref s)
349 if "html_logo_url" == *x => {
350 cx.layout.logo = s.to_string();
352 clean::NameValue(ref x, ref s)
353 if "html_playground_url" == *x => {
354 cx.layout.playground_url = s.to_string();
355 markdown::PLAYGROUND_KRATE.with(|slot| {
356 if slot.borrow().is_none() {
357 let name = krate.name.clone();
358 *slot.borrow_mut() = Some(Some(name));
362 clean::NameValue(ref x, ref s)
363 if "issue_tracker_base_url" == *x => {
364 cx.issue_tracker_base_url = Some(s.to_string());
367 if "html_no_source" == *x => {
368 cx.include_sources = false;
377 // Crawl the crate to build various caches used for the output
378 let analysis = ::ANALYSISKEY.with(|a| a.clone());
379 let analysis = analysis.borrow();
380 let public_items = analysis.as_ref().map(|a| a.public_items.clone());
381 let public_items = public_items.unwrap_or(DefIdSet());
382 let paths: HashMap<DefId, (Vec<String>, ItemType)> =
383 analysis.as_ref().map(|a| {
384 let paths = a.external_paths.borrow_mut().take().unwrap();
385 paths.into_iter().map(|(k, (v, t))| (k, (v, ItemType::from_type_kind(t)))).collect()
386 }).unwrap_or(HashMap::new());
387 let mut cache = Cache {
388 impls: HashMap::new(),
389 external_paths: paths.iter().map(|(&k, v)| (k, v.0.clone()))
392 implementors: HashMap::new(),
394 parent_stack: Vec::new(),
395 search_index: Vec::new(),
396 extern_locations: HashMap::new(),
397 primitive_locations: HashMap::new(),
398 remove_priv: cx.passes.contains("strip-private"),
400 public_items: public_items,
401 orphan_methods: Vec::new(),
402 traits: mem::replace(&mut krate.external_traits, HashMap::new()),
403 deref_trait_did: analysis.as_ref().and_then(|a| a.deref_trait_did),
404 typarams: analysis.as_ref().map(|a| {
405 a.external_typarams.borrow_mut().take().unwrap()
406 }).unwrap_or(HashMap::new()),
407 inlined: analysis.as_ref().map(|a| {
408 a.inlined.borrow_mut().take().unwrap()
409 }).unwrap_or(HashSet::new()),
412 // Cache where all our extern crates are located
413 for &(n, ref e) in &krate.externs {
414 cache.extern_locations.insert(n, (e.name.clone(),
415 extern_location(e, &cx.dst)));
416 let did = DefId { krate: n, xxx_node: ast::CRATE_NODE_ID };
417 cache.paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
420 // Cache where all known primitives have their documentation located.
422 // Favor linking to as local extern as possible, so iterate all crates in
423 // reverse topological order.
424 for &(n, ref e) in krate.externs.iter().rev() {
425 for &prim in &e.primitives {
426 cache.primitive_locations.insert(prim, n);
429 for &prim in &krate.primitives {
430 cache.primitive_locations.insert(prim, LOCAL_CRATE);
433 cache.stack.push(krate.name.clone());
434 krate = cache.fold_crate(krate);
436 // Build our search index
437 let index = try!(build_index(&krate, &mut cache));
439 // Freeze the cache now that the index has been built. Put an Arc into TLS
440 // for future parallelization opportunities
441 let cache = Arc::new(cache);
442 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
443 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
445 try!(write_shared(&cx, &krate, &*cache, index));
446 let krate = try!(render_sources(&mut cx, krate));
448 // And finally render the whole crate's documentation
452 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::Result<String> {
453 // Build the search index from the collected metadata
454 let mut nodeid_to_pathid = HashMap::new();
455 let mut pathid_to_nodeid = Vec::new();
457 let Cache { ref mut search_index,
459 ref mut paths, .. } = *cache;
461 // Attach all orphan methods to the type's definition if the type
462 // has since been learned.
463 for &(did, ref item) in orphan_methods {
464 match paths.get(&did) {
465 Some(&(ref fqp, _)) => {
466 // Needed to determine `self` type.
467 let parent_basename = Some(fqp[fqp.len() - 1].clone());
468 search_index.push(IndexItem {
470 name: item.name.clone().unwrap(),
471 path: fqp[..fqp.len() - 1].join("::"),
472 desc: shorter(item.doc_value()),
474 search_type: get_index_search_type(&item, parent_basename),
481 // Reduce `NodeId` in paths into smaller sequential numbers,
482 // and prune the paths that do not appear in the index.
483 for item in search_index.iter() {
486 if !nodeid_to_pathid.contains_key(&nodeid) {
487 let pathid = pathid_to_nodeid.len();
488 nodeid_to_pathid.insert(nodeid, pathid);
489 pathid_to_nodeid.push(nodeid);
495 assert_eq!(nodeid_to_pathid.len(), pathid_to_nodeid.len());
498 // Collect the index into a string
499 let mut w = io::Cursor::new(Vec::new());
500 try!(write!(&mut w, r#"searchIndex['{}'] = {{"items":["#, krate.name));
502 let mut lastpath = "".to_string();
503 for (i, item) in cache.search_index.iter().enumerate() {
504 // Omit the path if it is same to that of the prior item.
506 if lastpath == item.path {
509 lastpath = item.path.to_string();
514 try!(write!(&mut w, ","));
516 try!(write!(&mut w, r#"[{},"{}","{}",{}"#,
517 item.ty as usize, item.name, path,
518 item.desc.to_json().to_string()));
521 let pathid = *nodeid_to_pathid.get(&nodeid).unwrap();
522 try!(write!(&mut w, ",{}", pathid));
524 None => try!(write!(&mut w, ",null"))
526 match item.search_type {
527 Some(ref t) => try!(write!(&mut w, ",{}", t)),
528 None => try!(write!(&mut w, ",null"))
530 try!(write!(&mut w, "]"));
533 try!(write!(&mut w, r#"],"paths":["#));
535 for (i, &did) in pathid_to_nodeid.iter().enumerate() {
536 let &(ref fqp, short) = cache.paths.get(&did).unwrap();
538 try!(write!(&mut w, ","));
540 try!(write!(&mut w, r#"[{},"{}"]"#,
541 short as usize, *fqp.last().unwrap()));
544 try!(write!(&mut w, "]}};"));
546 Ok(String::from_utf8(w.into_inner()).unwrap())
549 fn write_shared(cx: &Context,
550 krate: &clean::Crate,
552 search_index: String) -> io::Result<()> {
553 // Write out the shared files. Note that these are shared among all rustdoc
554 // docs placed in the output directory, so this needs to be a synchronized
555 // operation with respect to all other rustdocs running around.
556 try!(mkdir(&cx.dst));
557 let _lock = ::flock::Lock::new(&cx.dst.join(".lock"));
559 // Add all the static files. These may already exist, but we just
560 // overwrite them anyway to make sure that they're fresh and up-to-date.
561 try!(write(cx.dst.join("jquery.js"),
562 include_bytes!("static/jquery-2.1.4.min.js")));
563 try!(write(cx.dst.join("main.js"), include_bytes!("static/main.js")));
564 try!(write(cx.dst.join("playpen.js"), include_bytes!("static/playpen.js")));
565 try!(write(cx.dst.join("main.css"), include_bytes!("static/main.css")));
566 try!(write(cx.dst.join("normalize.css"),
567 include_bytes!("static/normalize.css")));
568 try!(write(cx.dst.join("FiraSans-Regular.woff"),
569 include_bytes!("static/FiraSans-Regular.woff")));
570 try!(write(cx.dst.join("FiraSans-Medium.woff"),
571 include_bytes!("static/FiraSans-Medium.woff")));
572 try!(write(cx.dst.join("Heuristica-Italic.woff"),
573 include_bytes!("static/Heuristica-Italic.woff")));
574 try!(write(cx.dst.join("SourceSerifPro-Regular.woff"),
575 include_bytes!("static/SourceSerifPro-Regular.woff")));
576 try!(write(cx.dst.join("SourceSerifPro-Bold.woff"),
577 include_bytes!("static/SourceSerifPro-Bold.woff")));
578 try!(write(cx.dst.join("SourceCodePro-Regular.woff"),
579 include_bytes!("static/SourceCodePro-Regular.woff")));
580 try!(write(cx.dst.join("SourceCodePro-Semibold.woff"),
581 include_bytes!("static/SourceCodePro-Semibold.woff")));
583 fn collect(path: &Path, krate: &str,
584 key: &str) -> io::Result<Vec<String>> {
585 let mut ret = Vec::new();
587 for line in BufReader::new(try!(File::open(path))).lines() {
588 let line = try!(line);
589 if !line.starts_with(key) {
592 if line.starts_with(&format!("{}['{}']", key, krate)) {
595 ret.push(line.to_string());
601 // Update the search index
602 let dst = cx.dst.join("search-index.js");
603 let all_indexes = try!(collect(&dst, &krate.name, "searchIndex"));
604 let mut w = try!(File::create(&dst));
605 try!(writeln!(&mut w, "var searchIndex = {{}};"));
606 try!(writeln!(&mut w, "{}", search_index));
607 for index in &all_indexes {
608 try!(writeln!(&mut w, "{}", *index));
610 try!(writeln!(&mut w, "initSearch(searchIndex);"));
612 // Update the list of all implementors for traits
613 let dst = cx.dst.join("implementors");
615 for (&did, imps) in &cache.implementors {
616 // Private modules can leak through to this phase of rustdoc, which
617 // could contain implementations for otherwise private types. In some
618 // rare cases we could find an implementation for an item which wasn't
619 // indexed, so we just skip this step in that case.
621 // FIXME: this is a vague explanation for why this can't be a `get`, in
622 // theory it should be...
623 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
628 let mut mydst = dst.clone();
629 for part in &remote_path[..remote_path.len() - 1] {
633 mydst.push(&format!("{}.{}.js",
634 remote_item_type.to_static_str(),
635 remote_path[remote_path.len() - 1]));
636 let all_implementors = try!(collect(&mydst, &krate.name,
639 try!(mkdir(mydst.parent().unwrap()));
640 let mut f = BufWriter::new(try!(File::create(&mydst)));
641 try!(writeln!(&mut f, "(function() {{var implementors = {{}};"));
643 for implementor in &all_implementors {
644 try!(write!(&mut f, "{}", *implementor));
647 try!(write!(&mut f, r"implementors['{}'] = [", krate.name));
649 // If the trait and implementation are in the same crate, then
650 // there's no need to emit information about it (there's inlining
651 // going on). If they're in different crates then the crate defining
652 // the trait will be interested in our implementation.
653 if imp.def_id.krate == did.krate { continue }
654 try!(write!(&mut f, r#""{}","#, imp.impl_));
656 try!(writeln!(&mut f, r"];"));
657 try!(writeln!(&mut f, "{}", r"
658 if (window.register_implementors) {
659 window.register_implementors(implementors);
661 window.pending_implementors = implementors;
664 try!(writeln!(&mut f, r"}})()"));
669 fn render_sources(cx: &mut Context,
670 krate: clean::Crate) -> io::Result<clean::Crate> {
671 info!("emitting source files");
672 let dst = cx.dst.join("src");
674 let dst = dst.join(&krate.name);
676 let mut folder = SourceCollector {
678 seen: HashSet::new(),
681 // skip all invalid spans
682 folder.seen.insert("".to_string());
683 Ok(folder.fold_crate(krate))
686 /// Writes the entire contents of a string to a destination, not attempting to
687 /// catch any errors.
688 fn write(dst: PathBuf, contents: &[u8]) -> io::Result<()> {
689 try!(File::create(&dst)).write_all(contents)
692 /// Makes a directory on the filesystem, failing the thread if an error occurs and
693 /// skipping if the directory already exists.
694 fn mkdir(path: &Path) -> io::Result<()> {
702 /// Returns a documentation-level item type from the item.
703 fn shortty(item: &clean::Item) -> ItemType {
704 ItemType::from_item(item)
707 /// Takes a path to a source file and cleans the path to it. This canonicalizes
708 /// things like ".." to components which preserve the "top down" hierarchy of a
709 /// static HTML tree. Each component in the cleaned path will be passed as an
710 /// argument to `f`. The very last component of the path (ie the file name) will
711 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
712 // FIXME (#9639): The closure should deal with &[u8] instead of &str
713 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
714 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
717 // make it relative, if possible
718 let p = p.relative_from(src_root).unwrap_or(p);
720 let mut iter = p.iter().map(|x| x.to_str().unwrap()).peekable();
721 while let Some(c) = iter.next() {
722 if !keep_filename && iter.peek().is_none() {
734 /// Attempts to find where an external crate is located, given that we're
735 /// rendering in to the specified source destination.
736 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
737 // See if there's documentation generated into the local directory
738 let local_location = dst.join(&e.name);
739 if local_location.is_dir() {
743 // Failing that, see if there's an attribute specifying where to find this
745 for attr in &e.attrs {
747 clean::List(ref x, ref list) if "doc" == *x => {
750 clean::NameValue(ref x, ref s)
751 if "html_root_url" == *x => {
752 if s.ends_with("/") {
753 return Remote(s.to_string());
755 return Remote(format!("{}/", s));
765 // Well, at least we tried.
769 impl<'a> DocFolder for SourceCollector<'a> {
770 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
771 // If we're including source files, and we haven't seen this file yet,
772 // then we need to render it out to the filesystem
773 if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
775 // If it turns out that we couldn't read this file, then we probably
776 // can't read any of the files (generating html output from json or
777 // something like that), so just don't include sources for the
778 // entire crate. The other option is maintaining this mapping on a
779 // per-file basis, but that's probably not worth it...
781 .include_sources = match self.emit_source(&item.source .filename) {
784 println!("warning: source code was requested to be rendered, \
785 but processing `{}` had an error: {}",
786 item.source.filename, e);
787 println!(" skipping rendering of source code");
791 self.seen.insert(item.source.filename.clone());
794 self.fold_item_recur(item)
798 impl<'a> SourceCollector<'a> {
799 /// Renders the given filename into its corresponding HTML source file.
800 fn emit_source(&mut self, filename: &str) -> io::Result<()> {
801 let p = PathBuf::from(filename);
803 // If we couldn't open this file, then just returns because it
804 // probably means that it's some standard library macro thing and we
805 // can't have the source to it anyway.
806 let mut contents = Vec::new();
807 match File::open(&p).and_then(|mut f| f.read_to_end(&mut contents)) {
809 // macros from other libraries get special filenames which we can
811 Err(..) if filename.starts_with("<") &&
812 filename.ends_with("macros>") => return Ok(()),
813 Err(e) => return Err(e)
815 let contents = str::from_utf8(&contents).unwrap();
817 // Remove the utf-8 BOM if any
818 let contents = if contents.starts_with("\u{feff}") {
824 // Create the intermediate directories
825 let mut cur = self.dst.clone();
826 let mut root_path = String::from("../../");
827 clean_srcpath(&self.cx.src_root, &p, false, |component| {
829 mkdir(&cur).unwrap();
830 root_path.push_str("../");
833 let mut fname = p.file_name().expect("source has no filename")
836 cur.push(&fname[..]);
837 let mut w = BufWriter::new(try!(File::create(&cur)));
839 let title = format!("{} -- source", cur.file_name().unwrap()
841 let desc = format!("Source to the Rust file `{}`.", filename);
842 let page = layout::Page {
845 root_path: &root_path,
847 keywords: get_basic_keywords(),
849 try!(layout::render(&mut w, &self.cx.layout,
850 &page, &(""), &Source(contents)));
856 impl DocFolder for Cache {
857 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
858 // If this is a private module, we don't want it in the search index.
859 let orig_privmod = match item.inner {
860 clean::ModuleItem(..) => {
861 let prev = self.privmod;
862 self.privmod = prev || (self.remove_priv && item.visibility != Some(hir::Public));
868 // Register any generics to their corresponding string. This is used
869 // when pretty-printing types
871 clean::StructItem(ref s) => self.generics(&s.generics),
872 clean::EnumItem(ref e) => self.generics(&e.generics),
873 clean::FunctionItem(ref f) => self.generics(&f.generics),
874 clean::TypedefItem(ref t, _) => self.generics(&t.generics),
875 clean::TraitItem(ref t) => self.generics(&t.generics),
876 clean::ImplItem(ref i) => self.generics(&i.generics),
877 clean::TyMethodItem(ref i) => self.generics(&i.generics),
878 clean::MethodItem(ref i) => self.generics(&i.generics),
879 clean::ForeignFunctionItem(ref f) => self.generics(&f.generics),
883 // Propagate a trait methods' documentation to all implementors of the
885 if let clean::TraitItem(ref t) = item.inner {
886 self.traits.insert(item.def_id, t.clone());
889 // Collect all the implementors of traits.
890 if let clean::ImplItem(ref i) = item.inner {
892 Some(clean::ResolvedPath{ did, .. }) => {
893 self.implementors.entry(did).or_insert(vec![]).push(Implementor {
895 stability: item.stability.clone(),
899 Some(..) | None => {}
903 // Index this method for searching later on
904 if let Some(ref s) = item.name {
905 let (parent, is_method) = match item.inner {
906 clean::AssociatedTypeItem(..) |
907 clean::AssociatedConstItem(..) |
908 clean::TyMethodItem(..) |
909 clean::StructFieldItem(..) |
910 clean::VariantItem(..) => {
911 ((Some(*self.parent_stack.last().unwrap()),
912 Some(&self.stack[..self.stack.len() - 1])),
915 clean::MethodItem(..) => {
916 if self.parent_stack.is_empty() {
917 ((None, None), false)
919 let last = self.parent_stack.last().unwrap();
921 let path = match self.paths.get(&did) {
922 Some(&(_, ItemType::Trait)) =>
923 Some(&self.stack[..self.stack.len() - 1]),
924 // The current stack not necessarily has correlation
925 // for where the type was defined. On the other
926 // hand, `paths` always has the right
927 // information if present.
928 Some(&(ref fqp, ItemType::Struct)) |
929 Some(&(ref fqp, ItemType::Enum)) =>
930 Some(&fqp[..fqp.len() - 1]),
931 Some(..) => Some(&*self.stack),
934 ((Some(*last), path), true)
937 clean::TypedefItem(_, true) => {
938 // skip associated types in impls
939 ((None, None), false)
941 _ => ((None, Some(&*self.stack)), false)
943 let hidden_field = match item.inner {
944 clean::StructFieldItem(clean::HiddenStructField) => true,
949 (parent, Some(path)) if is_method || (!self.privmod && !hidden_field) => {
950 // Needed to determine `self` type.
951 let parent_basename = self.parent_stack.first().and_then(|parent| {
952 match self.paths.get(parent) {
953 Some(&(ref fqp, _)) => Some(fqp[fqp.len() - 1].clone()),
958 self.search_index.push(IndexItem {
961 path: path.join("::").to_string(),
962 desc: shorter(item.doc_value()),
964 search_type: get_index_search_type(&item, parent_basename),
967 (Some(parent), None) if is_method || (!self.privmod && !hidden_field)=> {
968 if parent.is_local() {
969 // We have a parent, but we don't know where they're
970 // defined yet. Wait for later to index this item.
971 self.orphan_methods.push((parent, item.clone()))
978 // Keep track of the fully qualified path for this item.
979 let pushed = if item.name.is_some() {
980 let n = item.name.as_ref().unwrap();
982 self.stack.push(n.to_string());
987 clean::StructItem(..) | clean::EnumItem(..) |
988 clean::TypedefItem(..) | clean::TraitItem(..) |
989 clean::FunctionItem(..) | clean::ModuleItem(..) |
990 clean::ForeignFunctionItem(..) if !self.privmod => {
991 // Reexported items mean that the same id can show up twice
992 // in the rustdoc ast that we're looking at. We know,
993 // however, that a reexported item doesn't show up in the
994 // `public_items` map, so we can skip inserting into the
995 // paths map if there was already an entry present and we're
996 // not a public item.
998 !self.paths.contains_key(&item.def_id) ||
999 !item.def_id.is_local() ||
1000 self.public_items.contains(&item.def_id)
1002 self.paths.insert(item.def_id,
1003 (self.stack.clone(), shortty(&item)));
1006 // link variants to their parent enum because pages aren't emitted
1008 clean::VariantItem(..) if !self.privmod => {
1009 let mut stack = self.stack.clone();
1011 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1014 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1015 self.paths.insert(item.def_id, (self.stack.clone(),
1022 // Maintain the parent stack
1023 let parent_pushed = match item.inner {
1024 clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
1025 self.parent_stack.push(item.def_id);
1028 clean::ImplItem(ref i) => {
1030 clean::ResolvedPath{ did, .. } => {
1031 self.parent_stack.push(did);
1035 match t.primitive_type() {
1037 let did = DefId::xxx_local(prim.to_node_id()); // TODO
1038 self.parent_stack.push(did);
1049 // Once we've recursively found all the generics, then hoard off all the
1050 // implementations elsewhere
1051 let ret = match self.fold_item_recur(item) {
1054 clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
1055 // extract relevant documentation for this impl
1056 let dox = match attrs.into_iter().find(|a| {
1058 clean::NameValue(ref x, _)
1065 Some(clean::NameValue(_, dox)) => Some(dox),
1066 Some(..) | None => None,
1069 // Figure out the id of this impl. This may map to a
1070 // primitive rather than always to a struct/enum.
1071 let did = match i.for_ {
1072 clean::ResolvedPath { did, .. } |
1073 clean::BorrowedRef {
1074 type_: box clean::ResolvedPath { did, .. }, ..
1080 t.primitive_type().and_then(|t| {
1081 self.primitive_locations.get(&t).map(|n| {
1082 let id = t.to_node_id();
1083 DefId { krate: *n, xxx_node: id }
1089 if let Some(did) = did {
1090 self.impls.entry(did).or_insert(vec![]).push(Impl {
1093 stability: item.stability.clone(),
1106 if pushed { self.stack.pop().unwrap(); }
1107 if parent_pushed { self.parent_stack.pop().unwrap(); }
1108 self.privmod = orig_privmod;
1114 fn generics(&mut self, generics: &clean::Generics) {
1115 for typ in &generics.type_params {
1116 self.typarams.insert(typ.did, typ.name.clone());
1122 /// Recurse in the directory structure and change the "root path" to make
1123 /// sure it always points to the top (relatively)
1124 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1125 F: FnOnce(&mut Context) -> T,
1128 panic!("Unexpected empty destination: {:?}", self.current);
1130 let prev = self.dst.clone();
1132 self.root_path.push_str("../");
1133 self.current.push(s);
1135 info!("Recursing into {}", self.dst.display());
1137 mkdir(&self.dst).unwrap();
1140 info!("Recursed; leaving {}", self.dst.display());
1142 // Go back to where we were at
1144 let len = self.root_path.len();
1145 self.root_path.truncate(len - 3);
1146 self.current.pop().unwrap();
1151 /// Main method for rendering a crate.
1153 /// This currently isn't parallelized, but it'd be pretty easy to add
1154 /// parallelization to this function.
1155 fn krate(self, mut krate: clean::Crate) -> io::Result<()> {
1156 let mut item = match krate.module.take() {
1158 None => return Ok(())
1160 item.name = Some(krate.name);
1162 // render the crate documentation
1163 let mut work = vec!((self, item));
1166 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
1167 work.push((cx.clone(), item));
1176 /// Non-parallelized version of rendering an item. This will take the input
1177 /// item, render its contents, and then invoke the specified closure with
1178 /// all sub-items which need to be rendered.
1180 /// The rendering driver uses this closure to queue up more work.
1181 fn item<F>(&mut self, item: clean::Item, mut f: F) -> io::Result<()> where
1182 F: FnMut(&mut Context, clean::Item),
1184 fn render(w: File, cx: &Context, it: &clean::Item,
1185 pushname: bool) -> io::Result<()> {
1186 // A little unfortunate that this is done like this, but it sure
1187 // does make formatting *a lot* nicer.
1188 CURRENT_LOCATION_KEY.with(|slot| {
1189 *slot.borrow_mut() = cx.current.clone();
1192 let mut title = cx.current.join("::");
1194 if !title.is_empty() {
1195 title.push_str("::");
1197 title.push_str(it.name.as_ref().unwrap());
1199 title.push_str(" - Rust");
1200 let tyname = shortty(it).to_static_str();
1201 let is_crate = match it.inner {
1202 clean::ModuleItem(clean::Module { items: _, is_crate: true }) => true,
1205 let desc = if is_crate {
1206 format!("API documentation for the Rust `{}` crate.",
1209 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1210 it.name.as_ref().unwrap(), tyname, cx.layout.krate)
1212 let keywords = make_item_keywords(it);
1213 let page = layout::Page {
1215 root_path: &cx.root_path,
1218 keywords: &keywords,
1221 markdown::reset_headers();
1223 // We have a huge number of calls to write, so try to alleviate some
1224 // of the pain by using a buffered writer instead of invoking the
1225 // write syscall all the time.
1226 let mut writer = BufWriter::new(w);
1227 if !cx.render_redirect_pages {
1228 try!(layout::render(&mut writer, &cx.layout, &page,
1229 &Sidebar{ cx: cx, item: it },
1230 &Item{ cx: cx, item: it }));
1232 let mut url = repeat("../").take(cx.current.len())
1233 .collect::<String>();
1234 match cache().paths.get(&it.def_id) {
1235 Some(&(ref names, _)) => {
1236 for name in &names[..names.len() - 1] {
1240 url.push_str(&item_path(it));
1241 try!(layout::redirect(&mut writer, &url));
1249 // Private modules may survive the strip-private pass if they
1250 // contain impls for public types. These modules can also
1251 // contain items such as publicly reexported structures.
1253 // External crates will provide links to these structures, so
1254 // these modules are recursed into, but not rendered normally (a
1255 // flag on the context).
1256 if !self.render_redirect_pages {
1257 self.render_redirect_pages = self.ignore_private_item(&item);
1261 // modules are special because they add a namespace. We also need to
1262 // recurse into the items of the module as well.
1263 clean::ModuleItem(..) => {
1264 let name = item.name.as_ref().unwrap().to_string();
1265 let mut item = Some(item);
1266 self.recurse(name, |this| {
1267 let item = item.take().unwrap();
1268 let dst = this.dst.join("index.html");
1269 let dst = try!(File::create(&dst));
1270 try!(render(dst, this, &item, false));
1272 let m = match item.inner {
1273 clean::ModuleItem(m) => m,
1277 // render sidebar-items.js used throughout this module
1279 let items = this.build_sidebar_items(&m);
1280 let js_dst = this.dst.join("sidebar-items.js");
1281 let mut js_out = BufWriter::new(try!(File::create(&js_dst)));
1282 try!(write!(&mut js_out, "initSidebarItems({});",
1283 json::as_json(&items)));
1286 for item in m.items {
1293 // Things which don't have names (like impls) don't get special
1294 // pages dedicated to them.
1295 _ if item.name.is_some() => {
1296 let dst = self.dst.join(&item_path(&item));
1297 let dst = try!(File::create(&dst));
1298 render(dst, self, &item, true)
1305 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1306 // BTreeMap instead of HashMap to get a sorted output
1307 let mut map = BTreeMap::new();
1308 for item in &m.items {
1309 if self.ignore_private_item(item) { continue }
1311 let short = shortty(item).to_static_str();
1312 let myname = match item.name {
1314 Some(ref s) => s.to_string(),
1316 let short = short.to_string();
1317 map.entry(short).or_insert(vec![])
1318 .push((myname, Some(plain_summary_line(item.doc_value()))));
1321 for (_, items) in &mut map {
1327 fn ignore_private_item(&self, it: &clean::Item) -> bool {
1329 clean::ModuleItem(ref m) => {
1330 (m.items.is_empty() &&
1331 it.doc_value().is_none() &&
1332 it.visibility != Some(hir::Public)) ||
1333 (self.passes.contains("strip-private") && it.visibility != Some(hir::Public))
1335 clean::PrimitiveItem(..) => it.visibility != Some(hir::Public),
1342 fn ismodule(&self) -> bool {
1343 match self.item.inner {
1344 clean::ModuleItem(..) => true, _ => false
1348 /// Generate a url appropriate for an `href` attribute back to the source of
1351 /// The url generated, when clicked, will redirect the browser back to the
1352 /// original source code.
1354 /// If `None` is returned, then a source link couldn't be generated. This
1355 /// may happen, for example, with externally inlined items where the source
1356 /// of their crate documentation isn't known.
1357 fn href(&self, cx: &Context) -> Option<String> {
1358 let href = if self.item.source.loline == self.item.source.hiline {
1359 format!("{}", self.item.source.loline)
1361 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1364 // First check to see if this is an imported macro source. In this case
1365 // we need to handle it specially as cross-crate inlined macros have...
1367 let imported_macro_from = match self.item.inner {
1368 clean::MacroItem(ref m) => m.imported_from.as_ref(),
1371 if let Some(krate) = imported_macro_from {
1372 let cache = cache();
1373 let root = cache.extern_locations.values().find(|&&(ref n, _)| {
1376 let root = match root {
1377 Some(&Remote(ref s)) => s.to_string(),
1378 Some(&Local) => self.cx.root_path.clone(),
1379 None | Some(&Unknown) => return None,
1381 Some(format!("{root}/{krate}/macro.{name}.html?gotomacrosrc=1",
1384 name = self.item.name.as_ref().unwrap()))
1386 // If this item is part of the local crate, then we're guaranteed to
1387 // know the span, so we plow forward and generate a proper url. The url
1388 // has anchors for the line numbers that we're linking to.
1389 } else if self.item.def_id.is_local() {
1390 let mut path = Vec::new();
1391 clean_srcpath(&cx.src_root, Path::new(&self.item.source.filename),
1393 path.push(component.to_string());
1395 Some(format!("{root}src/{krate}/{path}.html#{href}",
1396 root = self.cx.root_path,
1397 krate = self.cx.layout.krate,
1398 path = path.join("/"),
1401 // If this item is not part of the local crate, then things get a little
1402 // trickier. We don't actually know the span of the external item, but
1403 // we know that the documentation on the other end knows the span!
1405 // In this case, we generate a link to the *documentation* for this type
1406 // in the original crate. There's an extra URL parameter which says that
1407 // we want to go somewhere else, and the JS on the destination page will
1408 // pick it up and instantly redirect the browser to the source code.
1410 // If we don't know where the external documentation for this crate is
1411 // located, then we return `None`.
1413 let cache = cache();
1414 let path = &cache.external_paths[&self.item.def_id];
1415 let root = match cache.extern_locations[&self.item.def_id.krate] {
1416 (_, Remote(ref s)) => s.to_string(),
1417 (_, Local) => self.cx.root_path.clone(),
1418 (_, Unknown) => return None,
1420 Some(format!("{root}{path}/{file}?gotosrc={goto}",
1422 path = path[..path.len() - 1].join("/"),
1423 file = item_path(self.item),
1424 goto = self.item.def_id.xxx_node))
1430 impl<'a> fmt::Display for Item<'a> {
1431 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1432 // Write the breadcrumb trail header for the top
1433 try!(write!(fmt, "\n<h1 class='fqn'><span class='in-band'>"));
1434 match self.item.inner {
1435 clean::ModuleItem(ref m) => if m.is_crate {
1436 try!(write!(fmt, "Crate "));
1438 try!(write!(fmt, "Module "));
1440 clean::FunctionItem(..) => try!(write!(fmt, "Function ")),
1441 clean::TraitItem(..) => try!(write!(fmt, "Trait ")),
1442 clean::StructItem(..) => try!(write!(fmt, "Struct ")),
1443 clean::EnumItem(..) => try!(write!(fmt, "Enum ")),
1444 clean::PrimitiveItem(..) => try!(write!(fmt, "Primitive Type ")),
1447 let is_primitive = match self.item.inner {
1448 clean::PrimitiveItem(..) => true,
1452 let cur = &self.cx.current;
1453 let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
1454 for (i, component) in cur.iter().enumerate().take(amt) {
1455 try!(write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1456 repeat("../").take(cur.len() - i - 1)
1457 .collect::<String>(),
1461 try!(write!(fmt, "<a class='{}' href=''>{}</a>",
1462 shortty(self.item), self.item.name.as_ref().unwrap()));
1464 try!(write!(fmt, "</span>")); // in-band
1465 try!(write!(fmt, "<span class='out-of-band'>"));
1467 r##"<span id='render-detail'>
1468 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1469 [<span class='inner'>−</span>]
1475 // When this item is part of a `pub use` in a downstream crate, the
1476 // [src] link in the downstream documentation will actually come back to
1477 // this page, and this link will be auto-clicked. The `id` attribute is
1478 // used to find the link to auto-click.
1479 if self.cx.include_sources && !is_primitive {
1480 match self.href(self.cx) {
1482 try!(write!(fmt, "<a id='src-{}' class='srclink' \
1483 href='{}' title='{}'>[src]</a>",
1484 self.item.def_id.xxx_node, l, "goto source code"));
1490 try!(write!(fmt, "</span>")); // out-of-band
1492 try!(write!(fmt, "</h1>\n"));
1494 match self.item.inner {
1495 clean::ModuleItem(ref m) => {
1496 item_module(fmt, self.cx, self.item, &m.items)
1498 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1499 item_function(fmt, self.cx, self.item, f),
1500 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1501 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1502 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1503 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1504 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1505 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1506 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1507 item_static(fmt, self.cx, self.item, i),
1508 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1514 fn item_path(item: &clean::Item) -> String {
1516 clean::ModuleItem(..) => {
1517 format!("{}/index.html", item.name.as_ref().unwrap())
1520 format!("{}.{}.html",
1521 shortty(item).to_static_str(),
1522 *item.name.as_ref().unwrap())
1527 fn full_path(cx: &Context, item: &clean::Item) -> String {
1528 let mut s = cx.current.join("::");
1530 s.push_str(item.name.as_ref().unwrap());
1534 fn shorter<'a>(s: Option<&'a str>) -> String {
1536 Some(s) => s.lines().take_while(|line|{
1537 (*line).chars().any(|chr|{
1538 !chr.is_whitespace()
1540 }).collect::<Vec<_>>().join("\n"),
1541 None => "".to_string()
1546 fn plain_summary_line(s: Option<&str>) -> String {
1547 let line = shorter(s).replace("\n", " ");
1548 markdown::plain_summary_line(&line[..])
1551 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1552 if let Some(s) = short_stability(item, cx, true) {
1553 try!(write!(w, "<div class='stability'>{}</div>", s));
1555 if let Some(s) = item.doc_value() {
1556 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1561 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1562 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1563 try!(document(w, cx, item));
1565 let mut indices = (0..items.len()).filter(|i| {
1566 !cx.ignore_private_item(&items[*i])
1567 }).collect::<Vec<usize>>();
1569 // the order of item types in the listing
1570 fn reorder(ty: ItemType) -> u8 {
1572 ItemType::ExternCrate => 0,
1573 ItemType::Import => 1,
1574 ItemType::Primitive => 2,
1575 ItemType::Module => 3,
1576 ItemType::Macro => 4,
1577 ItemType::Struct => 5,
1578 ItemType::Enum => 6,
1579 ItemType::Constant => 7,
1580 ItemType::Static => 8,
1581 ItemType::Trait => 9,
1582 ItemType::Function => 10,
1583 ItemType::Typedef => 12,
1588 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1589 let ty1 = shortty(i1);
1590 let ty2 = shortty(i2);
1592 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1594 let s1 = i1.stability.as_ref().map(|s| s.level);
1595 let s2 = i2.stability.as_ref().map(|s| s.level);
1597 (Some(attr::Unstable), Some(attr::Stable)) => return Ordering::Greater,
1598 (Some(attr::Stable), Some(attr::Unstable)) => return Ordering::Less,
1601 i1.name.cmp(&i2.name)
1604 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1606 debug!("{:?}", indices);
1607 let mut curty = None;
1608 for &idx in &indices {
1609 let myitem = &items[idx];
1611 let myty = Some(shortty(myitem));
1612 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1613 // Put `extern crate` and `use` re-exports in the same section.
1615 } else if myty != curty {
1616 if curty.is_some() {
1617 try!(write!(w, "</table>"));
1620 let (short, name) = match myty.unwrap() {
1621 ItemType::ExternCrate |
1622 ItemType::Import => ("reexports", "Reexports"),
1623 ItemType::Module => ("modules", "Modules"),
1624 ItemType::Struct => ("structs", "Structs"),
1625 ItemType::Enum => ("enums", "Enums"),
1626 ItemType::Function => ("functions", "Functions"),
1627 ItemType::Typedef => ("types", "Type Definitions"),
1628 ItemType::Static => ("statics", "Statics"),
1629 ItemType::Constant => ("constants", "Constants"),
1630 ItemType::Trait => ("traits", "Traits"),
1631 ItemType::Impl => ("impls", "Implementations"),
1632 ItemType::TyMethod => ("tymethods", "Type Methods"),
1633 ItemType::Method => ("methods", "Methods"),
1634 ItemType::StructField => ("fields", "Struct Fields"),
1635 ItemType::Variant => ("variants", "Variants"),
1636 ItemType::Macro => ("macros", "Macros"),
1637 ItemType::Primitive => ("primitives", "Primitive Types"),
1638 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1639 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1642 "<h2 id='{id}' class='section-header'>\
1643 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1644 id = short, name = name));
1647 match myitem.inner {
1648 clean::ExternCrateItem(ref name, ref src) => {
1651 try!(write!(w, "<tr><td><code>{}extern crate {} as {};",
1652 VisSpace(myitem.visibility),
1657 try!(write!(w, "<tr><td><code>{}extern crate {};",
1658 VisSpace(myitem.visibility), name))
1661 try!(write!(w, "</code></td></tr>"));
1664 clean::ImportItem(ref import) => {
1665 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1666 VisSpace(myitem.visibility), *import));
1670 if myitem.name.is_none() { continue }
1671 let stab_docs = if let Some(s) = short_stability(myitem, cx, false) {
1677 <tr class='{stab} module-item'>
1678 <td><a class='{class}' href='{href}'
1679 title='{title}'>{name}</a></td>
1680 <td class='docblock short'>
1685 name = *myitem.name.as_ref().unwrap(),
1686 stab_docs = stab_docs,
1687 docs = Markdown(&shorter(myitem.doc_value())),
1688 class = shortty(myitem),
1689 stab = myitem.stability_class(),
1690 href = item_path(myitem),
1691 title = full_path(cx, myitem)));
1696 write!(w, "</table>")
1699 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Option<String> {
1700 item.stability.as_ref().and_then(|stab| {
1701 let reason = if show_reason && !stab.reason.is_empty() {
1702 format!(": {}", stab.reason)
1706 let text = if !stab.deprecated_since.is_empty() {
1707 let since = if show_reason {
1708 format!(" since {}", Escape(&stab.deprecated_since))
1712 format!("Deprecated{}{}", since, Markdown(&reason))
1713 } else if stab.level == attr::Unstable {
1714 let unstable_extra = if show_reason {
1715 match (!stab.feature.is_empty(), &cx.issue_tracker_base_url, stab.issue) {
1716 (true, &Some(ref tracker_url), Some(issue_no)) =>
1717 format!(" (<code>{}</code> <a href=\"{}{}\">#{}</a>)",
1718 Escape(&stab.feature), tracker_url, issue_no, issue_no),
1719 (false, &Some(ref tracker_url), Some(issue_no)) =>
1720 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
1723 format!(" (<code>{}</code>)", Escape(&stab.feature)),
1729 format!("Unstable{}{}", unstable_extra, Markdown(&reason))
1733 Some(format!("<em class='stab {}'>{}</em>",
1734 item.stability_class(), text))
1738 struct Initializer<'a>(&'a str);
1740 impl<'a> fmt::Display for Initializer<'a> {
1741 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1742 let Initializer(s) = *self;
1743 if s.is_empty() { return Ok(()); }
1744 try!(write!(f, "<code> = </code>"));
1745 write!(f, "<code>{}</code>", s)
1749 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1750 c: &clean::Constant) -> fmt::Result {
1751 try!(write!(w, "<pre class='rust const'>{vis}const \
1752 {name}: {typ}{init}</pre>",
1753 vis = VisSpace(it.visibility),
1754 name = it.name.as_ref().unwrap(),
1756 init = Initializer(&c.expr)));
1760 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1761 s: &clean::Static) -> fmt::Result {
1762 try!(write!(w, "<pre class='rust static'>{vis}static {mutability}\
1763 {name}: {typ}{init}</pre>",
1764 vis = VisSpace(it.visibility),
1765 mutability = MutableSpace(s.mutability),
1766 name = it.name.as_ref().unwrap(),
1768 init = Initializer(&s.expr)));
1772 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1773 f: &clean::Function) -> fmt::Result {
1774 try!(write!(w, "<pre class='rust fn'>{vis}{unsafety}{abi}{constness}fn \
1775 {name}{generics}{decl}{where_clause}</pre>",
1776 vis = VisSpace(it.visibility),
1777 unsafety = UnsafetySpace(f.unsafety),
1778 abi = AbiSpace(f.abi),
1779 constness = ConstnessSpace(f.constness),
1780 name = it.name.as_ref().unwrap(),
1781 generics = f.generics,
1782 where_clause = WhereClause(&f.generics),
1787 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1788 t: &clean::Trait) -> fmt::Result {
1789 let mut bounds = String::new();
1790 if !t.bounds.is_empty() {
1791 if !bounds.is_empty() {
1794 bounds.push_str(": ");
1795 for (i, p) in t.bounds.iter().enumerate() {
1796 if i > 0 { bounds.push_str(" + "); }
1797 bounds.push_str(&format!("{}", *p));
1801 // Output the trait definition
1802 try!(write!(w, "<pre class='rust trait'>{}{}trait {}{}{}{} ",
1803 VisSpace(it.visibility),
1804 UnsafetySpace(t.unsafety),
1805 it.name.as_ref().unwrap(),
1808 WhereClause(&t.generics)));
1810 let types = t.items.iter().filter(|m| {
1811 match m.inner { clean::AssociatedTypeItem(..) => true, _ => false }
1812 }).collect::<Vec<_>>();
1813 let consts = t.items.iter().filter(|m| {
1814 match m.inner { clean::AssociatedConstItem(..) => true, _ => false }
1815 }).collect::<Vec<_>>();
1816 let required = t.items.iter().filter(|m| {
1817 match m.inner { clean::TyMethodItem(_) => true, _ => false }
1818 }).collect::<Vec<_>>();
1819 let provided = t.items.iter().filter(|m| {
1820 match m.inner { clean::MethodItem(_) => true, _ => false }
1821 }).collect::<Vec<_>>();
1823 if t.items.is_empty() {
1824 try!(write!(w, "{{ }}"));
1826 try!(write!(w, "{{\n"));
1828 try!(write!(w, " "));
1829 try!(render_assoc_item(w, t, AssocItemLink::Anchor));
1830 try!(write!(w, ";\n"));
1832 if !types.is_empty() && !consts.is_empty() {
1833 try!(w.write_str("\n"));
1836 try!(write!(w, " "));
1837 try!(render_assoc_item(w, t, AssocItemLink::Anchor));
1838 try!(write!(w, ";\n"));
1840 if !consts.is_empty() && !required.is_empty() {
1841 try!(w.write_str("\n"));
1843 for m in &required {
1844 try!(write!(w, " "));
1845 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1846 try!(write!(w, ";\n"));
1848 if !required.is_empty() && !provided.is_empty() {
1849 try!(w.write_str("\n"));
1851 for m in &provided {
1852 try!(write!(w, " "));
1853 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1854 try!(write!(w, " {{ ... }}\n"));
1856 try!(write!(w, "}}"));
1858 try!(write!(w, "</pre>"));
1860 // Trait documentation
1861 try!(document(w, cx, it));
1863 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item)
1865 try!(write!(w, "<h3 id='{ty}.{name}' class='method stab {stab}'><code>",
1867 name = *m.name.as_ref().unwrap(),
1868 stab = m.stability_class()));
1869 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1870 try!(write!(w, "</code></h3>"));
1871 try!(document(w, cx, m));
1875 if !types.is_empty() {
1877 <h2 id='associated-types'>Associated Types</h2>
1878 <div class='methods'>
1881 try!(trait_item(w, cx, *t));
1883 try!(write!(w, "</div>"));
1886 if !consts.is_empty() {
1888 <h2 id='associated-const'>Associated Constants</h2>
1889 <div class='methods'>
1892 try!(trait_item(w, cx, *t));
1894 try!(write!(w, "</div>"));
1897 // Output the documentation for each function individually
1898 if !required.is_empty() {
1900 <h2 id='required-methods'>Required Methods</h2>
1901 <div class='methods'>
1903 for m in &required {
1904 try!(trait_item(w, cx, *m));
1906 try!(write!(w, "</div>"));
1908 if !provided.is_empty() {
1910 <h2 id='provided-methods'>Provided Methods</h2>
1911 <div class='methods'>
1913 for m in &provided {
1914 try!(trait_item(w, cx, *m));
1916 try!(write!(w, "</div>"));
1919 // If there are methods directly on this trait object, render them here.
1920 try!(render_assoc_items(w, cx, it.def_id, AssocItemRender::All));
1922 let cache = cache();
1924 <h2 id='implementors'>Implementors</h2>
1925 <ul class='item-list' id='implementors-list'>
1927 match cache.implementors.get(&it.def_id) {
1928 Some(implementors) => {
1929 for i in implementors {
1930 try!(writeln!(w, "<li><code>{}</code></li>", i.impl_));
1935 try!(write!(w, "</ul>"));
1936 try!(write!(w, r#"<script type="text/javascript" async
1937 src="{root_path}/implementors/{path}/{ty}.{name}.js">
1939 root_path = vec![".."; cx.current.len()].join("/"),
1940 path = if it.def_id.is_local() {
1941 cx.current.join("/")
1943 let path = &cache.external_paths[&it.def_id];
1944 path[..path.len() - 1].join("/")
1946 ty = shortty(it).to_static_str(),
1947 name = *it.name.as_ref().unwrap()));
1951 fn assoc_const(w: &mut fmt::Formatter, it: &clean::Item,
1952 ty: &clean::Type, default: Option<&String>)
1954 try!(write!(w, "const {}", it.name.as_ref().unwrap()));
1955 try!(write!(w, ": {}", ty));
1956 if let Some(default) = default {
1957 try!(write!(w, " = {}", default));
1962 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
1963 bounds: &Vec<clean::TyParamBound>,
1964 default: &Option<clean::Type>)
1966 try!(write!(w, "type {}", it.name.as_ref().unwrap()));
1967 if !bounds.is_empty() {
1968 try!(write!(w, ": {}", TyParamBounds(bounds)))
1970 if let Some(ref default) = *default {
1971 try!(write!(w, " = {}", default));
1976 fn render_assoc_item(w: &mut fmt::Formatter, meth: &clean::Item,
1977 link: AssocItemLink) -> fmt::Result {
1978 fn method(w: &mut fmt::Formatter,
1980 unsafety: hir::Unsafety,
1981 constness: hir::Constness,
1983 g: &clean::Generics,
1984 selfty: &clean::SelfTy,
1986 link: AssocItemLink)
1988 use syntax::abi::Abi;
1990 let name = it.name.as_ref().unwrap();
1991 let anchor = format!("#{}.{}", shortty(it), name);
1992 let href = match link {
1993 AssocItemLink::Anchor => anchor,
1994 AssocItemLink::GotoSource(did) => {
1995 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
1998 write!(w, "{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
1999 {generics}{decl}{where_clause}",
2000 UnsafetySpace(unsafety),
2001 ConstnessSpace(constness),
2003 Abi::Rust => String::new(),
2004 a => format!("extern {} ", a.to_string())
2009 decl = Method(selfty, d),
2010 where_clause = WhereClause(g))
2013 clean::TyMethodItem(ref m) => {
2014 method(w, meth, m.unsafety, hir::Constness::NotConst,
2015 m.abi, &m.generics, &m.self_, &m.decl, link)
2017 clean::MethodItem(ref m) => {
2018 method(w, meth, m.unsafety, m.constness,
2019 m.abi, &m.generics, &m.self_, &m.decl,
2022 clean::AssociatedConstItem(ref ty, ref default) => {
2023 assoc_const(w, meth, ty, default.as_ref())
2025 clean::AssociatedTypeItem(ref bounds, ref default) => {
2026 assoc_type(w, meth, bounds, default)
2028 _ => panic!("render_assoc_item called on non-associated-item")
2032 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2033 s: &clean::Struct) -> fmt::Result {
2034 try!(write!(w, "<pre class='rust struct'>"));
2035 try!(render_attributes(w, it));
2036 try!(render_struct(w,
2043 try!(write!(w, "</pre>"));
2045 try!(document(w, cx, it));
2046 let mut fields = s.fields.iter().filter(|f| {
2048 clean::StructFieldItem(clean::HiddenStructField) => false,
2049 clean::StructFieldItem(clean::TypedStructField(..)) => true,
2053 if let doctree::Plain = s.struct_type {
2054 if fields.peek().is_some() {
2055 try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
2056 for field in fields {
2057 try!(write!(w, "<tr class='stab {stab}'>
2058 <td id='structfield.{name}'>\
2059 <code>{name}</code></td><td>",
2060 stab = field.stability_class(),
2061 name = field.name.as_ref().unwrap()));
2062 try!(document(w, cx, field));
2063 try!(write!(w, "</td></tr>"));
2065 try!(write!(w, "</table>"));
2068 render_assoc_items(w, cx, it.def_id, AssocItemRender::All)
2071 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2072 e: &clean::Enum) -> fmt::Result {
2073 try!(write!(w, "<pre class='rust enum'>"));
2074 try!(render_attributes(w, it));
2075 try!(write!(w, "{}enum {}{}{}",
2076 VisSpace(it.visibility),
2077 it.name.as_ref().unwrap(),
2079 WhereClause(&e.generics)));
2080 if e.variants.is_empty() && !e.variants_stripped {
2081 try!(write!(w, " {{}}"));
2083 try!(write!(w, " {{\n"));
2084 for v in &e.variants {
2085 try!(write!(w, " "));
2086 let name = v.name.as_ref().unwrap();
2088 clean::VariantItem(ref var) => {
2090 clean::CLikeVariant => try!(write!(w, "{}", name)),
2091 clean::TupleVariant(ref tys) => {
2092 try!(write!(w, "{}(", name));
2093 for (i, ty) in tys.iter().enumerate() {
2095 try!(write!(w, ", "))
2097 try!(write!(w, "{}", *ty));
2099 try!(write!(w, ")"));
2101 clean::StructVariant(ref s) => {
2102 try!(render_struct(w,
2114 try!(write!(w, ",\n"));
2117 if e.variants_stripped {
2118 try!(write!(w, " // some variants omitted\n"));
2120 try!(write!(w, "}}"));
2122 try!(write!(w, "</pre>"));
2124 try!(document(w, cx, it));
2125 if !e.variants.is_empty() {
2126 try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
2127 for variant in &e.variants {
2128 try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
2129 name = variant.name.as_ref().unwrap()));
2130 try!(document(w, cx, variant));
2131 match variant.inner {
2132 clean::VariantItem(ref var) => {
2134 clean::StructVariant(ref s) => {
2135 let fields = s.fields.iter().filter(|f| {
2137 clean::StructFieldItem(ref t) => match *t {
2138 clean::HiddenStructField => false,
2139 clean::TypedStructField(..) => true,
2144 try!(write!(w, "<h3 class='fields'>Fields</h3>\n
2146 for field in fields {
2147 try!(write!(w, "<tr><td \
2148 id='variant.{v}.field.{f}'>\
2149 <code>{f}</code></td><td>",
2150 v = variant.name.as_ref().unwrap(),
2151 f = field.name.as_ref().unwrap()));
2152 try!(document(w, cx, field));
2153 try!(write!(w, "</td></tr>"));
2155 try!(write!(w, "</table>"));
2162 try!(write!(w, "</td></tr>"));
2164 try!(write!(w, "</table>"));
2167 try!(render_assoc_items(w, cx, it.def_id, AssocItemRender::All));
2171 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2172 for attr in &it.attrs {
2174 clean::Word(ref s) if *s == "must_use" => {
2175 try!(write!(w, "#[{}]\n", s));
2177 clean::NameValue(ref k, ref v) if *k == "must_use" => {
2178 try!(write!(w, "#[{} = \"{}\"]\n", k, v));
2186 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2187 g: Option<&clean::Generics>,
2188 ty: doctree::StructType,
2189 fields: &[clean::Item],
2191 structhead: bool) -> fmt::Result {
2192 try!(write!(w, "{}{}{}",
2193 VisSpace(it.visibility),
2194 if structhead {"struct "} else {""},
2195 it.name.as_ref().unwrap()));
2197 Some(g) => try!(write!(w, "{}{}", *g, WhereClause(g))),
2202 try!(write!(w, " {{\n{}", tab));
2203 let mut fields_stripped = false;
2204 for field in fields {
2206 clean::StructFieldItem(clean::HiddenStructField) => {
2207 fields_stripped = true;
2209 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
2210 try!(write!(w, " {}{}: {},\n{}",
2211 VisSpace(field.visibility),
2212 field.name.as_ref().unwrap(),
2216 _ => unreachable!(),
2220 if fields_stripped {
2221 try!(write!(w, " // some fields omitted\n{}", tab));
2223 try!(write!(w, "}}"));
2225 doctree::Tuple | doctree::Newtype => {
2226 try!(write!(w, "("));
2227 for (i, field) in fields.iter().enumerate() {
2229 try!(write!(w, ", "));
2232 clean::StructFieldItem(clean::HiddenStructField) => {
2233 try!(write!(w, "_"))
2235 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
2236 try!(write!(w, "{}{}", VisSpace(field.visibility), *ty))
2241 try!(write!(w, ");"));
2244 try!(write!(w, ";"));
2250 #[derive(Copy, Clone)]
2251 enum AssocItemLink {
2256 enum AssocItemRender<'a> {
2258 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type },
2261 fn render_assoc_items(w: &mut fmt::Formatter,
2264 what: AssocItemRender) -> fmt::Result {
2266 let v = match c.impls.get(&it) {
2268 None => return Ok(()),
2270 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
2271 i.impl_.trait_.is_none()
2273 if !non_trait.is_empty() {
2274 let render_header = match what {
2275 AssocItemRender::All => {
2276 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
2279 AssocItemRender::DerefFor { trait_, type_ } => {
2280 try!(write!(w, "<h2 id='deref-methods'>Methods from \
2281 {}<Target={}></h2>", trait_, type_));
2285 for i in &non_trait {
2286 try!(render_impl(w, cx, i, AssocItemLink::Anchor, render_header));
2289 if let AssocItemRender::DerefFor { .. } = what {
2292 if !traits.is_empty() {
2293 let deref_impl = traits.iter().find(|t| {
2294 match *t.impl_.trait_.as_ref().unwrap() {
2295 clean::ResolvedPath { did, .. } => {
2296 Some(did) == c.deref_trait_did
2301 if let Some(impl_) = deref_impl {
2302 try!(render_deref_methods(w, cx, impl_));
2304 try!(write!(w, "<h2 id='implementations'>Trait \
2305 Implementations</h2>"));
2306 let (derived, manual): (Vec<_>, Vec<&Impl>) = traits.iter().partition(|i| {
2310 let did = i.trait_did().unwrap();
2311 try!(render_impl(w, cx, i, AssocItemLink::GotoSource(did), true));
2313 if !derived.is_empty() {
2314 try!(write!(w, "<h3 id='derived_implementations'>\
2315 Derived Implementations \
2318 let did = i.trait_did().unwrap();
2319 try!(render_impl(w, cx, i, AssocItemLink::GotoSource(did), true));
2326 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl) -> fmt::Result {
2327 let deref_type = impl_.impl_.trait_.as_ref().unwrap();
2328 let target = impl_.impl_.items.iter().filter_map(|item| {
2330 clean::TypedefItem(ref t, true) => Some(&t.type_),
2333 }).next().expect("Expected associated type binding");
2334 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target };
2336 clean::ResolvedPath { did, .. } => render_assoc_items(w, cx, did, what),
2338 if let Some(prim) = target.primitive_type() {
2339 if let Some(c) = cache().primitive_locations.get(&prim) {
2340 let did = DefId { krate: *c, xxx_node: prim.to_node_id() };
2341 try!(render_assoc_items(w, cx, did, what));
2349 // Render_header is false when we are rendering a `Deref` impl and true
2350 // otherwise. If render_header is false, we will avoid rendering static
2351 // methods, since they are not accessible for the type implementing `Deref`
2352 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
2353 render_header: bool) -> fmt::Result {
2355 try!(write!(w, "<h3 class='impl'><code>{}</code></h3>", i.impl_));
2356 if let Some(ref dox) = i.dox {
2357 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(dox)));
2361 fn doctraititem(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2362 link: AssocItemLink, render_static: bool) -> fmt::Result {
2364 clean::MethodItem(..) | clean::TyMethodItem(..) => {
2365 // Only render when the method is not static or we allow static methods
2366 if !is_static_method(item) || render_static {
2367 try!(write!(w, "<h4 id='method.{}' class='{}'><code>",
2368 *item.name.as_ref().unwrap(),
2370 try!(render_assoc_item(w, item, link));
2371 try!(write!(w, "</code></h4>\n"));
2374 clean::TypedefItem(ref tydef, _) => {
2375 let name = item.name.as_ref().unwrap();
2376 try!(write!(w, "<h4 id='assoc_type.{}' class='{}'><code>",
2379 try!(write!(w, "type {} = {}", name, tydef.type_));
2380 try!(write!(w, "</code></h4>\n"));
2382 clean::AssociatedConstItem(ref ty, ref default) => {
2383 let name = item.name.as_ref().unwrap();
2384 try!(write!(w, "<h4 id='assoc_const.{}' class='{}'><code>",
2385 *name, shortty(item)));
2386 try!(assoc_const(w, item, ty, default.as_ref()));
2387 try!(write!(w, "</code></h4>\n"));
2389 clean::ConstantItem(ref c) => {
2390 let name = item.name.as_ref().unwrap();
2391 try!(write!(w, "<h4 id='assoc_const.{}' class='{}'><code>",
2392 *name, shortty(item)));
2393 try!(assoc_const(w, item, &c.type_, Some(&c.expr)));
2394 try!(write!(w, "</code></h4>\n"));
2396 clean::AssociatedTypeItem(ref bounds, ref default) => {
2397 let name = item.name.as_ref().unwrap();
2398 try!(write!(w, "<h4 id='assoc_type.{}' class='{}'><code>",
2401 try!(assoc_type(w, item, bounds, default));
2402 try!(write!(w, "</code></h4>\n"));
2404 _ => panic!("can't make docs for trait item with name {:?}", item.name)
2407 return if let AssocItemLink::Anchor = link {
2408 if is_static_method(item) && !render_static {
2411 document(w, cx, item)
2417 fn is_static_method(item: &clean::Item) -> bool {
2419 clean::MethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
2420 clean::TyMethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
2426 try!(write!(w, "<div class='impl-items'>"));
2427 for trait_item in &i.impl_.items {
2428 try!(doctraititem(w, cx, trait_item, link, render_header));
2431 fn render_default_items(w: &mut fmt::Formatter,
2436 render_static: bool) -> fmt::Result {
2437 for trait_item in &t.items {
2438 let n = trait_item.name.clone();
2439 match i.items.iter().find(|m| { m.name == n }) {
2440 Some(..) => continue,
2444 try!(doctraititem(w, cx, trait_item, AssocItemLink::GotoSource(did), render_static));
2449 // If we've implemented a trait, then also emit documentation for all
2450 // default methods which weren't overridden in the implementation block.
2451 // FIXME: this also needs to be done for associated types, whenever defaults
2453 if let Some(clean::ResolvedPath { did, .. }) = i.impl_.trait_ {
2454 if let Some(t) = cache().traits.get(&did) {
2455 try!(render_default_items(w, cx, did, t, &i.impl_, render_header));
2459 try!(write!(w, "</div>"));
2463 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2464 t: &clean::Typedef) -> fmt::Result {
2465 try!(write!(w, "<pre class='rust typedef'>type {}{}{where_clause} = {type_};</pre>",
2466 it.name.as_ref().unwrap(),
2468 where_clause = WhereClause(&t.generics),
2474 impl<'a> fmt::Display for Sidebar<'a> {
2475 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2478 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
2480 // the sidebar is designed to display sibling functions, modules and
2481 // other miscellaneous informations. since there are lots of sibling
2482 // items (and that causes quadratic growth in large modules),
2483 // we refactor common parts into a shared JavaScript file per module.
2484 // still, we don't move everything into JS because we want to preserve
2485 // as much HTML as possible in order to allow non-JS-enabled browsers
2486 // to navigate the documentation (though slightly inefficiently).
2488 try!(write!(fmt, "<p class='location'>"));
2489 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
2491 try!(write!(fmt, "::<wbr>"));
2493 try!(write!(fmt, "<a href='{}index.html'>{}</a>",
2494 &cx.root_path[..(cx.current.len() - i - 1) * 3],
2497 try!(write!(fmt, "</p>"));
2499 // sidebar refers to the enclosing module, not this module
2500 let relpath = if shortty(it) == ItemType::Module { "../" } else { "" };
2502 "<script>window.sidebarCurrent = {{\
2507 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
2508 ty = shortty(it).to_static_str(),
2511 // there is no sidebar-items.js beyond the crate root path
2512 // FIXME maybe dynamic crate loading can be merged here
2514 try!(write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
2522 impl<'a> fmt::Display for Source<'a> {
2523 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2524 let Source(s) = *self;
2525 let lines = s.lines().count();
2527 let mut tmp = lines;
2532 try!(write!(fmt, "<pre class=\"line-numbers\">"));
2533 for i in 1..lines + 1 {
2534 try!(write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols));
2536 try!(write!(fmt, "</pre>"));
2537 try!(write!(fmt, "{}", highlight::highlight(s, None, None)));
2542 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2543 t: &clean::Macro) -> fmt::Result {
2544 try!(w.write_str(&highlight::highlight(&t.source,
2550 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
2552 _p: &clean::PrimitiveType) -> fmt::Result {
2553 try!(document(w, cx, it));
2554 render_assoc_items(w, cx, it.def_id, AssocItemRender::All)
2557 fn get_basic_keywords() -> &'static str {
2558 "rust, rustlang, rust-lang"
2561 fn make_item_keywords(it: &clean::Item) -> String {
2562 format!("{}, {}", get_basic_keywords(), it.name.as_ref().unwrap())
2565 fn get_index_search_type(item: &clean::Item,
2566 parent: Option<String>) -> Option<IndexItemFunctionType> {
2567 let decl = match item.inner {
2568 clean::FunctionItem(ref f) => &f.decl,
2569 clean::MethodItem(ref m) => &m.decl,
2570 clean::TyMethodItem(ref m) => &m.decl,
2574 let mut inputs = Vec::new();
2576 // Consider `self` an argument as well.
2577 if let Some(name) = parent {
2578 inputs.push(Type { name: Some(name.to_ascii_lowercase()) });
2581 inputs.extend(&mut decl.inputs.values.iter().map(|arg| {
2582 get_index_type(&arg.type_)
2585 let output = match decl.output {
2586 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
2590 Some(IndexItemFunctionType { inputs: inputs, output: output })
2593 fn get_index_type(clean_type: &clean::Type) -> Type {
2594 Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
2597 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
2599 clean::ResolvedPath { ref path, .. } => {
2600 let segments = &path.segments;
2601 Some(segments[segments.len() - 1].name.clone())
2603 clean::Generic(ref s) => Some(s.clone()),
2604 clean::Primitive(ref p) => Some(format!("{:?}", p)),
2605 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
2606 // FIXME: add all from clean::Type.
2611 pub fn cache() -> Arc<Cache> {
2612 CACHE_KEY.with(|c| c.borrow().clone())