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};
43 use std::strbuf::StrBuf;
46 use serialize::json::ToJson;
49 use syntax::parse::token::InternedString;
50 use rustc::util::nodemap::NodeSet;
55 use html::format::{VisSpace, Method, FnStyleSpace};
58 use html::markdown::Markdown;
61 /// Major driving force in all rustdoc rendering. This contains information
62 /// about where in the tree-like hierarchy rendering is occurring and controls
63 /// how the current page is being rendered.
65 /// It is intended that this context is a lightweight object which can be fairly
66 /// easily cloned because it is cloned per work-job (about once per item in the
70 /// Current hierarchy of components leading down to what's currently being
72 pub current: Vec<~str> ,
73 /// String representation of how to get back to the root path of the 'doc/'
74 /// folder in terms of a relative URL.
75 pub root_path: StrBuf,
76 /// The current destination folder of where HTML artifacts should be placed.
77 /// This changes as the context descends into the module hierarchy.
79 /// This describes the layout of each page, and is not modified after
80 /// creation of the context (contains info like the favicon)
81 pub layout: layout::Layout,
82 /// This map is a list of what should be displayed on the sidebar of the
83 /// current page. The key is the section header (traits, modules,
84 /// functions), and the value is the list of containers belonging to this
85 /// header. This map will change depending on the surrounding context of the
87 pub sidebar: HashMap<~str, Vec<~str> >,
88 /// This flag indicates whether [src] links should be generated or not. If
89 /// the source files are present in the html rendering, then this will be
91 pub include_sources: bool,
94 /// Indicates where an external crate can be found.
95 pub enum ExternalLocation {
96 /// Remote URL root of the external crate
98 /// This external crate can be found in the local doc/ folder
100 /// The external crate could not be found.
104 /// Different ways an implementor of a trait can be rendered.
105 pub enum Implementor {
106 /// Paths are displayed specially by omitting the `impl XX for` cruft
107 PathType(clean::Type),
108 /// This is the generic representation of a trait implementor, used for
109 /// primitive types and otherwise non-path types.
110 OtherType(clean::Generics, /* trait */ clean::Type, /* for */ clean::Type),
113 /// This cache is used to store information about the `clean::Crate` being
114 /// rendered in order to provide more useful documentation. This contains
115 /// information like all implementors of a trait, all traits a type implements,
116 /// documentation for all known traits, etc.
118 /// This structure purposefully does not implement `Clone` because it's intended
119 /// to be a fairly large and expensive structure to clone. Instead this adheres
120 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
123 /// Mapping of typaram ids to the name of the type parameter. This is used
124 /// when pretty-printing a type (so pretty printing doesn't have to
125 /// painfully maintain a context like this)
126 pub typarams: HashMap<ast::NodeId, ~str>,
128 /// Maps a type id to all known implementations for that type. This is only
129 /// recognized for intra-crate `ResolvedPath` types, and is used to print
130 /// out extra documentation on the page of an enum/struct.
132 /// The values of the map are a list of implementations and documentation
133 /// found on that implementation.
134 pub impls: HashMap<ast::NodeId, Vec<(clean::Impl, Option<~str>)> >,
136 /// Maintains a mapping of local crate node ids to the fully qualified name
137 /// and "short type description" of that node. This is used when generating
138 /// URLs when a type is being linked to. External paths are not located in
139 /// this map because the `External` type itself has all the information
141 pub paths: HashMap<ast::NodeId, (Vec<~str> , &'static str)>,
143 /// This map contains information about all known traits of this crate.
144 /// Implementations of a crate should inherit the documentation of the
145 /// parent trait if no extra documentation is specified, and default methods
146 /// should show up in documentation about trait implementations.
147 pub traits: HashMap<ast::NodeId, clean::Trait>,
149 /// When rendering traits, it's often useful to be able to list all
150 /// implementors of the trait, and this mapping is exactly, that: a mapping
151 /// of trait ids to the list of known implementors of the trait
152 pub implementors: HashMap<ast::NodeId, Vec<Implementor> >,
154 /// Cache of where external crate documentation can be found.
155 pub extern_locations: HashMap<ast::CrateNum, ExternalLocation>,
157 // Private fields only used when initially crawling a crate to build a cache
160 parent_stack: Vec<ast::NodeId> ,
161 search_index: Vec<IndexItem> ,
163 public_items: NodeSet,
165 // In rare case where a structure is defined in one module but implemented
166 // in another, if the implementing module is parsed before defining module,
167 // then the fully qualified name of the structure isn't presented in `paths`
168 // yet when its implementation methods are being indexed. Caches such methods
169 // and their parent id here and indexes them at the end of crate parsing.
170 orphan_methods: Vec<(ast::NodeId, clean::Item)>,
173 /// Helper struct to render all source code to HTML pages
174 struct SourceCollector<'a> {
177 /// Processed source-file paths
179 /// Root destination to place all HTML output into
183 /// Wrapper struct to render the source code of a file. This will do things like
184 /// adding line numbers to the left-hand side.
185 struct Source<'a>(&'a str);
187 // Helper structs for rendering items/sidebars and carrying along contextual
190 struct Item<'a> { cx: &'a Context, item: &'a clean::Item, }
191 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
193 /// Struct representing one entry in the JS search index. These are all emitted
194 /// by hand to a large JS file at the end of cache-creation.
200 parent: Option<ast::NodeId>,
203 // TLS keys used to carry information around during rendering.
205 local_data_key!(pub cache_key: Arc<Cache>)
206 local_data_key!(pub current_location_key: Vec<~str> )
208 /// Generates the documentation for `crate` into the directory `dst`
209 pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> {
210 let mut cx = Context {
213 root_path: StrBuf::new(),
214 sidebar: HashMap::new(),
215 layout: layout::Layout {
218 krate: krate.name.clone(),
220 include_sources: true,
222 try!(mkdir(&cx.dst));
224 match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(&[])) {
226 for attr in attrs.iter() {
228 clean::NameValue(ref x, ref s) if "html_favicon_url" == *x => {
229 cx.layout.favicon = s.to_owned();
231 clean::NameValue(ref x, ref s) if "html_logo_url" == *x => {
232 cx.layout.logo = s.to_owned();
234 clean::Word(ref x) if "html_no_source" == *x => {
235 cx.include_sources = false;
244 // Crawl the crate to build various caches used for the output
245 let mut cache = local_data::get(::analysiskey, |analysis| {
246 let public_items = analysis.map(|a| a.public_items.clone());
247 let public_items = public_items.unwrap_or(NodeSet::new());
249 impls: HashMap::new(),
250 typarams: HashMap::new(),
251 paths: HashMap::new(),
252 traits: HashMap::new(),
253 implementors: HashMap::new(),
255 parent_stack: Vec::new(),
256 search_index: Vec::new(),
257 extern_locations: HashMap::new(),
259 public_items: public_items,
260 orphan_methods: Vec::new(),
263 cache.stack.push(krate.name.clone());
264 krate = cache.fold_crate(krate);
266 let Cache { search_index: ref mut index,
267 orphan_methods: ref meths, paths: ref mut paths, ..} = cache;
269 // Attach all orphan methods to the type's definition if the type
270 // has since been learned.
271 for &(ref pid, ref item) in meths.iter() {
272 match paths.find(pid) {
273 Some(&(ref fqp, _)) => {
274 index.push(IndexItem {
276 name: item.name.clone().unwrap(),
277 path: fqp.slice_to(fqp.len() - 1).connect("::"),
278 desc: shorter(item.doc_value()).to_owned(),
286 // Prune the paths that do not appear in the index.
287 let mut unseen: HashSet<ast::NodeId> = paths.keys().map(|&id| id).collect();
288 for item in index.iter() {
290 Some(ref pid) => { unseen.remove(pid); }
294 for pid in unseen.iter() {
299 // Publish the search index
301 let mut w = MemWriter::new();
302 try!(write!(&mut w, "searchIndex['{}'] = [", krate.name));
303 for (i, item) in cache.search_index.iter().enumerate() {
305 try!(write!(&mut w, ","));
307 try!(write!(&mut w, "\\{ty:\"{}\",name:\"{}\",path:\"{}\",desc:{}",
308 item.ty, item.name, item.path,
309 item.desc.to_json().to_str()));
312 try!(write!(&mut w, ",parent:'{}'", id));
316 try!(write!(&mut w, "\\}"));
318 try!(write!(&mut w, "];"));
319 try!(write!(&mut w, "allPaths['{}'] = \\{", krate.name));
320 for (i, (&id, &(ref fqp, short))) in cache.paths.iter().enumerate() {
322 try!(write!(&mut w, ","));
324 try!(write!(&mut w, "'{}':\\{type:'{}',name:'{}'\\}",
325 id, short, *fqp.last().unwrap()));
327 try!(write!(&mut w, "\\};"));
329 str::from_utf8(w.unwrap().as_slice()).unwrap().to_owned()
332 // Write out the shared files. Note that these are shared among all rustdoc
333 // docs placed in the output directory, so this needs to be a synchronized
334 // operation with respect to all other rustdocs running around.
336 try!(mkdir(&cx.dst));
337 let _lock = ::flock::Lock::new(&cx.dst.join(".lock"));
339 // Add all the static files. These may already exist, but we just
340 // overwrite them anyway to make sure that they're fresh and up-to-date.
341 try!(write(cx.dst.join("jquery.js"),
342 include_str!("static/jquery-2.1.0.min.js")));
343 try!(write(cx.dst.join("main.js"), include_str!("static/main.js")));
344 try!(write(cx.dst.join("main.css"), include_str!("static/main.css")));
345 try!(write(cx.dst.join("normalize.css"),
346 include_str!("static/normalize.css")));
348 // Update the search index
349 let dst = cx.dst.join("search-index.js");
350 let mut all_indexes = Vec::new();
351 all_indexes.push(index);
353 for line in BufferedReader::new(File::open(&dst)).lines() {
354 let line = try!(line);
355 if !line.starts_with("searchIndex") { continue }
356 if line.starts_with(format!("searchIndex['{}']", krate.name)) {
359 all_indexes.push(line);
362 let mut w = try!(File::create(&dst));
363 try!(writeln!(&mut w, r"var searchIndex = \{\}; var allPaths = \{\};"));
364 for index in all_indexes.iter() {
365 try!(writeln!(&mut w, "{}", *index));
367 try!(writeln!(&mut w, "initSearch(searchIndex);"));
370 // Render all source files (this may turn into a giant no-op)
372 info!("emitting source files");
373 let dst = cx.dst.join("src");
375 let dst = dst.join(krate.name.as_slice());
377 let mut folder = SourceCollector {
379 seen: HashSet::new(),
382 krate = folder.fold_crate(krate);
385 for &(n, ref e) in krate.externs.iter() {
386 cache.extern_locations.insert(n, extern_location(e, &cx.dst));
389 // And finally render the whole crate's documentation
390 cx.krate(krate, cache)
393 /// Writes the entire contents of a string to a destination, not attempting to
394 /// catch any errors.
395 fn write(dst: Path, contents: &str) -> io::IoResult<()> {
396 File::create(&dst).write(contents.as_bytes())
399 /// Makes a directory on the filesystem, failing the task if an error occurs and
400 /// skipping if the directory already exists.
401 fn mkdir(path: &Path) -> io::IoResult<()> {
403 fs::mkdir(path, io::UserRWX)
409 /// Takes a path to a source file and cleans the path to it. This canonicalizes
410 /// things like ".." to components which preserve the "top down" hierarchy of a
411 /// static HTML tree.
412 // FIXME (#9639): The closure should deal with &[u8] instead of &str
413 fn clean_srcpath(src: &[u8], f: |&str|) {
414 let p = Path::new(src);
415 if p.as_vec() != bytes!(".") {
416 for c in p.str_components().map(|x|x.unwrap()) {
426 /// Attempts to find where an external crate is located, given that we're
427 /// rendering in to the specified source destination.
428 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
429 // See if there's documentation generated into the local directory
430 let local_location = dst.join(e.name.as_slice());
431 if local_location.is_dir() {
435 // Failing that, see if there's an attribute specifying where to find this
437 for attr in e.attrs.iter() {
439 clean::List(ref x, ref list) if "doc" == *x => {
440 for attr in list.iter() {
442 clean::NameValue(ref x, ref s) if "html_root_url" == *x => {
443 if s.ends_with("/") {
444 return Remote(s.to_owned());
446 return Remote(*s + "/");
456 // Well, at least we tried.
460 impl<'a> DocFolder for SourceCollector<'a> {
461 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
462 // If we're including source files, and we haven't seen this file yet,
463 // then we need to render it out to the filesystem
464 if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
466 // If it turns out that we couldn't read this file, then we probably
467 // can't read any of the files (generating html output from json or
468 // something like that), so just don't include sources for the
469 // entire crate. The other option is maintaining this mapping on a
470 // per-file basis, but that's probably not worth it...
471 self.cx.include_sources = match self.emit_source(item.source.filename) {
474 println!("warning: source code was requested to be rendered, \
475 but processing `{}` had an error: {}",
476 item.source.filename, e);
477 println!(" skipping rendering of source code");
481 self.seen.insert(item.source.filename.clone());
484 self.fold_item_recur(item)
488 impl<'a> SourceCollector<'a> {
489 /// Renders the given filename into its corresponding HTML source file.
490 fn emit_source(&mut self, filename: &str) -> io::IoResult<()> {
491 let p = Path::new(filename);
493 // If we couldn't open this file, then just returns because it
494 // probably means that it's some standard library macro thing and we
495 // can't have the source to it anyway.
496 let contents = match File::open(&p).read_to_end() {
498 // macros from other libraries get special filenames which we can
500 Err(..) if filename.starts_with("<") &&
501 filename.ends_with("macros>") => return Ok(()),
502 Err(e) => return Err(e)
504 let contents = str::from_utf8(contents.as_slice()).unwrap();
506 // Remove the utf-8 BOM if any
507 let contents = if contents.starts_with("\ufeff") {
508 contents.as_slice().slice_from(3)
513 // Create the intermediate directories
514 let mut cur = self.dst.clone();
515 let mut root_path = StrBuf::from_str("../../");
516 clean_srcpath(p.dirname(), |component| {
518 mkdir(&cur).unwrap();
519 root_path.push_str("../");
522 cur.push(p.filename().expect("source has no filename") + bytes!(".html"));
523 let mut w = BufferedWriter::new(try!(File::create(&cur)));
525 let title = format!("{} -- source", cur.filename_display());
526 let page = layout::Page {
529 root_path: root_path.as_slice(),
531 try!(layout::render(&mut w as &mut Writer, &self.cx.layout,
532 &page, &(""), &Source(contents)));
538 impl DocFolder for Cache {
539 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
540 // If this is a private module, we don't want it in the search index.
541 let orig_privmod = match item.inner {
542 clean::ModuleItem(..) => {
543 let prev = self.privmod;
544 self.privmod = prev || item.visibility != Some(ast::Public);
550 // Register any generics to their corresponding string. This is used
551 // when pretty-printing types
553 clean::StructItem(ref s) => self.generics(&s.generics),
554 clean::EnumItem(ref e) => self.generics(&e.generics),
555 clean::FunctionItem(ref f) => self.generics(&f.generics),
556 clean::TypedefItem(ref t) => self.generics(&t.generics),
557 clean::TraitItem(ref t) => self.generics(&t.generics),
558 clean::ImplItem(ref i) => self.generics(&i.generics),
559 clean::TyMethodItem(ref i) => self.generics(&i.generics),
560 clean::MethodItem(ref i) => self.generics(&i.generics),
561 clean::ForeignFunctionItem(ref f) => self.generics(&f.generics),
565 // Propagate a trait methods' documentation to all implementors of the
568 clean::TraitItem(ref t) => {
569 self.traits.insert(item.id, t.clone());
574 // Collect all the implementors of traits.
576 clean::ImplItem(ref i) => {
578 Some(clean::ResolvedPath{ id, .. }) => {
579 let v = self.implementors.find_or_insert_with(id, |_|{
583 clean::ResolvedPath{..} => {
584 v.unshift(PathType(i.for_.clone()));
587 v.push(OtherType(i.generics.clone(),
588 i.trait_.get_ref().clone(),
593 Some(..) | None => {}
599 // Index this method for searching later on
602 let parent = match item.inner {
603 clean::TyMethodItem(..) |
604 clean::StructFieldItem(..) |
605 clean::VariantItem(..) => {
606 (Some(*self.parent_stack.last().unwrap()),
607 Some(self.stack.slice_to(self.stack.len() - 1)))
610 clean::MethodItem(..) => {
611 if self.parent_stack.len() == 0 {
614 let last = self.parent_stack.last().unwrap();
615 let path = match self.paths.find(last) {
616 Some(&(_, "trait")) =>
617 Some(self.stack.slice_to(self.stack.len() - 1)),
618 // The current stack not necessarily has correlation for
619 // where the type was defined. On the other hand,
620 // `paths` always has the right information if present.
621 Some(&(ref fqp, "struct")) | Some(&(ref fqp, "enum")) =>
622 Some(fqp.slice_to(fqp.len() - 1)),
623 Some(..) => Some(self.stack.as_slice()),
629 _ => (None, Some(self.stack.as_slice()))
632 (parent, Some(path)) if !self.privmod => {
633 self.search_index.push(IndexItem {
636 path: path.connect("::"),
637 desc: shorter(item.doc_value()).to_owned(),
641 (Some(parent), None) if !self.privmod => {
642 // We have a parent, but we don't know where they're
643 // defined yet. Wait for later to index this item.
644 self.orphan_methods.push((parent, item.clone()))
652 // Keep track of the fully qualified path for this item.
653 let pushed = if item.name.is_some() {
654 let n = item.name.get_ref();
656 self.stack.push(n.to_owned());
661 clean::StructItem(..) | clean::EnumItem(..) |
662 clean::TypedefItem(..) | clean::TraitItem(..) |
663 clean::FunctionItem(..) | clean::ModuleItem(..) |
664 clean::ForeignFunctionItem(..) => {
665 // Reexported items mean that the same id can show up twice in
666 // the rustdoc ast that we're looking at. We know, however, that
667 // a reexported item doesn't show up in the `public_items` map,
668 // so we can skip inserting into the paths map if there was
669 // already an entry present and we're not a public item.
670 if !self.paths.contains_key(&item.id) ||
671 self.public_items.contains(&item.id) {
672 self.paths.insert(item.id,
673 (self.stack.clone(), shortty(&item)));
676 // link variants to their parent enum because pages aren't emitted
678 clean::VariantItem(..) => {
679 let mut stack = self.stack.clone();
681 self.paths.insert(item.id, (stack, "enum"));
686 // Maintain the parent stack
687 let parent_pushed = match item.inner {
688 clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
689 self.parent_stack.push(item.id); true
691 clean::ImplItem(ref i) => {
693 clean::ResolvedPath{ id, .. } => {
694 self.parent_stack.push(id); true
702 // Once we've recursively found all the generics, then hoard off all the
703 // implementations elsewhere
704 let ret = match self.fold_item_recur(item) {
707 clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
709 clean::ResolvedPath { id, .. } => {
710 let v = self.impls.find_or_insert_with(id, |_| {
713 // extract relevant documentation for this impl
714 match attrs.move_iter().find(|a| {
716 clean::NameValue(ref x, _) if "doc" == *x => true,
720 Some(clean::NameValue(_, dox)) => {
721 v.push((i, Some(dox)));
732 // Private modules may survive the strip-private pass if
733 // they contain impls for public types, but those will get
735 clean::Item { inner: clean::ModuleItem(ref m),
737 if (m.items.len() == 0 &&
738 item.doc_value().is_none()) ||
739 visibility != Some(ast::Public) => None,
747 if pushed { self.stack.pop().unwrap(); }
748 if parent_pushed { self.parent_stack.pop().unwrap(); }
749 self.privmod = orig_privmod;
755 fn generics(&mut self, generics: &clean::Generics) {
756 for typ in generics.type_params.iter() {
757 self.typarams.insert(typ.id, typ.name.clone());
763 /// Recurse in the directory structure and change the "root path" to make
764 /// sure it always points to the top (relatively)
765 fn recurse<T>(&mut self, s: ~str, f: |&mut Context| -> T) -> T {
767 fail!("what {:?}", self);
769 let prev = self.dst.clone();
770 self.dst.push(s.as_slice());
771 self.root_path.push_str("../");
772 self.current.push(s);
774 info!("Recursing into {}", self.dst.display());
776 mkdir(&self.dst).unwrap();
779 info!("Recursed; leaving {}", self.dst.display());
781 // Go back to where we were at
783 let len = self.root_path.len();
784 self.root_path.truncate(len - 3);
785 self.current.pop().unwrap();
790 /// Main method for rendering a crate.
792 /// This currently isn't parallelized, but it'd be pretty easy to add
793 /// parallelization to this function.
794 fn krate(self, mut krate: clean::Crate, cache: Cache) -> io::IoResult<()> {
795 let mut item = match krate.module.take() {
797 None => return Ok(())
799 item.name = Some(krate.name);
801 // using a rwarc makes this parallelizable in the future
802 local_data::set(cache_key, Arc::new(cache));
804 let mut work = vec!((self, item));
807 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
808 work.push((cx.clone(), item));
816 /// Non-parellelized version of rendering an item. This will take the input
817 /// item, render its contents, and then invoke the specified closure with
818 /// all sub-items which need to be rendered.
820 /// The rendering driver uses this closure to queue up more work.
821 fn item(&mut self, item: clean::Item,
822 f: |&mut Context, clean::Item|) -> io::IoResult<()> {
823 fn render(w: io::File, cx: &mut Context, it: &clean::Item,
824 pushname: bool) -> io::IoResult<()> {
825 info!("Rendering an item to {}", w.path().display());
826 // A little unfortunate that this is done like this, but it sure
827 // does make formatting *a lot* nicer.
828 local_data::set(current_location_key, cx.current.clone());
830 let mut title = StrBuf::from_str(cx.current.connect("::"));
833 title.push_str("::");
835 title.push_str(*it.name.get_ref());
837 title.push_str(" - Rust");
838 let page = layout::Page {
840 root_path: cx.root_path.as_slice(),
841 title: title.as_slice(),
844 markdown::reset_headers();
846 // We have a huge number of calls to write, so try to alleviate some
847 // of the pain by using a buffered writer instead of invoking the
848 // write sycall all the time.
849 let mut writer = BufferedWriter::new(w);
850 try!(layout::render(&mut writer as &mut Writer, &cx.layout, &page,
851 &Sidebar{ cx: cx, item: it },
852 &Item{ cx: cx, item: it }));
857 // modules are special because they add a namespace. We also need to
858 // recurse into the items of the module as well.
859 clean::ModuleItem(..) => {
860 let name = item.name.get_ref().to_owned();
861 let mut item = Some(item);
862 self.recurse(name, |this| {
863 let item = item.take_unwrap();
864 let dst = this.dst.join("index.html");
865 let dst = try!(File::create(&dst));
866 try!(render(dst, this, &item, false));
868 let m = match item.inner {
869 clean::ModuleItem(m) => m,
872 this.sidebar = build_sidebar(&m);
873 for item in m.items.move_iter() {
880 // Things which don't have names (like impls) don't get special
881 // pages dedicated to them.
882 _ if item.name.is_some() => {
883 let dst = self.dst.join(item_path(&item));
884 let dst = try!(File::create(&dst));
885 render(dst, self, &item, true)
893 fn shortty(item: &clean::Item) -> &'static str {
895 clean::ModuleItem(..) => "mod",
896 clean::StructItem(..) => "struct",
897 clean::EnumItem(..) => "enum",
898 clean::FunctionItem(..) => "fn",
899 clean::TypedefItem(..) => "typedef",
900 clean::StaticItem(..) => "static",
901 clean::TraitItem(..) => "trait",
902 clean::ImplItem(..) => "impl",
903 clean::ViewItemItem(..) => "viewitem",
904 clean::TyMethodItem(..) => "tymethod",
905 clean::MethodItem(..) => "method",
906 clean::StructFieldItem(..) => "structfield",
907 clean::VariantItem(..) => "variant",
908 clean::ForeignFunctionItem(..) => "ffi",
909 clean::ForeignStaticItem(..) => "ffs",
910 clean::MacroItem(..) => "macro",
915 fn ismodule(&self) -> bool {
916 match self.item.inner {
917 clean::ModuleItem(..) => true, _ => false
922 impl<'a> fmt::Show for Item<'a> {
923 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
924 match attr::find_stability(self.item.attrs.iter()) {
925 Some(ref stability) => {
927 "<a class='stability {lvl}' title='{reason}'>{lvl}</a>",
928 lvl = stability.level.to_str(),
929 reason = match stability.text {
930 Some(ref s) => (*s).clone(),
931 None => InternedString::new(""),
937 if self.cx.include_sources {
938 let mut path = Vec::new();
939 clean_srcpath(self.item.source.filename.as_bytes(), |component| {
940 path.push(component.to_owned());
942 let href = if self.item.source.loline == self.item.source.hiline {
943 format!("{}", self.item.source.loline)
945 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
949 href='{root}src/{krate}/{path}.html\\#{href}'>\
951 root = self.cx.root_path,
952 krate = self.cx.layout.krate,
953 path = path.connect("/"),
957 // Write the breadcrumb trail header for the top
958 try!(write!(fmt.buf, "<h1 class='fqn'>"));
959 match self.item.inner {
960 clean::ModuleItem(ref m) => if m.is_crate {
961 try!(write!(fmt.buf, "Crate "));
963 try!(write!(fmt.buf, "Module "));
965 clean::FunctionItem(..) => try!(write!(fmt.buf, "Function ")),
966 clean::TraitItem(..) => try!(write!(fmt.buf, "Trait ")),
967 clean::StructItem(..) => try!(write!(fmt.buf, "Struct ")),
968 clean::EnumItem(..) => try!(write!(fmt.buf, "Enum ")),
971 let cur = self.cx.current.as_slice();
972 let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
973 for (i, component) in cur.iter().enumerate().take(amt) {
974 let mut trail = StrBuf::new();
975 for _ in range(0, cur.len() - i - 1) {
976 trail.push_str("../");
978 try!(write!(fmt.buf, "<a href='{}index.html'>{}</a>::",
979 trail, component.as_slice()));
981 try!(write!(fmt.buf, "<a class='{}' href=''>{}</a></h1>",
982 shortty(self.item), self.item.name.get_ref().as_slice()));
984 match self.item.inner {
985 clean::ModuleItem(ref m) => {
986 item_module(fmt.buf, self.cx, self.item, m.items.as_slice())
988 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
989 item_function(fmt.buf, self.item, f),
990 clean::TraitItem(ref t) => item_trait(fmt.buf, self.item, t),
991 clean::StructItem(ref s) => item_struct(fmt.buf, self.item, s),
992 clean::EnumItem(ref e) => item_enum(fmt.buf, self.item, e),
993 clean::TypedefItem(ref t) => item_typedef(fmt.buf, self.item, t),
994 clean::MacroItem(ref m) => item_macro(fmt.buf, self.item, m),
1000 fn item_path(item: &clean::Item) -> ~str {
1002 clean::ModuleItem(..) => *item.name.get_ref() + "/index.html",
1003 _ => shortty(item) + "." + *item.name.get_ref() + ".html"
1007 fn full_path(cx: &Context, item: &clean::Item) -> ~str {
1008 let mut s = StrBuf::from_str(cx.current.connect("::"));
1010 s.push_str(item.name.get_ref().as_slice());
1011 return s.into_owned();
1014 fn blank<'a>(s: Option<&'a str>) -> &'a str {
1021 fn shorter<'a>(s: Option<&'a str>) -> &'a str {
1023 Some(s) => match s.find_str("\n\n") {
1024 Some(pos) => s.slice_to(pos),
1031 fn document(w: &mut Writer, item: &clean::Item) -> fmt::Result {
1032 match item.doc_value() {
1034 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1041 fn item_module(w: &mut Writer, cx: &Context,
1042 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1043 try!(document(w, item));
1044 debug!("{:?}", items);
1045 let mut indices = slice::from_fn(items.len(), |i| i);
1047 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering {
1048 if shortty(i1) == shortty(i2) {
1049 return i1.name.cmp(&i2.name);
1051 match (&i1.inner, &i2.inner) {
1052 (&clean::ViewItemItem(ref a), &clean::ViewItemItem(ref b)) => {
1053 match (&a.inner, &b.inner) {
1054 (&clean::ExternCrate(..), _) => Less,
1055 (_, &clean::ExternCrate(..)) => Greater,
1056 _ => idx1.cmp(&idx2),
1059 (&clean::ViewItemItem(..), _) => Less,
1060 (_, &clean::ViewItemItem(..)) => Greater,
1061 (&clean::ModuleItem(..), _) => Less,
1062 (_, &clean::ModuleItem(..)) => Greater,
1063 (&clean::MacroItem(..), _) => Less,
1064 (_, &clean::MacroItem(..)) => Greater,
1065 (&clean::StructItem(..), _) => Less,
1066 (_, &clean::StructItem(..)) => Greater,
1067 (&clean::EnumItem(..), _) => Less,
1068 (_, &clean::EnumItem(..)) => Greater,
1069 (&clean::StaticItem(..), _) => Less,
1070 (_, &clean::StaticItem(..)) => Greater,
1071 (&clean::ForeignFunctionItem(..), _) => Less,
1072 (_, &clean::ForeignFunctionItem(..)) => Greater,
1073 (&clean::ForeignStaticItem(..), _) => Less,
1074 (_, &clean::ForeignStaticItem(..)) => Greater,
1075 (&clean::TraitItem(..), _) => Less,
1076 (_, &clean::TraitItem(..)) => Greater,
1077 (&clean::FunctionItem(..), _) => Less,
1078 (_, &clean::FunctionItem(..)) => Greater,
1079 (&clean::TypedefItem(..), _) => Less,
1080 (_, &clean::TypedefItem(..)) => Greater,
1081 _ => idx1.cmp(&idx2),
1085 debug!("{:?}", indices);
1086 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1088 debug!("{:?}", indices);
1090 for &idx in indices.iter() {
1091 let myitem = &items[idx];
1093 let myty = shortty(myitem);
1096 try!(write!(w, "</table>"));
1099 let (short, name) = match myitem.inner {
1100 clean::ModuleItem(..) => ("modules", "Modules"),
1101 clean::StructItem(..) => ("structs", "Structs"),
1102 clean::EnumItem(..) => ("enums", "Enums"),
1103 clean::FunctionItem(..) => ("functions", "Functions"),
1104 clean::TypedefItem(..) => ("types", "Type Definitions"),
1105 clean::StaticItem(..) => ("statics", "Statics"),
1106 clean::TraitItem(..) => ("traits", "Traits"),
1107 clean::ImplItem(..) => ("impls", "Implementations"),
1108 clean::ViewItemItem(..) => ("reexports", "Reexports"),
1109 clean::TyMethodItem(..) => ("tymethods", "Type Methods"),
1110 clean::MethodItem(..) => ("methods", "Methods"),
1111 clean::StructFieldItem(..) => ("fields", "Struct Fields"),
1112 clean::VariantItem(..) => ("variants", "Variants"),
1113 clean::ForeignFunctionItem(..) => ("ffi-fns", "Foreign Functions"),
1114 clean::ForeignStaticItem(..) => ("ffi-statics", "Foreign Statics"),
1115 clean::MacroItem(..) => ("macros", "Macros"),
1118 "<h2 id='{id}' class='section-link'>\
1119 <a href=\"\\#{id}\">{name}</a></h2>\n<table>",
1120 id = short, name = name));
1123 match myitem.inner {
1124 clean::StaticItem(ref s) | clean::ForeignStaticItem(ref s) => {
1125 struct Initializer<'a>(&'a str);
1126 impl<'a> fmt::Show for Initializer<'a> {
1127 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1128 let Initializer(s) = *self;
1129 if s.len() == 0 { return Ok(()); }
1130 try!(write!(f.buf, "<code> = </code>"));
1131 let tag = if s.contains("\n") { "pre" } else { "code" };
1132 try!(write!(f.buf, "<{tag}>{}</{tag}>",
1133 s.as_slice(), tag=tag));
1140 <td><code>{}static {}: {}</code>{}</td>
1141 <td class='docblock'>{} </td>
1144 VisSpace(myitem.visibility),
1145 *myitem.name.get_ref(),
1147 Initializer(s.expr),
1148 Markdown(blank(myitem.doc_value()))));
1151 clean::ViewItemItem(ref item) => {
1153 clean::ExternCrate(ref name, ref src, _) => {
1154 try!(write!(w, "<tr><td><code>extern crate {}",
1157 Some(ref src) => try!(write!(w, " = \"{}\"",
1161 try!(write!(w, ";</code></td></tr>"));
1164 clean::Import(ref imports) => {
1165 for import in imports.iter() {
1166 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1167 VisSpace(myitem.visibility),
1176 if myitem.name.is_none() { continue }
1179 <td><a class='{class}' href='{href}'
1180 title='{title}'>{}</a></td>
1181 <td class='docblock short'>{}</td>
1184 *myitem.name.get_ref(),
1185 Markdown(shorter(myitem.doc_value())),
1186 class = shortty(myitem),
1187 href = item_path(myitem),
1188 title = full_path(cx, myitem)));
1192 write!(w, "</table>")
1195 fn item_function(w: &mut Writer, it: &clean::Item,
1196 f: &clean::Function) -> fmt::Result {
1197 try!(write!(w, "<pre class='rust fn'>{vis}{fn_style}fn \
1198 {name}{generics}{decl}</pre>",
1199 vis = VisSpace(it.visibility),
1200 fn_style = FnStyleSpace(f.fn_style),
1201 name = it.name.get_ref().as_slice(),
1202 generics = f.generics,
1207 fn item_trait(w: &mut Writer, it: &clean::Item,
1208 t: &clean::Trait) -> fmt::Result {
1209 let mut parents = StrBuf::new();
1210 if t.parents.len() > 0 {
1211 parents.push_str(": ");
1212 for (i, p) in t.parents.iter().enumerate() {
1213 if i > 0 { parents.push_str(" + "); }
1214 parents.push_str(format!("{}", *p));
1218 // Output the trait definition
1219 try!(write!(w, "<pre class='rust trait'>{}trait {}{}{} ",
1220 VisSpace(it.visibility),
1221 it.name.get_ref().as_slice(),
1224 let required = t.methods.iter().filter(|m| m.is_req()).collect::<Vec<&clean::TraitMethod>>();
1225 let provided = t.methods.iter().filter(|m| !m.is_req()).collect::<Vec<&clean::TraitMethod>>();
1227 if t.methods.len() == 0 {
1228 try!(write!(w, "\\{ \\}"));
1230 try!(write!(w, "\\{\n"));
1231 for m in required.iter() {
1232 try!(write!(w, " "));
1233 try!(render_method(w, m.item()));
1234 try!(write!(w, ";\n"));
1236 if required.len() > 0 && provided.len() > 0 {
1237 try!(w.write("\n".as_bytes()));
1239 for m in provided.iter() {
1240 try!(write!(w, " "));
1241 try!(render_method(w, m.item()));
1242 try!(write!(w, " \\{ ... \\}\n"));
1244 try!(write!(w, "\\}"));
1246 try!(write!(w, "</pre>"));
1248 // Trait documentation
1249 try!(document(w, it));
1251 fn meth(w: &mut Writer, m: &clean::TraitMethod) -> fmt::Result {
1252 try!(write!(w, "<h3 id='{}.{}' class='method'><code>",
1254 *m.item().name.get_ref()));
1255 try!(render_method(w, m.item()));
1256 try!(write!(w, "</code></h3>"));
1257 try!(document(w, m.item()));
1261 // Output the documentation for each function individually
1262 if required.len() > 0 {
1264 <h2 id='required-methods'>Required Methods</h2>
1265 <div class='methods'>
1267 for m in required.iter() {
1270 try!(write!(w, "</div>"));
1272 if provided.len() > 0 {
1274 <h2 id='provided-methods'>Provided Methods</h2>
1275 <div class='methods'>
1277 for m in provided.iter() {
1280 try!(write!(w, "</div>"));
1283 local_data::get(cache_key, |cache| {
1284 let cache = cache.unwrap();
1285 match cache.implementors.find(&it.id) {
1286 Some(implementors) => {
1288 <h2 id='implementors'>Implementors</h2>
1289 <ul class='item-list'>
1291 for i in implementors.iter() {
1293 PathType(ref ty) => {
1294 try!(write!(w, "<li><code>{}</code></li>", *ty));
1296 OtherType(ref generics, ref trait_, ref for_) => {
1297 try!(write!(w, "<li><code>impl{} {} for {}</code></li>",
1298 *generics, *trait_, *for_));
1302 try!(write!(w, "</ul>"));
1310 fn render_method(w: &mut Writer, meth: &clean::Item) -> fmt::Result {
1311 fn fun(w: &mut Writer, it: &clean::Item, fn_style: ast::FnStyle,
1312 g: &clean::Generics, selfty: &clean::SelfTy,
1313 d: &clean::FnDecl) -> fmt::Result {
1314 write!(w, "{}fn <a href='\\#{ty}.{name}' class='fnname'>{name}</a>\
1317 ast::UnsafeFn => "unsafe ",
1321 name = it.name.get_ref().as_slice(),
1323 decl = Method(selfty, d))
1326 clean::TyMethodItem(ref m) => {
1327 fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
1329 clean::MethodItem(ref m) => {
1330 fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
1336 fn item_struct(w: &mut Writer, it: &clean::Item,
1337 s: &clean::Struct) -> fmt::Result {
1338 try!(write!(w, "<pre class='rust struct'>"));
1339 try!(render_struct(w,
1343 s.fields.as_slice(),
1347 try!(write!(w, "</pre>"));
1349 try!(document(w, it));
1350 match s.struct_type {
1351 doctree::Plain if s.fields.len() > 0 => {
1352 try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
1353 for field in s.fields.iter() {
1354 try!(write!(w, "<tr><td id='structfield.{name}'>\
1355 <code>{name}</code></td><td>",
1356 name = field.name.get_ref().as_slice()));
1357 try!(document(w, field));
1358 try!(write!(w, "</td></tr>"));
1360 try!(write!(w, "</table>"));
1364 render_methods(w, it)
1367 fn item_enum(w: &mut Writer, it: &clean::Item, e: &clean::Enum) -> fmt::Result {
1368 try!(write!(w, "<pre class='rust enum'>{}enum {}{}",
1369 VisSpace(it.visibility),
1370 it.name.get_ref().as_slice(),
1372 if e.variants.len() == 0 && !e.variants_stripped {
1373 try!(write!(w, " \\{\\}"));
1375 try!(write!(w, " \\{\n"));
1376 for v in e.variants.iter() {
1377 try!(write!(w, " "));
1378 let name = v.name.get_ref().as_slice();
1380 clean::VariantItem(ref var) => {
1382 clean::CLikeVariant => try!(write!(w, "{}", name)),
1383 clean::TupleVariant(ref tys) => {
1384 try!(write!(w, "{}(", name));
1385 for (i, ty) in tys.iter().enumerate() {
1387 try!(write!(w, ", "))
1389 try!(write!(w, "{}", *ty));
1391 try!(write!(w, ")"));
1393 clean::StructVariant(ref s) => {
1394 try!(render_struct(w,
1398 s.fields.as_slice(),
1407 try!(write!(w, ",\n"));
1410 if e.variants_stripped {
1411 try!(write!(w, " // some variants omitted\n"));
1413 try!(write!(w, "\\}"));
1415 try!(write!(w, "</pre>"));
1417 try!(document(w, it));
1418 if e.variants.len() > 0 {
1419 try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
1420 for variant in e.variants.iter() {
1421 try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
1422 name = variant.name.get_ref().as_slice()));
1423 try!(document(w, variant));
1424 match variant.inner {
1425 clean::VariantItem(ref var) => {
1427 clean::StructVariant(ref s) => {
1428 try!(write!(w, "<h3 class='fields'>Fields</h3>\n
1430 for field in s.fields.iter() {
1431 try!(write!(w, "<tr><td \
1432 id='variant.{v}.field.{f}'>\
1433 <code>{f}</code></td><td>",
1434 v = variant.name.get_ref().as_slice(),
1435 f = field.name.get_ref().as_slice()));
1436 try!(document(w, field));
1437 try!(write!(w, "</td></tr>"));
1439 try!(write!(w, "</table>"));
1446 try!(write!(w, "</td></tr>"));
1448 try!(write!(w, "</table>"));
1451 try!(render_methods(w, it));
1455 fn render_struct(w: &mut Writer, it: &clean::Item,
1456 g: Option<&clean::Generics>,
1457 ty: doctree::StructType,
1458 fields: &[clean::Item],
1459 fields_stripped: bool,
1461 structhead: bool) -> fmt::Result {
1462 try!(write!(w, "{}{}{}",
1463 VisSpace(it.visibility),
1464 if structhead {"struct "} else {""},
1465 it.name.get_ref().as_slice()));
1467 Some(g) => try!(write!(w, "{}", *g)),
1472 try!(write!(w, " \\{\n{}", tab));
1473 for field in fields.iter() {
1475 clean::StructFieldItem(ref ty) => {
1476 try!(write!(w, " {}{}: {},\n{}",
1477 VisSpace(field.visibility),
1478 field.name.get_ref().as_slice(),
1486 if fields_stripped {
1487 try!(write!(w, " // some fields omitted\n{}", tab));
1489 try!(write!(w, "\\}"));
1491 doctree::Tuple | doctree::Newtype => {
1492 try!(write!(w, "("));
1493 for (i, field) in fields.iter().enumerate() {
1495 try!(write!(w, ", "));
1498 clean::StructFieldItem(ref field) => {
1499 try!(write!(w, "{}", field.type_));
1504 try!(write!(w, ");"));
1507 try!(write!(w, ";"));
1513 fn render_methods(w: &mut Writer, it: &clean::Item) -> fmt::Result {
1514 local_data::get(cache_key, |cache| {
1515 let c = cache.unwrap();
1516 match c.impls.find(&it.id) {
1518 let mut non_trait = v.iter().filter(|p| {
1519 p.ref0().trait_.is_none()
1521 let non_trait = non_trait.collect::<Vec<&(clean::Impl, Option<~str>)>>();
1522 let mut traits = v.iter().filter(|p| {
1523 p.ref0().trait_.is_some()
1525 let traits = traits.collect::<Vec<&(clean::Impl, Option<~str>)>>();
1527 if non_trait.len() > 0 {
1528 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
1529 for &(ref i, ref dox) in non_trait.move_iter() {
1530 try!(render_impl(w, i, dox));
1533 if traits.len() > 0 {
1534 try!(write!(w, "<h2 id='implementations'>Trait \
1535 Implementations</h2>"));
1536 let mut any_derived = false;
1537 for & &(ref i, ref dox) in traits.iter() {
1539 try!(render_impl(w, i, dox));
1545 try!(write!(w, "<h3 id='derived_implementations'>Derived Implementations \
1547 for &(ref i, ref dox) in traits.move_iter() {
1549 try!(render_impl(w, i, dox));
1561 fn render_impl(w: &mut Writer, i: &clean::Impl,
1562 dox: &Option<~str>) -> fmt::Result {
1563 try!(write!(w, "<h3 class='impl'><code>impl{} ", i.generics));
1564 let trait_id = match i.trait_ {
1566 try!(write!(w, "{} for ", *ty));
1568 clean::ResolvedPath { id, .. } => Some(id),
1574 try!(write!(w, "{}</code></h3>", i.for_));
1577 try!(write!(w, "<div class='docblock'>{}</div>",
1578 Markdown(dox.as_slice())));
1583 fn docmeth(w: &mut Writer, item: &clean::Item) -> io::IoResult<bool> {
1584 try!(write!(w, "<h4 id='method.{}' class='method'><code>",
1585 *item.name.get_ref()));
1586 try!(render_method(w, item));
1587 try!(write!(w, "</code></h4>\n"));
1588 match item.doc_value() {
1590 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1597 try!(write!(w, "<div class='methods'>"));
1598 for meth in i.methods.iter() {
1599 if try!(docmeth(w, meth)) {
1603 // No documentation? Attempt to slurp in the trait's documentation
1604 let trait_id = match trait_id {
1608 try!(local_data::get(cache_key, |cache| {
1609 let cache = cache.unwrap();
1610 match cache.traits.find(&trait_id) {
1612 let name = meth.name.clone();
1613 match t.methods.iter().find(|t| t.item().name == name) {
1615 match method.item().doc_value() {
1618 "<div class='docblock'>{}</div>",
1633 // If we've implemented a trait, then also emit documentation for all
1634 // default methods which weren't overridden in the implementation block.
1638 try!(local_data::get(cache_key, |cache| {
1639 let cache = cache.unwrap();
1640 match cache.traits.find(&id) {
1642 for method in t.methods.iter() {
1643 let n = method.item().name.clone();
1644 match i.methods.iter().find(|m| m.name == n) {
1645 Some(..) => continue,
1649 try!(docmeth(w, method.item()));
1658 try!(write!(w, "</div>"));
1662 fn item_typedef(w: &mut Writer, it: &clean::Item,
1663 t: &clean::Typedef) -> fmt::Result {
1664 try!(write!(w, "<pre class='rust typedef'>type {}{} = {};</pre>",
1665 it.name.get_ref().as_slice(),
1672 impl<'a> fmt::Show for Sidebar<'a> {
1673 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1676 try!(write!(fmt.buf, "<p class='location'>"));
1677 let len = cx.current.len() - if it.is_mod() {1} else {0};
1678 for (i, name) in cx.current.iter().take(len).enumerate() {
1680 try!(write!(fmt.buf, "&\\#8203;::"));
1682 try!(write!(fmt.buf, "<a href='{}index.html'>{}</a>",
1685 .slice_to((cx.current.len() - i - 1) * 3),
1688 try!(write!(fmt.buf, "</p>"));
1690 fn block(w: &mut Writer, short: &str, longty: &str,
1691 cur: &clean::Item, cx: &Context) -> fmt::Result {
1692 let items = match cx.sidebar.find_equiv(&short) {
1693 Some(items) => items.as_slice(),
1694 None => return Ok(())
1696 try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
1697 for item in items.iter() {
1698 let class = if cur.name.get_ref() == item &&
1699 short == shortty(cur) { "current" } else { "" };
1700 try!(write!(w, "<a class='{ty} {class}' href='{curty, select,
1704 mod{{name}/index.html}
1705 other{#.{name}.html}
1706 }'>{name}</a><br/>",
1710 curty = shortty(cur),
1711 name = item.as_slice()));
1713 try!(write!(w, "</div>"));
1717 try!(block(fmt.buf, "mod", "Modules", it, cx));
1718 try!(block(fmt.buf, "struct", "Structs", it, cx));
1719 try!(block(fmt.buf, "enum", "Enums", it, cx));
1720 try!(block(fmt.buf, "trait", "Traits", it, cx));
1721 try!(block(fmt.buf, "fn", "Functions", it, cx));
1726 fn build_sidebar(m: &clean::Module) -> HashMap<~str, Vec<~str> > {
1727 let mut map = HashMap::new();
1728 for item in m.items.iter() {
1729 let short = shortty(item);
1730 let myname = match item.name {
1732 Some(ref s) => s.to_owned(),
1734 let v = map.find_or_insert_with(short.to_owned(), |_| Vec::new());
1738 for (_, items) in map.mut_iter() {
1739 items.as_mut_slice().sort();
1744 impl<'a> fmt::Show for Source<'a> {
1745 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1746 let Source(s) = *self;
1747 let lines = s.lines().len();
1749 let mut tmp = lines;
1754 try!(write!(fmt.buf, "<pre class='line-numbers'>"));
1755 for i in range(1, lines + 1) {
1756 try!(write!(fmt.buf, "<span id='{0:u}'>{0:1$u}</span>\n", i, cols));
1758 try!(write!(fmt.buf, "</pre>"));
1759 try!(write!(fmt.buf, "{}", highlight::highlight(s.as_slice(), None)));
1764 fn item_macro(w: &mut Writer, it: &clean::Item,
1765 t: &clean::Macro) -> fmt::Result {
1766 try!(w.write_str(highlight::highlight(t.source, Some("macro"))));