1 // Copyright 2013-2014 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 tasks. The cache is meant
21 //! to be a fairly large structure not implementing `Clone` (because it's shared
22 //! among tasks). The context, however, should be a lightweight structure. This
23 //! is cloned per-task 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 tasks are not parallelized (they haven't been a bottleneck yet), and
34 //! both occur before the crate is rendered.
36 use std::collections::{HashMap, HashSet};
38 use std::io::{fs, File, BufferedWriter, MemWriter, BufferedReader};
41 use std::string::String;
44 use serialize::json::ToJson;
48 use syntax::parse::token::InternedString;
49 use rustc::util::nodemap::NodeSet;
54 use html::format::{VisSpace, Method, FnStyleSpace, MutableSpace};
56 use html::item_type::{ItemType, shortty};
59 use html::markdown::Markdown;
62 /// Major driving force in all rustdoc rendering. This contains information
63 /// about where in the tree-like hierarchy rendering is occurring and controls
64 /// how the current page is being rendered.
66 /// It is intended that this context is a lightweight object which can be fairly
67 /// easily cloned because it is cloned per work-job (about once per item in the
71 /// Current hierarchy of components leading down to what's currently being
73 pub current: Vec<String>,
74 /// String representation of how to get back to the root path of the 'doc/'
75 /// folder in terms of a relative URL.
76 pub root_path: String,
77 /// The current destination folder of where HTML artifacts should be placed.
78 /// This changes as the context descends into the module hierarchy.
80 /// This describes the layout of each page, and is not modified after
81 /// creation of the context (contains info like the favicon)
82 pub layout: layout::Layout,
83 /// This map is a list of what should be displayed on the sidebar of the
84 /// current page. The key is the section header (traits, modules,
85 /// functions), and the value is the list of containers belonging to this
86 /// header. This map will change depending on the surrounding context of the
88 pub sidebar: HashMap<String, Vec<String>>,
89 /// This flag indicates whether [src] links should be generated or not. If
90 /// the source files are present in the html rendering, then this will be
92 pub include_sources: bool,
93 /// A flag, which when turned off, will render pages which redirect to the
94 /// real location of an item. This is used to allow external links to
95 /// publicly reused items to redirect to the right location.
96 pub render_redirect_pages: bool,
99 /// Indicates where an external crate can be found.
100 pub enum ExternalLocation {
101 /// Remote URL root of the external crate
103 /// This external crate can be found in the local doc/ folder
105 /// The external crate could not be found.
109 /// Metadata about an implementor of a trait.
110 pub struct Implementor {
112 generics: clean::Generics,
117 /// This cache is used to store information about the `clean::Crate` being
118 /// rendered in order to provide more useful documentation. This contains
119 /// information like all implementors of a trait, all traits a type implements,
120 /// documentation for all known traits, etc.
122 /// This structure purposefully does not implement `Clone` because it's intended
123 /// to be a fairly large and expensive structure to clone. Instead this adheres
124 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
127 /// Mapping of typaram ids to the name of the type parameter. This is used
128 /// when pretty-printing a type (so pretty printing doesn't have to
129 /// painfully maintain a context like this)
130 pub typarams: HashMap<ast::DefId, String>,
132 /// Maps a type id to all known implementations for that type. This is only
133 /// recognized for intra-crate `ResolvedPath` types, and is used to print
134 /// out extra documentation on the page of an enum/struct.
136 /// The values of the map are a list of implementations and documentation
137 /// found on that implementation.
138 pub impls: HashMap<ast::DefId, Vec<(clean::Impl, Option<String>)>>,
140 /// Maintains a mapping of local crate node ids to the fully qualified name
141 /// and "short type description" of that node. This is used when generating
142 /// URLs when a type is being linked to. External paths are not located in
143 /// this map because the `External` type itself has all the information
145 pub paths: HashMap<ast::DefId, (Vec<String>, ItemType)>,
147 /// Similar to `paths`, but only holds external paths. This is only used for
148 /// generating explicit hyperlinks to other crates.
149 pub external_paths: HashMap<ast::DefId, Vec<String>>,
151 /// This map contains information about all known traits of this crate.
152 /// Implementations of a crate should inherit the documentation of the
153 /// parent trait if no extra documentation is specified, and default methods
154 /// should show up in documentation about trait implementations.
155 pub traits: HashMap<ast::DefId, clean::Trait>,
157 /// When rendering traits, it's often useful to be able to list all
158 /// implementors of the trait, and this mapping is exactly, that: a mapping
159 /// of trait ids to the list of known implementors of the trait
160 pub implementors: HashMap<ast::DefId, Vec<Implementor>>,
162 /// Cache of where external crate documentation can be found.
163 pub extern_locations: HashMap<ast::CrateNum, ExternalLocation>,
165 /// Cache of where documentation for primitives can be found.
166 pub primitive_locations: HashMap<clean::Primitive, ast::CrateNum>,
168 /// Set of definitions which have been inlined from external crates.
169 pub inlined: HashSet<ast::DefId>,
171 // Private fields only used when initially crawling a crate to build a cache
174 parent_stack: Vec<ast::DefId>,
175 search_index: Vec<IndexItem>,
177 public_items: NodeSet,
179 // In rare case where a structure is defined in one module but implemented
180 // in another, if the implementing module is parsed before defining module,
181 // then the fully qualified name of the structure isn't presented in `paths`
182 // yet when its implementation methods are being indexed. Caches such methods
183 // and their parent id here and indexes them at the end of crate parsing.
184 orphan_methods: Vec<(ast::NodeId, clean::Item)>,
187 /// Helper struct to render all source code to HTML pages
188 struct SourceCollector<'a> {
191 /// Processed source-file paths
192 seen: HashSet<String>,
193 /// Root destination to place all HTML output into
197 /// Wrapper struct to render the source code of a file. This will do things like
198 /// adding line numbers to the left-hand side.
199 struct Source<'a>(&'a str);
201 // Helper structs for rendering items/sidebars and carrying along contextual
204 struct Item<'a> { cx: &'a Context, item: &'a clean::Item, }
205 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
207 /// Struct representing one entry in the JS search index. These are all emitted
208 /// by hand to a large JS file at the end of cache-creation.
214 parent: Option<ast::DefId>,
217 // TLS keys used to carry information around during rendering.
219 local_data_key!(pub cache_key: Arc<Cache>)
220 local_data_key!(pub current_location_key: Vec<String> )
222 /// Generates the documentation for `crate` into the directory `dst`
223 pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> {
224 let mut cx = Context {
227 root_path: String::new(),
228 sidebar: HashMap::new(),
229 layout: layout::Layout {
230 logo: "".to_string(),
231 favicon: "".to_string(),
232 krate: krate.name.clone(),
233 playground_url: "".to_string(),
235 include_sources: true,
236 render_redirect_pages: false,
238 try!(mkdir(&cx.dst));
240 // Crawl the crate attributes looking for attributes which control how we're
241 // going to emit HTML
242 match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(&[])) {
244 for attr in attrs.iter() {
246 clean::NameValue(ref x, ref s)
247 if "html_favicon_url" == x.as_slice() => {
248 cx.layout.favicon = s.to_string();
250 clean::NameValue(ref x, ref s)
251 if "html_logo_url" == x.as_slice() => {
252 cx.layout.logo = s.to_string();
254 clean::NameValue(ref x, ref s)
255 if "html_playground_url" == x.as_slice() => {
256 cx.layout.playground_url = s.to_string();
257 let name = krate.name.clone();
258 if markdown::playground_krate.get().is_none() {
259 markdown::playground_krate.replace(Some(Some(name)));
263 if "html_no_source" == x.as_slice() => {
264 cx.include_sources = false;
273 // Crawl the crate to build various caches used for the output
274 let analysis = ::analysiskey.get();
275 let public_items = analysis.as_ref().map(|a| a.public_items.clone());
276 let public_items = public_items.unwrap_or(NodeSet::new());
277 let paths: HashMap<ast::DefId, (Vec<String>, ItemType)> =
278 analysis.as_ref().map(|a| {
279 let paths = a.external_paths.borrow_mut().take_unwrap();
280 paths.move_iter().map(|(k, (v, t))| {
282 clean::TypeStruct => item_type::Struct,
283 clean::TypeEnum => item_type::Enum,
284 clean::TypeFunction => item_type::Function,
285 clean::TypeTrait => item_type::Trait,
286 clean::TypeModule => item_type::Module,
287 clean::TypeStatic => item_type::Static,
288 clean::TypeVariant => item_type::Variant,
291 }).unwrap_or(HashMap::new());
292 let mut cache = Cache {
293 impls: HashMap::new(),
294 external_paths: paths.iter().map(|(&k, &(ref v, _))| (k, v.clone()))
297 implementors: HashMap::new(),
299 parent_stack: Vec::new(),
300 search_index: Vec::new(),
301 extern_locations: HashMap::new(),
302 primitive_locations: HashMap::new(),
304 public_items: public_items,
305 orphan_methods: Vec::new(),
306 traits: analysis.as_ref().map(|a| {
307 a.external_traits.borrow_mut().take_unwrap()
308 }).unwrap_or(HashMap::new()),
309 typarams: analysis.as_ref().map(|a| {
310 a.external_typarams.borrow_mut().take_unwrap()
311 }).unwrap_or(HashMap::new()),
312 inlined: analysis.as_ref().map(|a| {
313 a.inlined.borrow_mut().take_unwrap()
314 }).unwrap_or(HashSet::new()),
316 cache.stack.push(krate.name.clone());
317 krate = cache.fold_crate(krate);
319 // Cache where all our extern crates are located
320 for &(n, ref e) in krate.externs.iter() {
321 cache.extern_locations.insert(n, extern_location(e, &cx.dst));
322 let did = ast::DefId { krate: n, node: ast::CRATE_NODE_ID };
323 cache.paths.insert(did, (vec![e.name.to_string()], item_type::Module));
326 // Cache where all known primitives have their documentation located.
328 // Favor linking to as local extern as possible, so iterate all crates in
329 // reverse topological order.
330 for &(n, ref e) in krate.externs.iter().rev() {
331 for &prim in e.primitives.iter() {
332 cache.primitive_locations.insert(prim, n);
335 for &prim in krate.primitives.iter() {
336 cache.primitive_locations.insert(prim, ast::LOCAL_CRATE);
339 // Build our search index
340 let index = try!(build_index(&krate, &mut cache));
342 // Freeze the cache now that the index has been built. Put an Arc into TLS
343 // for future parallelization opportunities
344 let cache = Arc::new(cache);
345 cache_key.replace(Some(cache.clone()));
346 current_location_key.replace(Some(Vec::new()));
348 try!(write_shared(&cx, &krate, &*cache, index));
349 let krate = try!(render_sources(&mut cx, krate));
351 // And finally render the whole crate's documentation
355 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult<String> {
356 // Build the search index from the collected metadata
357 let mut nodeid_to_pathid = HashMap::new();
358 let mut pathid_to_nodeid = Vec::new();
360 let Cache { ref mut search_index,
362 ref mut paths, .. } = *cache;
364 // Attach all orphan methods to the type's definition if the type
365 // has since been learned.
366 for &(pid, ref item) in orphan_methods.iter() {
367 let did = ast_util::local_def(pid);
368 match paths.find(&did) {
369 Some(&(ref fqp, _)) => {
370 search_index.push(IndexItem {
372 name: item.name.clone().unwrap(),
373 path: fqp.slice_to(fqp.len() - 1).connect("::")
375 desc: shorter(item.doc_value()).to_string(),
383 // Reduce `NodeId` in paths into smaller sequential numbers,
384 // and prune the paths that do not appear in the index.
385 for item in search_index.iter() {
388 if !nodeid_to_pathid.contains_key(&nodeid) {
389 let pathid = pathid_to_nodeid.len();
390 nodeid_to_pathid.insert(nodeid, pathid);
391 pathid_to_nodeid.push(nodeid);
397 assert_eq!(nodeid_to_pathid.len(), pathid_to_nodeid.len());
400 // Collect the index into a string
401 let mut w = MemWriter::new();
402 try!(write!(&mut w, r#"searchIndex['{}'] = {{"items":["#, krate.name));
404 let mut lastpath = "".to_string();
405 for (i, item) in cache.search_index.iter().enumerate() {
406 // Omit the path if it is same to that of the prior item.
408 if lastpath.as_slice() == item.path.as_slice() {
411 lastpath = item.path.to_string();
412 path = item.path.as_slice();
416 try!(write!(&mut w, ","));
418 try!(write!(&mut w, r#"[{:u},"{}","{}",{}"#,
419 item.ty, item.name, path,
420 item.desc.to_json().to_str()));
423 let pathid = *nodeid_to_pathid.find(&nodeid).unwrap();
424 try!(write!(&mut w, ",{}", pathid));
428 try!(write!(&mut w, "]"));
431 try!(write!(&mut w, r#"],"paths":["#));
433 for (i, &did) in pathid_to_nodeid.iter().enumerate() {
434 let &(ref fqp, short) = cache.paths.find(&did).unwrap();
436 try!(write!(&mut w, ","));
438 try!(write!(&mut w, r#"[{:u},"{}"]"#,
439 short, *fqp.last().unwrap()));
442 try!(write!(&mut w, "]}};"));
444 Ok(str::from_utf8(w.unwrap().as_slice()).unwrap().to_string())
447 fn write_shared(cx: &Context,
448 krate: &clean::Crate,
450 search_index: String) -> io::IoResult<()> {
451 // Write out the shared files. Note that these are shared among all rustdoc
452 // docs placed in the output directory, so this needs to be a synchronized
453 // operation with respect to all other rustdocs running around.
454 try!(mkdir(&cx.dst));
455 let _lock = ::flock::Lock::new(&cx.dst.join(".lock"));
457 // Add all the static files. These may already exist, but we just
458 // overwrite them anyway to make sure that they're fresh and up-to-date.
459 try!(write(cx.dst.join("jquery.js"),
460 include_bin!("static/jquery-2.1.0.min.js")));
461 try!(write(cx.dst.join("main.js"), include_bin!("static/main.js")));
462 try!(write(cx.dst.join("playpen.js"), include_bin!("static/playpen.js")));
463 try!(write(cx.dst.join("main.css"), include_bin!("static/main.css")));
464 try!(write(cx.dst.join("normalize.css"),
465 include_bin!("static/normalize.css")));
466 try!(write(cx.dst.join("FiraSans-Regular.woff"),
467 include_bin!("static/FiraSans-Regular.woff")));
468 try!(write(cx.dst.join("FiraSans-Medium.woff"),
469 include_bin!("static/FiraSans-Medium.woff")));
470 try!(write(cx.dst.join("Heuristica-Regular.woff"),
471 include_bin!("static/Heuristica-Regular.woff")));
472 try!(write(cx.dst.join("Heuristica-Italic.woff"),
473 include_bin!("static/Heuristica-Italic.woff")));
474 try!(write(cx.dst.join("Heuristica-Bold.woff"),
475 include_bin!("static/Heuristica-Bold.woff")));
477 fn collect(path: &Path, krate: &str,
478 key: &str) -> io::IoResult<Vec<String>> {
479 let mut ret = Vec::new();
481 for line in BufferedReader::new(File::open(path)).lines() {
482 let line = try!(line);
483 if !line.as_slice().starts_with(key) {
486 if line.as_slice().starts_with(
487 format!("{}['{}']", key, krate).as_slice()) {
490 ret.push(line.to_string());
496 // Update the search index
497 let dst = cx.dst.join("search-index.js");
498 let all_indexes = try!(collect(&dst, krate.name.as_slice(),
500 let mut w = try!(File::create(&dst));
501 try!(writeln!(&mut w, "var searchIndex = {{}};"));
502 try!(writeln!(&mut w, "{}", search_index));
503 for index in all_indexes.iter() {
504 try!(writeln!(&mut w, "{}", *index));
506 try!(writeln!(&mut w, "initSearch(searchIndex);"));
508 // Update the list of all implementors for traits
509 let dst = cx.dst.join("implementors");
511 for (&did, imps) in cache.implementors.iter() {
512 // Private modules can leak through to this phase of rustdoc, which
513 // could contain implementations for otherwise private types. In some
514 // rare cases we could find an implementation for an item which wasn't
515 // indexed, so we just skip this step in that case.
517 // FIXME: this is a vague explanation for why this can't be a `get`, in
518 // theory it should be...
519 let &(ref remote_path, remote_item_type) = match cache.paths.find(&did) {
524 let mut mydst = dst.clone();
525 for part in remote_path.slice_to(remote_path.len() - 1).iter() {
526 mydst.push(part.as_slice());
529 mydst.push(format!("{}.{}.js",
530 remote_item_type.to_static_str(),
531 *remote_path.get(remote_path.len() - 1)));
532 let all_implementors = try!(collect(&mydst, krate.name.as_slice(),
535 try!(mkdir(&mydst.dir_path()));
536 let mut f = BufferedWriter::new(try!(File::create(&mydst)));
537 try!(writeln!(&mut f, "(function() {{var implementors = {{}};"));
539 for implementor in all_implementors.iter() {
540 try!(write!(&mut f, "{}", *implementor));
543 try!(write!(&mut f, r"implementors['{}'] = [", krate.name));
544 for imp in imps.iter() {
545 // If the trait and implementation are in the same crate, then
546 // there's no need to emit information about it (there's inlining
547 // going on). If they're in different crates then the crate defining
548 // the trait will be interested in our implementation.
549 if imp.def_id.krate == did.krate { continue }
550 try!(write!(&mut f, r#""impl{} {} for {}","#,
551 imp.generics, imp.trait_, imp.for_));
553 try!(writeln!(&mut f, r"];"));
554 try!(writeln!(&mut f, "{}", r"
555 if (window.register_implementors) {
556 window.register_implementors(implementors);
558 window.pending_implementors = implementors;
561 try!(writeln!(&mut f, r"}})()"));
566 fn render_sources(cx: &mut Context,
567 krate: clean::Crate) -> io::IoResult<clean::Crate> {
568 info!("emitting source files");
569 let dst = cx.dst.join("src");
571 let dst = dst.join(krate.name.as_slice());
573 let mut folder = SourceCollector {
575 seen: HashSet::new(),
578 // skip all invalid spans
579 folder.seen.insert("".to_string());
580 Ok(folder.fold_crate(krate))
583 /// Writes the entire contents of a string to a destination, not attempting to
584 /// catch any errors.
585 fn write(dst: Path, contents: &[u8]) -> io::IoResult<()> {
586 File::create(&dst).write(contents)
589 /// Makes a directory on the filesystem, failing the task if an error occurs and
590 /// skipping if the directory already exists.
591 fn mkdir(path: &Path) -> io::IoResult<()> {
593 fs::mkdir(path, io::UserRWX)
599 /// Takes a path to a source file and cleans the path to it. This canonicalizes
600 /// things like ".." to components which preserve the "top down" hierarchy of a
601 /// static HTML tree.
602 // FIXME (#9639): The closure should deal with &[u8] instead of &str
603 fn clean_srcpath(src: &[u8], f: |&str|) {
604 let p = Path::new(src);
605 if p.as_vec() != b"." {
606 for c in p.str_components().map(|x|x.unwrap()) {
616 /// Attempts to find where an external crate is located, given that we're
617 /// rendering in to the specified source destination.
618 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
619 // See if there's documentation generated into the local directory
620 let local_location = dst.join(e.name.as_slice());
621 if local_location.is_dir() {
625 // Failing that, see if there's an attribute specifying where to find this
627 for attr in e.attrs.iter() {
629 clean::List(ref x, ref list) if "doc" == x.as_slice() => {
630 for attr in list.iter() {
632 clean::NameValue(ref x, ref s)
633 if "html_root_url" == x.as_slice() => {
634 if s.as_slice().ends_with("/") {
635 return Remote(s.to_string());
637 return Remote(format!("{}/", s));
647 // Well, at least we tried.
651 impl<'a> DocFolder for SourceCollector<'a> {
652 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
653 // If we're including source files, and we haven't seen this file yet,
654 // then we need to render it out to the filesystem
655 if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
657 // If it turns out that we couldn't read this file, then we probably
658 // can't read any of the files (generating html output from json or
659 // something like that), so just don't include sources for the
660 // entire crate. The other option is maintaining this mapping on a
661 // per-file basis, but that's probably not worth it...
663 .include_sources = match self.emit_source(item.source
668 println!("warning: source code was requested to be rendered, \
669 but processing `{}` had an error: {}",
670 item.source.filename, e);
671 println!(" skipping rendering of source code");
675 self.seen.insert(item.source.filename.clone());
678 self.fold_item_recur(item)
682 impl<'a> SourceCollector<'a> {
683 /// Renders the given filename into its corresponding HTML source file.
684 fn emit_source(&mut self, filename: &str) -> io::IoResult<()> {
685 let p = Path::new(filename);
687 // If we couldn't open this file, then just returns because it
688 // probably means that it's some standard library macro thing and we
689 // can't have the source to it anyway.
690 let contents = match File::open(&p).read_to_end() {
692 // macros from other libraries get special filenames which we can
694 Err(..) if filename.starts_with("<") &&
695 filename.ends_with("macros>") => return Ok(()),
696 Err(e) => return Err(e)
698 let contents = str::from_utf8(contents.as_slice()).unwrap();
700 // Remove the utf-8 BOM if any
701 let contents = if contents.starts_with("\ufeff") {
702 contents.as_slice().slice_from(3)
707 // Create the intermediate directories
708 let mut cur = self.dst.clone();
709 let mut root_path = String::from_str("../../");
710 clean_srcpath(p.dirname(), |component| {
712 mkdir(&cur).unwrap();
713 root_path.push_str("../");
716 cur.push(Vec::from_slice(p.filename().expect("source has no filename"))
718 let mut w = BufferedWriter::new(try!(File::create(&cur)));
720 let title = format!("{} -- source", cur.filename_display());
721 let page = layout::Page {
722 title: title.as_slice(),
724 root_path: root_path.as_slice(),
726 try!(layout::render(&mut w as &mut Writer, &self.cx.layout,
727 &page, &(""), &Source(contents)));
733 impl DocFolder for Cache {
734 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
735 // If this is a private module, we don't want it in the search index.
736 let orig_privmod = match item.inner {
737 clean::ModuleItem(..) => {
738 let prev = self.privmod;
739 self.privmod = prev || item.visibility != Some(ast::Public);
745 // Register any generics to their corresponding string. This is used
746 // when pretty-printing types
748 clean::StructItem(ref s) => self.generics(&s.generics),
749 clean::EnumItem(ref e) => self.generics(&e.generics),
750 clean::FunctionItem(ref f) => self.generics(&f.generics),
751 clean::TypedefItem(ref t) => self.generics(&t.generics),
752 clean::TraitItem(ref t) => self.generics(&t.generics),
753 clean::ImplItem(ref i) => self.generics(&i.generics),
754 clean::TyMethodItem(ref i) => self.generics(&i.generics),
755 clean::MethodItem(ref i) => self.generics(&i.generics),
756 clean::ForeignFunctionItem(ref f) => self.generics(&f.generics),
760 // Propagate a trait methods' documentation to all implementors of the
763 clean::TraitItem(ref t) => {
764 self.traits.insert(item.def_id, t.clone());
769 // Collect all the implementors of traits.
771 clean::ImplItem(ref i) => {
773 Some(clean::ResolvedPath{ did, .. }) => {
774 let v = self.implementors.find_or_insert_with(did, |_| {
779 generics: i.generics.clone(),
780 trait_: i.trait_.get_ref().clone(),
781 for_: i.for_.clone(),
784 Some(..) | None => {}
790 // Index this method for searching later on
793 let parent = match item.inner {
794 clean::TyMethodItem(..) |
795 clean::StructFieldItem(..) |
796 clean::VariantItem(..) => {
797 (Some(*self.parent_stack.last().unwrap()),
798 Some(self.stack.slice_to(self.stack.len() - 1)))
800 clean::MethodItem(..) => {
801 if self.parent_stack.len() == 0 {
804 let last = self.parent_stack.last().unwrap();
806 let path = match self.paths.find(&did) {
807 Some(&(_, item_type::Trait)) =>
808 Some(self.stack.slice_to(self.stack.len() - 1)),
809 // The current stack not necessarily has correlation for
810 // where the type was defined. On the other hand,
811 // `paths` always has the right information if present.
812 Some(&(ref fqp, item_type::Struct)) |
813 Some(&(ref fqp, item_type::Enum)) =>
814 Some(fqp.slice_to(fqp.len() - 1)),
815 Some(..) => Some(self.stack.as_slice()),
821 _ => (None, Some(self.stack.as_slice()))
824 (parent, Some(path)) if !self.privmod => {
825 self.search_index.push(IndexItem {
828 path: path.connect("::").to_string(),
829 desc: shorter(item.doc_value()).to_string(),
833 (Some(parent), None) if !self.privmod => {
834 if ast_util::is_local(parent) {
835 // We have a parent, but we don't know where they're
836 // defined yet. Wait for later to index this item.
837 self.orphan_methods.push((parent.node, item.clone()))
846 // Keep track of the fully qualified path for this item.
847 let pushed = if item.name.is_some() {
848 let n = item.name.get_ref();
850 self.stack.push(n.to_string());
855 clean::StructItem(..) | clean::EnumItem(..) |
856 clean::TypedefItem(..) | clean::TraitItem(..) |
857 clean::FunctionItem(..) | clean::ModuleItem(..) |
858 clean::ForeignFunctionItem(..) if !self.privmod => {
859 // Reexported items mean that the same id can show up twice
860 // in the rustdoc ast that we're looking at. We know,
861 // however, that a reexported item doesn't show up in the
862 // `public_items` map, so we can skip inserting into the
863 // paths map if there was already an entry present and we're
864 // not a public item.
865 let id = item.def_id.node;
866 if !self.paths.contains_key(&item.def_id) ||
867 !ast_util::is_local(item.def_id) ||
868 self.public_items.contains(&id) {
869 self.paths.insert(item.def_id,
870 (self.stack.clone(), shortty(&item)));
873 // link variants to their parent enum because pages aren't emitted
875 clean::VariantItem(..) if !self.privmod => {
876 let mut stack = self.stack.clone();
878 self.paths.insert(item.def_id, (stack, item_type::Enum));
881 clean::PrimitiveItem(..) if item.visibility.is_some() => {
882 self.paths.insert(item.def_id, (self.stack.clone(),
889 // Maintain the parent stack
890 let parent_pushed = match item.inner {
891 clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
892 self.parent_stack.push(item.def_id);
895 clean::ImplItem(ref i) => {
897 clean::ResolvedPath{ did, .. } => {
898 self.parent_stack.push(did);
907 // Once we've recursively found all the generics, then hoard off all the
908 // implementations elsewhere
909 let ret = match self.fold_item_recur(item) {
912 clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
913 use clean::{Primitive, Vector, ResolvedPath, BorrowedRef};
914 use clean::{FixedVector, Slice, Tuple, PrimitiveTuple};
916 // extract relevant documentation for this impl
917 let dox = match attrs.move_iter().find(|a| {
919 clean::NameValue(ref x, _)
920 if "doc" == x.as_slice() => {
926 Some(clean::NameValue(_, dox)) => Some(dox),
927 Some(..) | None => None,
930 // Figure out the id of this impl. This may map to a
931 // primitive rather than always to a struct/enum.
932 let did = match i.for_ {
933 ResolvedPath { did, .. } => Some(did),
935 // References to primitives are picked up as well to
936 // recognize implementations for &str, this may not
937 // be necessary in a DST world.
939 BorrowedRef { type_: box Primitive(p), ..} =>
941 Some(ast_util::local_def(p.to_node_id()))
944 // In a DST world, we may only need
945 // Vector/FixedVector, but for now we also pick up
946 // borrowed references
947 Vector(..) | FixedVector(..) |
948 BorrowedRef{ type_: box Vector(..), .. } |
949 BorrowedRef{ type_: box FixedVector(..), .. } =>
951 Some(ast_util::local_def(Slice.to_node_id()))
955 let id = PrimitiveTuple.to_node_id();
956 Some(ast_util::local_def(id))
964 let v = self.impls.find_or_insert_with(did, |_| {
980 if pushed { self.stack.pop().unwrap(); }
981 if parent_pushed { self.parent_stack.pop().unwrap(); }
982 self.privmod = orig_privmod;
988 fn generics(&mut self, generics: &clean::Generics) {
989 for typ in generics.type_params.iter() {
990 self.typarams.insert(typ.did, typ.name.clone());
996 /// Recurse in the directory structure and change the "root path" to make
997 /// sure it always points to the top (relatively)
998 fn recurse<T>(&mut self, s: String, f: |&mut Context| -> T) -> T {
1000 fail!("what {:?}", self);
1002 let prev = self.dst.clone();
1003 self.dst.push(s.as_slice());
1004 self.root_path.push_str("../");
1005 self.current.push(s);
1007 info!("Recursing into {}", self.dst.display());
1009 mkdir(&self.dst).unwrap();
1012 info!("Recursed; leaving {}", self.dst.display());
1014 // Go back to where we were at
1016 let len = self.root_path.len();
1017 self.root_path.truncate(len - 3);
1018 self.current.pop().unwrap();
1023 /// Main method for rendering a crate.
1025 /// This currently isn't parallelized, but it'd be pretty easy to add
1026 /// parallelization to this function.
1027 fn krate(self, mut krate: clean::Crate) -> io::IoResult<()> {
1028 let mut item = match krate.module.take() {
1030 None => return Ok(())
1032 item.name = Some(krate.name);
1034 let mut work = vec!((self, item));
1037 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
1038 work.push((cx.clone(), item));
1046 /// Non-parellelized version of rendering an item. This will take the input
1047 /// item, render its contents, and then invoke the specified closure with
1048 /// all sub-items which need to be rendered.
1050 /// The rendering driver uses this closure to queue up more work.
1051 fn item(&mut self, item: clean::Item,
1052 f: |&mut Context, clean::Item|) -> io::IoResult<()> {
1053 fn render(w: io::File, cx: &Context, it: &clean::Item,
1054 pushname: bool) -> io::IoResult<()> {
1055 info!("Rendering an item to {}", w.path().display());
1056 // A little unfortunate that this is done like this, but it sure
1057 // does make formatting *a lot* nicer.
1058 current_location_key.replace(Some(cx.current.clone()));
1060 let mut title = cx.current.connect("::");
1062 if title.len() > 0 {
1063 title.push_str("::");
1065 title.push_str(it.name.get_ref().as_slice());
1067 title.push_str(" - Rust");
1068 let page = layout::Page {
1069 ty: shortty(it).to_static_str(),
1070 root_path: cx.root_path.as_slice(),
1071 title: title.as_slice(),
1074 markdown::reset_headers();
1076 // We have a huge number of calls to write, so try to alleviate some
1077 // of the pain by using a buffered writer instead of invoking the
1078 // write sycall all the time.
1079 let mut writer = BufferedWriter::new(w);
1080 if !cx.render_redirect_pages {
1081 try!(layout::render(&mut writer, &cx.layout, &page,
1082 &Sidebar{ cx: cx, item: it },
1083 &Item{ cx: cx, item: it }));
1085 let mut url = "../".repeat(cx.current.len());
1086 match cache_key.get().unwrap().paths.find(&it.def_id) {
1087 Some(&(ref names, _)) => {
1088 for name in names.slice_to(names.len() - 1).iter() {
1089 url.push_str(name.as_slice());
1092 url.push_str(item_path(it).as_slice());
1093 try!(layout::redirect(&mut writer, url.as_slice()));
1101 // Private modules may survive the strip-private pass if they
1102 // contain impls for public types. These modules can also
1103 // contain items such as publicly reexported structures.
1105 // External crates will provide links to these structures, so
1106 // these modules are recursed into, but not rendered normally (a
1107 // flag on the context).
1108 if !self.render_redirect_pages {
1109 self.render_redirect_pages = ignore_private_item(&item);
1113 // modules are special because they add a namespace. We also need to
1114 // recurse into the items of the module as well.
1115 clean::ModuleItem(..) => {
1116 let name = item.name.get_ref().to_string();
1117 let mut item = Some(item);
1118 self.recurse(name, |this| {
1119 let item = item.take_unwrap();
1120 let dst = this.dst.join("index.html");
1121 let dst = try!(File::create(&dst));
1122 try!(render(dst, this, &item, false));
1124 let m = match item.inner {
1125 clean::ModuleItem(m) => m,
1128 this.sidebar = build_sidebar(&m);
1129 for item in m.items.move_iter() {
1136 // Things which don't have names (like impls) don't get special
1137 // pages dedicated to them.
1138 _ if item.name.is_some() => {
1139 let dst = self.dst.join(item_path(&item));
1140 let dst = try!(File::create(&dst));
1141 render(dst, self, &item, true)
1150 fn ismodule(&self) -> bool {
1151 match self.item.inner {
1152 clean::ModuleItem(..) => true, _ => false
1156 /// Generate a url appropriate for an `href` attribute back to the source of
1159 /// The url generated, when clicked, will redirect the browser back to the
1160 /// original source code.
1162 /// If `None` is returned, then a source link couldn't be generated. This
1163 /// may happen, for example, with externally inlined items where the source
1164 /// of their crate documentation isn't known.
1165 fn href(&self) -> Option<String> {
1166 // If this item is part of the local crate, then we're guaranteed to
1167 // know the span, so we plow forward and generate a proper url. The url
1168 // has anchors for the line numbers that we're linking to.
1169 if ast_util::is_local(self.item.def_id) {
1170 let mut path = Vec::new();
1171 clean_srcpath(self.item.source.filename.as_bytes(), |component| {
1172 path.push(component.to_string());
1174 let href = if self.item.source.loline == self.item.source.hiline {
1175 format!("{}", self.item.source.loline)
1178 self.item.source.loline,
1179 self.item.source.hiline)
1181 Some(format!("{root}src/{krate}/{path}.html#{href}",
1182 root = self.cx.root_path,
1183 krate = self.cx.layout.krate,
1184 path = path.connect("/"),
1187 // If this item is not part of the local crate, then things get a little
1188 // trickier. We don't actually know the span of the external item, but
1189 // we know that the documentation on the other end knows the span!
1191 // In this case, we generate a link to the *documentation* for this type
1192 // in the original crate. There's an extra URL parameter which says that
1193 // we want to go somewhere else, and the JS on the destination page will
1194 // pick it up and instantly redirect the browser to the source code.
1196 // If we don't know where the external documentation for this crate is
1197 // located, then we return `None`.
1199 let cache = cache_key.get().unwrap();
1200 let path = cache.external_paths.get(&self.item.def_id);
1201 let root = match *cache.extern_locations.get(&self.item.def_id.krate) {
1202 Remote(ref s) => s.to_string(),
1203 Local => self.cx.root_path.clone(),
1204 Unknown => return None,
1206 Some(format!("{root}{path}/{file}?gotosrc={goto}",
1208 path = path.slice_to(path.len() - 1).connect("/"),
1209 file = item_path(self.item),
1210 goto = self.item.def_id.node))
1215 impl<'a> fmt::Show for Item<'a> {
1216 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1217 // Write the breadcrumb trail header for the top
1218 try!(write!(fmt, "\n<h1 class='fqn'>"));
1219 match self.item.inner {
1220 clean::ModuleItem(ref m) => if m.is_crate {
1221 try!(write!(fmt, "Crate "));
1223 try!(write!(fmt, "Module "));
1225 clean::FunctionItem(..) => try!(write!(fmt, "Function ")),
1226 clean::TraitItem(..) => try!(write!(fmt, "Trait ")),
1227 clean::StructItem(..) => try!(write!(fmt, "Struct ")),
1228 clean::EnumItem(..) => try!(write!(fmt, "Enum ")),
1229 clean::PrimitiveItem(..) => try!(write!(fmt, "Primitive Type ")),
1232 let is_primitive = match self.item.inner {
1233 clean::PrimitiveItem(..) => true,
1237 let cur = self.cx.current.as_slice();
1238 let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
1239 for (i, component) in cur.iter().enumerate().take(amt) {
1240 try!(write!(fmt, "<a href='{}index.html'>{}</a>::",
1241 "../".repeat(cur.len() - i - 1),
1242 component.as_slice()));
1245 try!(write!(fmt, "<a class='{}' href=''>{}</a>",
1246 shortty(self.item), self.item.name.get_ref().as_slice()));
1248 // Write stability attributes
1249 match attr::find_stability_generic(self.item.attrs.iter()) {
1250 Some((ref stability, _)) => {
1252 "<a class='stability {lvl}' title='{reason}'>{lvl}</a>",
1253 lvl = stability.level.to_str(),
1254 reason = match stability.text {
1255 Some(ref s) => (*s).clone(),
1256 None => InternedString::new(""),
1264 // When this item is part of a `pub use` in a downstream crate, the
1265 // [src] link in the downstream documentation will actually come back to
1266 // this page, and this link will be auto-clicked. The `id` attribute is
1267 // used to find the link to auto-click.
1268 if self.cx.include_sources && !is_primitive {
1272 "<a class='source' id='src-{}' \
1273 href='{}'>[src]</a>",
1274 self.item.def_id.node, l));
1279 try!(write!(fmt, "</h1>\n"));
1281 match self.item.inner {
1282 clean::ModuleItem(ref m) => {
1283 item_module(fmt, self.cx, self.item, m.items.as_slice())
1285 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1286 item_function(fmt, self.item, f),
1287 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1288 clean::StructItem(ref s) => item_struct(fmt, self.item, s),
1289 clean::EnumItem(ref e) => item_enum(fmt, self.item, e),
1290 clean::TypedefItem(ref t) => item_typedef(fmt, self.item, t),
1291 clean::MacroItem(ref m) => item_macro(fmt, self.item, m),
1292 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.item, p),
1298 fn item_path(item: &clean::Item) -> String {
1300 clean::ModuleItem(..) => {
1301 format!("{}/index.html", item.name.get_ref())
1304 format!("{}.{}.html",
1305 shortty(item).to_static_str(),
1306 *item.name.get_ref())
1311 fn full_path(cx: &Context, item: &clean::Item) -> String {
1312 let mut s = cx.current.connect("::");
1314 s.push_str(item.name.get_ref().as_slice());
1318 fn blank<'a>(s: Option<&'a str>) -> &'a str {
1325 fn shorter<'a>(s: Option<&'a str>) -> &'a str {
1327 Some(s) => match s.find_str("\n\n") {
1328 Some(pos) => s.slice_to(pos),
1335 fn document(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
1336 match item.doc_value() {
1338 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1345 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1346 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1347 try!(document(w, item));
1348 let mut indices = range(0, items.len()).filter(|i| {
1349 !ignore_private_item(&items[*i])
1350 }).collect::<Vec<uint>>();
1352 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering {
1353 if shortty(i1) == shortty(i2) {
1354 return i1.name.cmp(&i2.name);
1356 match (&i1.inner, &i2.inner) {
1357 (&clean::ViewItemItem(ref a), &clean::ViewItemItem(ref b)) => {
1358 match (&a.inner, &b.inner) {
1359 (&clean::ExternCrate(..), _) => Less,
1360 (_, &clean::ExternCrate(..)) => Greater,
1361 _ => idx1.cmp(&idx2),
1364 (&clean::ViewItemItem(..), _) => Less,
1365 (_, &clean::ViewItemItem(..)) => Greater,
1366 (&clean::PrimitiveItem(..), _) => Less,
1367 (_, &clean::PrimitiveItem(..)) => Greater,
1368 (&clean::ModuleItem(..), _) => Less,
1369 (_, &clean::ModuleItem(..)) => Greater,
1370 (&clean::MacroItem(..), _) => Less,
1371 (_, &clean::MacroItem(..)) => Greater,
1372 (&clean::StructItem(..), _) => Less,
1373 (_, &clean::StructItem(..)) => Greater,
1374 (&clean::EnumItem(..), _) => Less,
1375 (_, &clean::EnumItem(..)) => Greater,
1376 (&clean::StaticItem(..), _) => Less,
1377 (_, &clean::StaticItem(..)) => Greater,
1378 (&clean::ForeignFunctionItem(..), _) => Less,
1379 (_, &clean::ForeignFunctionItem(..)) => Greater,
1380 (&clean::ForeignStaticItem(..), _) => Less,
1381 (_, &clean::ForeignStaticItem(..)) => Greater,
1382 (&clean::TraitItem(..), _) => Less,
1383 (_, &clean::TraitItem(..)) => Greater,
1384 (&clean::FunctionItem(..), _) => Less,
1385 (_, &clean::FunctionItem(..)) => Greater,
1386 (&clean::TypedefItem(..), _) => Less,
1387 (_, &clean::TypedefItem(..)) => Greater,
1388 _ => idx1.cmp(&idx2),
1392 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1394 debug!("{:?}", indices);
1395 let mut curty = None;
1396 for &idx in indices.iter() {
1397 let myitem = &items[idx];
1399 let myty = Some(shortty(myitem));
1401 if curty.is_some() {
1402 try!(write!(w, "</table>"));
1405 let (short, name) = match myitem.inner {
1406 clean::ModuleItem(..) => ("modules", "Modules"),
1407 clean::StructItem(..) => ("structs", "Structs"),
1408 clean::EnumItem(..) => ("enums", "Enums"),
1409 clean::FunctionItem(..) => ("functions", "Functions"),
1410 clean::TypedefItem(..) => ("types", "Type Definitions"),
1411 clean::StaticItem(..) => ("statics", "Statics"),
1412 clean::TraitItem(..) => ("traits", "Traits"),
1413 clean::ImplItem(..) => ("impls", "Implementations"),
1414 clean::ViewItemItem(..) => ("reexports", "Reexports"),
1415 clean::TyMethodItem(..) => ("tymethods", "Type Methods"),
1416 clean::MethodItem(..) => ("methods", "Methods"),
1417 clean::StructFieldItem(..) => ("fields", "Struct Fields"),
1418 clean::VariantItem(..) => ("variants", "Variants"),
1419 clean::ForeignFunctionItem(..) => ("ffi-fns", "Foreign Functions"),
1420 clean::ForeignStaticItem(..) => ("ffi-statics", "Foreign Statics"),
1421 clean::MacroItem(..) => ("macros", "Macros"),
1422 clean::PrimitiveItem(..) => ("primitives", "Primitive Types"),
1425 "<h2 id='{id}' class='section-header'>\
1426 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1427 id = short, name = name));
1430 match myitem.inner {
1431 clean::StaticItem(ref s) | clean::ForeignStaticItem(ref s) => {
1432 struct Initializer<'a>(&'a str, Item<'a>);
1433 impl<'a> fmt::Show for Initializer<'a> {
1434 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1435 let Initializer(s, item) = *self;
1436 if s.len() == 0 { return Ok(()); }
1437 try!(write!(f, "<code> = </code>"));
1438 if s.contains("\n") {
1441 write!(f, "<a href='{}'>[definition]</a>",
1447 write!(f, "<code>{}</code>", s.as_slice())
1454 <td><code>{}static {}{}: {}</code>{}</td>
1455 <td class='docblock'>{} </td>
1458 VisSpace(myitem.visibility),
1459 MutableSpace(s.mutability),
1460 *myitem.name.get_ref(),
1462 Initializer(s.expr.as_slice(), Item { cx: cx, item: myitem }),
1463 Markdown(blank(myitem.doc_value()))));
1466 clean::ViewItemItem(ref item) => {
1468 clean::ExternCrate(ref name, ref src, _) => {
1469 try!(write!(w, "<tr><td><code>extern crate {}",
1472 Some(ref src) => try!(write!(w, " = \"{}\"",
1476 try!(write!(w, ";</code></td></tr>"));
1479 clean::Import(ref import) => {
1480 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1481 VisSpace(myitem.visibility),
1489 if myitem.name.is_none() { continue }
1492 <td><a class='{class}' href='{href}'
1493 title='{title}'>{}</a></td>
1494 <td class='docblock short'>{}</td>
1497 *myitem.name.get_ref(),
1498 Markdown(shorter(myitem.doc_value())),
1499 class = shortty(myitem),
1500 href = item_path(myitem),
1501 title = full_path(cx, myitem)));
1505 write!(w, "</table>")
1508 fn item_function(w: &mut fmt::Formatter, it: &clean::Item,
1509 f: &clean::Function) -> fmt::Result {
1510 try!(write!(w, "<pre class='rust fn'>{vis}{fn_style}fn \
1511 {name}{generics}{decl}</pre>",
1512 vis = VisSpace(it.visibility),
1513 fn_style = FnStyleSpace(f.fn_style),
1514 name = it.name.get_ref().as_slice(),
1515 generics = f.generics,
1520 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1521 t: &clean::Trait) -> fmt::Result {
1522 let mut parents = String::new();
1523 if t.parents.len() > 0 {
1524 parents.push_str(": ");
1525 for (i, p) in t.parents.iter().enumerate() {
1526 if i > 0 { parents.push_str(" + "); }
1527 parents.push_str(format!("{}", *p).as_slice());
1531 // Output the trait definition
1532 try!(write!(w, "<pre class='rust trait'>{}trait {}{}{} ",
1533 VisSpace(it.visibility),
1534 it.name.get_ref().as_slice(),
1537 let required = t.methods.iter().filter(|m| m.is_req()).collect::<Vec<&clean::TraitMethod>>();
1538 let provided = t.methods.iter().filter(|m| !m.is_req()).collect::<Vec<&clean::TraitMethod>>();
1540 if t.methods.len() == 0 {
1541 try!(write!(w, "{{ }}"));
1543 try!(write!(w, "{{\n"));
1544 for m in required.iter() {
1545 try!(write!(w, " "));
1546 try!(render_method(w, m.item()));
1547 try!(write!(w, ";\n"));
1549 if required.len() > 0 && provided.len() > 0 {
1550 try!(w.write("\n".as_bytes()));
1552 for m in provided.iter() {
1553 try!(write!(w, " "));
1554 try!(render_method(w, m.item()));
1555 try!(write!(w, " {{ ... }}\n"));
1557 try!(write!(w, "}}"));
1559 try!(write!(w, "</pre>"));
1561 // Trait documentation
1562 try!(document(w, it));
1564 fn meth(w: &mut fmt::Formatter, m: &clean::TraitMethod) -> fmt::Result {
1565 try!(write!(w, "<h3 id='{}.{}' class='method'><code>",
1567 *m.item().name.get_ref()));
1568 try!(render_method(w, m.item()));
1569 try!(write!(w, "</code></h3>"));
1570 try!(document(w, m.item()));
1574 // Output the documentation for each function individually
1575 if required.len() > 0 {
1577 <h2 id='required-methods'>Required Methods</h2>
1578 <div class='methods'>
1580 for m in required.iter() {
1583 try!(write!(w, "</div>"));
1585 if provided.len() > 0 {
1587 <h2 id='provided-methods'>Provided Methods</h2>
1588 <div class='methods'>
1590 for m in provided.iter() {
1593 try!(write!(w, "</div>"));
1596 let cache = cache_key.get().unwrap();
1598 <h2 id='implementors'>Implementors</h2>
1599 <ul class='item-list' id='implementors-list'>
1601 match cache.implementors.find(&it.def_id) {
1602 Some(implementors) => {
1603 for i in implementors.iter() {
1604 try!(writeln!(w, "<li><code>impl{} {} for {}</code></li>",
1605 i.generics, i.trait_, i.for_));
1610 try!(write!(w, "</ul>"));
1611 try!(write!(w, r#"<script type="text/javascript" async
1612 src="{root_path}/implementors/{path}/{ty}.{name}.js">
1614 root_path = Vec::from_elem(cx.current.len(), "..").connect("/"),
1615 path = if ast_util::is_local(it.def_id) {
1616 cx.current.connect("/")
1618 let path = cache.external_paths.get(&it.def_id);
1619 path.slice_to(path.len() - 1).connect("/")
1621 ty = shortty(it).to_static_str(),
1622 name = *it.name.get_ref()));
1626 fn render_method(w: &mut fmt::Formatter, meth: &clean::Item) -> fmt::Result {
1627 fn fun(w: &mut fmt::Formatter, it: &clean::Item, fn_style: ast::FnStyle,
1628 g: &clean::Generics, selfty: &clean::SelfTy,
1629 d: &clean::FnDecl) -> fmt::Result {
1630 write!(w, "{}fn <a href='#{ty}.{name}' class='fnname'>{name}</a>\
1633 ast::UnsafeFn => "unsafe ",
1637 name = it.name.get_ref().as_slice(),
1639 decl = Method(selfty, d))
1642 clean::TyMethodItem(ref m) => {
1643 fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
1645 clean::MethodItem(ref m) => {
1646 fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
1652 fn item_struct(w: &mut fmt::Formatter, it: &clean::Item,
1653 s: &clean::Struct) -> fmt::Result {
1654 try!(write!(w, "<pre class='rust struct'>"));
1655 try!(render_struct(w,
1659 s.fields.as_slice(),
1662 try!(write!(w, "</pre>"));
1664 try!(document(w, it));
1665 let mut fields = s.fields.iter().filter(|f| {
1667 clean::StructFieldItem(clean::HiddenStructField) => false,
1668 clean::StructFieldItem(clean::TypedStructField(..)) => true,
1672 match s.struct_type {
1673 doctree::Plain if fields.peek().is_some() => {
1674 try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
1675 for field in fields {
1676 try!(write!(w, "<tr><td id='structfield.{name}'>\
1677 <code>{name}</code></td><td>",
1678 name = field.name.get_ref().as_slice()));
1679 try!(document(w, field));
1680 try!(write!(w, "</td></tr>"));
1682 try!(write!(w, "</table>"));
1686 render_methods(w, it)
1689 fn item_enum(w: &mut fmt::Formatter, it: &clean::Item,
1690 e: &clean::Enum) -> fmt::Result {
1691 try!(write!(w, "<pre class='rust enum'>{}enum {}{}",
1692 VisSpace(it.visibility),
1693 it.name.get_ref().as_slice(),
1695 if e.variants.len() == 0 && !e.variants_stripped {
1696 try!(write!(w, " {{}}"));
1698 try!(write!(w, " {{\n"));
1699 for v in e.variants.iter() {
1700 try!(write!(w, " "));
1701 let name = v.name.get_ref().as_slice();
1703 clean::VariantItem(ref var) => {
1705 clean::CLikeVariant => try!(write!(w, "{}", name)),
1706 clean::TupleVariant(ref tys) => {
1707 try!(write!(w, "{}(", name));
1708 for (i, ty) in tys.iter().enumerate() {
1710 try!(write!(w, ", "))
1712 try!(write!(w, "{}", *ty));
1714 try!(write!(w, ")"));
1716 clean::StructVariant(ref s) => {
1717 try!(render_struct(w,
1721 s.fields.as_slice(),
1729 try!(write!(w, ",\n"));
1732 if e.variants_stripped {
1733 try!(write!(w, " // some variants omitted\n"));
1735 try!(write!(w, "}}"));
1737 try!(write!(w, "</pre>"));
1739 try!(document(w, it));
1740 if e.variants.len() > 0 {
1741 try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
1742 for variant in e.variants.iter() {
1743 try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
1744 name = variant.name.get_ref().as_slice()));
1745 try!(document(w, variant));
1746 match variant.inner {
1747 clean::VariantItem(ref var) => {
1749 clean::StructVariant(ref s) => {
1750 let mut fields = s.fields.iter().filter(|f| {
1752 clean::StructFieldItem(ref t) => match *t {
1753 clean::HiddenStructField => false,
1754 clean::TypedStructField(..) => true,
1759 try!(write!(w, "<h3 class='fields'>Fields</h3>\n
1761 for field in fields {
1762 try!(write!(w, "<tr><td \
1763 id='variant.{v}.field.{f}'>\
1764 <code>{f}</code></td><td>",
1765 v = variant.name.get_ref().as_slice(),
1766 f = field.name.get_ref().as_slice()));
1767 try!(document(w, field));
1768 try!(write!(w, "</td></tr>"));
1770 try!(write!(w, "</table>"));
1777 try!(write!(w, "</td></tr>"));
1779 try!(write!(w, "</table>"));
1782 try!(render_methods(w, it));
1786 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
1787 g: Option<&clean::Generics>,
1788 ty: doctree::StructType,
1789 fields: &[clean::Item],
1791 structhead: bool) -> fmt::Result {
1792 try!(write!(w, "{}{}{}",
1793 VisSpace(it.visibility),
1794 if structhead {"struct "} else {""},
1795 it.name.get_ref().as_slice()));
1797 Some(g) => try!(write!(w, "{}", *g)),
1802 try!(write!(w, " {{\n{}", tab));
1803 let mut fields_stripped = false;
1804 for field in fields.iter() {
1806 clean::StructFieldItem(clean::HiddenStructField) => {
1807 fields_stripped = true;
1809 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
1810 try!(write!(w, " {}{}: {},\n{}",
1811 VisSpace(field.visibility),
1812 field.name.get_ref().as_slice(),
1816 _ => unreachable!(),
1820 if fields_stripped {
1821 try!(write!(w, " // some fields omitted\n{}", tab));
1823 try!(write!(w, "}}"));
1825 doctree::Tuple | doctree::Newtype => {
1826 try!(write!(w, "("));
1827 for (i, field) in fields.iter().enumerate() {
1829 try!(write!(w, ", "));
1832 clean::StructFieldItem(clean::HiddenStructField) => {
1833 try!(write!(w, "_"))
1835 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
1836 try!(write!(w, "{}{}", VisSpace(field.visibility), *ty))
1841 try!(write!(w, ");"));
1844 try!(write!(w, ";"));
1850 fn render_methods(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
1851 match cache_key.get().unwrap().impls.find(&it.def_id) {
1853 let mut non_trait = v.iter().filter(|p| {
1854 p.ref0().trait_.is_none()
1856 let non_trait = non_trait.collect::<Vec<&(clean::Impl, Option<String>)>>();
1857 let mut traits = v.iter().filter(|p| {
1858 p.ref0().trait_.is_some()
1860 let traits = traits.collect::<Vec<&(clean::Impl, Option<String>)>>();
1862 if non_trait.len() > 0 {
1863 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
1864 for &(ref i, ref dox) in non_trait.move_iter() {
1865 try!(render_impl(w, i, dox));
1868 if traits.len() > 0 {
1869 try!(write!(w, "<h2 id='implementations'>Trait \
1870 Implementations</h2>"));
1871 let mut any_derived = false;
1872 for & &(ref i, ref dox) in traits.iter() {
1874 try!(render_impl(w, i, dox));
1880 try!(write!(w, "<h3 id='derived_implementations'>Derived Implementations \
1882 for &(ref i, ref dox) in traits.move_iter() {
1884 try!(render_impl(w, i, dox));
1895 fn render_impl(w: &mut fmt::Formatter, i: &clean::Impl,
1896 dox: &Option<String>) -> fmt::Result {
1897 try!(write!(w, "<h3 class='impl'><code>impl{} ", i.generics));
1899 Some(ref ty) => try!(write!(w, "{} for ", *ty)),
1902 try!(write!(w, "{}</code></h3>", i.for_));
1905 try!(write!(w, "<div class='docblock'>{}</div>",
1906 Markdown(dox.as_slice())));
1911 fn docmeth(w: &mut fmt::Formatter, item: &clean::Item,
1912 dox: bool) -> fmt::Result {
1913 try!(write!(w, "<h4 id='method.{}' class='method'><code>",
1914 *item.name.get_ref()));
1915 try!(render_method(w, item));
1916 try!(write!(w, "</code></h4>\n"));
1917 match item.doc_value() {
1919 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1922 Some(..) | None => Ok(())
1926 try!(write!(w, "<div class='methods'>"));
1927 for meth in i.methods.iter() {
1928 try!(docmeth(w, meth, true));
1931 fn render_default_methods(w: &mut fmt::Formatter,
1933 i: &clean::Impl) -> fmt::Result {
1934 for method in t.methods.iter() {
1935 let n = method.item().name.clone();
1936 match i.methods.iter().find(|m| { m.name == n }) {
1937 Some(..) => continue,
1941 try!(docmeth(w, method.item(), false));
1946 // If we've implemented a trait, then also emit documentation for all
1947 // default methods which weren't overridden in the implementation block.
1949 Some(clean::ResolvedPath { did, .. }) => {
1951 match cache_key.get().unwrap().traits.find(&did) {
1952 Some(t) => try!(render_default_methods(w, t, i)),
1958 Some(..) | None => {}
1960 try!(write!(w, "</div>"));
1964 fn item_typedef(w: &mut fmt::Formatter, it: &clean::Item,
1965 t: &clean::Typedef) -> fmt::Result {
1966 try!(write!(w, "<pre class='rust typedef'>type {}{} = {};</pre>",
1967 it.name.get_ref().as_slice(),
1974 impl<'a> fmt::Show for Sidebar<'a> {
1975 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1978 try!(write!(fmt, "<p class='location'>"));
1979 let len = cx.current.len() - if it.is_mod() {1} else {0};
1980 for (i, name) in cx.current.iter().take(len).enumerate() {
1982 try!(write!(fmt, "​::"));
1984 try!(write!(fmt, "<a href='{}index.html'>{}</a>",
1987 .slice_to((cx.current.len() - i - 1) * 3),
1990 try!(write!(fmt, "</p>"));
1992 fn block(w: &mut fmt::Formatter, short: &str, longty: &str,
1993 cur: &clean::Item, cx: &Context) -> fmt::Result {
1994 let items = match cx.sidebar.find_equiv(&short) {
1995 Some(items) => items.as_slice(),
1996 None => return Ok(())
1998 try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
1999 for item in items.iter() {
2000 let curty = shortty(cur).to_static_str();
2001 let class = if cur.name.get_ref() == item &&
2002 short == curty { "current" } else { "" };
2003 try!(write!(w, "<a class='{ty} {class}' href='{href}{path}'>\
2007 href = if curty == "mod" {"../"} else {""},
2008 path = if short == "mod" {
2009 format!("{}/index.html", item.as_slice())
2011 format!("{}.{}.html", short, item.as_slice())
2013 name = item.as_slice()));
2015 try!(write!(w, "</div>"));
2019 try!(block(fmt, "mod", "Modules", it, cx));
2020 try!(block(fmt, "struct", "Structs", it, cx));
2021 try!(block(fmt, "enum", "Enums", it, cx));
2022 try!(block(fmt, "trait", "Traits", it, cx));
2023 try!(block(fmt, "fn", "Functions", it, cx));
2024 try!(block(fmt, "macro", "Macros", it, cx));
2029 fn build_sidebar(m: &clean::Module) -> HashMap<String, Vec<String>> {
2030 let mut map = HashMap::new();
2031 for item in m.items.iter() {
2032 if ignore_private_item(item) { continue }
2034 let short = shortty(item).to_static_str();
2035 let myname = match item.name {
2037 Some(ref s) => s.to_string(),
2039 let v = map.find_or_insert_with(short.to_string(), |_| Vec::new());
2043 for (_, items) in map.mut_iter() {
2044 items.as_mut_slice().sort();
2049 impl<'a> fmt::Show for Source<'a> {
2050 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2051 let Source(s) = *self;
2052 let lines = s.lines().count();
2054 let mut tmp = lines;
2059 try!(write!(fmt, "<pre class='line-numbers'>"));
2060 for i in range(1, lines + 1) {
2061 try!(write!(fmt, "<span id='{0:u}'>{0:1$u}</span>\n", i, cols));
2063 try!(write!(fmt, "</pre>"));
2064 try!(write!(fmt, "{}", highlight::highlight(s.as_slice(), None, None)));
2069 fn item_macro(w: &mut fmt::Formatter, it: &clean::Item,
2070 t: &clean::Macro) -> fmt::Result {
2071 try!(w.write(highlight::highlight(t.source.as_slice(), Some("macro"),
2076 fn item_primitive(w: &mut fmt::Formatter,
2078 _p: &clean::Primitive) -> fmt::Result {
2079 try!(document(w, it));
2080 render_methods(w, it)
2083 fn ignore_private_item(it: &clean::Item) -> bool {
2085 clean::ModuleItem(ref m) => {
2086 (m.items.len() == 0 && it.doc_value().is_none()) ||
2087 it.visibility != Some(ast::Public)
2089 clean::PrimitiveItem(..) => it.visibility != Some(ast::Public),