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};
56 use rustc::middle::def_id::{DefId, LOCAL_CRATE};
57 use rustc::util::nodemap::NodeSet;
58 use rustc_front::{hir, attr};
60 use clean::{self, SelfTy};
63 use html::escape::Escape;
64 use html::format::{ConstnessSpace};
65 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
66 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
67 use html::item_type::ItemType;
68 use html::markdown::{self, Markdown};
69 use html::{highlight, layout};
71 /// A pair of name and its optional document.
72 pub type NameDoc = (String, Option<String>);
74 /// Major driving force in all rustdoc rendering. This contains information
75 /// about where in the tree-like hierarchy rendering is occurring and controls
76 /// how the current page is being rendered.
78 /// It is intended that this context is a lightweight object which can be fairly
79 /// easily cloned because it is cloned per work-job (about once per item in the
83 /// Current hierarchy of components leading down to what's currently being
85 pub current: Vec<String>,
86 /// String representation of how to get back to the root path of the 'doc/'
87 /// folder in terms of a relative URL.
88 pub root_path: String,
89 /// The path to the crate root source minus the file name.
90 /// Used for simplifying paths to the highlighted source code files.
91 pub src_root: PathBuf,
92 /// The current destination folder of where HTML artifacts should be placed.
93 /// This changes as the context descends into the module hierarchy.
95 /// This describes the layout of each page, and is not modified after
96 /// creation of the context (contains info like the favicon and added html).
97 pub layout: layout::Layout,
98 /// This flag indicates whether [src] links should be generated or not. If
99 /// the source files are present in the html rendering, then this will be
101 pub include_sources: bool,
102 /// A flag, which when turned off, will render pages which redirect to the
103 /// real location of an item. This is used to allow external links to
104 /// publicly reused items to redirect to the right location.
105 pub render_redirect_pages: bool,
106 /// All the passes that were run on this crate.
107 pub passes: HashSet<String>,
108 /// The base-URL of the issue tracker for when an item has been tagged with
110 pub issue_tracker_base_url: Option<String>,
113 /// Indicates where an external crate can be found.
114 pub enum ExternalLocation {
115 /// Remote URL root of the external crate
117 /// This external crate can be found in the local doc/ folder
119 /// The external crate could not be found.
123 /// Metadata about an implementor of a trait.
124 pub struct Implementor {
126 pub stability: Option<clean::Stability>,
127 pub impl_: clean::Impl,
130 /// Metadata about implementations for a type.
133 pub impl_: clean::Impl,
134 pub dox: Option<String>,
135 pub stability: Option<clean::Stability>,
139 fn trait_did(&self) -> Option<DefId> {
140 self.impl_.trait_.as_ref().and_then(|tr| {
141 if let clean::ResolvedPath { did, .. } = *tr {Some(did)} else {None}
146 /// This cache is used to store information about the `clean::Crate` being
147 /// rendered in order to provide more useful documentation. This contains
148 /// information like all implementors of a trait, all traits a type implements,
149 /// documentation for all known traits, etc.
151 /// This structure purposefully does not implement `Clone` because it's intended
152 /// to be a fairly large and expensive structure to clone. Instead this adheres
153 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
154 /// rendering threads.
157 /// Mapping of typaram ids to the name of the type parameter. This is used
158 /// when pretty-printing a type (so pretty printing doesn't have to
159 /// painfully maintain a context like this)
160 pub typarams: HashMap<DefId, String>,
162 /// Maps a type id to all known implementations for that type. This is only
163 /// recognized for intra-crate `ResolvedPath` types, and is used to print
164 /// out extra documentation on the page of an enum/struct.
166 /// The values of the map are a list of implementations and documentation
167 /// found on that implementation.
168 pub impls: HashMap<DefId, Vec<Impl>>,
170 /// Maintains a mapping of local crate node ids to the fully qualified name
171 /// and "short type description" of that node. This is used when generating
172 /// URLs when a type is being linked to. External paths are not located in
173 /// this map because the `External` type itself has all the information
175 pub paths: HashMap<DefId, (Vec<String>, ItemType)>,
177 /// Similar to `paths`, but only holds external paths. This is only used for
178 /// generating explicit hyperlinks to other crates.
179 pub external_paths: HashMap<DefId, Vec<String>>,
181 /// This map contains information about all known traits of this crate.
182 /// Implementations of a crate should inherit the documentation of the
183 /// parent trait if no extra documentation is specified, and default methods
184 /// should show up in documentation about trait implementations.
185 pub traits: HashMap<DefId, clean::Trait>,
187 /// When rendering traits, it's often useful to be able to list all
188 /// implementors of the trait, and this mapping is exactly, that: a mapping
189 /// of trait ids to the list of known implementors of the trait
190 pub implementors: HashMap<DefId, Vec<Implementor>>,
192 /// Cache of where external crate documentation can be found.
193 pub extern_locations: HashMap<ast::CrateNum, (String, ExternalLocation)>,
195 /// Cache of where documentation for primitives can be found.
196 pub primitive_locations: HashMap<clean::PrimitiveType, ast::CrateNum>,
198 /// Set of definitions which have been inlined from external crates.
199 pub inlined: HashSet<DefId>,
201 // Private fields only used when initially crawling a crate to build a cache
204 parent_stack: Vec<DefId>,
205 search_index: Vec<IndexItem>,
208 public_items: NodeSet,
209 deref_trait_did: Option<DefId>,
211 // In rare case where a structure is defined in one module but implemented
212 // in another, if the implementing module is parsed before defining module,
213 // then the fully qualified name of the structure isn't presented in `paths`
214 // yet when its implementation methods are being indexed. Caches such methods
215 // and their parent id here and indexes them at the end of crate parsing.
216 orphan_methods: Vec<(ast::NodeId, clean::Item)>,
219 /// Helper struct to render all source code to HTML pages
220 struct SourceCollector<'a> {
223 /// Processed source-file paths
224 seen: HashSet<String>,
225 /// Root destination to place all HTML output into
229 /// Wrapper struct to render the source code of a file. This will do things like
230 /// adding line numbers to the left-hand side.
231 struct Source<'a>(&'a str);
233 // Helper structs for rendering items/sidebars and carrying along contextual
236 #[derive(Copy, Clone)]
239 item: &'a clean::Item,
242 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
244 /// Struct representing one entry in the JS search index. These are all emitted
245 /// by hand to a large JS file at the end of cache-creation.
251 parent: Option<DefId>,
252 search_type: Option<IndexItemFunctionType>,
255 /// A type used for the search index.
257 name: Option<String>,
260 impl fmt::Display for Type {
261 /// Formats type as {name: $name}.
262 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
263 // Wrapping struct fmt should never call us when self.name is None,
264 // but just to be safe we write `null` in that case.
266 Some(ref n) => write!(f, "{{\"name\":\"{}\"}}", n),
267 None => write!(f, "null")
272 /// Full type of functions/methods in the search index.
273 struct IndexItemFunctionType {
278 impl fmt::Display for IndexItemFunctionType {
279 /// Formats a full fn type as a JSON {inputs: [Type], outputs: Type/null}.
280 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
281 // If we couldn't figure out a type, just write `null`.
282 if self.inputs.iter().any(|ref i| i.name.is_none()) ||
283 (self.output.is_some() && self.output.as_ref().unwrap().name.is_none()) {
284 return write!(f, "null")
287 let inputs: Vec<String> = self.inputs.iter().map(|ref t| {
290 try!(write!(f, "{{\"inputs\":[{}],\"output\":", inputs.join(",")));
293 Some(ref t) => try!(write!(f, "{}", t)),
294 None => try!(write!(f, "null"))
297 Ok(try!(write!(f, "}}")))
301 // TLS keys used to carry information around during rendering.
303 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
304 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
305 RefCell::new(Vec::new()));
307 /// Generates the documentation for `crate` into the directory `dst`
308 pub fn run(mut krate: clean::Crate,
309 external_html: &ExternalHtml,
311 passes: HashSet<String>) -> io::Result<()> {
312 let src_root = match krate.src.parent() {
313 Some(p) => p.to_path_buf(),
314 None => PathBuf::new(),
316 let mut cx = Context {
321 root_path: String::new(),
322 layout: layout::Layout {
323 logo: "".to_string(),
324 favicon: "".to_string(),
325 external_html: external_html.clone(),
326 krate: krate.name.clone(),
327 playground_url: "".to_string(),
329 include_sources: true,
330 render_redirect_pages: false,
331 issue_tracker_base_url: None,
334 try!(mkdir(&cx.dst));
336 // Crawl the crate attributes looking for attributes which control how we're
337 // going to emit HTML
338 let default: &[_] = &[];
339 match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(default)) {
343 clean::NameValue(ref x, ref s)
344 if "html_favicon_url" == *x => {
345 cx.layout.favicon = s.to_string();
347 clean::NameValue(ref x, ref s)
348 if "html_logo_url" == *x => {
349 cx.layout.logo = s.to_string();
351 clean::NameValue(ref x, ref s)
352 if "html_playground_url" == *x => {
353 cx.layout.playground_url = s.to_string();
354 markdown::PLAYGROUND_KRATE.with(|slot| {
355 if slot.borrow().is_none() {
356 let name = krate.name.clone();
357 *slot.borrow_mut() = Some(Some(name));
361 clean::NameValue(ref x, ref s)
362 if "issue_tracker_base_url" == *x => {
363 cx.issue_tracker_base_url = Some(s.to_string());
366 if "html_no_source" == *x => {
367 cx.include_sources = false;
376 // Crawl the crate to build various caches used for the output
377 let analysis = ::ANALYSISKEY.with(|a| a.clone());
378 let analysis = analysis.borrow();
379 let public_items = analysis.as_ref().map(|a| a.public_items.clone());
380 let public_items = public_items.unwrap_or(NodeSet());
381 let paths: HashMap<DefId, (Vec<String>, ItemType)> =
382 analysis.as_ref().map(|a| {
383 let paths = a.external_paths.borrow_mut().take().unwrap();
384 paths.into_iter().map(|(k, (v, t))| (k, (v, ItemType::from_type_kind(t)))).collect()
385 }).unwrap_or(HashMap::new());
386 let mut cache = Cache {
387 impls: HashMap::new(),
388 external_paths: paths.iter().map(|(&k, v)| (k, v.0.clone()))
391 implementors: HashMap::new(),
393 parent_stack: Vec::new(),
394 search_index: Vec::new(),
395 extern_locations: HashMap::new(),
396 primitive_locations: HashMap::new(),
397 remove_priv: cx.passes.contains("strip-private"),
399 public_items: public_items,
400 orphan_methods: Vec::new(),
401 traits: mem::replace(&mut krate.external_traits, HashMap::new()),
402 deref_trait_did: analysis.as_ref().and_then(|a| a.deref_trait_did),
403 typarams: analysis.as_ref().map(|a| {
404 a.external_typarams.borrow_mut().take().unwrap()
405 }).unwrap_or(HashMap::new()),
406 inlined: analysis.as_ref().map(|a| {
407 a.inlined.borrow_mut().take().unwrap()
408 }).unwrap_or(HashSet::new()),
411 // Cache where all our extern crates are located
412 for &(n, ref e) in &krate.externs {
413 cache.extern_locations.insert(n, (e.name.clone(),
414 extern_location(e, &cx.dst)));
415 let did = DefId { krate: n, node: ast::CRATE_NODE_ID };
416 cache.paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
419 // Cache where all known primitives have their documentation located.
421 // Favor linking to as local extern as possible, so iterate all crates in
422 // reverse topological order.
423 for &(n, ref e) in krate.externs.iter().rev() {
424 for &prim in &e.primitives {
425 cache.primitive_locations.insert(prim, n);
428 for &prim in &krate.primitives {
429 cache.primitive_locations.insert(prim, LOCAL_CRATE);
432 cache.stack.push(krate.name.clone());
433 krate = cache.fold_crate(krate);
435 // Build our search index
436 let index = try!(build_index(&krate, &mut cache));
438 // Freeze the cache now that the index has been built. Put an Arc into TLS
439 // for future parallelization opportunities
440 let cache = Arc::new(cache);
441 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
442 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
444 try!(write_shared(&cx, &krate, &*cache, index));
445 let krate = try!(render_sources(&mut cx, krate));
447 // And finally render the whole crate's documentation
451 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::Result<String> {
452 // Build the search index from the collected metadata
453 let mut nodeid_to_pathid = HashMap::new();
454 let mut pathid_to_nodeid = Vec::new();
456 let Cache { ref mut search_index,
458 ref mut paths, .. } = *cache;
460 // Attach all orphan methods to the type's definition if the type
461 // has since been learned.
462 for &(pid, ref item) in orphan_methods {
463 let did = DefId::local(pid);
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.node, 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.
997 let id = item.def_id.node;
998 if !self.paths.contains_key(&item.def_id) ||
999 !item.def_id.is_local() ||
1000 self.public_items.contains(&id) {
1001 self.paths.insert(item.def_id,
1002 (self.stack.clone(), shortty(&item)));
1005 // link variants to their parent enum because pages aren't emitted
1007 clean::VariantItem(..) if !self.privmod => {
1008 let mut stack = self.stack.clone();
1010 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1013 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1014 self.paths.insert(item.def_id, (self.stack.clone(),
1021 // Maintain the parent stack
1022 let parent_pushed = match item.inner {
1023 clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
1024 self.parent_stack.push(item.def_id);
1027 clean::ImplItem(ref i) => {
1029 clean::ResolvedPath{ did, .. } => {
1030 self.parent_stack.push(did);
1034 match t.primitive_type() {
1036 let did = DefId::local(prim.to_node_id());
1037 self.parent_stack.push(did);
1048 // Once we've recursively found all the generics, then hoard off all the
1049 // implementations elsewhere
1050 let ret = match self.fold_item_recur(item) {
1053 clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
1054 // extract relevant documentation for this impl
1055 let dox = match attrs.into_iter().find(|a| {
1057 clean::NameValue(ref x, _)
1064 Some(clean::NameValue(_, dox)) => Some(dox),
1065 Some(..) | None => None,
1068 // Figure out the id of this impl. This may map to a
1069 // primitive rather than always to a struct/enum.
1070 let did = match i.for_ {
1071 clean::ResolvedPath { did, .. } |
1072 clean::BorrowedRef {
1073 type_: box clean::ResolvedPath { did, .. }, ..
1079 t.primitive_type().and_then(|t| {
1080 self.primitive_locations.get(&t).map(|n| {
1081 let id = t.to_node_id();
1082 DefId { krate: *n, node: id }
1088 if let Some(did) = did {
1089 self.impls.entry(did).or_insert(vec![]).push(Impl {
1092 stability: item.stability.clone(),
1105 if pushed { self.stack.pop().unwrap(); }
1106 if parent_pushed { self.parent_stack.pop().unwrap(); }
1107 self.privmod = orig_privmod;
1113 fn generics(&mut self, generics: &clean::Generics) {
1114 for typ in &generics.type_params {
1115 self.typarams.insert(typ.did, typ.name.clone());
1121 /// Recurse in the directory structure and change the "root path" to make
1122 /// sure it always points to the top (relatively)
1123 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1124 F: FnOnce(&mut Context) -> T,
1127 panic!("Unexpected empty destination: {:?}", self.current);
1129 let prev = self.dst.clone();
1131 self.root_path.push_str("../");
1132 self.current.push(s);
1134 info!("Recursing into {}", self.dst.display());
1136 mkdir(&self.dst).unwrap();
1139 info!("Recursed; leaving {}", self.dst.display());
1141 // Go back to where we were at
1143 let len = self.root_path.len();
1144 self.root_path.truncate(len - 3);
1145 self.current.pop().unwrap();
1150 /// Main method for rendering a crate.
1152 /// This currently isn't parallelized, but it'd be pretty easy to add
1153 /// parallelization to this function.
1154 fn krate(self, mut krate: clean::Crate) -> io::Result<()> {
1155 let mut item = match krate.module.take() {
1157 None => return Ok(())
1159 item.name = Some(krate.name);
1161 // render the crate documentation
1162 let mut work = vec!((self, item));
1165 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
1166 work.push((cx.clone(), item));
1175 /// Non-parallelized version of rendering an item. This will take the input
1176 /// item, render its contents, and then invoke the specified closure with
1177 /// all sub-items which need to be rendered.
1179 /// The rendering driver uses this closure to queue up more work.
1180 fn item<F>(&mut self, item: clean::Item, mut f: F) -> io::Result<()> where
1181 F: FnMut(&mut Context, clean::Item),
1183 fn render(w: File, cx: &Context, it: &clean::Item,
1184 pushname: bool) -> io::Result<()> {
1185 // A little unfortunate that this is done like this, but it sure
1186 // does make formatting *a lot* nicer.
1187 CURRENT_LOCATION_KEY.with(|slot| {
1188 *slot.borrow_mut() = cx.current.clone();
1191 let mut title = cx.current.join("::");
1193 if !title.is_empty() {
1194 title.push_str("::");
1196 title.push_str(it.name.as_ref().unwrap());
1198 title.push_str(" - Rust");
1199 let tyname = shortty(it).to_static_str();
1200 let is_crate = match it.inner {
1201 clean::ModuleItem(clean::Module { items: _, is_crate: true }) => true,
1204 let desc = if is_crate {
1205 format!("API documentation for the Rust `{}` crate.",
1208 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1209 it.name.as_ref().unwrap(), tyname, cx.layout.krate)
1211 let keywords = make_item_keywords(it);
1212 let page = layout::Page {
1214 root_path: &cx.root_path,
1217 keywords: &keywords,
1220 markdown::reset_headers();
1222 // We have a huge number of calls to write, so try to alleviate some
1223 // of the pain by using a buffered writer instead of invoking the
1224 // write syscall all the time.
1225 let mut writer = BufWriter::new(w);
1226 if !cx.render_redirect_pages {
1227 try!(layout::render(&mut writer, &cx.layout, &page,
1228 &Sidebar{ cx: cx, item: it },
1229 &Item{ cx: cx, item: it }));
1231 let mut url = repeat("../").take(cx.current.len())
1232 .collect::<String>();
1233 match cache().paths.get(&it.def_id) {
1234 Some(&(ref names, _)) => {
1235 for name in &names[..names.len() - 1] {
1239 url.push_str(&item_path(it));
1240 try!(layout::redirect(&mut writer, &url));
1248 // Private modules may survive the strip-private pass if they
1249 // contain impls for public types. These modules can also
1250 // contain items such as publicly reexported structures.
1252 // External crates will provide links to these structures, so
1253 // these modules are recursed into, but not rendered normally (a
1254 // flag on the context).
1255 if !self.render_redirect_pages {
1256 self.render_redirect_pages = self.ignore_private_item(&item);
1260 // modules are special because they add a namespace. We also need to
1261 // recurse into the items of the module as well.
1262 clean::ModuleItem(..) => {
1263 let name = item.name.as_ref().unwrap().to_string();
1264 let mut item = Some(item);
1265 self.recurse(name, |this| {
1266 let item = item.take().unwrap();
1267 let dst = this.dst.join("index.html");
1268 let dst = try!(File::create(&dst));
1269 try!(render(dst, this, &item, false));
1271 let m = match item.inner {
1272 clean::ModuleItem(m) => m,
1276 // render sidebar-items.js used throughout this module
1278 let items = this.build_sidebar_items(&m);
1279 let js_dst = this.dst.join("sidebar-items.js");
1280 let mut js_out = BufWriter::new(try!(File::create(&js_dst)));
1281 try!(write!(&mut js_out, "initSidebarItems({});",
1282 json::as_json(&items)));
1285 for item in m.items {
1292 // Things which don't have names (like impls) don't get special
1293 // pages dedicated to them.
1294 _ if item.name.is_some() => {
1295 let dst = self.dst.join(&item_path(&item));
1296 let dst = try!(File::create(&dst));
1297 render(dst, self, &item, true)
1304 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1305 // BTreeMap instead of HashMap to get a sorted output
1306 let mut map = BTreeMap::new();
1307 for item in &m.items {
1308 if self.ignore_private_item(item) { continue }
1310 let short = shortty(item).to_static_str();
1311 let myname = match item.name {
1313 Some(ref s) => s.to_string(),
1315 let short = short.to_string();
1316 map.entry(short).or_insert(vec![])
1317 .push((myname, Some(plain_summary_line(item.doc_value()))));
1320 for (_, items) in &mut map {
1326 fn ignore_private_item(&self, it: &clean::Item) -> bool {
1328 clean::ModuleItem(ref m) => {
1329 (m.items.is_empty() &&
1330 it.doc_value().is_none() &&
1331 it.visibility != Some(hir::Public)) ||
1332 (self.passes.contains("strip-private") && it.visibility != Some(hir::Public))
1334 clean::PrimitiveItem(..) => it.visibility != Some(hir::Public),
1341 fn ismodule(&self) -> bool {
1342 match self.item.inner {
1343 clean::ModuleItem(..) => true, _ => false
1347 /// Generate a url appropriate for an `href` attribute back to the source of
1350 /// The url generated, when clicked, will redirect the browser back to the
1351 /// original source code.
1353 /// If `None` is returned, then a source link couldn't be generated. This
1354 /// may happen, for example, with externally inlined items where the source
1355 /// of their crate documentation isn't known.
1356 fn href(&self, cx: &Context) -> Option<String> {
1357 let href = if self.item.source.loline == self.item.source.hiline {
1358 format!("{}", self.item.source.loline)
1360 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1363 // First check to see if this is an imported macro source. In this case
1364 // we need to handle it specially as cross-crate inlined macros have...
1366 let imported_macro_from = match self.item.inner {
1367 clean::MacroItem(ref m) => m.imported_from.as_ref(),
1370 if let Some(krate) = imported_macro_from {
1371 let cache = cache();
1372 let root = cache.extern_locations.values().find(|&&(ref n, _)| {
1375 let root = match root {
1376 Some(&Remote(ref s)) => s.to_string(),
1377 Some(&Local) => self.cx.root_path.clone(),
1378 None | Some(&Unknown) => return None,
1380 Some(format!("{root}/{krate}/macro.{name}.html?gotomacrosrc=1",
1383 name = self.item.name.as_ref().unwrap()))
1385 // If this item is part of the local crate, then we're guaranteed to
1386 // know the span, so we plow forward and generate a proper url. The url
1387 // has anchors for the line numbers that we're linking to.
1388 } else if self.item.def_id.is_local() {
1389 let mut path = Vec::new();
1390 clean_srcpath(&cx.src_root, Path::new(&self.item.source.filename),
1392 path.push(component.to_string());
1394 Some(format!("{root}src/{krate}/{path}.html#{href}",
1395 root = self.cx.root_path,
1396 krate = self.cx.layout.krate,
1397 path = path.join("/"),
1400 // If this item is not part of the local crate, then things get a little
1401 // trickier. We don't actually know the span of the external item, but
1402 // we know that the documentation on the other end knows the span!
1404 // In this case, we generate a link to the *documentation* for this type
1405 // in the original crate. There's an extra URL parameter which says that
1406 // we want to go somewhere else, and the JS on the destination page will
1407 // pick it up and instantly redirect the browser to the source code.
1409 // If we don't know where the external documentation for this crate is
1410 // located, then we return `None`.
1412 let cache = cache();
1413 let path = &cache.external_paths[&self.item.def_id];
1414 let root = match cache.extern_locations[&self.item.def_id.krate] {
1415 (_, Remote(ref s)) => s.to_string(),
1416 (_, Local) => self.cx.root_path.clone(),
1417 (_, Unknown) => return None,
1419 Some(format!("{root}{path}/{file}?gotosrc={goto}",
1421 path = path[..path.len() - 1].join("/"),
1422 file = item_path(self.item),
1423 goto = self.item.def_id.node))
1429 impl<'a> fmt::Display for Item<'a> {
1430 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1431 // Write the breadcrumb trail header for the top
1432 try!(write!(fmt, "\n<h1 class='fqn'><span class='in-band'>"));
1433 match self.item.inner {
1434 clean::ModuleItem(ref m) => if m.is_crate {
1435 try!(write!(fmt, "Crate "));
1437 try!(write!(fmt, "Module "));
1439 clean::FunctionItem(..) => try!(write!(fmt, "Function ")),
1440 clean::TraitItem(..) => try!(write!(fmt, "Trait ")),
1441 clean::StructItem(..) => try!(write!(fmt, "Struct ")),
1442 clean::EnumItem(..) => try!(write!(fmt, "Enum ")),
1443 clean::PrimitiveItem(..) => try!(write!(fmt, "Primitive Type ")),
1446 let is_primitive = match self.item.inner {
1447 clean::PrimitiveItem(..) => true,
1451 let cur = &self.cx.current;
1452 let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
1453 for (i, component) in cur.iter().enumerate().take(amt) {
1454 try!(write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1455 repeat("../").take(cur.len() - i - 1)
1456 .collect::<String>(),
1460 try!(write!(fmt, "<a class='{}' href=''>{}</a>",
1461 shortty(self.item), self.item.name.as_ref().unwrap()));
1463 try!(write!(fmt, "</span>")); // in-band
1464 try!(write!(fmt, "<span class='out-of-band'>"));
1466 r##"<span id='render-detail'>
1467 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1468 [<span class='inner'>−</span>]
1474 // When this item is part of a `pub use` in a downstream crate, the
1475 // [src] link in the downstream documentation will actually come back to
1476 // this page, and this link will be auto-clicked. The `id` attribute is
1477 // used to find the link to auto-click.
1478 if self.cx.include_sources && !is_primitive {
1479 match self.href(self.cx) {
1481 try!(write!(fmt, "<a id='src-{}' class='srclink' \
1482 href='{}' title='{}'>[src]</a>",
1483 self.item.def_id.node, l, "goto source code"));
1489 try!(write!(fmt, "</span>")); // out-of-band
1491 try!(write!(fmt, "</h1>\n"));
1493 match self.item.inner {
1494 clean::ModuleItem(ref m) => {
1495 item_module(fmt, self.cx, self.item, &m.items)
1497 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1498 item_function(fmt, self.cx, self.item, f),
1499 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1500 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1501 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1502 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1503 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1504 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1505 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1506 item_static(fmt, self.cx, self.item, i),
1507 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1513 fn item_path(item: &clean::Item) -> String {
1515 clean::ModuleItem(..) => {
1516 format!("{}/index.html", item.name.as_ref().unwrap())
1519 format!("{}.{}.html",
1520 shortty(item).to_static_str(),
1521 *item.name.as_ref().unwrap())
1526 fn full_path(cx: &Context, item: &clean::Item) -> String {
1527 let mut s = cx.current.join("::");
1529 s.push_str(item.name.as_ref().unwrap());
1533 fn shorter<'a>(s: Option<&'a str>) -> String {
1535 Some(s) => s.lines().take_while(|line|{
1536 (*line).chars().any(|chr|{
1537 !chr.is_whitespace()
1539 }).collect::<Vec<_>>().join("\n"),
1540 None => "".to_string()
1545 fn plain_summary_line(s: Option<&str>) -> String {
1546 let line = shorter(s).replace("\n", " ");
1547 markdown::plain_summary_line(&line[..])
1550 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1551 if let Some(s) = short_stability(item, cx, true) {
1552 try!(write!(w, "<div class='stability'>{}</div>", s));
1554 if let Some(s) = item.doc_value() {
1555 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1560 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1561 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1562 try!(document(w, cx, item));
1564 let mut indices = (0..items.len()).filter(|i| {
1565 !cx.ignore_private_item(&items[*i])
1566 }).collect::<Vec<usize>>();
1568 // the order of item types in the listing
1569 fn reorder(ty: ItemType) -> u8 {
1571 ItemType::ExternCrate => 0,
1572 ItemType::Import => 1,
1573 ItemType::Primitive => 2,
1574 ItemType::Module => 3,
1575 ItemType::Macro => 4,
1576 ItemType::Struct => 5,
1577 ItemType::Enum => 6,
1578 ItemType::Constant => 7,
1579 ItemType::Static => 8,
1580 ItemType::Trait => 9,
1581 ItemType::Function => 10,
1582 ItemType::Typedef => 12,
1587 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1588 let ty1 = shortty(i1);
1589 let ty2 = shortty(i2);
1591 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1593 let s1 = i1.stability.as_ref().map(|s| s.level);
1594 let s2 = i2.stability.as_ref().map(|s| s.level);
1596 (Some(attr::Unstable), Some(attr::Stable)) => return Ordering::Greater,
1597 (Some(attr::Stable), Some(attr::Unstable)) => return Ordering::Less,
1600 i1.name.cmp(&i2.name)
1603 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1605 debug!("{:?}", indices);
1606 let mut curty = None;
1607 for &idx in &indices {
1608 let myitem = &items[idx];
1610 let myty = Some(shortty(myitem));
1611 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1612 // Put `extern crate` and `use` re-exports in the same section.
1614 } else if myty != curty {
1615 if curty.is_some() {
1616 try!(write!(w, "</table>"));
1619 let (short, name) = match myty.unwrap() {
1620 ItemType::ExternCrate |
1621 ItemType::Import => ("reexports", "Reexports"),
1622 ItemType::Module => ("modules", "Modules"),
1623 ItemType::Struct => ("structs", "Structs"),
1624 ItemType::Enum => ("enums", "Enums"),
1625 ItemType::Function => ("functions", "Functions"),
1626 ItemType::Typedef => ("types", "Type Definitions"),
1627 ItemType::Static => ("statics", "Statics"),
1628 ItemType::Constant => ("constants", "Constants"),
1629 ItemType::Trait => ("traits", "Traits"),
1630 ItemType::Impl => ("impls", "Implementations"),
1631 ItemType::TyMethod => ("tymethods", "Type Methods"),
1632 ItemType::Method => ("methods", "Methods"),
1633 ItemType::StructField => ("fields", "Struct Fields"),
1634 ItemType::Variant => ("variants", "Variants"),
1635 ItemType::Macro => ("macros", "Macros"),
1636 ItemType::Primitive => ("primitives", "Primitive Types"),
1637 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1638 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1641 "<h2 id='{id}' class='section-header'>\
1642 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1643 id = short, name = name));
1646 match myitem.inner {
1647 clean::ExternCrateItem(ref name, ref src) => {
1650 try!(write!(w, "<tr><td><code>{}extern crate {} as {};",
1651 VisSpace(myitem.visibility),
1656 try!(write!(w, "<tr><td><code>{}extern crate {};",
1657 VisSpace(myitem.visibility), name))
1660 try!(write!(w, "</code></td></tr>"));
1663 clean::ImportItem(ref import) => {
1664 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1665 VisSpace(myitem.visibility), *import));
1669 if myitem.name.is_none() { continue }
1670 let stab_docs = if let Some(s) = short_stability(myitem, cx, false) {
1676 <tr class='{stab} module-item'>
1677 <td><a class='{class}' href='{href}'
1678 title='{title}'>{name}</a></td>
1679 <td class='docblock short'>
1684 name = *myitem.name.as_ref().unwrap(),
1685 stab_docs = stab_docs,
1686 docs = Markdown(&shorter(myitem.doc_value())),
1687 class = shortty(myitem),
1688 stab = myitem.stability_class(),
1689 href = item_path(myitem),
1690 title = full_path(cx, myitem)));
1695 write!(w, "</table>")
1698 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Option<String> {
1699 item.stability.as_ref().and_then(|stab| {
1700 let reason = if show_reason && !stab.reason.is_empty() {
1701 format!(": {}", stab.reason)
1705 let text = if !stab.deprecated_since.is_empty() {
1706 let since = if show_reason {
1707 format!(" since {}", Escape(&stab.deprecated_since))
1711 format!("Deprecated{}{}", since, Markdown(&reason))
1712 } else if stab.level == attr::Unstable {
1713 let unstable_extra = if show_reason {
1714 match (!stab.feature.is_empty(), &cx.issue_tracker_base_url, stab.issue) {
1715 (true, &Some(ref tracker_url), Some(issue_no)) =>
1716 format!(" (<code>{}</code> <a href=\"{}{}\">#{}</a>)",
1717 Escape(&stab.feature), tracker_url, issue_no, issue_no),
1718 (false, &Some(ref tracker_url), Some(issue_no)) =>
1719 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
1722 format!(" (<code>{}</code>)", Escape(&stab.feature)),
1728 format!("Unstable{}{}", unstable_extra, Markdown(&reason))
1732 Some(format!("<em class='stab {}'>{}</em>",
1733 item.stability_class(), text))
1737 struct Initializer<'a>(&'a str);
1739 impl<'a> fmt::Display for Initializer<'a> {
1740 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1741 let Initializer(s) = *self;
1742 if s.is_empty() { return Ok(()); }
1743 try!(write!(f, "<code> = </code>"));
1744 write!(f, "<code>{}</code>", s)
1748 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1749 c: &clean::Constant) -> fmt::Result {
1750 try!(write!(w, "<pre class='rust const'>{vis}const \
1751 {name}: {typ}{init}</pre>",
1752 vis = VisSpace(it.visibility),
1753 name = it.name.as_ref().unwrap(),
1755 init = Initializer(&c.expr)));
1759 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1760 s: &clean::Static) -> fmt::Result {
1761 try!(write!(w, "<pre class='rust static'>{vis}static {mutability}\
1762 {name}: {typ}{init}</pre>",
1763 vis = VisSpace(it.visibility),
1764 mutability = MutableSpace(s.mutability),
1765 name = it.name.as_ref().unwrap(),
1767 init = Initializer(&s.expr)));
1771 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1772 f: &clean::Function) -> fmt::Result {
1773 try!(write!(w, "<pre class='rust fn'>{vis}{unsafety}{abi}{constness}fn \
1774 {name}{generics}{decl}{where_clause}</pre>",
1775 vis = VisSpace(it.visibility),
1776 unsafety = UnsafetySpace(f.unsafety),
1777 abi = AbiSpace(f.abi),
1778 constness = ConstnessSpace(f.constness),
1779 name = it.name.as_ref().unwrap(),
1780 generics = f.generics,
1781 where_clause = WhereClause(&f.generics),
1786 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1787 t: &clean::Trait) -> fmt::Result {
1788 let mut bounds = String::new();
1789 if !t.bounds.is_empty() {
1790 if !bounds.is_empty() {
1793 bounds.push_str(": ");
1794 for (i, p) in t.bounds.iter().enumerate() {
1795 if i > 0 { bounds.push_str(" + "); }
1796 bounds.push_str(&format!("{}", *p));
1800 // Output the trait definition
1801 try!(write!(w, "<pre class='rust trait'>{}{}trait {}{}{}{} ",
1802 VisSpace(it.visibility),
1803 UnsafetySpace(t.unsafety),
1804 it.name.as_ref().unwrap(),
1807 WhereClause(&t.generics)));
1809 let types = t.items.iter().filter(|m| {
1810 match m.inner { clean::AssociatedTypeItem(..) => true, _ => false }
1811 }).collect::<Vec<_>>();
1812 let consts = t.items.iter().filter(|m| {
1813 match m.inner { clean::AssociatedConstItem(..) => true, _ => false }
1814 }).collect::<Vec<_>>();
1815 let required = t.items.iter().filter(|m| {
1816 match m.inner { clean::TyMethodItem(_) => true, _ => false }
1817 }).collect::<Vec<_>>();
1818 let provided = t.items.iter().filter(|m| {
1819 match m.inner { clean::MethodItem(_) => true, _ => false }
1820 }).collect::<Vec<_>>();
1822 if t.items.is_empty() {
1823 try!(write!(w, "{{ }}"));
1825 try!(write!(w, "{{\n"));
1827 try!(write!(w, " "));
1828 try!(render_assoc_item(w, t, AssocItemLink::Anchor));
1829 try!(write!(w, ";\n"));
1831 if !types.is_empty() && !consts.is_empty() {
1832 try!(w.write_str("\n"));
1835 try!(write!(w, " "));
1836 try!(render_assoc_item(w, t, AssocItemLink::Anchor));
1837 try!(write!(w, ";\n"));
1839 if !consts.is_empty() && !required.is_empty() {
1840 try!(w.write_str("\n"));
1842 for m in &required {
1843 try!(write!(w, " "));
1844 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1845 try!(write!(w, ";\n"));
1847 if !required.is_empty() && !provided.is_empty() {
1848 try!(w.write_str("\n"));
1850 for m in &provided {
1851 try!(write!(w, " "));
1852 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1853 try!(write!(w, " {{ ... }}\n"));
1855 try!(write!(w, "}}"));
1857 try!(write!(w, "</pre>"));
1859 // Trait documentation
1860 try!(document(w, cx, it));
1862 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item)
1864 try!(write!(w, "<h3 id='{ty}.{name}' class='method stab {stab}'><code>",
1866 name = *m.name.as_ref().unwrap(),
1867 stab = m.stability_class()));
1868 try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1869 try!(write!(w, "</code></h3>"));
1870 try!(document(w, cx, m));
1874 if !types.is_empty() {
1876 <h2 id='associated-types'>Associated Types</h2>
1877 <div class='methods'>
1880 try!(trait_item(w, cx, *t));
1882 try!(write!(w, "</div>"));
1885 if !consts.is_empty() {
1887 <h2 id='associated-const'>Associated Constants</h2>
1888 <div class='methods'>
1891 try!(trait_item(w, cx, *t));
1893 try!(write!(w, "</div>"));
1896 // Output the documentation for each function individually
1897 if !required.is_empty() {
1899 <h2 id='required-methods'>Required Methods</h2>
1900 <div class='methods'>
1902 for m in &required {
1903 try!(trait_item(w, cx, *m));
1905 try!(write!(w, "</div>"));
1907 if !provided.is_empty() {
1909 <h2 id='provided-methods'>Provided Methods</h2>
1910 <div class='methods'>
1912 for m in &provided {
1913 try!(trait_item(w, cx, *m));
1915 try!(write!(w, "</div>"));
1918 // If there are methods directly on this trait object, render them here.
1919 try!(render_assoc_items(w, cx, it.def_id, AssocItemRender::All));
1921 let cache = cache();
1923 <h2 id='implementors'>Implementors</h2>
1924 <ul class='item-list' id='implementors-list'>
1926 match cache.implementors.get(&it.def_id) {
1927 Some(implementors) => {
1928 for i in implementors {
1929 try!(writeln!(w, "<li><code>{}</code></li>", i.impl_));
1934 try!(write!(w, "</ul>"));
1935 try!(write!(w, r#"<script type="text/javascript" async
1936 src="{root_path}/implementors/{path}/{ty}.{name}.js">
1938 root_path = vec![".."; cx.current.len()].join("/"),
1939 path = if it.def_id.is_local() {
1940 cx.current.join("/")
1942 let path = &cache.external_paths[&it.def_id];
1943 path[..path.len() - 1].join("/")
1945 ty = shortty(it).to_static_str(),
1946 name = *it.name.as_ref().unwrap()));
1950 fn assoc_const(w: &mut fmt::Formatter, it: &clean::Item,
1951 ty: &clean::Type, default: Option<&String>)
1953 try!(write!(w, "const {}", it.name.as_ref().unwrap()));
1954 try!(write!(w, ": {}", ty));
1955 if let Some(default) = default {
1956 try!(write!(w, " = {}", default));
1961 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
1962 bounds: &Vec<clean::TyParamBound>,
1963 default: &Option<clean::Type>)
1965 try!(write!(w, "type {}", it.name.as_ref().unwrap()));
1966 if !bounds.is_empty() {
1967 try!(write!(w, ": {}", TyParamBounds(bounds)))
1969 if let Some(ref default) = *default {
1970 try!(write!(w, " = {}", default));
1975 fn render_assoc_item(w: &mut fmt::Formatter, meth: &clean::Item,
1976 link: AssocItemLink) -> fmt::Result {
1977 fn method(w: &mut fmt::Formatter,
1979 unsafety: hir::Unsafety,
1980 constness: hir::Constness,
1982 g: &clean::Generics,
1983 selfty: &clean::SelfTy,
1985 link: AssocItemLink)
1987 use syntax::abi::Abi;
1989 let name = it.name.as_ref().unwrap();
1990 let anchor = format!("#{}.{}", shortty(it), name);
1991 let href = match link {
1992 AssocItemLink::Anchor => anchor,
1993 AssocItemLink::GotoSource(did) => {
1994 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
1997 write!(w, "{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
1998 {generics}{decl}{where_clause}",
1999 UnsafetySpace(unsafety),
2000 ConstnessSpace(constness),
2002 Abi::Rust => String::new(),
2003 a => format!("extern {} ", a.to_string())
2008 decl = Method(selfty, d),
2009 where_clause = WhereClause(g))
2012 clean::TyMethodItem(ref m) => {
2013 method(w, meth, m.unsafety, hir::Constness::NotConst,
2014 m.abi, &m.generics, &m.self_, &m.decl, link)
2016 clean::MethodItem(ref m) => {
2017 method(w, meth, m.unsafety, m.constness,
2018 m.abi, &m.generics, &m.self_, &m.decl,
2021 clean::AssociatedConstItem(ref ty, ref default) => {
2022 assoc_const(w, meth, ty, default.as_ref())
2024 clean::AssociatedTypeItem(ref bounds, ref default) => {
2025 assoc_type(w, meth, bounds, default)
2027 _ => panic!("render_assoc_item called on non-associated-item")
2031 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2032 s: &clean::Struct) -> fmt::Result {
2033 try!(write!(w, "<pre class='rust struct'>"));
2034 try!(render_attributes(w, it));
2035 try!(render_struct(w,
2042 try!(write!(w, "</pre>"));
2044 try!(document(w, cx, it));
2045 let mut fields = s.fields.iter().filter(|f| {
2047 clean::StructFieldItem(clean::HiddenStructField) => false,
2048 clean::StructFieldItem(clean::TypedStructField(..)) => true,
2052 if let doctree::Plain = s.struct_type {
2053 if fields.peek().is_some() {
2054 try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
2055 for field in fields {
2056 try!(write!(w, "<tr class='stab {stab}'>
2057 <td id='structfield.{name}'>\
2058 <code>{name}</code></td><td>",
2059 stab = field.stability_class(),
2060 name = field.name.as_ref().unwrap()));
2061 try!(document(w, cx, field));
2062 try!(write!(w, "</td></tr>"));
2064 try!(write!(w, "</table>"));
2067 render_assoc_items(w, cx, it.def_id, AssocItemRender::All)
2070 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2071 e: &clean::Enum) -> fmt::Result {
2072 try!(write!(w, "<pre class='rust enum'>"));
2073 try!(render_attributes(w, it));
2074 try!(write!(w, "{}enum {}{}{}",
2075 VisSpace(it.visibility),
2076 it.name.as_ref().unwrap(),
2078 WhereClause(&e.generics)));
2079 if e.variants.is_empty() && !e.variants_stripped {
2080 try!(write!(w, " {{}}"));
2082 try!(write!(w, " {{\n"));
2083 for v in &e.variants {
2084 try!(write!(w, " "));
2085 let name = v.name.as_ref().unwrap();
2087 clean::VariantItem(ref var) => {
2089 clean::CLikeVariant => try!(write!(w, "{}", name)),
2090 clean::TupleVariant(ref tys) => {
2091 try!(write!(w, "{}(", name));
2092 for (i, ty) in tys.iter().enumerate() {
2094 try!(write!(w, ", "))
2096 try!(write!(w, "{}", *ty));
2098 try!(write!(w, ")"));
2100 clean::StructVariant(ref s) => {
2101 try!(render_struct(w,
2113 try!(write!(w, ",\n"));
2116 if e.variants_stripped {
2117 try!(write!(w, " // some variants omitted\n"));
2119 try!(write!(w, "}}"));
2121 try!(write!(w, "</pre>"));
2123 try!(document(w, cx, it));
2124 if !e.variants.is_empty() {
2125 try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
2126 for variant in &e.variants {
2127 try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
2128 name = variant.name.as_ref().unwrap()));
2129 try!(document(w, cx, variant));
2130 match variant.inner {
2131 clean::VariantItem(ref var) => {
2133 clean::StructVariant(ref s) => {
2134 let fields = s.fields.iter().filter(|f| {
2136 clean::StructFieldItem(ref t) => match *t {
2137 clean::HiddenStructField => false,
2138 clean::TypedStructField(..) => true,
2143 try!(write!(w, "<h3 class='fields'>Fields</h3>\n
2145 for field in fields {
2146 try!(write!(w, "<tr><td \
2147 id='variant.{v}.field.{f}'>\
2148 <code>{f}</code></td><td>",
2149 v = variant.name.as_ref().unwrap(),
2150 f = field.name.as_ref().unwrap()));
2151 try!(document(w, cx, field));
2152 try!(write!(w, "</td></tr>"));
2154 try!(write!(w, "</table>"));
2161 try!(write!(w, "</td></tr>"));
2163 try!(write!(w, "</table>"));
2166 try!(render_assoc_items(w, cx, it.def_id, AssocItemRender::All));
2170 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2171 for attr in &it.attrs {
2173 clean::Word(ref s) if *s == "must_use" => {
2174 try!(write!(w, "#[{}]\n", s));
2176 clean::NameValue(ref k, ref v) if *k == "must_use" => {
2177 try!(write!(w, "#[{} = \"{}\"]\n", k, v));
2185 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2186 g: Option<&clean::Generics>,
2187 ty: doctree::StructType,
2188 fields: &[clean::Item],
2190 structhead: bool) -> fmt::Result {
2191 try!(write!(w, "{}{}{}",
2192 VisSpace(it.visibility),
2193 if structhead {"struct "} else {""},
2194 it.name.as_ref().unwrap()));
2196 Some(g) => try!(write!(w, "{}{}", *g, WhereClause(g))),
2201 try!(write!(w, " {{\n{}", tab));
2202 let mut fields_stripped = false;
2203 for field in fields {
2205 clean::StructFieldItem(clean::HiddenStructField) => {
2206 fields_stripped = true;
2208 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
2209 try!(write!(w, " {}{}: {},\n{}",
2210 VisSpace(field.visibility),
2211 field.name.as_ref().unwrap(),
2215 _ => unreachable!(),
2219 if fields_stripped {
2220 try!(write!(w, " // some fields omitted\n{}", tab));
2222 try!(write!(w, "}}"));
2224 doctree::Tuple | doctree::Newtype => {
2225 try!(write!(w, "("));
2226 for (i, field) in fields.iter().enumerate() {
2228 try!(write!(w, ", "));
2231 clean::StructFieldItem(clean::HiddenStructField) => {
2232 try!(write!(w, "_"))
2234 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
2235 try!(write!(w, "{}{}", VisSpace(field.visibility), *ty))
2240 try!(write!(w, ");"));
2243 try!(write!(w, ";"));
2249 #[derive(Copy, Clone)]
2250 enum AssocItemLink {
2255 enum AssocItemRender<'a> {
2257 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type },
2260 fn render_assoc_items(w: &mut fmt::Formatter,
2263 what: AssocItemRender) -> fmt::Result {
2265 let v = match c.impls.get(&it) {
2267 None => return Ok(()),
2269 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
2270 i.impl_.trait_.is_none()
2272 if !non_trait.is_empty() {
2273 let render_header = match what {
2274 AssocItemRender::All => {
2275 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
2278 AssocItemRender::DerefFor { trait_, type_ } => {
2279 try!(write!(w, "<h2 id='deref-methods'>Methods from \
2280 {}<Target={}></h2>", trait_, type_));
2284 for i in &non_trait {
2285 try!(render_impl(w, cx, i, AssocItemLink::Anchor, render_header));
2288 if let AssocItemRender::DerefFor { .. } = what {
2291 if !traits.is_empty() {
2292 let deref_impl = traits.iter().find(|t| {
2293 match *t.impl_.trait_.as_ref().unwrap() {
2294 clean::ResolvedPath { did, .. } => {
2295 Some(did) == c.deref_trait_did
2300 if let Some(impl_) = deref_impl {
2301 try!(render_deref_methods(w, cx, impl_));
2303 try!(write!(w, "<h2 id='implementations'>Trait \
2304 Implementations</h2>"));
2305 let (derived, manual): (Vec<_>, Vec<&Impl>) = traits.iter().partition(|i| {
2309 let did = i.trait_did().unwrap();
2310 try!(render_impl(w, cx, i, AssocItemLink::GotoSource(did), true));
2312 if !derived.is_empty() {
2313 try!(write!(w, "<h3 id='derived_implementations'>\
2314 Derived Implementations \
2317 let did = i.trait_did().unwrap();
2318 try!(render_impl(w, cx, i, AssocItemLink::GotoSource(did), true));
2325 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl) -> fmt::Result {
2326 let deref_type = impl_.impl_.trait_.as_ref().unwrap();
2327 let target = impl_.impl_.items.iter().filter_map(|item| {
2329 clean::TypedefItem(ref t, true) => Some(&t.type_),
2332 }).next().expect("Expected associated type binding");
2333 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target };
2335 clean::ResolvedPath { did, .. } => render_assoc_items(w, cx, did, what),
2337 if let Some(prim) = target.primitive_type() {
2338 if let Some(c) = cache().primitive_locations.get(&prim) {
2339 let did = DefId { krate: *c, node: prim.to_node_id() };
2340 try!(render_assoc_items(w, cx, did, what));
2348 // Render_header is false when we are rendering a `Deref` impl and true
2349 // otherwise. If render_header is false, we will avoid rendering static
2350 // methods, since they are not accessible for the type implementing `Deref`
2351 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
2352 render_header: bool) -> fmt::Result {
2354 try!(write!(w, "<h3 class='impl'><code>{}</code></h3>", i.impl_));
2355 if let Some(ref dox) = i.dox {
2356 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(dox)));
2360 fn doctraititem(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2361 link: AssocItemLink, render_static: bool) -> fmt::Result {
2363 clean::MethodItem(..) | clean::TyMethodItem(..) => {
2364 // Only render when the method is not static or we allow static methods
2365 if !is_static_method(item) || render_static {
2366 try!(write!(w, "<h4 id='method.{}' class='{}'><code>",
2367 *item.name.as_ref().unwrap(),
2369 try!(render_assoc_item(w, item, link));
2370 try!(write!(w, "</code></h4>\n"));
2373 clean::TypedefItem(ref tydef, _) => {
2374 let name = item.name.as_ref().unwrap();
2375 try!(write!(w, "<h4 id='assoc_type.{}' class='{}'><code>",
2378 try!(write!(w, "type {} = {}", name, tydef.type_));
2379 try!(write!(w, "</code></h4>\n"));
2381 clean::AssociatedConstItem(ref ty, ref default) => {
2382 let name = item.name.as_ref().unwrap();
2383 try!(write!(w, "<h4 id='assoc_const.{}' class='{}'><code>",
2384 *name, shortty(item)));
2385 try!(assoc_const(w, item, ty, default.as_ref()));
2386 try!(write!(w, "</code></h4>\n"));
2388 clean::ConstantItem(ref c) => {
2389 let name = item.name.as_ref().unwrap();
2390 try!(write!(w, "<h4 id='assoc_const.{}' class='{}'><code>",
2391 *name, shortty(item)));
2392 try!(assoc_const(w, item, &c.type_, Some(&c.expr)));
2393 try!(write!(w, "</code></h4>\n"));
2395 clean::AssociatedTypeItem(ref bounds, ref default) => {
2396 let name = item.name.as_ref().unwrap();
2397 try!(write!(w, "<h4 id='assoc_type.{}' class='{}'><code>",
2400 try!(assoc_type(w, item, bounds, default));
2401 try!(write!(w, "</code></h4>\n"));
2403 _ => panic!("can't make docs for trait item with name {:?}", item.name)
2406 return if let AssocItemLink::Anchor = link {
2407 if is_static_method(item) && !render_static {
2410 document(w, cx, item)
2416 fn is_static_method(item: &clean::Item) -> bool {
2418 clean::MethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
2419 clean::TyMethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
2425 try!(write!(w, "<div class='impl-items'>"));
2426 for trait_item in &i.impl_.items {
2427 try!(doctraititem(w, cx, trait_item, link, render_header));
2430 fn render_default_items(w: &mut fmt::Formatter,
2435 render_static: bool) -> fmt::Result {
2436 for trait_item in &t.items {
2437 let n = trait_item.name.clone();
2438 match i.items.iter().find(|m| { m.name == n }) {
2439 Some(..) => continue,
2443 try!(doctraititem(w, cx, trait_item, AssocItemLink::GotoSource(did), render_static));
2448 // If we've implemented a trait, then also emit documentation for all
2449 // default methods which weren't overridden in the implementation block.
2450 // FIXME: this also needs to be done for associated types, whenever defaults
2452 if let Some(clean::ResolvedPath { did, .. }) = i.impl_.trait_ {
2453 if let Some(t) = cache().traits.get(&did) {
2454 try!(render_default_items(w, cx, did, t, &i.impl_, render_header));
2458 try!(write!(w, "</div>"));
2462 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2463 t: &clean::Typedef) -> fmt::Result {
2464 try!(write!(w, "<pre class='rust typedef'>type {}{}{where_clause} = {type_};</pre>",
2465 it.name.as_ref().unwrap(),
2467 where_clause = WhereClause(&t.generics),
2473 impl<'a> fmt::Display for Sidebar<'a> {
2474 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2477 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
2479 // the sidebar is designed to display sibling functions, modules and
2480 // other miscellaneous informations. since there are lots of sibling
2481 // items (and that causes quadratic growth in large modules),
2482 // we refactor common parts into a shared JavaScript file per module.
2483 // still, we don't move everything into JS because we want to preserve
2484 // as much HTML as possible in order to allow non-JS-enabled browsers
2485 // to navigate the documentation (though slightly inefficiently).
2487 try!(write!(fmt, "<p class='location'>"));
2488 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
2490 try!(write!(fmt, "::<wbr>"));
2492 try!(write!(fmt, "<a href='{}index.html'>{}</a>",
2493 &cx.root_path[..(cx.current.len() - i - 1) * 3],
2496 try!(write!(fmt, "</p>"));
2498 // sidebar refers to the enclosing module, not this module
2499 let relpath = if shortty(it) == ItemType::Module { "../" } else { "" };
2501 "<script>window.sidebarCurrent = {{\
2506 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
2507 ty = shortty(it).to_static_str(),
2510 // there is no sidebar-items.js beyond the crate root path
2511 // FIXME maybe dynamic crate loading can be merged here
2513 try!(write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
2521 impl<'a> fmt::Display for Source<'a> {
2522 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2523 let Source(s) = *self;
2524 let lines = s.lines().count();
2526 let mut tmp = lines;
2531 try!(write!(fmt, "<pre class=\"line-numbers\">"));
2532 for i in 1..lines + 1 {
2533 try!(write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols));
2535 try!(write!(fmt, "</pre>"));
2536 try!(write!(fmt, "{}", highlight::highlight(s, None, None)));
2541 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2542 t: &clean::Macro) -> fmt::Result {
2543 try!(w.write_str(&highlight::highlight(&t.source,
2549 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
2551 _p: &clean::PrimitiveType) -> fmt::Result {
2552 try!(document(w, cx, it));
2553 render_assoc_items(w, cx, it.def_id, AssocItemRender::All)
2556 fn get_basic_keywords() -> &'static str {
2557 "rust, rustlang, rust-lang"
2560 fn make_item_keywords(it: &clean::Item) -> String {
2561 format!("{}, {}", get_basic_keywords(), it.name.as_ref().unwrap())
2564 fn get_index_search_type(item: &clean::Item,
2565 parent: Option<String>) -> Option<IndexItemFunctionType> {
2566 let decl = match item.inner {
2567 clean::FunctionItem(ref f) => &f.decl,
2568 clean::MethodItem(ref m) => &m.decl,
2569 clean::TyMethodItem(ref m) => &m.decl,
2573 let mut inputs = Vec::new();
2575 // Consider `self` an argument as well.
2576 if let Some(name) = parent {
2577 inputs.push(Type { name: Some(name.to_ascii_lowercase()) });
2580 inputs.extend(&mut decl.inputs.values.iter().map(|arg| {
2581 get_index_type(&arg.type_)
2584 let output = match decl.output {
2585 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
2589 Some(IndexItemFunctionType { inputs: inputs, output: output })
2592 fn get_index_type(clean_type: &clean::Type) -> Type {
2593 Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
2596 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
2598 clean::ResolvedPath { ref path, .. } => {
2599 let segments = &path.segments;
2600 Some(segments[segments.len() - 1].name.clone())
2602 clean::Generic(ref s) => Some(s.clone()),
2603 clean::Primitive(ref p) => Some(format!("{:?}", p)),
2604 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
2605 // FIXME: add all from clean::Type.
2610 pub fn cache() -> Arc<Cache> {
2611 CACHE_KEY.with(|c| c.borrow().clone())