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, PuritySpace};
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 // Attach all orphan methods to the type's definition if the type
267 // has since been learned.
268 let Cache { search_index: ref mut index,
269 orphan_methods: ref meths, paths: ref paths, ..} = cache;
270 for &(ref pid, ref item) in meths.iter() {
271 match paths.find(pid) {
272 Some(&(ref fqp, _)) => {
273 index.push(IndexItem {
275 name: item.name.clone().unwrap(),
276 path: fqp.slice_to(fqp.len() - 1).connect("::"),
277 desc: shorter(item.doc_value()).to_owned(),
286 // Publish the search index
288 let mut w = MemWriter::new();
289 try!(write!(&mut w, "searchIndex['{}'] = [", krate.name));
290 for (i, item) in cache.search_index.iter().enumerate() {
292 try!(write!(&mut w, ","));
294 try!(write!(&mut w, "\\{ty:\"{}\",name:\"{}\",path:\"{}\",desc:{}",
295 item.ty, item.name, item.path,
296 item.desc.to_json().to_str()));
299 try!(write!(&mut w, ",parent:'{}'", id));
303 try!(write!(&mut w, "\\}"));
305 try!(write!(&mut w, "];"));
306 try!(write!(&mut w, "allPaths['{}'] = \\{", krate.name));
307 for (i, (&id, &(ref fqp, short))) in cache.paths.iter().enumerate() {
309 try!(write!(&mut w, ","));
311 try!(write!(&mut w, "'{}':\\{type:'{}',name:'{}'\\}",
312 id, short, *fqp.last().unwrap()));
314 try!(write!(&mut w, "\\};"));
316 str::from_utf8(w.unwrap().as_slice()).unwrap().to_owned()
319 // Write out the shared files. Note that these are shared among all rustdoc
320 // docs placed in the output directory, so this needs to be a synchronized
321 // operation with respect to all other rustdocs running around.
323 try!(mkdir(&cx.dst));
324 let _lock = ::flock::Lock::new(&cx.dst.join(".lock"));
326 // Add all the static files. These may already exist, but we just
327 // overwrite them anyway to make sure that they're fresh and up-to-date.
328 try!(write(cx.dst.join("jquery.js"),
329 include_str!("static/jquery-2.1.0.min.js")));
330 try!(write(cx.dst.join("main.js"), include_str!("static/main.js")));
331 try!(write(cx.dst.join("main.css"), include_str!("static/main.css")));
332 try!(write(cx.dst.join("normalize.css"),
333 include_str!("static/normalize.css")));
335 // Update the search index
336 let dst = cx.dst.join("search-index.js");
337 let mut all_indexes = Vec::new();
338 all_indexes.push(index);
340 for line in BufferedReader::new(File::open(&dst)).lines() {
341 let line = try!(line);
342 if !line.starts_with("searchIndex") { continue }
343 if line.starts_with(format!("searchIndex['{}']", krate.name)) {
346 all_indexes.push(line);
349 let mut w = try!(File::create(&dst));
350 try!(writeln!(&mut w, r"var searchIndex = \{\}; var allPaths = \{\};"));
351 for index in all_indexes.iter() {
352 try!(writeln!(&mut w, "{}", *index));
354 try!(writeln!(&mut w, "initSearch(searchIndex);"));
357 // Render all source files (this may turn into a giant no-op)
359 info!("emitting source files");
360 let dst = cx.dst.join("src");
362 let dst = dst.join(krate.name.as_slice());
364 let mut folder = SourceCollector {
366 seen: HashSet::new(),
369 krate = folder.fold_crate(krate);
372 for &(n, ref e) in krate.externs.iter() {
373 cache.extern_locations.insert(n, extern_location(e, &cx.dst));
376 // And finally render the whole crate's documentation
377 cx.krate(krate, cache)
380 /// Writes the entire contents of a string to a destination, not attempting to
381 /// catch any errors.
382 fn write(dst: Path, contents: &str) -> io::IoResult<()> {
383 File::create(&dst).write(contents.as_bytes())
386 /// Makes a directory on the filesystem, failing the task if an error occurs and
387 /// skipping if the directory already exists.
388 fn mkdir(path: &Path) -> io::IoResult<()> {
390 fs::mkdir(path, io::UserRWX)
396 /// Takes a path to a source file and cleans the path to it. This canonicalizes
397 /// things like ".." to components which preserve the "top down" hierarchy of a
398 /// static HTML tree.
399 // FIXME (#9639): The closure should deal with &[u8] instead of &str
400 fn clean_srcpath(src: &[u8], f: |&str|) {
401 let p = Path::new(src);
402 if p.as_vec() != bytes!(".") {
403 for c in p.str_components().map(|x|x.unwrap()) {
413 /// Attempts to find where an external crate is located, given that we're
414 /// rendering in to the specified source destination.
415 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
416 // See if there's documentation generated into the local directory
417 let local_location = dst.join(e.name.as_slice());
418 if local_location.is_dir() {
422 // Failing that, see if there's an attribute specifying where to find this
424 for attr in e.attrs.iter() {
426 clean::List(ref x, ref list) if "doc" == *x => {
427 for attr in list.iter() {
429 clean::NameValue(ref x, ref s) if "html_root_url" == *x => {
430 if s.ends_with("/") {
431 return Remote(s.to_owned());
433 return Remote(*s + "/");
443 // Well, at least we tried.
447 impl<'a> DocFolder for SourceCollector<'a> {
448 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
449 // If we're including source files, and we haven't seen this file yet,
450 // then we need to render it out to the filesystem
451 if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
453 // If it turns out that we couldn't read this file, then we probably
454 // can't read any of the files (generating html output from json or
455 // something like that), so just don't include sources for the
456 // entire crate. The other option is maintaining this mapping on a
457 // per-file basis, but that's probably not worth it...
458 self.cx.include_sources = match self.emit_source(item.source.filename) {
461 println!("warning: source code was requested to be rendered, \
462 but processing `{}` had an error: {}",
463 item.source.filename, e);
464 println!(" skipping rendering of source code");
468 self.seen.insert(item.source.filename.clone());
471 self.fold_item_recur(item)
475 impl<'a> SourceCollector<'a> {
476 /// Renders the given filename into its corresponding HTML source file.
477 fn emit_source(&mut self, filename: &str) -> io::IoResult<()> {
478 let p = Path::new(filename);
480 // If we couldn't open this file, then just returns because it
481 // probably means that it's some standard library macro thing and we
482 // can't have the source to it anyway.
483 let contents = match File::open(&p).read_to_end() {
485 // macros from other libraries get special filenames which we can
487 Err(..) if filename.starts_with("<") &&
488 filename.ends_with("macros>") => return Ok(()),
489 Err(e) => return Err(e)
491 let contents = str::from_utf8(contents.as_slice()).unwrap();
493 // Remove the utf-8 BOM if any
494 let contents = if contents.starts_with("\ufeff") {
495 contents.as_slice().slice_from(3)
500 // Create the intermediate directories
501 let mut cur = self.dst.clone();
502 let mut root_path = StrBuf::from_str("../../");
503 clean_srcpath(p.dirname(), |component| {
505 mkdir(&cur).unwrap();
506 root_path.push_str("../");
509 cur.push(p.filename().expect("source has no filename") + bytes!(".html"));
510 let mut w = BufferedWriter::new(try!(File::create(&cur)));
512 let title = format!("{} -- source", cur.filename_display());
513 let page = layout::Page {
516 root_path: root_path.as_slice(),
518 try!(layout::render(&mut w as &mut Writer, &self.cx.layout,
519 &page, &(""), &Source(contents)));
525 impl DocFolder for Cache {
526 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
527 // If this is a private module, we don't want it in the search index.
528 let orig_privmod = match item.inner {
529 clean::ModuleItem(..) => {
530 let prev = self.privmod;
531 self.privmod = prev || item.visibility != Some(ast::Public);
537 // Register any generics to their corresponding string. This is used
538 // when pretty-printing types
540 clean::StructItem(ref s) => self.generics(&s.generics),
541 clean::EnumItem(ref e) => self.generics(&e.generics),
542 clean::FunctionItem(ref f) => self.generics(&f.generics),
543 clean::TypedefItem(ref t) => self.generics(&t.generics),
544 clean::TraitItem(ref t) => self.generics(&t.generics),
545 clean::ImplItem(ref i) => self.generics(&i.generics),
546 clean::TyMethodItem(ref i) => self.generics(&i.generics),
547 clean::MethodItem(ref i) => self.generics(&i.generics),
548 clean::ForeignFunctionItem(ref f) => self.generics(&f.generics),
552 // Propagate a trait methods' documentation to all implementors of the
555 clean::TraitItem(ref t) => {
556 self.traits.insert(item.id, t.clone());
561 // Collect all the implementors of traits.
563 clean::ImplItem(ref i) => {
565 Some(clean::ResolvedPath{ id, .. }) => {
566 let v = self.implementors.find_or_insert_with(id, |_|{
570 clean::ResolvedPath{..} => {
571 v.unshift(PathType(i.for_.clone()));
574 v.push(OtherType(i.generics.clone(),
575 i.trait_.get_ref().clone(),
580 Some(..) | None => {}
586 // Index this method for searching later on
589 let parent = match item.inner {
590 clean::TyMethodItem(..) |
591 clean::StructFieldItem(..) |
592 clean::VariantItem(..) => {
593 (Some(*self.parent_stack.last().unwrap()),
594 Some(self.stack.slice_to(self.stack.len() - 1)))
597 clean::MethodItem(..) => {
598 if self.parent_stack.len() == 0 {
601 let last = self.parent_stack.last().unwrap();
602 let path = match self.paths.find(last) {
603 Some(&(_, "trait")) =>
604 Some(self.stack.slice_to(self.stack.len() - 1)),
605 // The current stack not necessarily has correlation for
606 // where the type was defined. On the other hand,
607 // `paths` always has the right information if present.
608 Some(&(ref fqp, "struct")) | Some(&(ref fqp, "enum")) =>
609 Some(fqp.slice_to(fqp.len() - 1)),
610 Some(..) => Some(self.stack.as_slice()),
616 _ => (None, Some(self.stack.as_slice()))
619 (parent, Some(path)) if !self.privmod => {
620 self.search_index.push(IndexItem {
623 path: path.connect("::"),
624 desc: shorter(item.doc_value()).to_owned(),
628 (Some(parent), None) if !self.privmod => {
629 // We have a parent, but we don't know where they're
630 // defined yet. Wait for later to index this item.
631 self.orphan_methods.push((parent, item.clone()))
639 // Keep track of the fully qualified path for this item.
640 let pushed = if item.name.is_some() {
641 let n = item.name.get_ref();
643 self.stack.push(n.to_owned());
648 clean::StructItem(..) | clean::EnumItem(..) |
649 clean::TypedefItem(..) | clean::TraitItem(..) |
650 clean::FunctionItem(..) | clean::ModuleItem(..) |
651 clean::ForeignFunctionItem(..) => {
652 // Reexported items mean that the same id can show up twice in
653 // the rustdoc ast that we're looking at. We know, however, that
654 // a reexported item doesn't show up in the `public_items` map,
655 // so we can skip inserting into the paths map if there was
656 // already an entry present and we're not a public item.
657 if !self.paths.contains_key(&item.id) ||
658 self.public_items.contains(&item.id) {
659 self.paths.insert(item.id,
660 (self.stack.clone(), shortty(&item)));
663 // link variants to their parent enum because pages aren't emitted
665 clean::VariantItem(..) => {
666 let mut stack = self.stack.clone();
668 self.paths.insert(item.id, (stack, "enum"));
673 // Maintain the parent stack
674 let parent_pushed = match item.inner {
675 clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
676 self.parent_stack.push(item.id); true
678 clean::ImplItem(ref i) => {
680 clean::ResolvedPath{ id, .. } => {
681 self.parent_stack.push(id); true
689 // Once we've recursively found all the generics, then hoard off all the
690 // implementations elsewhere
691 let ret = match self.fold_item_recur(item) {
694 clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
696 clean::ResolvedPath { id, .. } => {
697 let v = self.impls.find_or_insert_with(id, |_| {
700 // extract relevant documentation for this impl
701 match attrs.move_iter().find(|a| {
703 clean::NameValue(ref x, _) if "doc" == *x => true,
707 Some(clean::NameValue(_, dox)) => {
708 v.push((i, Some(dox)));
719 // Private modules may survive the strip-private pass if
720 // they contain impls for public types, but those will get
722 clean::Item { inner: clean::ModuleItem(ref m),
724 if (m.items.len() == 0 &&
725 item.doc_value().is_none()) ||
726 visibility != Some(ast::Public) => None,
734 if pushed { self.stack.pop().unwrap(); }
735 if parent_pushed { self.parent_stack.pop().unwrap(); }
736 self.privmod = orig_privmod;
742 fn generics(&mut self, generics: &clean::Generics) {
743 for typ in generics.type_params.iter() {
744 self.typarams.insert(typ.id, typ.name.clone());
750 /// Recurse in the directory structure and change the "root path" to make
751 /// sure it always points to the top (relatively)
752 fn recurse<T>(&mut self, s: ~str, f: |&mut Context| -> T) -> T {
754 fail!("what {:?}", self);
756 let prev = self.dst.clone();
757 self.dst.push(s.as_slice());
758 self.root_path.push_str("../");
759 self.current.push(s);
761 info!("Recursing into {}", self.dst.display());
763 mkdir(&self.dst).unwrap();
766 info!("Recursed; leaving {}", self.dst.display());
768 // Go back to where we were at
770 let len = self.root_path.len();
771 self.root_path.truncate(len - 3);
772 self.current.pop().unwrap();
777 /// Main method for rendering a crate.
779 /// This currently isn't parallelized, but it'd be pretty easy to add
780 /// parallelization to this function.
781 fn krate(self, mut krate: clean::Crate, cache: Cache) -> io::IoResult<()> {
782 let mut item = match krate.module.take() {
784 None => return Ok(())
786 item.name = Some(krate.name);
788 // using a rwarc makes this parallelizable in the future
789 local_data::set(cache_key, Arc::new(cache));
791 let mut work = vec!((self, item));
794 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
795 work.push((cx.clone(), item));
803 /// Non-parellelized version of rendering an item. This will take the input
804 /// item, render its contents, and then invoke the specified closure with
805 /// all sub-items which need to be rendered.
807 /// The rendering driver uses this closure to queue up more work.
808 fn item(&mut self, item: clean::Item,
809 f: |&mut Context, clean::Item|) -> io::IoResult<()> {
810 fn render(w: io::File, cx: &mut Context, it: &clean::Item,
811 pushname: bool) -> io::IoResult<()> {
812 info!("Rendering an item to {}", w.path().display());
813 // A little unfortunate that this is done like this, but it sure
814 // does make formatting *a lot* nicer.
815 local_data::set(current_location_key, cx.current.clone());
817 let mut title = StrBuf::from_str(cx.current.connect("::"));
820 title.push_str("::");
822 title.push_str(*it.name.get_ref());
824 title.push_str(" - Rust");
825 let page = layout::Page {
827 root_path: cx.root_path.as_slice(),
828 title: title.as_slice(),
831 markdown::reset_headers();
833 // We have a huge number of calls to write, so try to alleviate some
834 // of the pain by using a buffered writer instead of invoking the
835 // write sycall all the time.
836 let mut writer = BufferedWriter::new(w);
837 try!(layout::render(&mut writer as &mut Writer, &cx.layout, &page,
838 &Sidebar{ cx: cx, item: it },
839 &Item{ cx: cx, item: it }));
844 // modules are special because they add a namespace. We also need to
845 // recurse into the items of the module as well.
846 clean::ModuleItem(..) => {
847 let name = item.name.get_ref().to_owned();
848 let mut item = Some(item);
849 self.recurse(name, |this| {
850 let item = item.take_unwrap();
851 let dst = this.dst.join("index.html");
852 let dst = try!(File::create(&dst));
853 try!(render(dst, this, &item, false));
855 let m = match item.inner {
856 clean::ModuleItem(m) => m,
859 this.sidebar = build_sidebar(&m);
860 for item in m.items.move_iter() {
867 // Things which don't have names (like impls) don't get special
868 // pages dedicated to them.
869 _ if item.name.is_some() => {
870 let dst = self.dst.join(item_path(&item));
871 let dst = try!(File::create(&dst));
872 render(dst, self, &item, true)
880 fn shortty(item: &clean::Item) -> &'static str {
882 clean::ModuleItem(..) => "mod",
883 clean::StructItem(..) => "struct",
884 clean::EnumItem(..) => "enum",
885 clean::FunctionItem(..) => "fn",
886 clean::TypedefItem(..) => "typedef",
887 clean::StaticItem(..) => "static",
888 clean::TraitItem(..) => "trait",
889 clean::ImplItem(..) => "impl",
890 clean::ViewItemItem(..) => "viewitem",
891 clean::TyMethodItem(..) => "tymethod",
892 clean::MethodItem(..) => "method",
893 clean::StructFieldItem(..) => "structfield",
894 clean::VariantItem(..) => "variant",
895 clean::ForeignFunctionItem(..) => "ffi",
896 clean::ForeignStaticItem(..) => "ffs",
897 clean::MacroItem(..) => "macro",
902 fn ismodule(&self) -> bool {
903 match self.item.inner {
904 clean::ModuleItem(..) => true, _ => false
909 impl<'a> fmt::Show for Item<'a> {
910 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
911 match attr::find_stability(self.item.attrs.iter()) {
912 Some(ref stability) => {
914 "<a class='stability {lvl}' title='{reason}'>{lvl}</a>",
915 lvl = stability.level.to_str(),
916 reason = match stability.text {
917 Some(ref s) => (*s).clone(),
918 None => InternedString::new(""),
924 if self.cx.include_sources {
925 let mut path = Vec::new();
926 clean_srcpath(self.item.source.filename.as_bytes(), |component| {
927 path.push(component.to_owned());
929 let href = if self.item.source.loline == self.item.source.hiline {
930 format!("{}", self.item.source.loline)
932 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
936 href='{root}src/{krate}/{path}.html\\#{href}'>\
938 root = self.cx.root_path,
939 krate = self.cx.layout.krate,
940 path = path.connect("/"),
944 // Write the breadcrumb trail header for the top
945 try!(write!(fmt.buf, "<h1 class='fqn'>"));
946 match self.item.inner {
947 clean::ModuleItem(ref m) => if m.is_crate {
948 try!(write!(fmt.buf, "Crate "));
950 try!(write!(fmt.buf, "Module "));
952 clean::FunctionItem(..) => try!(write!(fmt.buf, "Function ")),
953 clean::TraitItem(..) => try!(write!(fmt.buf, "Trait ")),
954 clean::StructItem(..) => try!(write!(fmt.buf, "Struct ")),
955 clean::EnumItem(..) => try!(write!(fmt.buf, "Enum ")),
958 let cur = self.cx.current.as_slice();
959 let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
960 for (i, component) in cur.iter().enumerate().take(amt) {
961 let mut trail = StrBuf::new();
962 for _ in range(0, cur.len() - i - 1) {
963 trail.push_str("../");
965 try!(write!(fmt.buf, "<a href='{}index.html'>{}</a>::",
966 trail, component.as_slice()));
968 try!(write!(fmt.buf, "<a class='{}' href=''>{}</a></h1>",
969 shortty(self.item), self.item.name.get_ref().as_slice()));
971 match self.item.inner {
972 clean::ModuleItem(ref m) => {
973 item_module(fmt.buf, self.cx, self.item, m.items.as_slice())
975 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
976 item_function(fmt.buf, self.item, f),
977 clean::TraitItem(ref t) => item_trait(fmt.buf, self.item, t),
978 clean::StructItem(ref s) => item_struct(fmt.buf, self.item, s),
979 clean::EnumItem(ref e) => item_enum(fmt.buf, self.item, e),
980 clean::TypedefItem(ref t) => item_typedef(fmt.buf, self.item, t),
981 clean::MacroItem(ref m) => item_macro(fmt.buf, self.item, m),
987 fn item_path(item: &clean::Item) -> ~str {
989 clean::ModuleItem(..) => *item.name.get_ref() + "/index.html",
990 _ => shortty(item) + "." + *item.name.get_ref() + ".html"
994 fn full_path(cx: &Context, item: &clean::Item) -> ~str {
995 let mut s = StrBuf::from_str(cx.current.connect("::"));
997 s.push_str(item.name.get_ref().as_slice());
998 return s.into_owned();
1001 fn blank<'a>(s: Option<&'a str>) -> &'a str {
1008 fn shorter<'a>(s: Option<&'a str>) -> &'a str {
1010 Some(s) => match s.find_str("\n\n") {
1011 Some(pos) => s.slice_to(pos),
1018 fn document(w: &mut Writer, item: &clean::Item) -> fmt::Result {
1019 match item.doc_value() {
1021 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1028 fn item_module(w: &mut Writer, cx: &Context,
1029 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1030 try!(document(w, item));
1031 debug!("{:?}", items);
1032 let mut indices = slice::from_fn(items.len(), |i| i);
1034 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering {
1035 if shortty(i1) == shortty(i2) {
1036 return i1.name.cmp(&i2.name);
1038 match (&i1.inner, &i2.inner) {
1039 (&clean::ViewItemItem(ref a), &clean::ViewItemItem(ref b)) => {
1040 match (&a.inner, &b.inner) {
1041 (&clean::ExternCrate(..), _) => Less,
1042 (_, &clean::ExternCrate(..)) => Greater,
1043 _ => idx1.cmp(&idx2),
1046 (&clean::ViewItemItem(..), _) => Less,
1047 (_, &clean::ViewItemItem(..)) => Greater,
1048 (&clean::ModuleItem(..), _) => Less,
1049 (_, &clean::ModuleItem(..)) => Greater,
1050 (&clean::MacroItem(..), _) => Less,
1051 (_, &clean::MacroItem(..)) => Greater,
1052 (&clean::StructItem(..), _) => Less,
1053 (_, &clean::StructItem(..)) => Greater,
1054 (&clean::EnumItem(..), _) => Less,
1055 (_, &clean::EnumItem(..)) => Greater,
1056 (&clean::StaticItem(..), _) => Less,
1057 (_, &clean::StaticItem(..)) => Greater,
1058 (&clean::ForeignFunctionItem(..), _) => Less,
1059 (_, &clean::ForeignFunctionItem(..)) => Greater,
1060 (&clean::ForeignStaticItem(..), _) => Less,
1061 (_, &clean::ForeignStaticItem(..)) => Greater,
1062 (&clean::TraitItem(..), _) => Less,
1063 (_, &clean::TraitItem(..)) => Greater,
1064 (&clean::FunctionItem(..), _) => Less,
1065 (_, &clean::FunctionItem(..)) => Greater,
1066 (&clean::TypedefItem(..), _) => Less,
1067 (_, &clean::TypedefItem(..)) => Greater,
1068 _ => idx1.cmp(&idx2),
1072 debug!("{:?}", indices);
1073 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1075 debug!("{:?}", indices);
1077 for &idx in indices.iter() {
1078 let myitem = &items[idx];
1080 let myty = shortty(myitem);
1083 try!(write!(w, "</table>"));
1086 let (short, name) = match myitem.inner {
1087 clean::ModuleItem(..) => ("modules", "Modules"),
1088 clean::StructItem(..) => ("structs", "Structs"),
1089 clean::EnumItem(..) => ("enums", "Enums"),
1090 clean::FunctionItem(..) => ("functions", "Functions"),
1091 clean::TypedefItem(..) => ("types", "Type Definitions"),
1092 clean::StaticItem(..) => ("statics", "Statics"),
1093 clean::TraitItem(..) => ("traits", "Traits"),
1094 clean::ImplItem(..) => ("impls", "Implementations"),
1095 clean::ViewItemItem(..) => ("reexports", "Reexports"),
1096 clean::TyMethodItem(..) => ("tymethods", "Type Methods"),
1097 clean::MethodItem(..) => ("methods", "Methods"),
1098 clean::StructFieldItem(..) => ("fields", "Struct Fields"),
1099 clean::VariantItem(..) => ("variants", "Variants"),
1100 clean::ForeignFunctionItem(..) => ("ffi-fns", "Foreign Functions"),
1101 clean::ForeignStaticItem(..) => ("ffi-statics", "Foreign Statics"),
1102 clean::MacroItem(..) => ("macros", "Macros"),
1105 "<h2 id='{id}' class='section-link'>\
1106 <a href=\"\\#{id}\">{name}</a></h2>\n<table>",
1107 id = short, name = name));
1110 match myitem.inner {
1111 clean::StaticItem(ref s) | clean::ForeignStaticItem(ref s) => {
1112 struct Initializer<'a>(&'a str);
1113 impl<'a> fmt::Show for Initializer<'a> {
1114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1115 let Initializer(s) = *self;
1116 if s.len() == 0 { return Ok(()); }
1117 try!(write!(f.buf, "<code> = </code>"));
1118 let tag = if s.contains("\n") { "pre" } else { "code" };
1119 try!(write!(f.buf, "<{tag}>{}</{tag}>",
1120 s.as_slice(), tag=tag));
1127 <td><code>{}static {}: {}</code>{}</td>
1128 <td class='docblock'>{} </td>
1131 VisSpace(myitem.visibility),
1132 *myitem.name.get_ref(),
1134 Initializer(s.expr),
1135 Markdown(blank(myitem.doc_value()))));
1138 clean::ViewItemItem(ref item) => {
1140 clean::ExternCrate(ref name, ref src, _) => {
1141 try!(write!(w, "<tr><td><code>extern crate {}",
1144 Some(ref src) => try!(write!(w, " = \"{}\"",
1148 try!(write!(w, ";</code></td></tr>"));
1151 clean::Import(ref imports) => {
1152 for import in imports.iter() {
1153 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1154 VisSpace(myitem.visibility),
1163 if myitem.name.is_none() { continue }
1166 <td><a class='{class}' href='{href}'
1167 title='{title}'>{}</a></td>
1168 <td class='docblock short'>{}</td>
1171 *myitem.name.get_ref(),
1172 Markdown(shorter(myitem.doc_value())),
1173 class = shortty(myitem),
1174 href = item_path(myitem),
1175 title = full_path(cx, myitem)));
1179 write!(w, "</table>")
1182 fn item_function(w: &mut Writer, it: &clean::Item,
1183 f: &clean::Function) -> fmt::Result {
1184 try!(write!(w, "<pre class='rust fn'>{vis}{purity}fn \
1185 {name}{generics}{decl}</pre>",
1186 vis = VisSpace(it.visibility),
1187 purity = PuritySpace(f.purity),
1188 name = it.name.get_ref().as_slice(),
1189 generics = f.generics,
1194 fn item_trait(w: &mut Writer, it: &clean::Item,
1195 t: &clean::Trait) -> fmt::Result {
1196 let mut parents = StrBuf::new();
1197 if t.parents.len() > 0 {
1198 parents.push_str(": ");
1199 for (i, p) in t.parents.iter().enumerate() {
1200 if i > 0 { parents.push_str(" + "); }
1201 parents.push_str(format!("{}", *p));
1205 // Output the trait definition
1206 try!(write!(w, "<pre class='rust trait'>{}trait {}{}{} ",
1207 VisSpace(it.visibility),
1208 it.name.get_ref().as_slice(),
1211 let required = t.methods.iter().filter(|m| m.is_req()).collect::<~[&clean::TraitMethod]>();
1212 let provided = t.methods.iter().filter(|m| !m.is_req()).collect::<~[&clean::TraitMethod]>();
1214 if t.methods.len() == 0 {
1215 try!(write!(w, "\\{ \\}"));
1217 try!(write!(w, "\\{\n"));
1218 for m in required.iter() {
1219 try!(write!(w, " "));
1220 try!(render_method(w, m.item()));
1221 try!(write!(w, ";\n"));
1223 if required.len() > 0 && provided.len() > 0 {
1224 try!(w.write("\n".as_bytes()));
1226 for m in provided.iter() {
1227 try!(write!(w, " "));
1228 try!(render_method(w, m.item()));
1229 try!(write!(w, " \\{ ... \\}\n"));
1231 try!(write!(w, "\\}"));
1233 try!(write!(w, "</pre>"));
1235 // Trait documentation
1236 try!(document(w, it));
1238 fn meth(w: &mut Writer, m: &clean::TraitMethod) -> fmt::Result {
1239 try!(write!(w, "<h3 id='{}.{}' class='method'><code>",
1241 *m.item().name.get_ref()));
1242 try!(render_method(w, m.item()));
1243 try!(write!(w, "</code></h3>"));
1244 try!(document(w, m.item()));
1248 // Output the documentation for each function individually
1249 if required.len() > 0 {
1251 <h2 id='required-methods'>Required Methods</h2>
1252 <div class='methods'>
1254 for m in required.iter() {
1257 try!(write!(w, "</div>"));
1259 if provided.len() > 0 {
1261 <h2 id='provided-methods'>Provided Methods</h2>
1262 <div class='methods'>
1264 for m in provided.iter() {
1267 try!(write!(w, "</div>"));
1270 local_data::get(cache_key, |cache| {
1271 let cache = cache.unwrap();
1272 match cache.implementors.find(&it.id) {
1273 Some(implementors) => {
1275 <h2 id='implementors'>Implementors</h2>
1276 <ul class='item-list'>
1278 for i in implementors.iter() {
1280 PathType(ref ty) => {
1281 try!(write!(w, "<li><code>{}</code></li>", *ty));
1283 OtherType(ref generics, ref trait_, ref for_) => {
1284 try!(write!(w, "<li><code>impl{} {} for {}</code></li>",
1285 *generics, *trait_, *for_));
1289 try!(write!(w, "</ul>"));
1297 fn render_method(w: &mut Writer, meth: &clean::Item) -> fmt::Result {
1298 fn fun(w: &mut Writer, it: &clean::Item, purity: ast::Purity,
1299 g: &clean::Generics, selfty: &clean::SelfTy,
1300 d: &clean::FnDecl) -> fmt::Result {
1301 write!(w, "{}fn <a href='\\#{ty}.{name}' class='fnname'>{name}</a>\
1304 ast::UnsafeFn => "unsafe ",
1308 name = it.name.get_ref().as_slice(),
1310 decl = Method(selfty, d))
1313 clean::TyMethodItem(ref m) => {
1314 fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl)
1316 clean::MethodItem(ref m) => {
1317 fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl)
1323 fn item_struct(w: &mut Writer, it: &clean::Item,
1324 s: &clean::Struct) -> fmt::Result {
1325 try!(write!(w, "<pre class='rust struct'>"));
1326 try!(render_struct(w,
1330 s.fields.as_slice(),
1334 try!(write!(w, "</pre>"));
1336 try!(document(w, it));
1337 match s.struct_type {
1338 doctree::Plain if s.fields.len() > 0 => {
1339 try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
1340 for field in s.fields.iter() {
1341 try!(write!(w, "<tr><td id='structfield.{name}'>\
1342 <code>{name}</code></td><td>",
1343 name = field.name.get_ref().as_slice()));
1344 try!(document(w, field));
1345 try!(write!(w, "</td></tr>"));
1347 try!(write!(w, "</table>"));
1351 render_methods(w, it)
1354 fn item_enum(w: &mut Writer, it: &clean::Item, e: &clean::Enum) -> fmt::Result {
1355 try!(write!(w, "<pre class='rust enum'>{}enum {}{}",
1356 VisSpace(it.visibility),
1357 it.name.get_ref().as_slice(),
1359 if e.variants.len() == 0 && !e.variants_stripped {
1360 try!(write!(w, " \\{\\}"));
1362 try!(write!(w, " \\{\n"));
1363 for v in e.variants.iter() {
1364 try!(write!(w, " "));
1365 let name = v.name.get_ref().as_slice();
1367 clean::VariantItem(ref var) => {
1369 clean::CLikeVariant => try!(write!(w, "{}", name)),
1370 clean::TupleVariant(ref tys) => {
1371 try!(write!(w, "{}(", name));
1372 for (i, ty) in tys.iter().enumerate() {
1374 try!(write!(w, ", "))
1376 try!(write!(w, "{}", *ty));
1378 try!(write!(w, ")"));
1380 clean::StructVariant(ref s) => {
1381 try!(render_struct(w,
1385 s.fields.as_slice(),
1394 try!(write!(w, ",\n"));
1397 if e.variants_stripped {
1398 try!(write!(w, " // some variants omitted\n"));
1400 try!(write!(w, "\\}"));
1402 try!(write!(w, "</pre>"));
1404 try!(document(w, it));
1405 if e.variants.len() > 0 {
1406 try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
1407 for variant in e.variants.iter() {
1408 try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
1409 name = variant.name.get_ref().as_slice()));
1410 try!(document(w, variant));
1411 match variant.inner {
1412 clean::VariantItem(ref var) => {
1414 clean::StructVariant(ref s) => {
1415 try!(write!(w, "<h3 class='fields'>Fields</h3>\n
1417 for field in s.fields.iter() {
1418 try!(write!(w, "<tr><td \
1419 id='variant.{v}.field.{f}'>\
1420 <code>{f}</code></td><td>",
1421 v = variant.name.get_ref().as_slice(),
1422 f = field.name.get_ref().as_slice()));
1423 try!(document(w, field));
1424 try!(write!(w, "</td></tr>"));
1426 try!(write!(w, "</table>"));
1433 try!(write!(w, "</td></tr>"));
1435 try!(write!(w, "</table>"));
1438 try!(render_methods(w, it));
1442 fn render_struct(w: &mut Writer, it: &clean::Item,
1443 g: Option<&clean::Generics>,
1444 ty: doctree::StructType,
1445 fields: &[clean::Item],
1446 fields_stripped: bool,
1448 structhead: bool) -> fmt::Result {
1449 try!(write!(w, "{}{}{}",
1450 VisSpace(it.visibility),
1451 if structhead {"struct "} else {""},
1452 it.name.get_ref().as_slice()));
1454 Some(g) => try!(write!(w, "{}", *g)),
1459 try!(write!(w, " \\{\n{}", tab));
1460 for field in fields.iter() {
1462 clean::StructFieldItem(ref ty) => {
1463 try!(write!(w, " {}{}: {},\n{}",
1464 VisSpace(field.visibility),
1465 field.name.get_ref().as_slice(),
1473 if fields_stripped {
1474 try!(write!(w, " // some fields omitted\n{}", tab));
1476 try!(write!(w, "\\}"));
1478 doctree::Tuple | doctree::Newtype => {
1479 try!(write!(w, "("));
1480 for (i, field) in fields.iter().enumerate() {
1482 try!(write!(w, ", "));
1485 clean::StructFieldItem(ref field) => {
1486 try!(write!(w, "{}", field.type_));
1491 try!(write!(w, ");"));
1494 try!(write!(w, ";"));
1500 fn render_methods(w: &mut Writer, it: &clean::Item) -> fmt::Result {
1501 local_data::get(cache_key, |cache| {
1502 let c = cache.unwrap();
1503 match c.impls.find(&it.id) {
1505 let mut non_trait = v.iter().filter(|p| {
1506 p.ref0().trait_.is_none()
1508 let non_trait = non_trait.collect::<~[&(clean::Impl, Option<~str>)]>();
1509 let mut traits = v.iter().filter(|p| {
1510 p.ref0().trait_.is_some()
1512 let traits = traits.collect::<~[&(clean::Impl, Option<~str>)]>();
1514 if non_trait.len() > 0 {
1515 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
1516 for &(ref i, ref dox) in non_trait.move_iter() {
1517 try!(render_impl(w, i, dox));
1520 if traits.len() > 0 {
1521 try!(write!(w, "<h2 id='implementations'>Trait \
1522 Implementations</h2>"));
1523 let mut any_derived = false;
1524 for & &(ref i, ref dox) in traits.iter() {
1526 try!(render_impl(w, i, dox));
1532 try!(write!(w, "<h3 id='derived_implementations'>Derived Implementations \
1534 for &(ref i, ref dox) in traits.move_iter() {
1536 try!(render_impl(w, i, dox));
1548 fn render_impl(w: &mut Writer, i: &clean::Impl,
1549 dox: &Option<~str>) -> fmt::Result {
1550 try!(write!(w, "<h3 class='impl'><code>impl{} ", i.generics));
1551 let trait_id = match i.trait_ {
1553 try!(write!(w, "{} for ", *ty));
1555 clean::ResolvedPath { id, .. } => Some(id),
1561 try!(write!(w, "{}</code></h3>", i.for_));
1564 try!(write!(w, "<div class='docblock'>{}</div>",
1565 Markdown(dox.as_slice())));
1570 fn docmeth(w: &mut Writer, item: &clean::Item) -> io::IoResult<bool> {
1571 try!(write!(w, "<h4 id='method.{}' class='method'><code>",
1572 *item.name.get_ref()));
1573 try!(render_method(w, item));
1574 try!(write!(w, "</code></h4>\n"));
1575 match item.doc_value() {
1577 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1584 try!(write!(w, "<div class='methods'>"));
1585 for meth in i.methods.iter() {
1586 if try!(docmeth(w, meth)) {
1590 // No documentation? Attempt to slurp in the trait's documentation
1591 let trait_id = match trait_id {
1595 try!(local_data::get(cache_key, |cache| {
1596 let cache = cache.unwrap();
1597 match cache.traits.find(&trait_id) {
1599 let name = meth.name.clone();
1600 match t.methods.iter().find(|t| t.item().name == name) {
1602 match method.item().doc_value() {
1605 "<div class='docblock'>{}</div>",
1620 // If we've implemented a trait, then also emit documentation for all
1621 // default methods which weren't overridden in the implementation block.
1625 try!(local_data::get(cache_key, |cache| {
1626 let cache = cache.unwrap();
1627 match cache.traits.find(&id) {
1629 for method in t.methods.iter() {
1630 let n = method.item().name.clone();
1631 match i.methods.iter().find(|m| m.name == n) {
1632 Some(..) => continue,
1636 try!(docmeth(w, method.item()));
1645 try!(write!(w, "</div>"));
1649 fn item_typedef(w: &mut Writer, it: &clean::Item,
1650 t: &clean::Typedef) -> fmt::Result {
1651 try!(write!(w, "<pre class='rust typedef'>type {}{} = {};</pre>",
1652 it.name.get_ref().as_slice(),
1659 impl<'a> fmt::Show for Sidebar<'a> {
1660 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1663 try!(write!(fmt.buf, "<p class='location'>"));
1664 let len = cx.current.len() - if it.is_mod() {1} else {0};
1665 for (i, name) in cx.current.iter().take(len).enumerate() {
1667 try!(write!(fmt.buf, "&\\#8203;::"));
1669 try!(write!(fmt.buf, "<a href='{}index.html'>{}</a>",
1672 .slice_to((cx.current.len() - i - 1) * 3),
1675 try!(write!(fmt.buf, "</p>"));
1677 fn block(w: &mut Writer, short: &str, longty: &str,
1678 cur: &clean::Item, cx: &Context) -> fmt::Result {
1679 let items = match cx.sidebar.find_equiv(&short) {
1680 Some(items) => items.as_slice(),
1681 None => return Ok(())
1683 try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
1684 for item in items.iter() {
1685 let class = if cur.name.get_ref() == item &&
1686 short == shortty(cur) { "current" } else { "" };
1687 try!(write!(w, "<a class='{ty} {class}' href='{curty, select,
1691 mod{{name}/index.html}
1692 other{#.{name}.html}
1693 }'>{name}</a><br/>",
1697 curty = shortty(cur),
1698 name = item.as_slice()));
1700 try!(write!(w, "</div>"));
1704 try!(block(fmt.buf, "mod", "Modules", it, cx));
1705 try!(block(fmt.buf, "struct", "Structs", it, cx));
1706 try!(block(fmt.buf, "enum", "Enums", it, cx));
1707 try!(block(fmt.buf, "trait", "Traits", it, cx));
1708 try!(block(fmt.buf, "fn", "Functions", it, cx));
1713 fn build_sidebar(m: &clean::Module) -> HashMap<~str, Vec<~str> > {
1714 let mut map = HashMap::new();
1715 for item in m.items.iter() {
1716 let short = shortty(item);
1717 let myname = match item.name {
1719 Some(ref s) => s.to_owned(),
1721 let v = map.find_or_insert_with(short.to_owned(), |_| Vec::new());
1725 for (_, items) in map.mut_iter() {
1726 items.as_mut_slice().sort();
1731 impl<'a> fmt::Show for Source<'a> {
1732 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1733 let Source(s) = *self;
1734 let lines = s.lines().len();
1736 let mut tmp = lines;
1741 try!(write!(fmt.buf, "<pre class='line-numbers'>"));
1742 for i in range(1, lines + 1) {
1743 try!(write!(fmt.buf, "<span id='{0:u}'>{0:1$u}</span>\n", i, cols));
1745 try!(write!(fmt.buf, "</pre>"));
1746 try!(write!(fmt.buf, "{}", highlight::highlight(s.as_slice(), None)));
1751 fn item_macro(w: &mut Writer, it: &clean::Item,
1752 t: &clean::Macro) -> fmt::Result {
1753 try!(w.write_str(highlight::highlight(t.source, Some("macro"))));