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 externalfiles::ExternalHtml;
47 use serialize::Encodable;
48 use serialize::json::ToJson;
51 use rustc::util::nodemap::NodeSet;
56 use html::format::{VisSpace, Method, FnStyleSpace, MutableSpace, Stability};
57 use html::format::{ConciseStability};
59 use html::item_type::{ItemType, shortty};
62 use html::markdown::Markdown;
64 use stability_summary;
66 /// Major driving force in all rustdoc rendering. This contains information
67 /// about where in the tree-like hierarchy rendering is occurring and controls
68 /// how the current page is being rendered.
70 /// It is intended that this context is a lightweight object which can be fairly
71 /// easily cloned because it is cloned per work-job (about once per item in the
75 /// Current hierarchy of components leading down to what's currently being
77 pub current: Vec<String>,
78 /// String representation of how to get back to the root path of the 'doc/'
79 /// folder in terms of a relative URL.
80 pub root_path: String,
81 /// The current destination folder of where HTML artifacts should be placed.
82 /// This changes as the context descends into the module hierarchy.
84 /// This describes the layout of each page, and is not modified after
85 /// creation of the context (contains info like the favicon and added html).
86 pub layout: layout::Layout,
87 /// This map is a list of what should be displayed on the sidebar of the
88 /// current page. The key is the section header (traits, modules,
89 /// functions), and the value is the list of containers belonging to this
90 /// header. This map will change depending on the surrounding context of the
92 pub sidebar: HashMap<String, Vec<String>>,
93 /// This flag indicates whether [src] links should be generated or not. If
94 /// the source files are present in the html rendering, then this will be
96 pub include_sources: bool,
97 /// A flag, which when turned off, will render pages which redirect to the
98 /// real location of an item. This is used to allow external links to
99 /// publicly reused items to redirect to the right location.
100 pub render_redirect_pages: bool,
103 /// Indicates where an external crate can be found.
104 pub enum ExternalLocation {
105 /// Remote URL root of the external crate
107 /// This external crate can be found in the local doc/ folder
109 /// The external crate could not be found.
113 /// Metadata about an implementor of a trait.
114 pub struct Implementor {
116 generics: clean::Generics,
119 stability: Option<clean::Stability>,
122 /// Metadata about implementations for a type.
127 stability: Option<clean::Stability>,
130 /// This cache is used to store information about the `clean::Crate` being
131 /// rendered in order to provide more useful documentation. This contains
132 /// information like all implementors of a trait, all traits a type implements,
133 /// documentation for all known traits, etc.
135 /// This structure purposefully does not implement `Clone` because it's intended
136 /// to be a fairly large and expensive structure to clone. Instead this adheres
137 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
140 /// Mapping of typaram ids to the name of the type parameter. This is used
141 /// when pretty-printing a type (so pretty printing doesn't have to
142 /// painfully maintain a context like this)
143 pub typarams: HashMap<ast::DefId, String>,
145 /// Maps a type id to all known implementations for that type. This is only
146 /// recognized for intra-crate `ResolvedPath` types, and is used to print
147 /// out extra documentation on the page of an enum/struct.
149 /// The values of the map are a list of implementations and documentation
150 /// found on that implementation.
151 pub impls: HashMap<ast::DefId, Vec<Impl>>,
153 /// Maintains a mapping of local crate node ids to the fully qualified name
154 /// and "short type description" of that node. This is used when generating
155 /// URLs when a type is being linked to. External paths are not located in
156 /// this map because the `External` type itself has all the information
158 pub paths: HashMap<ast::DefId, (Vec<String>, ItemType)>,
160 /// Similar to `paths`, but only holds external paths. This is only used for
161 /// generating explicit hyperlinks to other crates.
162 pub external_paths: HashMap<ast::DefId, Vec<String>>,
164 /// This map contains information about all known traits of this crate.
165 /// Implementations of a crate should inherit the documentation of the
166 /// parent trait if no extra documentation is specified, and default methods
167 /// should show up in documentation about trait implementations.
168 pub traits: HashMap<ast::DefId, clean::Trait>,
170 /// When rendering traits, it's often useful to be able to list all
171 /// implementors of the trait, and this mapping is exactly, that: a mapping
172 /// of trait ids to the list of known implementors of the trait
173 pub implementors: HashMap<ast::DefId, Vec<Implementor>>,
175 /// Cache of where external crate documentation can be found.
176 pub extern_locations: HashMap<ast::CrateNum, ExternalLocation>,
178 /// Cache of where documentation for primitives can be found.
179 pub primitive_locations: HashMap<clean::Primitive, ast::CrateNum>,
181 /// Set of definitions which have been inlined from external crates.
182 pub inlined: HashSet<ast::DefId>,
184 // Private fields only used when initially crawling a crate to build a cache
187 parent_stack: Vec<ast::DefId>,
188 search_index: Vec<IndexItem>,
190 public_items: NodeSet,
192 // In rare case where a structure is defined in one module but implemented
193 // in another, if the implementing module is parsed before defining module,
194 // then the fully qualified name of the structure isn't presented in `paths`
195 // yet when its implementation methods are being indexed. Caches such methods
196 // and their parent id here and indexes them at the end of crate parsing.
197 orphan_methods: Vec<(ast::NodeId, clean::Item)>,
200 /// Helper struct to render all source code to HTML pages
201 struct SourceCollector<'a> {
204 /// Processed source-file paths
205 seen: HashSet<String>,
206 /// Root destination to place all HTML output into
210 /// Wrapper struct to render the source code of a file. This will do things like
211 /// adding line numbers to the left-hand side.
212 struct Source<'a>(&'a str);
214 // Helper structs for rendering items/sidebars and carrying along contextual
217 struct Item<'a> { cx: &'a Context, item: &'a clean::Item, }
218 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
220 /// Struct representing one entry in the JS search index. These are all emitted
221 /// by hand to a large JS file at the end of cache-creation.
227 parent: Option<ast::DefId>,
230 // TLS keys used to carry information around during rendering.
232 local_data_key!(pub cache_key: Arc<Cache>)
233 local_data_key!(pub current_location_key: Vec<String> )
235 /// Generates the documentation for `crate` into the directory `dst`
236 pub fn run(mut krate: clean::Crate, external_html: &ExternalHtml, dst: Path) -> io::IoResult<()> {
237 let mut cx = Context {
240 root_path: String::new(),
241 sidebar: HashMap::new(),
242 layout: layout::Layout {
243 logo: "".to_string(),
244 favicon: "".to_string(),
245 external_html: external_html.clone(),
246 krate: krate.name.clone(),
247 playground_url: "".to_string(),
249 include_sources: true,
250 render_redirect_pages: false,
253 try!(mkdir(&cx.dst));
255 // Crawl the crate, building a summary of the stability levels. NOTE: this
256 // summary *must* be computed with the original `krate`; the folding below
257 // removes the impls from their modules.
258 let summary = stability_summary::build(&krate);
260 // Crawl the crate attributes looking for attributes which control how we're
261 // going to emit HTML
262 match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(&[])) {
264 for attr in attrs.iter() {
266 clean::NameValue(ref x, ref s)
267 if "html_favicon_url" == x.as_slice() => {
268 cx.layout.favicon = s.to_string();
270 clean::NameValue(ref x, ref s)
271 if "html_logo_url" == x.as_slice() => {
272 cx.layout.logo = s.to_string();
274 clean::NameValue(ref x, ref s)
275 if "html_playground_url" == x.as_slice() => {
276 cx.layout.playground_url = s.to_string();
277 let name = krate.name.clone();
278 if markdown::playground_krate.get().is_none() {
279 markdown::playground_krate.replace(Some(Some(name)));
283 if "html_no_source" == x.as_slice() => {
284 cx.include_sources = false;
293 // Crawl the crate to build various caches used for the output
294 let analysis = ::analysiskey.get();
295 let public_items = analysis.as_ref().map(|a| a.public_items.clone());
296 let public_items = public_items.unwrap_or(NodeSet::new());
297 let paths: HashMap<ast::DefId, (Vec<String>, ItemType)> =
298 analysis.as_ref().map(|a| {
299 let paths = a.external_paths.borrow_mut().take_unwrap();
300 paths.move_iter().map(|(k, (v, t))| {
302 clean::TypeStruct => item_type::Struct,
303 clean::TypeEnum => item_type::Enum,
304 clean::TypeFunction => item_type::Function,
305 clean::TypeTrait => item_type::Trait,
306 clean::TypeModule => item_type::Module,
307 clean::TypeStatic => item_type::Static,
308 clean::TypeVariant => item_type::Variant,
311 }).unwrap_or(HashMap::new());
312 let mut cache = Cache {
313 impls: HashMap::new(),
314 external_paths: paths.iter().map(|(&k, &(ref v, _))| (k, v.clone()))
317 implementors: HashMap::new(),
319 parent_stack: Vec::new(),
320 search_index: Vec::new(),
321 extern_locations: HashMap::new(),
322 primitive_locations: HashMap::new(),
324 public_items: public_items,
325 orphan_methods: Vec::new(),
326 traits: analysis.as_ref().map(|a| {
327 a.external_traits.borrow_mut().take_unwrap()
328 }).unwrap_or(HashMap::new()),
329 typarams: analysis.as_ref().map(|a| {
330 a.external_typarams.borrow_mut().take_unwrap()
331 }).unwrap_or(HashMap::new()),
332 inlined: analysis.as_ref().map(|a| {
333 a.inlined.borrow_mut().take_unwrap()
334 }).unwrap_or(HashSet::new()),
336 cache.stack.push(krate.name.clone());
337 krate = cache.fold_crate(krate);
339 // Cache where all our extern crates are located
340 for &(n, ref e) in krate.externs.iter() {
341 cache.extern_locations.insert(n, extern_location(e, &cx.dst));
342 let did = ast::DefId { krate: n, node: ast::CRATE_NODE_ID };
343 cache.paths.insert(did, (vec![e.name.to_string()], item_type::Module));
346 // Cache where all known primitives have their documentation located.
348 // Favor linking to as local extern as possible, so iterate all crates in
349 // reverse topological order.
350 for &(n, ref e) in krate.externs.iter().rev() {
351 for &prim in e.primitives.iter() {
352 cache.primitive_locations.insert(prim, n);
355 for &prim in krate.primitives.iter() {
356 cache.primitive_locations.insert(prim, ast::LOCAL_CRATE);
359 // Build our search index
360 let index = try!(build_index(&krate, &mut cache));
362 // Freeze the cache now that the index has been built. Put an Arc into TLS
363 // for future parallelization opportunities
364 let cache = Arc::new(cache);
365 cache_key.replace(Some(cache.clone()));
366 current_location_key.replace(Some(Vec::new()));
368 try!(write_shared(&cx, &krate, &*cache, index));
369 let krate = try!(render_sources(&mut cx, krate));
371 // And finally render the whole crate's documentation
372 cx.krate(krate, summary)
375 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult<String> {
376 // Build the search index from the collected metadata
377 let mut nodeid_to_pathid = HashMap::new();
378 let mut pathid_to_nodeid = Vec::new();
380 let Cache { ref mut search_index,
382 ref mut paths, .. } = *cache;
384 // Attach all orphan methods to the type's definition if the type
385 // has since been learned.
386 for &(pid, ref item) in orphan_methods.iter() {
387 let did = ast_util::local_def(pid);
388 match paths.find(&did) {
389 Some(&(ref fqp, _)) => {
390 search_index.push(IndexItem {
392 name: item.name.clone().unwrap(),
393 path: fqp.slice_to(fqp.len() - 1).connect("::"),
394 desc: shorter(item.doc_value()).to_string(),
402 // Reduce `NodeId` in paths into smaller sequential numbers,
403 // and prune the paths that do not appear in the index.
404 for item in search_index.iter() {
407 if !nodeid_to_pathid.contains_key(&nodeid) {
408 let pathid = pathid_to_nodeid.len();
409 nodeid_to_pathid.insert(nodeid, pathid);
410 pathid_to_nodeid.push(nodeid);
416 assert_eq!(nodeid_to_pathid.len(), pathid_to_nodeid.len());
419 // Collect the index into a string
420 let mut w = MemWriter::new();
421 try!(write!(&mut w, r#"searchIndex['{}'] = {{"items":["#, krate.name));
423 let mut lastpath = "".to_string();
424 for (i, item) in cache.search_index.iter().enumerate() {
425 // Omit the path if it is same to that of the prior item.
427 if lastpath.as_slice() == item.path.as_slice() {
430 lastpath = item.path.to_string();
431 path = item.path.as_slice();
435 try!(write!(&mut w, ","));
437 try!(write!(&mut w, r#"[{:u},"{}","{}",{}"#,
438 item.ty, item.name, path,
439 item.desc.to_json().to_string()));
442 let pathid = *nodeid_to_pathid.find(&nodeid).unwrap();
443 try!(write!(&mut w, ",{}", pathid));
447 try!(write!(&mut w, "]"));
450 try!(write!(&mut w, r#"],"paths":["#));
452 for (i, &did) in pathid_to_nodeid.iter().enumerate() {
453 let &(ref fqp, short) = cache.paths.find(&did).unwrap();
455 try!(write!(&mut w, ","));
457 try!(write!(&mut w, r#"[{:u},"{}"]"#,
458 short, *fqp.last().unwrap()));
461 try!(write!(&mut w, "]}};"));
463 Ok(String::from_utf8(w.unwrap()).unwrap())
466 fn write_shared(cx: &Context,
467 krate: &clean::Crate,
469 search_index: String) -> io::IoResult<()> {
470 // Write out the shared files. Note that these are shared among all rustdoc
471 // docs placed in the output directory, so this needs to be a synchronized
472 // operation with respect to all other rustdocs running around.
473 try!(mkdir(&cx.dst));
474 let _lock = ::flock::Lock::new(&cx.dst.join(".lock"));
476 // Add all the static files. These may already exist, but we just
477 // overwrite them anyway to make sure that they're fresh and up-to-date.
478 try!(write(cx.dst.join("jquery.js"),
479 include_bin!("static/jquery-2.1.0.min.js")));
480 try!(write(cx.dst.join("main.js"), include_bin!("static/main.js")));
481 try!(write(cx.dst.join("playpen.js"), include_bin!("static/playpen.js")));
482 try!(write(cx.dst.join("main.css"), include_bin!("static/main.css")));
483 try!(write(cx.dst.join("normalize.css"),
484 include_bin!("static/normalize.css")));
485 try!(write(cx.dst.join("FiraSans-Regular.woff"),
486 include_bin!("static/FiraSans-Regular.woff")));
487 try!(write(cx.dst.join("FiraSans-Medium.woff"),
488 include_bin!("static/FiraSans-Medium.woff")));
489 try!(write(cx.dst.join("Heuristica-Italic.woff"),
490 include_bin!("static/Heuristica-Italic.woff")));
491 try!(write(cx.dst.join("SourceSerifPro-Regular.woff"),
492 include_bin!("static/SourceSerifPro-Regular.woff")));
493 try!(write(cx.dst.join("SourceSerifPro-Bold.woff"),
494 include_bin!("static/SourceSerifPro-Bold.woff")));
495 try!(write(cx.dst.join("SourceCodePro-Regular.woff"),
496 include_bin!("static/SourceCodePro-Regular.woff")));
497 try!(write(cx.dst.join("SourceCodePro-Semibold.woff"),
498 include_bin!("static/SourceCodePro-Semibold.woff")));
500 fn collect(path: &Path, krate: &str,
501 key: &str) -> io::IoResult<Vec<String>> {
502 let mut ret = Vec::new();
504 for line in BufferedReader::new(File::open(path)).lines() {
505 let line = try!(line);
506 if !line.as_slice().starts_with(key) {
509 if line.as_slice().starts_with(
510 format!("{}['{}']", key, krate).as_slice()) {
513 ret.push(line.to_string());
519 // Update the search index
520 let dst = cx.dst.join("search-index.js");
521 let all_indexes = try!(collect(&dst, krate.name.as_slice(),
523 let mut w = try!(File::create(&dst));
524 try!(writeln!(&mut w, "var searchIndex = {{}};"));
525 try!(writeln!(&mut w, "{}", search_index));
526 for index in all_indexes.iter() {
527 try!(writeln!(&mut w, "{}", *index));
529 try!(writeln!(&mut w, "initSearch(searchIndex);"));
531 // Update the list of all implementors for traits
532 let dst = cx.dst.join("implementors");
534 for (&did, imps) in cache.implementors.iter() {
535 // Private modules can leak through to this phase of rustdoc, which
536 // could contain implementations for otherwise private types. In some
537 // rare cases we could find an implementation for an item which wasn't
538 // indexed, so we just skip this step in that case.
540 // FIXME: this is a vague explanation for why this can't be a `get`, in
541 // theory it should be...
542 let &(ref remote_path, remote_item_type) = match cache.paths.find(&did) {
547 let mut mydst = dst.clone();
548 for part in remote_path.slice_to(remote_path.len() - 1).iter() {
549 mydst.push(part.as_slice());
552 mydst.push(format!("{}.{}.js",
553 remote_item_type.to_static_str(),
554 remote_path[remote_path.len() - 1]));
555 let all_implementors = try!(collect(&mydst, krate.name.as_slice(),
558 try!(mkdir(&mydst.dir_path()));
559 let mut f = BufferedWriter::new(try!(File::create(&mydst)));
560 try!(writeln!(&mut f, "(function() {{var implementors = {{}};"));
562 for implementor in all_implementors.iter() {
563 try!(write!(&mut f, "{}", *implementor));
566 try!(write!(&mut f, r"implementors['{}'] = [", krate.name));
567 for imp in imps.iter() {
568 // If the trait and implementation are in the same crate, then
569 // there's no need to emit information about it (there's inlining
570 // going on). If they're in different crates then the crate defining
571 // the trait will be interested in our implementation.
572 if imp.def_id.krate == did.krate { continue }
573 try!(write!(&mut f, r#""{}impl{} {} for {}","#,
574 ConciseStability(&imp.stability),
575 imp.generics, imp.trait_, imp.for_));
577 try!(writeln!(&mut f, r"];"));
578 try!(writeln!(&mut f, "{}", r"
579 if (window.register_implementors) {
580 window.register_implementors(implementors);
582 window.pending_implementors = implementors;
585 try!(writeln!(&mut f, r"}})()"));
590 fn render_sources(cx: &mut Context,
591 krate: clean::Crate) -> io::IoResult<clean::Crate> {
592 info!("emitting source files");
593 let dst = cx.dst.join("src");
595 let dst = dst.join(krate.name.as_slice());
597 let mut folder = SourceCollector {
599 seen: HashSet::new(),
602 // skip all invalid spans
603 folder.seen.insert("".to_string());
604 Ok(folder.fold_crate(krate))
607 /// Writes the entire contents of a string to a destination, not attempting to
608 /// catch any errors.
609 fn write(dst: Path, contents: &[u8]) -> io::IoResult<()> {
610 File::create(&dst).write(contents)
613 /// Makes a directory on the filesystem, failing the task if an error occurs and
614 /// skipping if the directory already exists.
615 fn mkdir(path: &Path) -> io::IoResult<()> {
617 fs::mkdir(path, io::UserRWX)
623 /// Takes a path to a source file and cleans the path to it. This canonicalizes
624 /// things like ".." to components which preserve the "top down" hierarchy of a
625 /// static HTML tree.
626 // FIXME (#9639): The closure should deal with &[u8] instead of &str
627 fn clean_srcpath(src: &[u8], f: |&str|) {
628 let p = Path::new(src);
629 if p.as_vec() != b"." {
630 for c in p.str_components().map(|x|x.unwrap()) {
640 /// Attempts to find where an external crate is located, given that we're
641 /// rendering in to the specified source destination.
642 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
643 // See if there's documentation generated into the local directory
644 let local_location = dst.join(e.name.as_slice());
645 if local_location.is_dir() {
649 // Failing that, see if there's an attribute specifying where to find this
651 for attr in e.attrs.iter() {
653 clean::List(ref x, ref list) if "doc" == x.as_slice() => {
654 for attr in list.iter() {
656 clean::NameValue(ref x, ref s)
657 if "html_root_url" == x.as_slice() => {
658 if s.as_slice().ends_with("/") {
659 return Remote(s.to_string());
661 return Remote(format!("{}/", s));
671 // Well, at least we tried.
675 impl<'a> DocFolder for SourceCollector<'a> {
676 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
677 // If we're including source files, and we haven't seen this file yet,
678 // then we need to render it out to the filesystem
679 if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
681 // If it turns out that we couldn't read this file, then we probably
682 // can't read any of the files (generating html output from json or
683 // something like that), so just don't include sources for the
684 // entire crate. The other option is maintaining this mapping on a
685 // per-file basis, but that's probably not worth it...
687 .include_sources = match self.emit_source(item.source
692 println!("warning: source code was requested to be rendered, \
693 but processing `{}` had an error: {}",
694 item.source.filename, e);
695 println!(" skipping rendering of source code");
699 self.seen.insert(item.source.filename.clone());
702 self.fold_item_recur(item)
706 impl<'a> SourceCollector<'a> {
707 /// Renders the given filename into its corresponding HTML source file.
708 fn emit_source(&mut self, filename: &str) -> io::IoResult<()> {
709 let p = Path::new(filename);
711 // If we couldn't open this file, then just returns because it
712 // probably means that it's some standard library macro thing and we
713 // can't have the source to it anyway.
714 let contents = match File::open(&p).read_to_end() {
716 // macros from other libraries get special filenames which we can
718 Err(..) if filename.starts_with("<") &&
719 filename.ends_with("macros>") => return Ok(()),
720 Err(e) => return Err(e)
722 let contents = str::from_utf8(contents.as_slice()).unwrap();
724 // Remove the utf-8 BOM if any
725 let contents = if contents.starts_with("\ufeff") {
726 contents.slice_from(3)
731 // Create the intermediate directories
732 let mut cur = self.dst.clone();
733 let mut root_path = String::from_str("../../");
734 clean_srcpath(p.dirname(), |component| {
736 mkdir(&cur).unwrap();
737 root_path.push_str("../");
740 cur.push(Vec::from_slice(p.filename().expect("source has no filename"))
742 let mut w = BufferedWriter::new(try!(File::create(&cur)));
744 let title = format!("{} -- source", cur.filename_display());
745 let page = layout::Page {
746 title: title.as_slice(),
748 root_path: root_path.as_slice(),
750 try!(layout::render(&mut w as &mut Writer, &self.cx.layout,
751 &page, &(""), &Source(contents)));
757 impl DocFolder for Cache {
758 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
759 // If this is a private module, we don't want it in the search index.
760 let orig_privmod = match item.inner {
761 clean::ModuleItem(..) => {
762 let prev = self.privmod;
763 self.privmod = prev || item.visibility != Some(ast::Public);
769 // Register any generics to their corresponding string. This is used
770 // when pretty-printing types
772 clean::StructItem(ref s) => self.generics(&s.generics),
773 clean::EnumItem(ref e) => self.generics(&e.generics),
774 clean::FunctionItem(ref f) => self.generics(&f.generics),
775 clean::TypedefItem(ref t) => self.generics(&t.generics),
776 clean::TraitItem(ref t) => self.generics(&t.generics),
777 clean::ImplItem(ref i) => self.generics(&i.generics),
778 clean::TyMethodItem(ref i) => self.generics(&i.generics),
779 clean::MethodItem(ref i) => self.generics(&i.generics),
780 clean::ForeignFunctionItem(ref f) => self.generics(&f.generics),
784 // Propagate a trait methods' documentation to all implementors of the
787 clean::TraitItem(ref t) => {
788 self.traits.insert(item.def_id, t.clone());
793 // Collect all the implementors of traits.
795 clean::ImplItem(ref i) => {
797 Some(clean::ResolvedPath{ did, .. }) => {
798 let v = self.implementors.find_or_insert_with(did, |_| {
803 generics: i.generics.clone(),
804 trait_: i.trait_.get_ref().clone(),
805 for_: i.for_.clone(),
806 stability: item.stability.clone(),
809 Some(..) | None => {}
815 // Index this method for searching later on
818 let parent = match item.inner {
819 clean::TyMethodItem(..) |
820 clean::StructFieldItem(..) |
821 clean::VariantItem(..) => {
822 (Some(*self.parent_stack.last().unwrap()),
823 Some(self.stack.slice_to(self.stack.len() - 1)))
825 clean::MethodItem(..) => {
826 if self.parent_stack.len() == 0 {
829 let last = self.parent_stack.last().unwrap();
831 let path = match self.paths.find(&did) {
832 Some(&(_, item_type::Trait)) =>
833 Some(self.stack.slice_to(self.stack.len() - 1)),
834 // The current stack not necessarily has correlation for
835 // where the type was defined. On the other hand,
836 // `paths` always has the right information if present.
837 Some(&(ref fqp, item_type::Struct)) |
838 Some(&(ref fqp, item_type::Enum)) =>
839 Some(fqp.slice_to(fqp.len() - 1)),
840 Some(..) => Some(self.stack.as_slice()),
846 _ => (None, Some(self.stack.as_slice()))
848 let hidden_field = match item.inner {
849 clean::StructFieldItem(clean::HiddenStructField) => true,
853 (parent, Some(path)) if !self.privmod && !hidden_field => {
854 self.search_index.push(IndexItem {
857 path: path.connect("::").to_string(),
858 desc: shorter(item.doc_value()).to_string(),
862 (Some(parent), None) if !self.privmod => {
863 if ast_util::is_local(parent) {
864 // We have a parent, but we don't know where they're
865 // defined yet. Wait for later to index this item.
866 self.orphan_methods.push((parent.node, item.clone()))
875 // Keep track of the fully qualified path for this item.
876 let pushed = if item.name.is_some() {
877 let n = item.name.get_ref();
879 self.stack.push(n.to_string());
884 clean::StructItem(..) | clean::EnumItem(..) |
885 clean::TypedefItem(..) | clean::TraitItem(..) |
886 clean::FunctionItem(..) | clean::ModuleItem(..) |
887 clean::ForeignFunctionItem(..) if !self.privmod => {
888 // Reexported items mean that the same id can show up twice
889 // in the rustdoc ast that we're looking at. We know,
890 // however, that a reexported item doesn't show up in the
891 // `public_items` map, so we can skip inserting into the
892 // paths map if there was already an entry present and we're
893 // not a public item.
894 let id = item.def_id.node;
895 if !self.paths.contains_key(&item.def_id) ||
896 !ast_util::is_local(item.def_id) ||
897 self.public_items.contains(&id) {
898 self.paths.insert(item.def_id,
899 (self.stack.clone(), shortty(&item)));
902 // link variants to their parent enum because pages aren't emitted
904 clean::VariantItem(..) if !self.privmod => {
905 let mut stack = self.stack.clone();
907 self.paths.insert(item.def_id, (stack, item_type::Enum));
910 clean::PrimitiveItem(..) if item.visibility.is_some() => {
911 self.paths.insert(item.def_id, (self.stack.clone(),
918 // Maintain the parent stack
919 let parent_pushed = match item.inner {
920 clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
921 self.parent_stack.push(item.def_id);
924 clean::ImplItem(ref i) => {
926 clean::ResolvedPath{ did, .. } => {
927 self.parent_stack.push(did);
936 // Once we've recursively found all the generics, then hoard off all the
937 // implementations elsewhere
938 let ret = match self.fold_item_recur(item) {
941 clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
942 use clean::{Primitive, Vector, ResolvedPath, BorrowedRef};
943 use clean::{FixedVector, Slice, Tuple, PrimitiveTuple};
945 // extract relevant documentation for this impl
946 let dox = match attrs.move_iter().find(|a| {
948 clean::NameValue(ref x, _)
949 if "doc" == x.as_slice() => {
955 Some(clean::NameValue(_, dox)) => Some(dox),
956 Some(..) | None => None,
959 // Figure out the id of this impl. This may map to a
960 // primitive rather than always to a struct/enum.
961 let did = match i.for_ {
962 ResolvedPath { did, .. } => Some(did),
964 // References to primitives are picked up as well to
965 // recognize implementations for &str, this may not
966 // be necessary in a DST world.
968 BorrowedRef { type_: box Primitive(p), ..} =>
970 Some(ast_util::local_def(p.to_node_id()))
973 // In a DST world, we may only need
974 // Vector/FixedVector, but for now we also pick up
975 // borrowed references
976 Vector(..) | FixedVector(..) |
977 BorrowedRef{ type_: box Vector(..), .. } |
978 BorrowedRef{ type_: box FixedVector(..), .. } =>
980 Some(ast_util::local_def(Slice.to_node_id()))
984 let id = PrimitiveTuple.to_node_id();
985 Some(ast_util::local_def(id))
993 let v = self.impls.find_or_insert_with(did, |_| {
999 stability: item.stability.clone(),
1013 if pushed { self.stack.pop().unwrap(); }
1014 if parent_pushed { self.parent_stack.pop().unwrap(); }
1015 self.privmod = orig_privmod;
1021 fn generics(&mut self, generics: &clean::Generics) {
1022 for typ in generics.type_params.iter() {
1023 self.typarams.insert(typ.did, typ.name.clone());
1029 /// Recurse in the directory structure and change the "root path" to make
1030 /// sure it always points to the top (relatively)
1031 fn recurse<T>(&mut self, s: String, f: |&mut Context| -> T) -> T {
1033 fail!("what {:?}", self);
1035 let prev = self.dst.clone();
1036 self.dst.push(s.as_slice());
1037 self.root_path.push_str("../");
1038 self.current.push(s);
1040 info!("Recursing into {}", self.dst.display());
1042 mkdir(&self.dst).unwrap();
1045 info!("Recursed; leaving {}", self.dst.display());
1047 // Go back to where we were at
1049 let len = self.root_path.len();
1050 self.root_path.truncate(len - 3);
1051 self.current.pop().unwrap();
1056 /// Main method for rendering a crate.
1058 /// This currently isn't parallelized, but it'd be pretty easy to add
1059 /// parallelization to this function.
1060 fn krate(mut self, mut krate: clean::Crate,
1061 stability: stability_summary::ModuleSummary) -> io::IoResult<()> {
1062 let mut item = match krate.module.take() {
1064 None => return Ok(())
1066 item.name = Some(krate.name);
1068 // render stability dashboard
1069 try!(self.recurse(stability.name.clone(), |this| {
1070 let json_dst = &this.dst.join("stability.json");
1071 let mut json_out = BufferedWriter::new(try!(File::create(json_dst)));
1072 try!(stability.encode(&mut json::Encoder::new(&mut json_out)));
1074 let title = stability.name.clone().append(" - Stability dashboard");
1075 let page = layout::Page {
1077 root_path: this.root_path.as_slice(),
1078 title: title.as_slice(),
1080 let html_dst = &this.dst.join("stability.html");
1081 let mut html_out = BufferedWriter::new(try!(File::create(html_dst)));
1082 layout::render(&mut html_out, &this.layout, &page,
1083 &Sidebar{ cx: this, item: &item },
1087 // render the crate documentation
1088 let mut work = vec!((self, item));
1091 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
1092 work.push((cx.clone(), item));
1101 /// Non-parellelized version of rendering an item. This will take the input
1102 /// item, render its contents, and then invoke the specified closure with
1103 /// all sub-items which need to be rendered.
1105 /// The rendering driver uses this closure to queue up more work.
1106 fn item(&mut self, item: clean::Item,
1107 f: |&mut Context, clean::Item|) -> io::IoResult<()> {
1108 fn render(w: io::File, cx: &Context, it: &clean::Item,
1109 pushname: bool) -> io::IoResult<()> {
1110 info!("Rendering an item to {}", w.path().display());
1111 // A little unfortunate that this is done like this, but it sure
1112 // does make formatting *a lot* nicer.
1113 current_location_key.replace(Some(cx.current.clone()));
1115 let mut title = cx.current.connect("::");
1117 if title.len() > 0 {
1118 title.push_str("::");
1120 title.push_str(it.name.get_ref().as_slice());
1122 title.push_str(" - Rust");
1123 let page = layout::Page {
1124 ty: shortty(it).to_static_str(),
1125 root_path: cx.root_path.as_slice(),
1126 title: title.as_slice(),
1129 markdown::reset_headers();
1131 // We have a huge number of calls to write, so try to alleviate some
1132 // of the pain by using a buffered writer instead of invoking the
1133 // write sycall all the time.
1134 let mut writer = BufferedWriter::new(w);
1135 if !cx.render_redirect_pages {
1136 try!(layout::render(&mut writer, &cx.layout, &page,
1137 &Sidebar{ cx: cx, item: it },
1138 &Item{ cx: cx, item: it }));
1140 let mut url = "../".repeat(cx.current.len());
1141 match cache_key.get().unwrap().paths.find(&it.def_id) {
1142 Some(&(ref names, _)) => {
1143 for name in names.slice_to(names.len() - 1).iter() {
1144 url.push_str(name.as_slice());
1147 url.push_str(item_path(it).as_slice());
1148 try!(layout::redirect(&mut writer, url.as_slice()));
1156 // Private modules may survive the strip-private pass if they
1157 // contain impls for public types. These modules can also
1158 // contain items such as publicly reexported structures.
1160 // External crates will provide links to these structures, so
1161 // these modules are recursed into, but not rendered normally (a
1162 // flag on the context).
1163 if !self.render_redirect_pages {
1164 self.render_redirect_pages = ignore_private_item(&item);
1168 // modules are special because they add a namespace. We also need to
1169 // recurse into the items of the module as well.
1170 clean::ModuleItem(..) => {
1171 let name = item.name.get_ref().to_string();
1172 let mut item = Some(item);
1173 self.recurse(name, |this| {
1174 let item = item.take_unwrap();
1175 let dst = this.dst.join("index.html");
1176 let dst = try!(File::create(&dst));
1177 try!(render(dst, this, &item, false));
1179 let m = match item.inner {
1180 clean::ModuleItem(m) => m,
1183 this.sidebar = build_sidebar(&m);
1184 for item in m.items.move_iter() {
1191 // Things which don't have names (like impls) don't get special
1192 // pages dedicated to them.
1193 _ if item.name.is_some() => {
1194 let dst = self.dst.join(item_path(&item));
1195 let dst = try!(File::create(&dst));
1196 render(dst, self, &item, true)
1205 fn ismodule(&self) -> bool {
1206 match self.item.inner {
1207 clean::ModuleItem(..) => true, _ => false
1211 /// Generate a url appropriate for an `href` attribute back to the source of
1214 /// The url generated, when clicked, will redirect the browser back to the
1215 /// original source code.
1217 /// If `None` is returned, then a source link couldn't be generated. This
1218 /// may happen, for example, with externally inlined items where the source
1219 /// of their crate documentation isn't known.
1220 fn href(&self) -> Option<String> {
1221 // If this item is part of the local crate, then we're guaranteed to
1222 // know the span, so we plow forward and generate a proper url. The url
1223 // has anchors for the line numbers that we're linking to.
1224 if ast_util::is_local(self.item.def_id) {
1225 let mut path = Vec::new();
1226 clean_srcpath(self.item.source.filename.as_bytes(), |component| {
1227 path.push(component.to_string());
1229 let href = if self.item.source.loline == self.item.source.hiline {
1230 format!("{}", self.item.source.loline)
1233 self.item.source.loline,
1234 self.item.source.hiline)
1236 Some(format!("{root}src/{krate}/{path}.html#{href}",
1237 root = self.cx.root_path,
1238 krate = self.cx.layout.krate,
1239 path = path.connect("/"),
1242 // If this item is not part of the local crate, then things get a little
1243 // trickier. We don't actually know the span of the external item, but
1244 // we know that the documentation on the other end knows the span!
1246 // In this case, we generate a link to the *documentation* for this type
1247 // in the original crate. There's an extra URL parameter which says that
1248 // we want to go somewhere else, and the JS on the destination page will
1249 // pick it up and instantly redirect the browser to the source code.
1251 // If we don't know where the external documentation for this crate is
1252 // located, then we return `None`.
1254 let cache = cache_key.get().unwrap();
1255 let path = cache.external_paths.get(&self.item.def_id);
1256 let root = match *cache.extern_locations.get(&self.item.def_id.krate) {
1257 Remote(ref s) => s.to_string(),
1258 Local => self.cx.root_path.clone(),
1259 Unknown => return None,
1261 Some(format!("{root}{path}/{file}?gotosrc={goto}",
1263 path = path.slice_to(path.len() - 1).connect("/"),
1264 file = item_path(self.item),
1265 goto = self.item.def_id.node))
1272 impl<'a> fmt::Show for Item<'a> {
1273 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1274 // Write the breadcrumb trail header for the top
1275 try!(write!(fmt, "\n<h1 class='fqn'>"));
1276 match self.item.inner {
1277 clean::ModuleItem(ref m) => if m.is_crate {
1278 try!(write!(fmt, "Crate "));
1280 try!(write!(fmt, "Module "));
1282 clean::FunctionItem(..) => try!(write!(fmt, "Function ")),
1283 clean::TraitItem(..) => try!(write!(fmt, "Trait ")),
1284 clean::StructItem(..) => try!(write!(fmt, "Struct ")),
1285 clean::EnumItem(..) => try!(write!(fmt, "Enum ")),
1286 clean::PrimitiveItem(..) => try!(write!(fmt, "Primitive Type ")),
1289 let is_primitive = match self.item.inner {
1290 clean::PrimitiveItem(..) => true,
1294 let cur = self.cx.current.as_slice();
1295 let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
1296 for (i, component) in cur.iter().enumerate().take(amt) {
1297 try!(write!(fmt, "<a href='{}index.html'>{}</a>::",
1298 "../".repeat(cur.len() - i - 1),
1299 component.as_slice()));
1302 try!(write!(fmt, "<a class='{}' href=''>{}</a>",
1303 shortty(self.item), self.item.name.get_ref().as_slice()));
1305 // Write stability level
1306 try!(write!(fmt, "{}", Stability(&self.item.stability)));
1308 // Links to out-of-band information, i.e. src and stability dashboard
1309 try!(write!(fmt, "<span class='out-of-band'>"));
1311 // Write stability dashboard link
1312 match self.item.inner {
1313 clean::ModuleItem(ref m) if m.is_crate => {
1314 try!(write!(fmt, "<a href='stability.html'>[stability dashboard]</a> "));
1321 // When this item is part of a `pub use` in a downstream crate, the
1322 // [src] link in the downstream documentation will actually come back to
1323 // this page, and this link will be auto-clicked. The `id` attribute is
1324 // used to find the link to auto-click.
1325 if self.cx.include_sources && !is_primitive {
1328 try!(write!(fmt, "<a id='src-{}' href='{}'>[src]</a>",
1329 self.item.def_id.node, l));
1335 try!(write!(fmt, "</span>"));
1337 try!(write!(fmt, "</h1>\n"));
1339 match self.item.inner {
1340 clean::ModuleItem(ref m) => {
1341 item_module(fmt, self.cx, self.item, m.items.as_slice())
1343 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1344 item_function(fmt, self.item, f),
1345 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1346 clean::StructItem(ref s) => item_struct(fmt, self.item, s),
1347 clean::EnumItem(ref e) => item_enum(fmt, self.item, e),
1348 clean::TypedefItem(ref t) => item_typedef(fmt, self.item, t),
1349 clean::MacroItem(ref m) => item_macro(fmt, self.item, m),
1350 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.item, p),
1356 fn item_path(item: &clean::Item) -> String {
1358 clean::ModuleItem(..) => {
1359 format!("{}/index.html", item.name.get_ref())
1362 format!("{}.{}.html",
1363 shortty(item).to_static_str(),
1364 *item.name.get_ref())
1369 fn full_path(cx: &Context, item: &clean::Item) -> String {
1370 let mut s = cx.current.connect("::");
1372 s.push_str(item.name.get_ref().as_slice());
1376 fn blank<'a>(s: Option<&'a str>) -> &'a str {
1383 fn shorter<'a>(s: Option<&'a str>) -> &'a str {
1385 Some(s) => match s.find_str("\n\n") {
1386 Some(pos) => s.slice_to(pos),
1393 fn document(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
1394 match item.doc_value() {
1396 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1403 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1404 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1405 try!(document(w, item));
1407 let mut indices = range(0, items.len()).filter(|i| {
1408 !ignore_private_item(&items[*i])
1409 }).collect::<Vec<uint>>();
1411 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering {
1412 if shortty(i1) == shortty(i2) {
1413 return i1.name.cmp(&i2.name);
1415 match (&i1.inner, &i2.inner) {
1416 (&clean::ViewItemItem(ref a), &clean::ViewItemItem(ref b)) => {
1417 match (&a.inner, &b.inner) {
1418 (&clean::ExternCrate(..), _) => Less,
1419 (_, &clean::ExternCrate(..)) => Greater,
1420 _ => idx1.cmp(&idx2),
1423 (&clean::ViewItemItem(..), _) => Less,
1424 (_, &clean::ViewItemItem(..)) => Greater,
1425 (&clean::PrimitiveItem(..), _) => Less,
1426 (_, &clean::PrimitiveItem(..)) => Greater,
1427 (&clean::ModuleItem(..), _) => Less,
1428 (_, &clean::ModuleItem(..)) => Greater,
1429 (&clean::MacroItem(..), _) => Less,
1430 (_, &clean::MacroItem(..)) => Greater,
1431 (&clean::StructItem(..), _) => Less,
1432 (_, &clean::StructItem(..)) => Greater,
1433 (&clean::EnumItem(..), _) => Less,
1434 (_, &clean::EnumItem(..)) => Greater,
1435 (&clean::StaticItem(..), _) => Less,
1436 (_, &clean::StaticItem(..)) => Greater,
1437 (&clean::ForeignFunctionItem(..), _) => Less,
1438 (_, &clean::ForeignFunctionItem(..)) => Greater,
1439 (&clean::ForeignStaticItem(..), _) => Less,
1440 (_, &clean::ForeignStaticItem(..)) => Greater,
1441 (&clean::TraitItem(..), _) => Less,
1442 (_, &clean::TraitItem(..)) => Greater,
1443 (&clean::FunctionItem(..), _) => Less,
1444 (_, &clean::FunctionItem(..)) => Greater,
1445 (&clean::TypedefItem(..), _) => Less,
1446 (_, &clean::TypedefItem(..)) => Greater,
1447 _ => idx1.cmp(&idx2),
1451 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1453 debug!("{:?}", indices);
1454 let mut curty = None;
1455 for &idx in indices.iter() {
1456 let myitem = &items[idx];
1458 let myty = Some(shortty(myitem));
1460 if curty.is_some() {
1461 try!(write!(w, "</table>"));
1464 let (short, name) = match myitem.inner {
1465 clean::ModuleItem(..) => ("modules", "Modules"),
1466 clean::StructItem(..) => ("structs", "Structs"),
1467 clean::EnumItem(..) => ("enums", "Enums"),
1468 clean::FunctionItem(..) => ("functions", "Functions"),
1469 clean::TypedefItem(..) => ("types", "Type Definitions"),
1470 clean::StaticItem(..) => ("statics", "Statics"),
1471 clean::TraitItem(..) => ("traits", "Traits"),
1472 clean::ImplItem(..) => ("impls", "Implementations"),
1473 clean::ViewItemItem(..) => ("reexports", "Reexports"),
1474 clean::TyMethodItem(..) => ("tymethods", "Type Methods"),
1475 clean::MethodItem(..) => ("methods", "Methods"),
1476 clean::StructFieldItem(..) => ("fields", "Struct Fields"),
1477 clean::VariantItem(..) => ("variants", "Variants"),
1478 clean::ForeignFunctionItem(..) => ("ffi-fns", "Foreign Functions"),
1479 clean::ForeignStaticItem(..) => ("ffi-statics", "Foreign Statics"),
1480 clean::MacroItem(..) => ("macros", "Macros"),
1481 clean::PrimitiveItem(..) => ("primitives", "Primitive Types"),
1484 "<h2 id='{id}' class='section-header'>\
1485 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1486 id = short, name = name));
1489 match myitem.inner {
1490 clean::StaticItem(ref s) | clean::ForeignStaticItem(ref s) => {
1491 struct Initializer<'a>(&'a str, Item<'a>);
1492 impl<'a> fmt::Show for Initializer<'a> {
1493 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1494 let Initializer(s, item) = *self;
1495 if s.len() == 0 { return Ok(()); }
1496 try!(write!(f, "<code> = </code>"));
1497 if s.contains("\n") {
1500 write!(f, "<a href='{}'>[definition]</a>",
1506 write!(f, "<code>{}</code>", s.as_slice())
1513 <td>{}<code>{}static {}{}: {}</code>{}</td>
1514 <td class='docblock'>{} </td>
1517 ConciseStability(&myitem.stability),
1518 VisSpace(myitem.visibility),
1519 MutableSpace(s.mutability),
1520 *myitem.name.get_ref(),
1522 Initializer(s.expr.as_slice(), Item { cx: cx, item: myitem }),
1523 Markdown(blank(myitem.doc_value()))));
1526 clean::ViewItemItem(ref item) => {
1528 clean::ExternCrate(ref name, ref src, _) => {
1529 try!(write!(w, "<tr><td><code>extern crate {}",
1532 Some(ref src) => try!(write!(w, " = \"{}\"",
1536 try!(write!(w, ";</code></td></tr>"));
1539 clean::Import(ref import) => {
1540 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1541 VisSpace(myitem.visibility),
1549 if myitem.name.is_none() { continue }
1552 <td>{stab}<a class='{class}' href='{href}'
1553 title='{title}'>{}</a></td>
1554 <td class='docblock short'>{}</td>
1557 *myitem.name.get_ref(),
1558 Markdown(shorter(myitem.doc_value())),
1559 class = shortty(myitem),
1560 href = item_path(myitem),
1561 title = full_path(cx, myitem),
1562 stab = ConciseStability(&myitem.stability)));
1567 write!(w, "</table>")
1570 fn item_function(w: &mut fmt::Formatter, it: &clean::Item,
1571 f: &clean::Function) -> fmt::Result {
1572 try!(write!(w, "<pre class='rust fn'>{vis}{fn_style}fn \
1573 {name}{generics}{decl}</pre>",
1574 vis = VisSpace(it.visibility),
1575 fn_style = FnStyleSpace(f.fn_style),
1576 name = it.name.get_ref().as_slice(),
1577 generics = f.generics,
1582 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1583 t: &clean::Trait) -> fmt::Result {
1584 let mut parents = String::new();
1585 if t.parents.len() > 0 {
1586 parents.push_str(": ");
1587 for (i, p) in t.parents.iter().enumerate() {
1588 if i > 0 { parents.push_str(" + "); }
1589 parents.push_str(format!("{}", *p).as_slice());
1593 // Output the trait definition
1594 try!(write!(w, "<pre class='rust trait'>{}trait {}{}{} ",
1595 VisSpace(it.visibility),
1596 it.name.get_ref().as_slice(),
1599 let required = t.methods.iter().filter(|m| m.is_req()).collect::<Vec<&clean::TraitMethod>>();
1600 let provided = t.methods.iter().filter(|m| !m.is_req()).collect::<Vec<&clean::TraitMethod>>();
1602 if t.methods.len() == 0 {
1603 try!(write!(w, "{{ }}"));
1605 try!(write!(w, "{{\n"));
1606 for m in required.iter() {
1607 try!(write!(w, " "));
1608 try!(render_method(w, m.item()));
1609 try!(write!(w, ";\n"));
1611 if required.len() > 0 && provided.len() > 0 {
1612 try!(w.write("\n".as_bytes()));
1614 for m in provided.iter() {
1615 try!(write!(w, " "));
1616 try!(render_method(w, m.item()));
1617 try!(write!(w, " {{ ... }}\n"));
1619 try!(write!(w, "}}"));
1621 try!(write!(w, "</pre>"));
1623 // Trait documentation
1624 try!(document(w, it));
1626 fn meth(w: &mut fmt::Formatter, m: &clean::TraitMethod) -> fmt::Result {
1627 try!(write!(w, "<h3 id='{}.{}' class='method'>{}<code>",
1629 *m.item().name.get_ref(),
1630 ConciseStability(&m.item().stability)));
1631 try!(render_method(w, m.item()));
1632 try!(write!(w, "</code></h3>"));
1633 try!(document(w, m.item()));
1637 // Output the documentation for each function individually
1638 if required.len() > 0 {
1640 <h2 id='required-methods'>Required Methods</h2>
1641 <div class='methods'>
1643 for m in required.iter() {
1646 try!(write!(w, "</div>"));
1648 if provided.len() > 0 {
1650 <h2 id='provided-methods'>Provided Methods</h2>
1651 <div class='methods'>
1653 for m in provided.iter() {
1656 try!(write!(w, "</div>"));
1659 let cache = cache_key.get().unwrap();
1661 <h2 id='implementors'>Implementors</h2>
1662 <ul class='item-list' id='implementors-list'>
1664 match cache.implementors.find(&it.def_id) {
1665 Some(implementors) => {
1666 for i in implementors.iter() {
1667 try!(writeln!(w, "<li>{}<code>impl{} {} for {}</code></li>",
1668 ConciseStability(&i.stability),
1669 i.generics, i.trait_, i.for_));
1674 try!(write!(w, "</ul>"));
1675 try!(write!(w, r#"<script type="text/javascript" async
1676 src="{root_path}/implementors/{path}/{ty}.{name}.js">
1678 root_path = Vec::from_elem(cx.current.len(), "..").connect("/"),
1679 path = if ast_util::is_local(it.def_id) {
1680 cx.current.connect("/")
1682 let path = cache.external_paths.get(&it.def_id);
1683 path.slice_to(path.len() - 1).connect("/")
1685 ty = shortty(it).to_static_str(),
1686 name = *it.name.get_ref()));
1690 fn render_method(w: &mut fmt::Formatter, meth: &clean::Item) -> fmt::Result {
1691 fn fun(w: &mut fmt::Formatter, it: &clean::Item, fn_style: ast::FnStyle,
1692 g: &clean::Generics, selfty: &clean::SelfTy,
1693 d: &clean::FnDecl) -> fmt::Result {
1694 write!(w, "{}fn <a href='#{ty}.{name}' class='fnname'>{name}</a>\
1697 ast::UnsafeFn => "unsafe ",
1701 name = it.name.get_ref().as_slice(),
1703 decl = Method(selfty, d))
1706 clean::TyMethodItem(ref m) => {
1707 fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
1709 clean::MethodItem(ref m) => {
1710 fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
1716 fn item_struct(w: &mut fmt::Formatter, it: &clean::Item,
1717 s: &clean::Struct) -> fmt::Result {
1718 try!(write!(w, "<pre class='rust struct'>"));
1719 try!(render_struct(w,
1723 s.fields.as_slice(),
1726 try!(write!(w, "</pre>"));
1728 try!(document(w, it));
1729 let mut fields = s.fields.iter().filter(|f| {
1731 clean::StructFieldItem(clean::HiddenStructField) => false,
1732 clean::StructFieldItem(clean::TypedStructField(..)) => true,
1736 match s.struct_type {
1738 if fields.peek().is_some() {
1739 try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
1740 for field in fields {
1741 try!(write!(w, "<tr><td id='structfield.{name}'>\
1742 {stab}<code>{name}</code></td><td>",
1743 stab = ConciseStability(&field.stability),
1744 name = field.name.get_ref().as_slice()));
1745 try!(document(w, field));
1746 try!(write!(w, "</td></tr>"));
1748 try!(write!(w, "</table>"));
1753 render_methods(w, it)
1756 fn item_enum(w: &mut fmt::Formatter, it: &clean::Item,
1757 e: &clean::Enum) -> fmt::Result {
1758 try!(write!(w, "<pre class='rust enum'>{}enum {}{}",
1759 VisSpace(it.visibility),
1760 it.name.get_ref().as_slice(),
1762 if e.variants.len() == 0 && !e.variants_stripped {
1763 try!(write!(w, " {{}}"));
1765 try!(write!(w, " {{\n"));
1766 for v in e.variants.iter() {
1767 try!(write!(w, " "));
1768 let name = v.name.get_ref().as_slice();
1770 clean::VariantItem(ref var) => {
1772 clean::CLikeVariant => try!(write!(w, "{}", name)),
1773 clean::TupleVariant(ref tys) => {
1774 try!(write!(w, "{}(", name));
1775 for (i, ty) in tys.iter().enumerate() {
1777 try!(write!(w, ", "))
1779 try!(write!(w, "{}", *ty));
1781 try!(write!(w, ")"));
1783 clean::StructVariant(ref s) => {
1784 try!(render_struct(w,
1788 s.fields.as_slice(),
1796 try!(write!(w, ",\n"));
1799 if e.variants_stripped {
1800 try!(write!(w, " // some variants omitted\n"));
1802 try!(write!(w, "}}"));
1804 try!(write!(w, "</pre>"));
1806 try!(document(w, it));
1807 if e.variants.len() > 0 {
1808 try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
1809 for variant in e.variants.iter() {
1810 try!(write!(w, "<tr><td id='variant.{name}'>{stab}<code>{name}</code></td><td>",
1811 stab = ConciseStability(&variant.stability),
1812 name = variant.name.get_ref().as_slice()));
1813 try!(document(w, variant));
1814 match variant.inner {
1815 clean::VariantItem(ref var) => {
1817 clean::StructVariant(ref s) => {
1818 let mut fields = s.fields.iter().filter(|f| {
1820 clean::StructFieldItem(ref t) => match *t {
1821 clean::HiddenStructField => false,
1822 clean::TypedStructField(..) => true,
1827 try!(write!(w, "<h3 class='fields'>Fields</h3>\n
1829 for field in fields {
1830 try!(write!(w, "<tr><td \
1831 id='variant.{v}.field.{f}'>\
1832 <code>{f}</code></td><td>",
1833 v = variant.name.get_ref().as_slice(),
1834 f = field.name.get_ref().as_slice()));
1835 try!(document(w, field));
1836 try!(write!(w, "</td></tr>"));
1838 try!(write!(w, "</table>"));
1845 try!(write!(w, "</td></tr>"));
1847 try!(write!(w, "</table>"));
1850 try!(render_methods(w, it));
1854 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
1855 g: Option<&clean::Generics>,
1856 ty: doctree::StructType,
1857 fields: &[clean::Item],
1859 structhead: bool) -> fmt::Result {
1860 try!(write!(w, "{}{}{}",
1861 VisSpace(it.visibility),
1862 if structhead {"struct "} else {""},
1863 it.name.get_ref().as_slice()));
1865 Some(g) => try!(write!(w, "{}", *g)),
1870 try!(write!(w, " {{\n{}", tab));
1871 let mut fields_stripped = false;
1872 for field in fields.iter() {
1874 clean::StructFieldItem(clean::HiddenStructField) => {
1875 fields_stripped = true;
1877 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
1878 try!(write!(w, " {}{}: {},\n{}",
1879 VisSpace(field.visibility),
1880 field.name.get_ref().as_slice(),
1884 _ => unreachable!(),
1888 if fields_stripped {
1889 try!(write!(w, " // some fields omitted\n{}", tab));
1891 try!(write!(w, "}}"));
1893 doctree::Tuple | doctree::Newtype => {
1894 try!(write!(w, "("));
1895 for (i, field) in fields.iter().enumerate() {
1897 try!(write!(w, ", "));
1900 clean::StructFieldItem(clean::HiddenStructField) => {
1901 try!(write!(w, "_"))
1903 clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
1904 try!(write!(w, "{}{}", VisSpace(field.visibility), *ty))
1909 try!(write!(w, ");"));
1912 try!(write!(w, ";"));
1918 fn render_methods(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
1919 match cache_key.get().unwrap().impls.find(&it.def_id) {
1921 let (non_trait, traits) = v.partitioned(|i| i.impl_.trait_.is_none());
1922 if non_trait.len() > 0 {
1923 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
1924 for i in non_trait.iter() {
1925 try!(render_impl(w, i));
1928 if traits.len() > 0 {
1929 try!(write!(w, "<h2 id='implementations'>Trait \
1930 Implementations</h2>"));
1931 let (derived, manual) = traits.partition(|i| i.impl_.derived);
1932 for i in manual.iter() {
1933 try!(render_impl(w, i));
1935 if derived.len() > 0 {
1936 try!(write!(w, "<h3 id='derived_implementations'>Derived Implementations \
1938 for i in derived.iter() {
1939 try!(render_impl(w, i));
1949 fn render_impl(w: &mut fmt::Formatter, i: &Impl) -> fmt::Result {
1950 try!(write!(w, "<h3 class='impl'>{}<code>impl{} ",
1951 ConciseStability(&i.stability),
1953 match i.impl_.trait_ {
1954 Some(ref ty) => try!(write!(w, "{} for ", *ty)),
1957 try!(write!(w, "{}</code></h3>", i.impl_.for_));
1960 try!(write!(w, "<div class='docblock'>{}</div>",
1961 Markdown(dox.as_slice())));
1966 fn docmeth(w: &mut fmt::Formatter, item: &clean::Item,
1967 dox: bool) -> fmt::Result {
1968 try!(write!(w, "<h4 id='method.{}' class='method'>{}<code>",
1969 *item.name.get_ref(),
1970 ConciseStability(&item.stability)));
1971 try!(render_method(w, item));
1972 try!(write!(w, "</code></h4>\n"));
1973 match item.doc_value() {
1975 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1978 Some(..) | None => Ok(())
1982 try!(write!(w, "<div class='impl-methods'>"));
1983 for meth in i.impl_.methods.iter() {
1984 try!(docmeth(w, meth, true));
1987 fn render_default_methods(w: &mut fmt::Formatter,
1989 i: &clean::Impl) -> fmt::Result {
1990 for method in t.methods.iter() {
1991 let n = method.item().name.clone();
1992 match i.methods.iter().find(|m| { m.name == n }) {
1993 Some(..) => continue,
1997 try!(docmeth(w, method.item(), false));
2002 // If we've implemented a trait, then also emit documentation for all
2003 // default methods which weren't overridden in the implementation block.
2004 match i.impl_.trait_ {
2005 Some(clean::ResolvedPath { did, .. }) => {
2007 match cache_key.get().unwrap().traits.find(&did) {
2008 Some(t) => try!(render_default_methods(w, t, &i.impl_)),
2014 Some(..) | None => {}
2016 try!(write!(w, "</div>"));
2020 fn item_typedef(w: &mut fmt::Formatter, it: &clean::Item,
2021 t: &clean::Typedef) -> fmt::Result {
2022 try!(write!(w, "<pre class='rust typedef'>type {}{} = {};</pre>",
2023 it.name.get_ref().as_slice(),
2030 impl<'a> fmt::Show for Sidebar<'a> {
2031 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2034 try!(write!(fmt, "<p class='location'>"));
2035 let len = cx.current.len() - if it.is_mod() {1} else {0};
2036 for (i, name) in cx.current.iter().take(len).enumerate() {
2038 try!(write!(fmt, "​::"));
2040 try!(write!(fmt, "<a href='{}index.html'>{}</a>",
2043 .slice_to((cx.current.len() - i - 1) * 3),
2046 try!(write!(fmt, "</p>"));
2048 fn block(w: &mut fmt::Formatter, short: &str, longty: &str,
2049 cur: &clean::Item, cx: &Context) -> fmt::Result {
2050 let items = match cx.sidebar.find_equiv(&short) {
2051 Some(items) => items.as_slice(),
2052 None => return Ok(())
2054 try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
2055 for item in items.iter() {
2056 let curty = shortty(cur).to_static_str();
2057 let class = if cur.name.get_ref() == item &&
2058 short == curty { "current" } else { "" };
2059 try!(write!(w, "<a class='{ty} {class}' href='{href}{path}'>\
2063 href = if curty == "mod" {"../"} else {""},
2064 path = if short == "mod" {
2065 format!("{}/index.html", item.as_slice())
2067 format!("{}.{}.html", short, item.as_slice())
2069 name = item.as_slice()));
2071 try!(write!(w, "</div>"));
2075 try!(block(fmt, "mod", "Modules", it, cx));
2076 try!(block(fmt, "struct", "Structs", it, cx));
2077 try!(block(fmt, "enum", "Enums", it, cx));
2078 try!(block(fmt, "trait", "Traits", it, cx));
2079 try!(block(fmt, "fn", "Functions", it, cx));
2080 try!(block(fmt, "macro", "Macros", it, cx));
2085 fn build_sidebar(m: &clean::Module) -> HashMap<String, Vec<String>> {
2086 let mut map = HashMap::new();
2087 for item in m.items.iter() {
2088 if ignore_private_item(item) { continue }
2090 let short = shortty(item).to_static_str();
2091 let myname = match item.name {
2093 Some(ref s) => s.to_string(),
2095 let v = map.find_or_insert_with(short.to_string(), |_| Vec::new());
2099 for (_, items) in map.mut_iter() {
2100 items.as_mut_slice().sort();
2105 impl<'a> fmt::Show for Source<'a> {
2106 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2107 let Source(s) = *self;
2108 let lines = s.lines().count();
2110 let mut tmp = lines;
2115 try!(write!(fmt, "<pre class='line-numbers'>"));
2116 for i in range(1, lines + 1) {
2117 try!(write!(fmt, "<span id='{0:u}'>{0:1$u}</span>\n", i, cols));
2119 try!(write!(fmt, "</pre>"));
2120 try!(write!(fmt, "{}", highlight::highlight(s.as_slice(), None, None)));
2125 fn item_macro(w: &mut fmt::Formatter, it: &clean::Item,
2126 t: &clean::Macro) -> fmt::Result {
2127 try!(w.write(highlight::highlight(t.source.as_slice(), Some("macro"),
2132 fn item_primitive(w: &mut fmt::Formatter,
2134 _p: &clean::Primitive) -> fmt::Result {
2135 try!(document(w, it));
2136 render_methods(w, it)
2139 fn ignore_private_item(it: &clean::Item) -> bool {
2141 clean::ModuleItem(ref m) => {
2142 (m.items.len() == 0 && it.doc_value().is_none()) ||
2143 it.visibility != Some(ast::Public)
2145 clean::PrimitiveItem(..) => it.visibility != Some(ast::Public),