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 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};
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,
95 /// Indicates where an external crate can be found.
96 pub enum ExternalLocation {
97 /// Remote URL root of the external crate
99 /// This external crate can be found in the local doc/ folder
101 /// The external crate could not be found.
105 /// Different ways an implementor of a trait can be rendered.
106 pub enum Implementor {
107 /// Paths are displayed specially by omitting the `impl XX for` cruft
108 PathType(clean::Type),
109 /// This is the generic representation of a trait implementor, used for
110 /// primitive types and otherwise non-path types.
111 OtherType(clean::Generics, /* trait */ clean::Type, /* for */ clean::Type),
114 /// This cache is used to store information about the `clean::Crate` being
115 /// rendered in order to provide more useful documentation. This contains
116 /// information like all implementors of a trait, all traits a type implements,
117 /// documentation for all known traits, etc.
119 /// This structure purposefully does not implement `Clone` because it's intended
120 /// to be a fairly large and expensive structure to clone. Instead this adheres
121 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
124 /// Mapping of typaram ids to the name of the type parameter. This is used
125 /// when pretty-printing a type (so pretty printing doesn't have to
126 /// painfully maintain a context like this)
127 pub typarams: HashMap<ast::DefId, String>,
129 /// Maps a type id to all known implementations for that type. This is only
130 /// recognized for intra-crate `ResolvedPath` types, and is used to print
131 /// out extra documentation on the page of an enum/struct.
133 /// The values of the map are a list of implementations and documentation
134 /// found on that implementation.
135 pub impls: HashMap<ast::NodeId, Vec<(clean::Impl, Option<String>)>>,
137 /// Maintains a mapping of local crate node ids to the fully qualified name
138 /// and "short type description" of that node. This is used when generating
139 /// URLs when a type is being linked to. External paths are not located in
140 /// this map because the `External` type itself has all the information
142 pub paths: HashMap<ast::DefId, (Vec<String>, ItemType)>,
144 /// This map contains information about all known traits of this crate.
145 /// Implementations of a crate should inherit the documentation of the
146 /// parent trait if no extra documentation is specified, and default methods
147 /// should show up in documentation about trait implementations.
148 pub traits: HashMap<ast::DefId, clean::Trait>,
150 /// When rendering traits, it's often useful to be able to list all
151 /// implementors of the trait, and this mapping is exactly, that: a mapping
152 /// of trait ids to the list of known implementors of the trait
153 pub implementors: HashMap<ast::DefId, Vec<Implementor>>,
155 /// Cache of where external crate documentation can be found.
156 pub extern_locations: HashMap<ast::CrateNum, ExternalLocation>,
158 // Private fields only used when initially crawling a crate to build a cache
161 parent_stack: Vec<ast::DefId>,
162 search_index: Vec<IndexItem>,
164 public_items: NodeSet,
166 // In rare case where a structure is defined in one module but implemented
167 // in another, if the implementing module is parsed before defining module,
168 // then the fully qualified name of the structure isn't presented in `paths`
169 // yet when its implementation methods are being indexed. Caches such methods
170 // and their parent id here and indexes them at the end of crate parsing.
171 orphan_methods: Vec<(ast::NodeId, clean::Item)>,
174 /// Helper struct to render all source code to HTML pages
175 struct SourceCollector<'a> {
178 /// Processed source-file paths
179 seen: HashSet<String>,
180 /// Root destination to place all HTML output into
184 /// Wrapper struct to render the source code of a file. This will do things like
185 /// adding line numbers to the left-hand side.
186 struct Source<'a>(&'a str);
188 // Helper structs for rendering items/sidebars and carrying along contextual
191 struct Item<'a> { cx: &'a Context, item: &'a clean::Item, }
192 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
194 /// Struct representing one entry in the JS search index. These are all emitted
195 /// by hand to a large JS file at the end of cache-creation.
201 parent: Option<ast::DefId>,
204 // TLS keys used to carry information around during rendering.
206 local_data_key!(pub cache_key: Arc<Cache>)
207 local_data_key!(pub current_location_key: Vec<String> )
209 /// Generates the documentation for `crate` into the directory `dst`
210 pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> {
211 let mut cx = Context {
214 root_path: String::new(),
215 sidebar: HashMap::new(),
216 layout: layout::Layout {
217 logo: "".to_strbuf(),
218 favicon: "".to_strbuf(),
219 krate: krate.name.clone(),
221 include_sources: true,
223 try!(mkdir(&cx.dst));
225 match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(&[])) {
227 for attr in attrs.iter() {
229 clean::NameValue(ref x, ref s)
230 if "html_favicon_url" == x.as_slice() => {
231 cx.layout.favicon = s.to_strbuf();
233 clean::NameValue(ref x, ref s)
234 if "html_logo_url" == x.as_slice() => {
235 cx.layout.logo = s.to_strbuf();
238 if "html_no_source" == x.as_slice() => {
239 cx.include_sources = false;
248 // Crawl the crate to build various caches used for the output
249 let analysis = ::analysiskey.get();
250 let public_items = analysis.as_ref().map(|a| a.public_items.clone());
251 let public_items = public_items.unwrap_or(NodeSet::new());
252 let paths = analysis.as_ref().map(|a| {
253 let paths = a.external_paths.borrow_mut().take_unwrap();
254 paths.move_iter().map(|(k, (v, t))| {
256 clean::TypeStruct => item_type::Struct,
257 clean::TypeEnum => item_type::Enum,
258 clean::TypeFunction => item_type::Function,
259 clean::TypeTrait => item_type::Trait,
260 clean::TypeModule => item_type::Module,
261 clean::TypeStatic => item_type::Static,
262 clean::TypeVariant => item_type::Variant,
265 }).unwrap_or(HashMap::new());
266 let mut cache = Cache {
267 impls: HashMap::new(),
269 implementors: HashMap::new(),
271 parent_stack: Vec::new(),
272 search_index: Vec::new(),
273 extern_locations: HashMap::new(),
275 public_items: public_items,
276 orphan_methods: Vec::new(),
277 traits: analysis.as_ref().map(|a| {
278 a.external_traits.borrow_mut().take_unwrap()
279 }).unwrap_or(HashMap::new()),
280 typarams: analysis.as_ref().map(|a| {
281 a.external_typarams.borrow_mut().take_unwrap()
282 }).unwrap_or(HashMap::new()),
284 cache.stack.push(krate.name.clone());
285 krate = cache.fold_crate(krate);
287 let mut nodeid_to_pathid = HashMap::new();
288 let mut pathid_to_nodeid = Vec::new();
290 let Cache { search_index: ref mut index,
291 orphan_methods: ref meths, paths: ref mut paths, ..} = cache;
293 // Attach all orphan methods to the type's definition if the type
294 // has since been learned.
295 for &(pid, ref item) in meths.iter() {
296 let did = ast_util::local_def(pid);
297 match paths.find(&did) {
298 Some(&(ref fqp, _)) => {
299 index.push(IndexItem {
301 name: item.name.clone().unwrap(),
302 path: fqp.slice_to(fqp.len() - 1).connect("::")
304 desc: shorter(item.doc_value()).to_strbuf(),
312 // Reduce `NodeId` in paths into smaller sequential numbers,
313 // and prune the paths that do not appear in the index.
314 for item in index.iter() {
317 if !nodeid_to_pathid.contains_key(&nodeid) {
318 let pathid = pathid_to_nodeid.len();
319 nodeid_to_pathid.insert(nodeid, pathid);
320 pathid_to_nodeid.push(nodeid);
326 assert_eq!(nodeid_to_pathid.len(), pathid_to_nodeid.len());
329 // Publish the search index
331 let mut w = MemWriter::new();
332 try!(write!(&mut w, r#"searchIndex['{}'] = \{"items":["#, krate.name));
334 let mut lastpath = "".to_strbuf();
335 for (i, item) in cache.search_index.iter().enumerate() {
336 // Omit the path if it is same to that of the prior item.
338 if lastpath.as_slice() == item.path.as_slice() {
341 lastpath = item.path.to_strbuf();
342 path = item.path.as_slice();
346 try!(write!(&mut w, ","));
348 try!(write!(&mut w, r#"[{:u},"{}","{}",{}"#,
349 item.ty, item.name, path,
350 item.desc.to_json().to_str()));
353 let pathid = *nodeid_to_pathid.find(&nodeid).unwrap();
354 try!(write!(&mut w, ",{}", pathid));
358 try!(write!(&mut w, "]"));
361 try!(write!(&mut w, r#"],"paths":["#));
363 for (i, &did) in pathid_to_nodeid.iter().enumerate() {
364 let &(ref fqp, short) = cache.paths.find(&did).unwrap();
366 try!(write!(&mut w, ","));
368 try!(write!(&mut w, r#"[{:u},"{}"]"#,
369 short, *fqp.last().unwrap()));
372 try!(write!(&mut w, r"]\};"));
374 str::from_utf8(w.unwrap().as_slice()).unwrap().to_owned()
377 // Write out the shared files. Note that these are shared among all rustdoc
378 // docs placed in the output directory, so this needs to be a synchronized
379 // operation with respect to all other rustdocs running around.
381 try!(mkdir(&cx.dst));
382 let _lock = ::flock::Lock::new(&cx.dst.join(".lock"));
384 // Add all the static files. These may already exist, but we just
385 // overwrite them anyway to make sure that they're fresh and up-to-date.
386 try!(write(cx.dst.join("jquery.js"),
387 include_bin!("static/jquery-2.1.0.min.js")));
388 try!(write(cx.dst.join("main.js"), include_bin!("static/main.js")));
389 try!(write(cx.dst.join("main.css"), include_bin!("static/main.css")));
390 try!(write(cx.dst.join("normalize.css"),
391 include_bin!("static/normalize.css")));
392 try!(write(cx.dst.join("FiraSans-Regular.woff"),
393 include_bin!("static/FiraSans-Regular.woff")));
394 try!(write(cx.dst.join("FiraSans-Medium.woff"),
395 include_bin!("static/FiraSans-Medium.woff")));
396 try!(write(cx.dst.join("Heuristica-Regular.woff"),
397 include_bin!("static/Heuristica-Regular.woff")));
398 try!(write(cx.dst.join("Heuristica-Italic.woff"),
399 include_bin!("static/Heuristica-Italic.woff")));
400 try!(write(cx.dst.join("Heuristica-Bold.woff"),
401 include_bin!("static/Heuristica-Bold.woff")));
403 fn collect(path: &Path, krate: &str,
404 key: &str) -> io::IoResult<Vec<String>> {
405 let mut ret = Vec::new();
407 for line in BufferedReader::new(File::open(path)).lines() {
408 let line = try!(line);
409 if !line.as_slice().starts_with(key) {
412 if line.as_slice().starts_with(
413 format!("{}['{}']", key, krate).as_slice()) {
416 ret.push(line.to_strbuf());
422 // Update the search index
423 let dst = cx.dst.join("search-index.js");
424 let all_indexes = try!(collect(&dst, krate.name.as_slice(),
426 let mut w = try!(File::create(&dst));
427 try!(writeln!(&mut w, r"var searchIndex = \{\};"));
428 try!(writeln!(&mut w, "{}", index));
429 for index in all_indexes.iter() {
430 try!(writeln!(&mut w, "{}", *index));
432 try!(writeln!(&mut w, "initSearch(searchIndex);"));
434 // Update the list of all implementors for traits
435 let dst = cx.dst.join("implementors");
437 for (&did, imps) in cache.implementors.iter() {
438 if ast_util::is_local(did) { continue }
439 let &(ref remote_path, remote_item_type) = cache.paths.get(&did);
441 let mut mydst = dst.clone();
442 for part in remote_path.slice_to(remote_path.len() - 1).iter() {
443 mydst.push(part.as_slice());
446 mydst.push(format!("{}.{}.js",
447 remote_item_type.to_static_str(),
448 *remote_path.get(remote_path.len() - 1)));
449 let all_implementors = try!(collect(&mydst, krate.name.as_slice(),
452 try!(mkdir(&mydst.dir_path()));
453 let mut f = BufferedWriter::new(try!(File::create(&mydst)));
454 try!(writeln!(&mut f, r"(function() \{var implementors = \{\};"));
456 for implementor in all_implementors.iter() {
457 try!(writeln!(&mut f, "{}", *implementor));
460 try!(write!(&mut f, r"implementors['{}'] = \{", krate.name));
461 for imp in imps.iter() {
462 let &(ref path, item_type) = match *imp {
463 PathType(clean::ResolvedPath { did, .. }) => {
464 cache.paths.get(&did)
466 PathType(..) | OtherType(..) => continue,
468 try!(write!(&mut f, r#"{}:"#, *path.get(path.len() - 1)));
469 try!(write!(&mut f, r#""{}"#,
470 path.slice_to(path.len() - 1).connect("/")));
471 try!(write!(&mut f, r#"/{}.{}.html","#,
472 item_type.to_static_str(),
473 *path.get(path.len() - 1)));
475 try!(writeln!(&mut f, r"\};"));
476 try!(writeln!(&mut f, "{}", r"
477 if (window.register_implementors) {
478 window.register_implementors(implementors);
480 window.pending_implementors = implementors;
483 try!(writeln!(&mut f, r"\})()"));
487 // Render all source files (this may turn into a giant no-op)
489 info!("emitting source files");
490 let dst = cx.dst.join("src");
492 let dst = dst.join(krate.name.as_slice());
494 let mut folder = SourceCollector {
496 seen: HashSet::new(),
499 krate = folder.fold_crate(krate);
502 for &(n, ref e) in krate.externs.iter() {
503 cache.extern_locations.insert(n, extern_location(e, &cx.dst));
504 let did = ast::DefId { krate: n, node: ast::CRATE_NODE_ID };
505 cache.paths.insert(did, (Vec::new(), item_type::Module));
508 // And finally render the whole crate's documentation
509 cx.krate(krate, cache)
512 /// Writes the entire contents of a string to a destination, not attempting to
513 /// catch any errors.
514 fn write(dst: Path, contents: &[u8]) -> io::IoResult<()> {
515 File::create(&dst).write(contents)
518 /// Makes a directory on the filesystem, failing the task if an error occurs and
519 /// skipping if the directory already exists.
520 fn mkdir(path: &Path) -> io::IoResult<()> {
522 fs::mkdir(path, io::UserRWX)
528 /// Takes a path to a source file and cleans the path to it. This canonicalizes
529 /// things like ".." to components which preserve the "top down" hierarchy of a
530 /// static HTML tree.
531 // FIXME (#9639): The closure should deal with &[u8] instead of &str
532 fn clean_srcpath(src: &[u8], f: |&str|) {
533 let p = Path::new(src);
534 if p.as_vec() != bytes!(".") {
535 for c in p.str_components().map(|x|x.unwrap()) {
545 /// Attempts to find where an external crate is located, given that we're
546 /// rendering in to the specified source destination.
547 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
548 // See if there's documentation generated into the local directory
549 let local_location = dst.join(e.name.as_slice());
550 if local_location.is_dir() {
554 // Failing that, see if there's an attribute specifying where to find this
556 for attr in e.attrs.iter() {
558 clean::List(ref x, ref list) if "doc" == x.as_slice() => {
559 for attr in list.iter() {
561 clean::NameValue(ref x, ref s)
562 if "html_root_url" == x.as_slice() => {
563 if s.as_slice().ends_with("/") {
564 return Remote(s.to_strbuf());
566 return Remote(format_strbuf!("{}/", s));
576 // Well, at least we tried.
580 impl<'a> DocFolder for SourceCollector<'a> {
581 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
582 // If we're including source files, and we haven't seen this file yet,
583 // then we need to render it out to the filesystem
584 if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
586 // If it turns out that we couldn't read this file, then we probably
587 // can't read any of the files (generating html output from json or
588 // something like that), so just don't include sources for the
589 // entire crate. The other option is maintaining this mapping on a
590 // per-file basis, but that's probably not worth it...
592 .include_sources = match self.emit_source(item.source
597 println!("warning: source code was requested to be rendered, \
598 but processing `{}` had an error: {}",
599 item.source.filename, e);
600 println!(" skipping rendering of source code");
604 self.seen.insert(item.source.filename.clone());
607 self.fold_item_recur(item)
611 impl<'a> SourceCollector<'a> {
612 /// Renders the given filename into its corresponding HTML source file.
613 fn emit_source(&mut self, filename: &str) -> io::IoResult<()> {
614 let p = Path::new(filename);
616 // If we couldn't open this file, then just returns because it
617 // probably means that it's some standard library macro thing and we
618 // can't have the source to it anyway.
619 let contents = match File::open(&p).read_to_end() {
621 // macros from other libraries get special filenames which we can
623 Err(..) if filename.starts_with("<") &&
624 filename.ends_with("macros>") => return Ok(()),
625 Err(e) => return Err(e)
627 let contents = str::from_utf8(contents.as_slice()).unwrap();
629 // Remove the utf-8 BOM if any
630 let contents = if contents.starts_with("\ufeff") {
631 contents.as_slice().slice_from(3)
636 // Create the intermediate directories
637 let mut cur = self.dst.clone();
638 let mut root_path = String::from_str("../../");
639 clean_srcpath(p.dirname(), |component| {
641 mkdir(&cur).unwrap();
642 root_path.push_str("../");
645 cur.push(Vec::from_slice(p.filename().expect("source has no filename"))
646 .append(bytes!(".html")));
647 let mut w = BufferedWriter::new(try!(File::create(&cur)));
649 let title = format!("{} -- source", cur.filename_display());
650 let page = layout::Page {
651 title: title.as_slice(),
653 root_path: root_path.as_slice(),
655 try!(layout::render(&mut w as &mut Writer, &self.cx.layout,
656 &page, &(""), &Source(contents)));
662 impl DocFolder for Cache {
663 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
664 // If this is a private module, we don't want it in the search index.
665 let orig_privmod = match item.inner {
666 clean::ModuleItem(..) => {
667 let prev = self.privmod;
668 self.privmod = prev || item.visibility != Some(ast::Public);
674 // Register any generics to their corresponding string. This is used
675 // when pretty-printing types
677 clean::StructItem(ref s) => self.generics(&s.generics),
678 clean::EnumItem(ref e) => self.generics(&e.generics),
679 clean::FunctionItem(ref f) => self.generics(&f.generics),
680 clean::TypedefItem(ref t) => self.generics(&t.generics),
681 clean::TraitItem(ref t) => self.generics(&t.generics),
682 clean::ImplItem(ref i) => self.generics(&i.generics),
683 clean::TyMethodItem(ref i) => self.generics(&i.generics),
684 clean::MethodItem(ref i) => self.generics(&i.generics),
685 clean::ForeignFunctionItem(ref f) => self.generics(&f.generics),
689 // Propagate a trait methods' documentation to all implementors of the
692 clean::TraitItem(ref t) => {
693 self.traits.insert(item.def_id, t.clone());
698 // Collect all the implementors of traits.
700 clean::ImplItem(ref i) => {
702 Some(clean::ResolvedPath{ did, .. }) => {
703 let v = self.implementors.find_or_insert_with(did, |_| {
707 clean::ResolvedPath{..} => {
708 v.unshift(PathType(i.for_.clone()));
711 v.push(OtherType(i.generics.clone(),
712 i.trait_.get_ref().clone(),
717 Some(..) | None => {}
723 // Index this method for searching later on
726 let parent = match item.inner {
727 clean::TyMethodItem(..) |
728 clean::StructFieldItem(..) |
729 clean::VariantItem(..) => {
730 (Some(*self.parent_stack.last().unwrap()),
731 Some(self.stack.slice_to(self.stack.len() - 1)))
733 clean::MethodItem(..) => {
734 if self.parent_stack.len() == 0 {
737 let last = self.parent_stack.last().unwrap();
739 let path = match self.paths.find(&did) {
740 Some(&(_, item_type::Trait)) =>
741 Some(self.stack.slice_to(self.stack.len() - 1)),
742 // The current stack not necessarily has correlation for
743 // where the type was defined. On the other hand,
744 // `paths` always has the right information if present.
745 Some(&(ref fqp, item_type::Struct)) |
746 Some(&(ref fqp, item_type::Enum)) =>
747 Some(fqp.slice_to(fqp.len() - 1)),
748 Some(..) => Some(self.stack.as_slice()),
754 _ => (None, Some(self.stack.as_slice()))
757 (parent, Some(path)) if !self.privmod => {
758 self.search_index.push(IndexItem {
761 path: path.connect("::").to_strbuf(),
762 desc: shorter(item.doc_value()).to_strbuf(),
766 (Some(parent), None) if !self.privmod => {
767 if ast_util::is_local(parent) {
768 // We have a parent, but we don't know where they're
769 // defined yet. Wait for later to index this item.
770 self.orphan_methods.push((parent.node, item.clone()))
779 // Keep track of the fully qualified path for this item.
780 let pushed = if item.name.is_some() {
781 let n = item.name.get_ref();
783 self.stack.push(n.to_strbuf());
788 clean::StructItem(..) | clean::EnumItem(..) |
789 clean::TypedefItem(..) | clean::TraitItem(..) |
790 clean::FunctionItem(..) | clean::ModuleItem(..) |
791 clean::ForeignFunctionItem(..) => {
792 // Reexported items mean that the same id can show up twice
793 // in the rustdoc ast that we're looking at. We know,
794 // however, that a reexported item doesn't show up in the
795 // `public_items` map, so we can skip inserting into the
796 // paths map if there was already an entry present and we're
797 // not a public item.
798 let id = item.def_id.node;
799 if !self.paths.contains_key(&item.def_id) ||
800 self.public_items.contains(&id) {
801 self.paths.insert(item.def_id,
802 (self.stack.clone(), shortty(&item)));
805 // link variants to their parent enum because pages aren't emitted
807 clean::VariantItem(..) => {
808 let mut stack = self.stack.clone();
810 self.paths.insert(item.def_id, (stack, item_type::Enum));
815 // Maintain the parent stack
816 let parent_pushed = match item.inner {
817 clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
818 self.parent_stack.push(item.def_id);
821 clean::ImplItem(ref i) => {
823 clean::ResolvedPath{ did, .. } => {
824 self.parent_stack.push(did);
833 // Once we've recursively found all the generics, then hoard off all the
834 // implementations elsewhere
835 let ret = match self.fold_item_recur(item) {
838 clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
840 clean::ResolvedPath { did, .. }
841 if ast_util::is_local(did) =>
843 let v = self.impls.find_or_insert_with(did.node, |_| {
846 // extract relevant documentation for this impl
847 match attrs.move_iter().find(|a| {
849 clean::NameValue(ref x, _)
850 if "doc" == x.as_slice() => {
856 Some(clean::NameValue(_, dox)) => {
857 v.push((i, Some(dox)));
868 // Private modules may survive the strip-private pass if
869 // they contain impls for public types, but those will get
871 clean::Item { inner: clean::ModuleItem(ref m),
873 if (m.items.len() == 0 &&
874 item.doc_value().is_none()) ||
875 visibility != Some(ast::Public) => None,
883 if pushed { self.stack.pop().unwrap(); }
884 if parent_pushed { self.parent_stack.pop().unwrap(); }
885 self.privmod = orig_privmod;
891 fn generics(&mut self, generics: &clean::Generics) {
892 for typ in generics.type_params.iter() {
893 self.typarams.insert(typ.did, typ.name.clone());
899 /// Recurse in the directory structure and change the "root path" to make
900 /// sure it always points to the top (relatively)
901 fn recurse<T>(&mut self, s: String, f: |&mut Context| -> T) -> T {
903 fail!("what {:?}", self);
905 let prev = self.dst.clone();
906 self.dst.push(s.as_slice());
907 self.root_path.push_str("../");
908 self.current.push(s);
910 info!("Recursing into {}", self.dst.display());
912 mkdir(&self.dst).unwrap();
915 info!("Recursed; leaving {}", self.dst.display());
917 // Go back to where we were at
919 let len = self.root_path.len();
920 self.root_path.truncate(len - 3);
921 self.current.pop().unwrap();
926 /// Main method for rendering a crate.
928 /// This currently isn't parallelized, but it'd be pretty easy to add
929 /// parallelization to this function.
930 fn krate(self, mut krate: clean::Crate, cache: Cache) -> io::IoResult<()> {
931 let mut item = match krate.module.take() {
933 None => return Ok(())
935 item.name = Some(krate.name);
937 // using a rwarc makes this parallelizable in the future
938 cache_key.replace(Some(Arc::new(cache)));
940 let mut work = vec!((self, item));
943 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
944 work.push((cx.clone(), item));
952 /// Non-parellelized version of rendering an item. This will take the input
953 /// item, render its contents, and then invoke the specified closure with
954 /// all sub-items which need to be rendered.
956 /// The rendering driver uses this closure to queue up more work.
957 fn item(&mut self, item: clean::Item,
958 f: |&mut Context, clean::Item|) -> io::IoResult<()> {
959 fn render(w: io::File, cx: &mut Context, it: &clean::Item,
960 pushname: bool) -> io::IoResult<()> {
961 info!("Rendering an item to {}", w.path().display());
962 // A little unfortunate that this is done like this, but it sure
963 // does make formatting *a lot* nicer.
964 current_location_key.replace(Some(cx.current.clone()));
966 let mut title = cx.current.connect("::");
969 title.push_str("::");
971 title.push_str(it.name.get_ref().as_slice());
973 title.push_str(" - Rust");
974 let page = layout::Page {
975 ty: shortty(it).to_static_str(),
976 root_path: cx.root_path.as_slice(),
977 title: title.as_slice(),
980 markdown::reset_headers();
982 // We have a huge number of calls to write, so try to alleviate some
983 // of the pain by using a buffered writer instead of invoking the
984 // write sycall all the time.
985 let mut writer = BufferedWriter::new(w);
986 try!(layout::render(&mut writer as &mut Writer, &cx.layout, &page,
987 &Sidebar{ cx: cx, item: it },
988 &Item{ cx: cx, item: it }));
993 // modules are special because they add a namespace. We also need to
994 // recurse into the items of the module as well.
995 clean::ModuleItem(..) => {
996 let name = item.name.get_ref().to_strbuf();
997 let mut item = Some(item);
998 self.recurse(name, |this| {
999 let item = item.take_unwrap();
1000 let dst = this.dst.join("index.html");
1001 let dst = try!(File::create(&dst));
1002 try!(render(dst, this, &item, false));
1004 let m = match item.inner {
1005 clean::ModuleItem(m) => m,
1008 this.sidebar = build_sidebar(&m);
1009 for item in m.items.move_iter() {
1016 // Things which don't have names (like impls) don't get special
1017 // pages dedicated to them.
1018 _ if item.name.is_some() => {
1019 let dst = self.dst.join(item_path(&item));
1020 let dst = try!(File::create(&dst));
1021 render(dst, self, &item, true)
1030 fn ismodule(&self) -> bool {
1031 match self.item.inner {
1032 clean::ModuleItem(..) => true, _ => false
1036 fn link(&self) -> String {
1037 let mut path = Vec::new();
1038 clean_srcpath(self.item.source.filename.as_bytes(), |component| {
1039 path.push(component.to_owned());
1041 let href = if self.item.source.loline == self.item.source.hiline {
1042 format_strbuf!("{}", self.item.source.loline)
1044 format_strbuf!("{}-{}",
1045 self.item.source.loline,
1046 self.item.source.hiline)
1048 format_strbuf!("{root}src/{krate}/{path}.html\\#{href}",
1049 root = self.cx.root_path,
1050 krate = self.cx.layout.krate,
1051 path = path.connect("/"),
1056 impl<'a> fmt::Show for Item<'a> {
1057 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1058 // Write the breadcrumb trail header for the top
1059 try!(write!(fmt, "\n<h1 class='fqn'>"));
1060 match self.item.inner {
1061 clean::ModuleItem(ref m) => if m.is_crate {
1062 try!(write!(fmt, "Crate "));
1064 try!(write!(fmt, "Module "));
1066 clean::FunctionItem(..) => try!(write!(fmt, "Function ")),
1067 clean::TraitItem(..) => try!(write!(fmt, "Trait ")),
1068 clean::StructItem(..) => try!(write!(fmt, "Struct ")),
1069 clean::EnumItem(..) => try!(write!(fmt, "Enum ")),
1072 let cur = self.cx.current.as_slice();
1073 let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
1074 for (i, component) in cur.iter().enumerate().take(amt) {
1075 let mut trail = String::new();
1076 for _ in range(0, cur.len() - i - 1) {
1077 trail.push_str("../");
1079 try!(write!(fmt, "<a href='{}index.html'>{}</a>::",
1080 trail, component.as_slice()));
1082 try!(write!(fmt, "<a class='{}' href=''>{}</a>",
1083 shortty(self.item), self.item.name.get_ref().as_slice()));
1085 // Write stability attributes
1086 match attr::find_stability_generic(self.item.attrs.iter()) {
1087 Some((ref stability, _)) => {
1089 "<a class='stability {lvl}' title='{reason}'>{lvl}</a>",
1090 lvl = stability.level.to_str(),
1091 reason = match stability.text {
1092 Some(ref s) => (*s).clone(),
1093 None => InternedString::new(""),
1100 if self.cx.include_sources {
1101 try!(write!(fmt, "<a class='source' href='{}'>[src]</a>",
1104 try!(write!(fmt, "</h1>\n"));
1106 match self.item.inner {
1107 clean::ModuleItem(ref m) => {
1108 item_module(fmt, self.cx, self.item, m.items.as_slice())
1110 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1111 item_function(fmt, self.item, f),
1112 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1113 clean::StructItem(ref s) => item_struct(fmt, self.item, s),
1114 clean::EnumItem(ref e) => item_enum(fmt, self.item, e),
1115 clean::TypedefItem(ref t) => item_typedef(fmt, self.item, t),
1116 clean::MacroItem(ref m) => item_macro(fmt, self.item, m),
1122 fn item_path(item: &clean::Item) -> String {
1124 clean::ModuleItem(..) => {
1125 format_strbuf!("{}/index.html", item.name.get_ref())
1128 format_strbuf!("{}.{}.html",
1129 shortty(item).to_static_str(),
1130 *item.name.get_ref())
1135 fn full_path(cx: &Context, item: &clean::Item) -> String {
1136 let mut s = cx.current.connect("::");
1138 s.push_str(item.name.get_ref().as_slice());
1142 fn blank<'a>(s: Option<&'a str>) -> &'a str {
1149 fn shorter<'a>(s: Option<&'a str>) -> &'a str {
1151 Some(s) => match s.find_str("\n\n") {
1152 Some(pos) => s.slice_to(pos),
1159 fn document(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
1160 match item.doc_value() {
1162 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1169 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1170 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1171 try!(document(w, item));
1172 debug!("{:?}", items);
1173 let mut indices = Vec::from_fn(items.len(), |i| i);
1175 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering {
1176 if shortty(i1) == shortty(i2) {
1177 return i1.name.cmp(&i2.name);
1179 match (&i1.inner, &i2.inner) {
1180 (&clean::ViewItemItem(ref a), &clean::ViewItemItem(ref b)) => {
1181 match (&a.inner, &b.inner) {
1182 (&clean::ExternCrate(..), _) => Less,
1183 (_, &clean::ExternCrate(..)) => Greater,
1184 _ => idx1.cmp(&idx2),
1187 (&clean::ViewItemItem(..), _) => Less,
1188 (_, &clean::ViewItemItem(..)) => Greater,
1189 (&clean::ModuleItem(..), _) => Less,
1190 (_, &clean::ModuleItem(..)) => Greater,
1191 (&clean::MacroItem(..), _) => Less,
1192 (_, &clean::MacroItem(..)) => Greater,
1193 (&clean::StructItem(..), _) => Less,
1194 (_, &clean::StructItem(..)) => Greater,
1195 (&clean::EnumItem(..), _) => Less,
1196 (_, &clean::EnumItem(..)) => Greater,
1197 (&clean::StaticItem(..), _) => Less,
1198 (_, &clean::StaticItem(..)) => Greater,
1199 (&clean::ForeignFunctionItem(..), _) => Less,
1200 (_, &clean::ForeignFunctionItem(..)) => Greater,
1201 (&clean::ForeignStaticItem(..), _) => Less,
1202 (_, &clean::ForeignStaticItem(..)) => Greater,
1203 (&clean::TraitItem(..), _) => Less,
1204 (_, &clean::TraitItem(..)) => Greater,
1205 (&clean::FunctionItem(..), _) => Less,
1206 (_, &clean::FunctionItem(..)) => Greater,
1207 (&clean::TypedefItem(..), _) => Less,
1208 (_, &clean::TypedefItem(..)) => Greater,
1209 _ => idx1.cmp(&idx2),
1213 debug!("{:?}", indices);
1214 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1216 debug!("{:?}", indices);
1217 let mut curty = None;
1218 for &idx in indices.iter() {
1219 let myitem = &items[idx];
1221 let myty = Some(shortty(myitem));
1223 if curty.is_some() {
1224 try!(write!(w, "</table>"));
1227 let (short, name) = match myitem.inner {
1228 clean::ModuleItem(..) => ("modules", "Modules"),
1229 clean::StructItem(..) => ("structs", "Structs"),
1230 clean::EnumItem(..) => ("enums", "Enums"),
1231 clean::FunctionItem(..) => ("functions", "Functions"),
1232 clean::TypedefItem(..) => ("types", "Type Definitions"),
1233 clean::StaticItem(..) => ("statics", "Statics"),
1234 clean::TraitItem(..) => ("traits", "Traits"),
1235 clean::ImplItem(..) => ("impls", "Implementations"),
1236 clean::ViewItemItem(..) => ("reexports", "Reexports"),
1237 clean::TyMethodItem(..) => ("tymethods", "Type Methods"),
1238 clean::MethodItem(..) => ("methods", "Methods"),
1239 clean::StructFieldItem(..) => ("fields", "Struct Fields"),
1240 clean::VariantItem(..) => ("variants", "Variants"),
1241 clean::ForeignFunctionItem(..) => ("ffi-fns", "Foreign Functions"),
1242 clean::ForeignStaticItem(..) => ("ffi-statics", "Foreign Statics"),
1243 clean::MacroItem(..) => ("macros", "Macros"),
1246 "<h2 id='{id}' class='section-header'>\
1247 <a href=\"\\#{id}\">{name}</a></h2>\n<table>",
1248 id = short, name = name));
1251 match myitem.inner {
1252 clean::StaticItem(ref s) | clean::ForeignStaticItem(ref s) => {
1253 struct Initializer<'a>(&'a str, Item<'a>);
1254 impl<'a> fmt::Show for Initializer<'a> {
1255 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1256 let Initializer(s, item) = *self;
1257 if s.len() == 0 { return Ok(()); }
1258 try!(write!(f, "<code> = </code>"));
1259 if s.contains("\n") {
1260 write!(f, "<a href='{}'>[definition]</a>",
1263 write!(f, "<code>{}</code>", s.as_slice())
1270 <td><code>{}static {}: {}</code>{}</td>
1271 <td class='docblock'>{} </td>
1274 VisSpace(myitem.visibility),
1275 *myitem.name.get_ref(),
1277 Initializer(s.expr.as_slice(), Item { cx: cx, item: myitem }),
1278 Markdown(blank(myitem.doc_value()))));
1281 clean::ViewItemItem(ref item) => {
1283 clean::ExternCrate(ref name, ref src, _) => {
1284 try!(write!(w, "<tr><td><code>extern crate {}",
1287 Some(ref src) => try!(write!(w, " = \"{}\"",
1291 try!(write!(w, ";</code></td></tr>"));
1294 clean::Import(ref import) => {
1295 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1296 VisSpace(myitem.visibility),
1304 if myitem.name.is_none() { continue }
1307 <td><a class='{class}' href='{href}'
1308 title='{title}'>{}</a></td>
1309 <td class='docblock short'>{}</td>
1312 *myitem.name.get_ref(),
1313 Markdown(shorter(myitem.doc_value())),
1314 class = shortty(myitem),
1315 href = item_path(myitem),
1316 title = full_path(cx, myitem)));
1320 write!(w, "</table>")
1323 fn item_function(w: &mut fmt::Formatter, it: &clean::Item,
1324 f: &clean::Function) -> fmt::Result {
1325 try!(write!(w, "<pre class='rust fn'>{vis}{fn_style}fn \
1326 {name}{generics}{decl}</pre>",
1327 vis = VisSpace(it.visibility),
1328 fn_style = FnStyleSpace(f.fn_style),
1329 name = it.name.get_ref().as_slice(),
1330 generics = f.generics,
1335 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1336 t: &clean::Trait) -> fmt::Result {
1337 let mut parents = String::new();
1338 if t.parents.len() > 0 {
1339 parents.push_str(": ");
1340 for (i, p) in t.parents.iter().enumerate() {
1341 if i > 0 { parents.push_str(" + "); }
1342 parents.push_str(format!("{}", *p).as_slice());
1346 // Output the trait definition
1347 try!(write!(w, "<pre class='rust trait'>{}trait {}{}{} ",
1348 VisSpace(it.visibility),
1349 it.name.get_ref().as_slice(),
1352 let required = t.methods.iter().filter(|m| m.is_req()).collect::<Vec<&clean::TraitMethod>>();
1353 let provided = t.methods.iter().filter(|m| !m.is_req()).collect::<Vec<&clean::TraitMethod>>();
1355 if t.methods.len() == 0 {
1356 try!(write!(w, "\\{ \\}"));
1358 try!(write!(w, "\\{\n"));
1359 for m in required.iter() {
1360 try!(write!(w, " "));
1361 try!(render_method(w, m.item()));
1362 try!(write!(w, ";\n"));
1364 if required.len() > 0 && provided.len() > 0 {
1365 try!(w.write("\n".as_bytes()));
1367 for m in provided.iter() {
1368 try!(write!(w, " "));
1369 try!(render_method(w, m.item()));
1370 try!(write!(w, " \\{ ... \\}\n"));
1372 try!(write!(w, "\\}"));
1374 try!(write!(w, "</pre>"));
1376 // Trait documentation
1377 try!(document(w, it));
1379 fn meth(w: &mut fmt::Formatter, m: &clean::TraitMethod) -> fmt::Result {
1380 try!(write!(w, "<h3 id='{}.{}' class='method'><code>",
1382 *m.item().name.get_ref()));
1383 try!(render_method(w, m.item()));
1384 try!(write!(w, "</code></h3>"));
1385 try!(document(w, m.item()));
1389 // Output the documentation for each function individually
1390 if required.len() > 0 {
1392 <h2 id='required-methods'>Required Methods</h2>
1393 <div class='methods'>
1395 for m in required.iter() {
1398 try!(write!(w, "</div>"));
1400 if provided.len() > 0 {
1402 <h2 id='provided-methods'>Provided Methods</h2>
1403 <div class='methods'>
1405 for m in provided.iter() {
1408 try!(write!(w, "</div>"));
1411 match cache_key.get().unwrap().implementors.find(&it.def_id) {
1412 Some(implementors) => {
1414 <h2 id='implementors'>Implementors</h2>
1415 <ul class='item-list' id='implementors-list'>
1417 for i in implementors.iter() {
1419 PathType(ref ty) => {
1420 try!(write!(w, "<li><code>{}</code></li>", *ty));
1422 OtherType(ref generics, ref trait_, ref for_) => {
1423 try!(write!(w, "<li><code>impl{} {} for {}</code></li>",
1424 *generics, *trait_, *for_));
1428 try!(write!(w, "</ul>"));
1429 try!(write!(w, r#"<script type="text/javascript" async
1430 src="{}/implementors/{}/{}.{}.js"></script>"#,
1431 cx.current.iter().map(|_| "..")
1432 .collect::<Vec<&str>>().connect("/"),
1433 cx.current.connect("/"),
1434 shortty(it).to_static_str(),
1435 *it.name.get_ref()));
1442 fn render_method(w: &mut fmt::Formatter, meth: &clean::Item) -> fmt::Result {
1443 fn fun(w: &mut fmt::Formatter, it: &clean::Item, fn_style: ast::FnStyle,
1444 g: &clean::Generics, selfty: &clean::SelfTy,
1445 d: &clean::FnDecl) -> fmt::Result {
1446 write!(w, "{}fn <a href='\\#{ty}.{name}' class='fnname'>{name}</a>\
1449 ast::UnsafeFn => "unsafe ",
1453 name = it.name.get_ref().as_slice(),
1455 decl = Method(selfty, d))
1458 clean::TyMethodItem(ref m) => {
1459 fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
1461 clean::MethodItem(ref m) => {
1462 fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
1468 fn item_struct(w: &mut fmt::Formatter, it: &clean::Item,
1469 s: &clean::Struct) -> fmt::Result {
1470 try!(write!(w, "<pre class='rust struct'>"));
1471 try!(render_struct(w,
1475 s.fields.as_slice(),
1478 try!(write!(w, "</pre>"));
1480 try!(document(w, it));
1481 let mut fields = s.fields.iter().filter(|f| {
1483 clean::StructFieldItem(clean::HiddenStructField) => false,
1484 clean::StructFieldItem(clean::TypedStructField(..)) => true,
1488 match s.struct_type {
1489 doctree::Plain if fields.peek().is_some() => {
1490 try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
1491 for field in fields {
1492 try!(write!(w, "<tr><td id='structfield.{name}'>\
1493 <code>{name}</code></td><td>",
1494 name = field.name.get_ref().as_slice()));
1495 try!(document(w, field));
1496 try!(write!(w, "</td></tr>"));
1498 try!(write!(w, "</table>"));
1502 render_methods(w, it)
1505 fn item_enum(w: &mut fmt::Formatter, it: &clean::Item,
1506 e: &clean::Enum) -> fmt::Result {
1507 try!(write!(w, "<pre class='rust enum'>{}enum {}{}",
1508 VisSpace(it.visibility),
1509 it.name.get_ref().as_slice(),
1511 if e.variants.len() == 0 && !e.variants_stripped {
1512 try!(write!(w, " \\{\\}"));
1514 try!(write!(w, " \\{\n"));
1515 for v in e.variants.iter() {
1516 try!(write!(w, " "));
1517 let name = v.name.get_ref().as_slice();
1519 clean::VariantItem(ref var) => {
1521 clean::CLikeVariant => try!(write!(w, "{}", name)),
1522 clean::TupleVariant(ref tys) => {
1523 try!(write!(w, "{}(", name));
1524 for (i, ty) in tys.iter().enumerate() {
1526 try!(write!(w, ", "))
1528 try!(write!(w, "{}", *ty));
1530 try!(write!(w, ")"));
1532 clean::StructVariant(ref s) => {
1533 try!(render_struct(w,
1537 s.fields.as_slice(),
1545 try!(write!(w, ",\n"));
1548 if e.variants_stripped {
1549 try!(write!(w, " // some variants omitted\n"));
1551 try!(write!(w, "\\}"));
1553 try!(write!(w, "</pre>"));
1555 try!(document(w, it));
1556 if e.variants.len() > 0 {
1557 try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
1558 for variant in e.variants.iter() {
1559 try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
1560 name = variant.name.get_ref().as_slice()));
1561 try!(document(w, variant));
1562 match variant.inner {
1563 clean::VariantItem(ref var) => {
1565 clean::StructVariant(ref s) => {
1566 let mut fields = s.fields.iter().filter(|f| {
1568 clean::StructFieldItem(ref t) => match *t {
1569 clean::HiddenStructField => false,
1570 clean::TypedStructField(..) => true,
1575 try!(write!(w, "<h3 class='fields'>Fields</h3>\n
1577 for field in fields {
1578 try!(write!(w, "<tr><td \
1579 id='variant.{v}.field.{f}'>\
1580 <code>{f}</code></td><td>",
1581 v = variant.name.get_ref().as_slice(),
1582 f = field.name.get_ref().as_slice()));
1583 try!(document(w, field));
1584 try!(write!(w, "</td></tr>"));
1586 try!(write!(w, "</table>"));
1593 try!(write!(w, "</td></tr>"));
1595 try!(write!(w, "</table>"));
1598 try!(render_methods(w, it));
1602 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
1603 g: Option<&clean::Generics>,
1604 ty: doctree::StructType,
1605 fields: &[clean::Item],
1607 structhead: bool) -> fmt::Result {
1608 try!(write!(w, "{}{}{}",
1609 VisSpace(it.visibility),
1610 if structhead {"struct "} else {""},
1611 it.name.get_ref().as_slice()));
1613 Some(g) => try!(write!(w, "{}", *g)),
1618 try!(write!(w, " \\{\n{}", tab));
1619 let mut fields_stripped = false;
1620 for field in fields.iter() {
1622 clean::StructFieldItem(clean::HiddenStructField) => {
1623 fields_stripped = true;
1625 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
1626 try!(write!(w, " {}{}: {},\n{}",
1627 VisSpace(field.visibility),
1628 field.name.get_ref().as_slice(),
1632 _ => unreachable!(),
1636 if fields_stripped {
1637 try!(write!(w, " // some fields omitted\n{}", tab));
1639 try!(write!(w, "\\}"));
1641 doctree::Tuple | doctree::Newtype => {
1642 try!(write!(w, "("));
1643 for (i, field) in fields.iter().enumerate() {
1645 try!(write!(w, ", "));
1648 clean::StructFieldItem(clean::HiddenStructField) => {
1649 try!(write!(w, "_"))
1651 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
1652 try!(write!(w, "{}{}", VisSpace(field.visibility), *ty))
1657 try!(write!(w, ");"));
1660 try!(write!(w, ";"));
1666 fn render_methods(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
1667 match cache_key.get().unwrap().impls.find(&it.def_id.node) {
1669 let mut non_trait = v.iter().filter(|p| {
1670 p.ref0().trait_.is_none()
1672 let non_trait = non_trait.collect::<Vec<&(clean::Impl, Option<String>)>>();
1673 let mut traits = v.iter().filter(|p| {
1674 p.ref0().trait_.is_some()
1676 let traits = traits.collect::<Vec<&(clean::Impl, Option<String>)>>();
1678 if non_trait.len() > 0 {
1679 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
1680 for &(ref i, ref dox) in non_trait.move_iter() {
1681 try!(render_impl(w, i, dox));
1684 if traits.len() > 0 {
1685 try!(write!(w, "<h2 id='implementations'>Trait \
1686 Implementations</h2>"));
1687 let mut any_derived = false;
1688 for & &(ref i, ref dox) in traits.iter() {
1690 try!(render_impl(w, i, dox));
1696 try!(write!(w, "<h3 id='derived_implementations'>Derived Implementations \
1698 for &(ref i, ref dox) in traits.move_iter() {
1700 try!(render_impl(w, i, dox));
1711 fn render_impl(w: &mut fmt::Formatter, i: &clean::Impl,
1712 dox: &Option<String>) -> fmt::Result {
1713 try!(write!(w, "<h3 class='impl'><code>impl{} ", i.generics));
1715 Some(ref ty) => try!(write!(w, "{} for ", *ty)),
1718 try!(write!(w, "{}</code></h3>", i.for_));
1721 try!(write!(w, "<div class='docblock'>{}</div>",
1722 Markdown(dox.as_slice())));
1727 fn docmeth(w: &mut fmt::Formatter, item: &clean::Item,
1728 dox: bool) -> fmt::Result {
1729 try!(write!(w, "<h4 id='method.{}' class='method'><code>",
1730 *item.name.get_ref()));
1731 try!(render_method(w, item));
1732 try!(write!(w, "</code></h4>\n"));
1733 match item.doc_value() {
1735 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1738 Some(..) | None => Ok(())
1742 try!(write!(w, "<div class='methods'>"));
1743 for meth in i.methods.iter() {
1744 try!(docmeth(w, meth, true));
1747 fn render_default_methods(w: &mut fmt::Formatter,
1749 i: &clean::Impl) -> fmt::Result {
1750 for method in t.methods.iter() {
1751 let n = method.item().name.clone();
1752 match i.methods.iter().find(|m| { m.name == n }) {
1753 Some(..) => continue,
1757 try!(docmeth(w, method.item(), false));
1762 // If we've implemented a trait, then also emit documentation for all
1763 // default methods which weren't overridden in the implementation block.
1765 Some(clean::ResolvedPath { did, .. }) => {
1767 match cache_key.get().unwrap().traits.find(&did) {
1768 Some(t) => try!(render_default_methods(w, t, i)),
1774 Some(..) | None => {}
1776 try!(write!(w, "</div>"));
1780 fn item_typedef(w: &mut fmt::Formatter, it: &clean::Item,
1781 t: &clean::Typedef) -> fmt::Result {
1782 try!(write!(w, "<pre class='rust typedef'>type {}{} = {};</pre>",
1783 it.name.get_ref().as_slice(),
1790 impl<'a> fmt::Show for Sidebar<'a> {
1791 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1794 try!(write!(fmt, "<p class='location'>"));
1795 let len = cx.current.len() - if it.is_mod() {1} else {0};
1796 for (i, name) in cx.current.iter().take(len).enumerate() {
1798 try!(write!(fmt, "&\\#8203;::"));
1800 try!(write!(fmt, "<a href='{}index.html'>{}</a>",
1803 .slice_to((cx.current.len() - i - 1) * 3),
1806 try!(write!(fmt, "</p>"));
1808 fn block(w: &mut fmt::Formatter, short: &str, longty: &str,
1809 cur: &clean::Item, cx: &Context) -> fmt::Result {
1810 let items = match cx.sidebar.find_equiv(&short) {
1811 Some(items) => items.as_slice(),
1812 None => return Ok(())
1814 try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
1815 for item in items.iter() {
1816 let curty = shortty(cur).to_static_str();
1817 let class = if cur.name.get_ref() == item &&
1818 short == curty { "current" } else { "" };
1819 try!(write!(w, "<a class='{ty} {class}' href='{curty, select,
1823 mod{{name}/index.html}
1824 other{#.{name}.html}
1825 }'>{name}</a><br/>",
1830 name = item.as_slice()));
1832 try!(write!(w, "</div>"));
1836 try!(block(fmt, "mod", "Modules", it, cx));
1837 try!(block(fmt, "struct", "Structs", it, cx));
1838 try!(block(fmt, "enum", "Enums", it, cx));
1839 try!(block(fmt, "trait", "Traits", it, cx));
1840 try!(block(fmt, "fn", "Functions", it, cx));
1841 try!(block(fmt, "macro", "Macros", it, cx));
1846 fn build_sidebar(m: &clean::Module) -> HashMap<String, Vec<String>> {
1847 let mut map = HashMap::new();
1848 for item in m.items.iter() {
1849 let short = shortty(item).to_static_str();
1850 let myname = match item.name {
1852 Some(ref s) => s.to_strbuf(),
1854 let v = map.find_or_insert_with(short.to_strbuf(), |_| Vec::new());
1858 for (_, items) in map.mut_iter() {
1859 items.as_mut_slice().sort();
1864 impl<'a> fmt::Show for Source<'a> {
1865 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1866 let Source(s) = *self;
1867 let lines = s.lines().len();
1869 let mut tmp = lines;
1874 try!(write!(fmt, "<pre class='line-numbers'>"));
1875 for i in range(1, lines + 1) {
1876 try!(write!(fmt, "<span id='{0:u}'>{0:1$u}</span>\n", i, cols));
1878 try!(write!(fmt, "</pre>"));
1879 try!(write!(fmt, "{}", highlight::highlight(s.as_slice(), None)));
1884 fn item_macro(w: &mut fmt::Formatter, it: &clean::Item,
1885 t: &clean::Macro) -> fmt::Result {
1886 try!(w.write(highlight::highlight(t.source.as_slice(), Some("macro")).as_bytes()));