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.
39 use std::io::{fs, File, BufferedWriter, MemWriter, BufferedReader};
42 use collections::{HashMap, HashSet};
45 use serialize::json::ToJson;
48 use syntax::parse::token::InternedString;
49 use rustc::util::nodemap::NodeSet;
54 use html::format::{VisSpace, Method, PuritySpace};
57 use html::markdown::Markdown;
60 /// Major driving force in all rustdoc rendering. This contains information
61 /// about where in the tree-like hierarchy rendering is occurring and controls
62 /// how the current page is being rendered.
64 /// It is intended that this context is a lightweight object which can be fairly
65 /// easily cloned because it is cloned per work-job (about once per item in the
69 /// Current hierarchy of components leading down to what's currently being
72 /// String representation of how to get back to the root path of the 'doc/'
73 /// folder in terms of a relative URL.
75 /// The current destination folder of where HTML artifacts should be placed.
76 /// This changes as the context descends into the module hierarchy.
78 /// This describes the layout of each page, and is not modified after
79 /// creation of the context (contains info like the favicon)
80 layout: layout::Layout,
81 /// This map is a list of what should be displayed on the sidebar of the
82 /// current page. The key is the section header (traits, modules,
83 /// functions), and the value is the list of containers belonging to this
84 /// header. This map will change depending on the surrounding context of the
86 sidebar: HashMap<~str, Vec<~str> >,
87 /// This flag indicates whether [src] links should be generated or not. If
88 /// the source files are present in the html rendering, then this will be
90 include_sources: bool,
93 /// Indicates where an external crate can be found.
94 pub enum ExternalLocation {
95 /// Remote URL root of the external crate
97 /// This external crate can be found in the local doc/ folder
99 /// The external crate could not be found.
103 /// Different ways an implementor of a trait can be rendered.
104 pub enum Implementor {
105 /// Paths are displayed specially by omitting the `impl XX for` cruft
106 PathType(clean::Type),
107 /// This is the generic representation of a trait implementor, used for
108 /// primitive types and otherwise non-path types.
109 OtherType(clean::Generics, /* trait */ clean::Type, /* for */ clean::Type),
112 /// This cache is used to store information about the `clean::Crate` being
113 /// rendered in order to provide more useful documentation. This contains
114 /// information like all implementors of a trait, all traits a type implements,
115 /// documentation for all known traits, etc.
117 /// This structure purposefully does not implement `Clone` because it's intended
118 /// to be a fairly large and expensive structure to clone. Instead this adheres
119 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
122 /// Mapping of typaram ids to the name of the type parameter. This is used
123 /// when pretty-printing a type (so pretty printing doesn't have to
124 /// painfully maintain a context like this)
125 typarams: HashMap<ast::NodeId, ~str>,
127 /// Maps a type id to all known implementations for that type. This is only
128 /// recognized for intra-crate `ResolvedPath` types, and is used to print
129 /// out extra documentation on the page of an enum/struct.
131 /// The values of the map are a list of implementations and documentation
132 /// found on that implementation.
133 impls: HashMap<ast::NodeId, Vec<(clean::Impl, Option<~str>)> >,
135 /// Maintains a mapping of local crate node ids to the fully qualified name
136 /// and "short type description" of that node. This is used when generating
137 /// URLs when a type is being linked to. External paths are not located in
138 /// this map because the `External` type itself has all the information
140 paths: HashMap<ast::NodeId, (Vec<~str> , &'static str)>,
142 /// This map contains information about all known traits of this crate.
143 /// Implementations of a crate should inherit the documentation of the
144 /// parent trait if no extra documentation is specified, and default methods
145 /// should show up in documentation about trait implementations.
146 traits: HashMap<ast::NodeId, clean::Trait>,
148 /// When rendering traits, it's often useful to be able to list all
149 /// implementors of the trait, and this mapping is exactly, that: a mapping
150 /// of trait ids to the list of known implementors of the trait
151 implementors: HashMap<ast::NodeId, Vec<Implementor> >,
153 /// Cache of where external crate documentation can be found.
154 extern_locations: HashMap<ast::CrateNum, ExternalLocation>,
156 // Private fields only used when initially crawling a crate to build a cache
158 priv stack: Vec<~str> ,
159 priv parent_stack: Vec<ast::NodeId> ,
160 priv search_index: Vec<IndexItem> ,
162 priv public_items: NodeSet,
164 // In rare case where a structure is defined in one module but implemented
165 // in another, if the implementing module is parsed before defining module,
166 // then the fully qualified name of the structure isn't presented in `paths`
167 // yet when its implementation methods are being indexed. Caches such methods
168 // and their parent id here and indexes them at the end of crate parsing.
169 priv orphan_methods: Vec<(ast::NodeId, clean::Item)>,
172 /// Helper struct to render all source code to HTML pages
173 struct SourceCollector<'a> {
176 /// Processed source-file paths
178 /// Root destination to place all HTML output into
182 /// Wrapper struct to render the source code of a file. This will do things like
183 /// adding line numbers to the left-hand side.
184 struct Source<'a>(&'a str);
186 // Helper structs for rendering items/sidebars and carrying along contextual
189 struct Item<'a> { cx: &'a Context, item: &'a clean::Item, }
190 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
192 /// Struct representing one entry in the JS search index. These are all emitted
193 /// by hand to a large JS file at the end of cache-creation.
199 parent: Option<ast::NodeId>,
202 // TLS keys used to carry information around during rendering.
204 local_data_key!(pub cache_key: Arc<Cache>)
205 local_data_key!(pub current_location_key: Vec<~str> )
207 /// Generates the documentation for `crate` into the directory `dst`
208 pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> {
209 let mut cx = Context {
213 sidebar: HashMap::new(),
214 layout: layout::Layout {
217 krate: krate.name.clone(),
219 include_sources: true,
221 try!(mkdir(&cx.dst));
223 match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(&[])) {
225 for attr in attrs.iter() {
227 clean::NameValue(ref x, ref s) if "html_favicon_url" == *x => {
228 cx.layout.favicon = s.to_owned();
230 clean::NameValue(ref x, ref s) if "html_logo_url" == *x => {
231 cx.layout.logo = s.to_owned();
233 clean::Word(ref x) if "html_no_source" == *x => {
234 cx.include_sources = false;
243 // Crawl the crate to build various caches used for the output
244 let mut cache = local_data::get(::analysiskey, |analysis| {
245 let public_items = analysis.map(|a| a.public_items.clone());
246 let public_items = public_items.unwrap_or(NodeSet::new());
248 impls: HashMap::new(),
249 typarams: HashMap::new(),
250 paths: HashMap::new(),
251 traits: HashMap::new(),
252 implementors: HashMap::new(),
254 parent_stack: Vec::new(),
255 search_index: Vec::new(),
256 extern_locations: HashMap::new(),
258 public_items: public_items,
259 orphan_methods: Vec::new(),
262 cache.stack.push(krate.name.clone());
263 krate = cache.fold_crate(krate);
265 // Attach all orphan methods to the type's definition if the type
266 // has since been learned.
267 let Cache { search_index: ref mut index,
268 orphan_methods: ref meths, paths: ref paths, ..} = cache;
269 for &(ref pid, ref item) in meths.iter() {
270 match paths.find(pid) {
271 Some(&(ref fqp, _)) => {
272 index.push(IndexItem {
274 name: item.name.clone().unwrap(),
275 path: fqp.slice_to(fqp.len() - 1).connect("::"),
276 desc: shorter(item.doc_value()).to_owned(),
285 // Publish the search index
287 let mut w = MemWriter::new();
288 try!(write!(&mut w, "searchIndex['{}'] = [", krate.name));
289 for (i, item) in cache.search_index.iter().enumerate() {
291 try!(write!(&mut w, ","));
293 try!(write!(&mut w, "\\{ty:\"{}\",name:\"{}\",path:\"{}\",desc:{}",
294 item.ty, item.name, item.path,
295 item.desc.to_json().to_str()));
298 try!(write!(&mut w, ",parent:'{}'", id));
302 try!(write!(&mut w, "\\}"));
304 try!(write!(&mut w, "];"));
305 try!(write!(&mut w, "allPaths['{}'] = \\{", krate.name));
306 for (i, (&id, &(ref fqp, short))) in cache.paths.iter().enumerate() {
308 try!(write!(&mut w, ","));
310 try!(write!(&mut w, "'{}':\\{type:'{}',name:'{}'\\}",
311 id, short, *fqp.last().unwrap()));
313 try!(write!(&mut w, "\\};"));
315 str::from_utf8_owned(w.unwrap()).unwrap()
318 // Write out the shared files. Note that these are shared among all rustdoc
319 // docs placed in the output directory, so this needs to be a synchronized
320 // operation with respect to all other rustdocs running around.
322 try!(mkdir(&cx.dst));
323 let _lock = ::flock::Lock::new(&cx.dst.join(".lock"));
325 // Add all the static files. These may already exist, but we just
326 // overwrite them anyway to make sure that they're fresh and up-to-date.
327 try!(write(cx.dst.join("jquery.js"),
328 include_str!("static/jquery-2.1.0.min.js")));
329 try!(write(cx.dst.join("main.js"), include_str!("static/main.js")));
330 try!(write(cx.dst.join("main.css"), include_str!("static/main.css")));
331 try!(write(cx.dst.join("normalize.css"),
332 include_str!("static/normalize.css")));
334 // Update the search index
335 let dst = cx.dst.join("search-index.js");
336 let mut all_indexes = Vec::new();
337 all_indexes.push(index);
339 for line in BufferedReader::new(File::open(&dst)).lines() {
340 let line = try!(line);
341 if !line.starts_with("searchIndex") { continue }
342 if line.starts_with(format!("searchIndex['{}']", krate.name)) {
345 all_indexes.push(line);
348 let mut w = try!(File::create(&dst));
349 try!(writeln!(&mut w, r"var searchIndex = \{\}; var allPaths = \{\};"));
350 for index in all_indexes.iter() {
351 try!(writeln!(&mut w, "{}", *index));
353 try!(writeln!(&mut w, "initSearch(searchIndex);"));
356 // Render all source files (this may turn into a giant no-op)
358 info!("emitting source files");
359 let dst = cx.dst.join("src");
361 let dst = dst.join(krate.name.as_slice());
363 let mut folder = SourceCollector {
365 seen: HashSet::new(),
368 krate = folder.fold_crate(krate);
371 for &(n, ref e) in krate.externs.iter() {
372 cache.extern_locations.insert(n, extern_location(e, &cx.dst));
375 // And finally render the whole crate's documentation
376 cx.krate(krate, cache)
379 /// Writes the entire contents of a string to a destination, not attempting to
380 /// catch any errors.
381 fn write(dst: Path, contents: &str) -> io::IoResult<()> {
382 File::create(&dst).write(contents.as_bytes())
385 /// Makes a directory on the filesystem, failing the task if an error occurs and
386 /// skipping if the directory already exists.
387 fn mkdir(path: &Path) -> io::IoResult<()> {
389 fs::mkdir(path, io::UserRWX)
395 /// Takes a path to a source file and cleans the path to it. This canonicalizes
396 /// things like ".." to components which preserve the "top down" hierarchy of a
397 /// static HTML tree.
398 // FIXME (#9639): The closure should deal with &[u8] instead of &str
399 fn clean_srcpath(src: &[u8], f: |&str|) {
400 let p = Path::new(src);
401 if p.as_vec() != bytes!(".") {
402 for c in p.str_components().map(|x|x.unwrap()) {
412 /// Attempts to find where an external crate is located, given that we're
413 /// rendering in to the specified source destination.
414 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
415 // See if there's documentation generated into the local directory
416 let local_location = dst.join(e.name.as_slice());
417 if local_location.is_dir() {
421 // Failing that, see if there's an attribute specifying where to find this
423 for attr in e.attrs.iter() {
425 clean::List(ref x, ref list) if "doc" == *x => {
426 for attr in list.iter() {
428 clean::NameValue(ref x, ref s) if "html_root_url" == *x => {
429 if s.ends_with("/") {
430 return Remote(s.to_owned());
432 return Remote(*s + "/");
442 // Well, at least we tried.
446 impl<'a> DocFolder for SourceCollector<'a> {
447 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
448 // If we're including source files, and we haven't seen this file yet,
449 // then we need to render it out to the filesystem
450 if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
452 // If it turns out that we couldn't read this file, then we probably
453 // can't read any of the files (generating html output from json or
454 // something like that), so just don't include sources for the
455 // entire crate. The other option is maintaining this mapping on a
456 // per-file basis, but that's probably not worth it...
457 self.cx.include_sources = match self.emit_source(item.source.filename) {
460 println!("warning: source code was requested to be rendered, \
461 but processing `{}` had an error: {}",
462 item.source.filename, e);
463 println!(" skipping rendering of source code");
467 self.seen.insert(item.source.filename.clone());
470 self.fold_item_recur(item)
474 impl<'a> SourceCollector<'a> {
475 /// Renders the given filename into its corresponding HTML source file.
476 fn emit_source(&mut self, filename: &str) -> io::IoResult<()> {
477 let p = Path::new(filename);
479 // If we couldn't open this file, then just returns because it
480 // probably means that it's some standard library macro thing and we
481 // can't have the source to it anyway.
482 let contents = match File::open(&p).read_to_end() {
484 // macros from other libraries get special filenames which we can
486 Err(..) if filename.starts_with("<") &&
487 filename.ends_with("macros>") => return Ok(()),
488 Err(e) => return Err(e)
490 let contents = str::from_utf8_owned(contents).unwrap();
492 // Remove the utf-8 BOM if any
493 let contents = if contents.starts_with("\ufeff") {
494 contents.as_slice().slice_from(3)
499 // Create the intermediate directories
500 let mut cur = self.dst.clone();
501 let mut root_path = ~"../../";
502 clean_srcpath(p.dirname(), |component| {
504 mkdir(&cur).unwrap();
505 root_path.push_str("../");
508 cur.push(p.filename().expect("source has no filename") + bytes!(".html"));
509 let mut w = BufferedWriter::new(try!(File::create(&cur)));
511 let title = format!("{} -- source", cur.filename_display());
512 let page = layout::Page {
515 root_path: root_path,
517 try!(layout::render(&mut w as &mut Writer, &self.cx.layout,
518 &page, &(""), &Source(contents)));
524 impl DocFolder for Cache {
525 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
526 // If this is a private module, we don't want it in the search index.
527 let orig_privmod = match item.inner {
528 clean::ModuleItem(..) => {
529 let prev = self.privmod;
530 self.privmod = prev || item.visibility != Some(ast::Public);
536 // Register any generics to their corresponding string. This is used
537 // when pretty-printing types
539 clean::StructItem(ref s) => self.generics(&s.generics),
540 clean::EnumItem(ref e) => self.generics(&e.generics),
541 clean::FunctionItem(ref f) => self.generics(&f.generics),
542 clean::TypedefItem(ref t) => self.generics(&t.generics),
543 clean::TraitItem(ref t) => self.generics(&t.generics),
544 clean::ImplItem(ref i) => self.generics(&i.generics),
545 clean::TyMethodItem(ref i) => self.generics(&i.generics),
546 clean::MethodItem(ref i) => self.generics(&i.generics),
547 clean::ForeignFunctionItem(ref f) => self.generics(&f.generics),
551 // Propagate a trait methods' documentation to all implementors of the
554 clean::TraitItem(ref t) => {
555 self.traits.insert(item.id, t.clone());
560 // Collect all the implementors of traits.
562 clean::ImplItem(ref i) => {
564 Some(clean::ResolvedPath{ id, .. }) => {
565 let v = self.implementors.find_or_insert_with(id, |_|{
569 clean::ResolvedPath{..} => {
570 v.unshift(PathType(i.for_.clone()));
573 v.push(OtherType(i.generics.clone(),
574 i.trait_.get_ref().clone(),
579 Some(..) | None => {}
585 // Index this method for searching later on
588 let parent = match item.inner {
589 clean::TyMethodItem(..) |
590 clean::StructFieldItem(..) |
591 clean::VariantItem(..) => {
592 (Some(*self.parent_stack.last().unwrap()),
593 Some(self.stack.slice_to(self.stack.len() - 1)))
596 clean::MethodItem(..) => {
597 if self.parent_stack.len() == 0 {
600 let last = self.parent_stack.last().unwrap();
601 let path = match self.paths.find(last) {
602 Some(&(_, "trait")) =>
603 Some(self.stack.slice_to(self.stack.len() - 1)),
604 // The current stack not necessarily has correlation for
605 // where the type was defined. On the other hand,
606 // `paths` always has the right information if present.
607 Some(&(ref fqp, "struct")) | Some(&(ref fqp, "enum")) =>
608 Some(fqp.slice_to(fqp.len() - 1)),
609 Some(..) => Some(self.stack.as_slice()),
615 _ => (None, Some(self.stack.as_slice()))
618 (parent, Some(path)) if !self.privmod => {
619 self.search_index.push(IndexItem {
622 path: path.connect("::"),
623 desc: shorter(item.doc_value()).to_owned(),
627 (Some(parent), None) if !self.privmod => {
628 // We have a parent, but we don't know where they're
629 // defined yet. Wait for later to index this item.
630 self.orphan_methods.push((parent, item.clone()))
638 // Keep track of the fully qualified path for this item.
639 let pushed = if item.name.is_some() {
640 let n = item.name.get_ref();
642 self.stack.push(n.to_owned());
647 clean::StructItem(..) | clean::EnumItem(..) |
648 clean::TypedefItem(..) | clean::TraitItem(..) |
649 clean::FunctionItem(..) | clean::ModuleItem(..) |
650 clean::ForeignFunctionItem(..) => {
651 // Reexported items mean that the same id can show up twice in
652 // the rustdoc ast that we're looking at. We know, however, that
653 // a reexported item doesn't show up in the `public_items` map,
654 // so we can skip inserting into the paths map if there was
655 // already an entry present and we're not a public item.
656 if !self.paths.contains_key(&item.id) ||
657 self.public_items.contains(&item.id) {
658 self.paths.insert(item.id,
659 (self.stack.clone(), shortty(&item)));
662 // link variants to their parent enum because pages aren't emitted
664 clean::VariantItem(..) => {
665 let mut stack = self.stack.clone();
667 self.paths.insert(item.id, (stack, "enum"));
672 // Maintain the parent stack
673 let parent_pushed = match item.inner {
674 clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
675 self.parent_stack.push(item.id); true
677 clean::ImplItem(ref i) => {
679 clean::ResolvedPath{ id, .. } => {
680 self.parent_stack.push(id); true
688 // Once we've recursively found all the generics, then hoard off all the
689 // implementations elsewhere
690 let ret = match self.fold_item_recur(item) {
693 clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
695 clean::ResolvedPath { id, .. } => {
696 let v = self.impls.find_or_insert_with(id, |_| {
699 // extract relevant documentation for this impl
700 match attrs.move_iter().find(|a| {
702 clean::NameValue(ref x, _) if "doc" == *x => true,
706 Some(clean::NameValue(_, dox)) => {
707 v.push((i, Some(dox)));
718 // Private modules may survive the strip-private pass if
719 // they contain impls for public types, but those will get
721 clean::Item { inner: clean::ModuleItem(ref m),
723 if (m.items.len() == 0 &&
724 item.doc_value().is_none()) ||
725 visibility != Some(ast::Public) => None,
733 if pushed { self.stack.pop().unwrap(); }
734 if parent_pushed { self.parent_stack.pop().unwrap(); }
735 self.privmod = orig_privmod;
741 fn generics(&mut self, generics: &clean::Generics) {
742 for typ in generics.type_params.iter() {
743 self.typarams.insert(typ.id, typ.name.clone());
749 /// Recurse in the directory structure and change the "root path" to make
750 /// sure it always points to the top (relatively)
751 fn recurse<T>(&mut self, s: ~str, f: |&mut Context| -> T) -> T {
753 fail!("what {:?}", self);
755 let prev = self.dst.clone();
756 self.dst.push(s.as_slice());
757 self.root_path.push_str("../");
758 self.current.push(s);
760 info!("Recursing into {}", self.dst.display());
762 mkdir(&self.dst).unwrap();
765 info!("Recursed; leaving {}", self.dst.display());
767 // Go back to where we were at
769 let len = self.root_path.len();
770 self.root_path.truncate(len - 3);
771 self.current.pop().unwrap();
776 /// Main method for rendering a crate.
778 /// This currently isn't parallelized, but it'd be pretty easy to add
779 /// parallelization to this function.
780 fn krate(self, mut krate: clean::Crate, cache: Cache) -> io::IoResult<()> {
781 let mut item = match krate.module.take() {
783 None => return Ok(())
785 item.name = Some(krate.name);
787 // using a rwarc makes this parallelizable in the future
788 local_data::set(cache_key, Arc::new(cache));
790 let mut work = vec!((self, item));
793 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
794 work.push((cx.clone(), item));
802 /// Non-parellelized version of rendering an item. This will take the input
803 /// item, render its contents, and then invoke the specified closure with
804 /// all sub-items which need to be rendered.
806 /// The rendering driver uses this closure to queue up more work.
807 fn item(&mut self, item: clean::Item,
808 f: |&mut Context, clean::Item|) -> io::IoResult<()> {
809 fn render(w: io::File, cx: &mut Context, it: &clean::Item,
810 pushname: bool) -> io::IoResult<()> {
811 info!("Rendering an item to {}", w.path().display());
812 // A little unfortunate that this is done like this, but it sure
813 // does make formatting *a lot* nicer.
814 local_data::set(current_location_key, cx.current.clone());
816 let mut title = cx.current.connect("::");
818 if title.len() > 0 { title.push_str("::"); }
819 title.push_str(*it.name.get_ref());
821 title.push_str(" - Rust");
822 let page = layout::Page {
824 root_path: cx.root_path,
828 markdown::reset_headers();
830 // We have a huge number of calls to write, so try to alleviate some
831 // of the pain by using a buffered writer instead of invoking the
832 // write sycall all the time.
833 let mut writer = BufferedWriter::new(w);
834 try!(layout::render(&mut writer as &mut Writer, &cx.layout, &page,
835 &Sidebar{ cx: cx, item: it },
836 &Item{ cx: cx, item: it }));
841 // modules are special because they add a namespace. We also need to
842 // recurse into the items of the module as well.
843 clean::ModuleItem(..) => {
844 let name = item.name.get_ref().to_owned();
845 let mut item = Some(item);
846 self.recurse(name, |this| {
847 let item = item.take_unwrap();
848 let dst = this.dst.join("index.html");
849 let dst = try!(File::create(&dst));
850 try!(render(dst, this, &item, false));
852 let m = match item.inner {
853 clean::ModuleItem(m) => m,
856 this.sidebar = build_sidebar(&m);
857 for item in m.items.move_iter() {
864 // Things which don't have names (like impls) don't get special
865 // pages dedicated to them.
866 _ if item.name.is_some() => {
867 let dst = self.dst.join(item_path(&item));
868 let dst = try!(File::create(&dst));
869 render(dst, self, &item, true)
877 fn shortty(item: &clean::Item) -> &'static str {
879 clean::ModuleItem(..) => "mod",
880 clean::StructItem(..) => "struct",
881 clean::EnumItem(..) => "enum",
882 clean::FunctionItem(..) => "fn",
883 clean::TypedefItem(..) => "typedef",
884 clean::StaticItem(..) => "static",
885 clean::TraitItem(..) => "trait",
886 clean::ImplItem(..) => "impl",
887 clean::ViewItemItem(..) => "viewitem",
888 clean::TyMethodItem(..) => "tymethod",
889 clean::MethodItem(..) => "method",
890 clean::StructFieldItem(..) => "structfield",
891 clean::VariantItem(..) => "variant",
892 clean::ForeignFunctionItem(..) => "ffi",
893 clean::ForeignStaticItem(..) => "ffs",
894 clean::MacroItem(..) => "macro",
899 fn ismodule(&self) -> bool {
900 match self.item.inner {
901 clean::ModuleItem(..) => true, _ => false
906 impl<'a> fmt::Show for Item<'a> {
907 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
908 match attr::find_stability(self.item.attrs.iter()) {
909 Some(ref stability) => {
911 "<a class='stability {lvl}' title='{reason}'>{lvl}</a>",
912 lvl = stability.level.to_str(),
913 reason = match stability.text {
914 Some(ref s) => (*s).clone(),
915 None => InternedString::new(""),
921 if self.cx.include_sources {
922 let mut path = Vec::new();
923 clean_srcpath(self.item.source.filename.as_bytes(), |component| {
924 path.push(component.to_owned());
926 let href = if self.item.source.loline == self.item.source.hiline {
927 format!("{}", self.item.source.loline)
929 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
933 href='{root}src/{krate}/{path}.html\\#{href}'>\
935 root = self.cx.root_path,
936 krate = self.cx.layout.krate,
937 path = path.connect("/"),
941 // Write the breadcrumb trail header for the top
942 try!(write!(fmt.buf, "<h1 class='fqn'>"));
943 match self.item.inner {
944 clean::ModuleItem(ref m) => if m.is_crate {
945 try!(write!(fmt.buf, "Crate "));
947 try!(write!(fmt.buf, "Module "));
949 clean::FunctionItem(..) => try!(write!(fmt.buf, "Function ")),
950 clean::TraitItem(..) => try!(write!(fmt.buf, "Trait ")),
951 clean::StructItem(..) => try!(write!(fmt.buf, "Struct ")),
952 clean::EnumItem(..) => try!(write!(fmt.buf, "Enum ")),
955 let cur = self.cx.current.as_slice();
956 let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
957 for (i, component) in cur.iter().enumerate().take(amt) {
959 for _ in range(0, cur.len() - i - 1) {
960 trail.push_str("../");
962 try!(write!(fmt.buf, "<a href='{}index.html'>{}</a>::",
963 trail, component.as_slice()));
965 try!(write!(fmt.buf, "<a class='{}' href=''>{}</a></h1>",
966 shortty(self.item), self.item.name.get_ref().as_slice()));
968 match self.item.inner {
969 clean::ModuleItem(ref m) => {
970 item_module(fmt.buf, self.cx, self.item, m.items.as_slice())
972 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
973 item_function(fmt.buf, self.item, f),
974 clean::TraitItem(ref t) => item_trait(fmt.buf, self.item, t),
975 clean::StructItem(ref s) => item_struct(fmt.buf, self.item, s),
976 clean::EnumItem(ref e) => item_enum(fmt.buf, self.item, e),
977 clean::TypedefItem(ref t) => item_typedef(fmt.buf, self.item, t),
978 clean::MacroItem(ref m) => item_macro(fmt.buf, self.item, m),
984 fn item_path(item: &clean::Item) -> ~str {
986 clean::ModuleItem(..) => *item.name.get_ref() + "/index.html",
987 _ => shortty(item) + "." + *item.name.get_ref() + ".html"
991 fn full_path(cx: &Context, item: &clean::Item) -> ~str {
992 let mut s = cx.current.connect("::");
994 s.push_str(item.name.get_ref().as_slice());
998 fn blank<'a>(s: Option<&'a str>) -> &'a str {
1005 fn shorter<'a>(s: Option<&'a str>) -> &'a str {
1007 Some(s) => match s.find_str("\n\n") {
1008 Some(pos) => s.slice_to(pos),
1015 fn document(w: &mut Writer, item: &clean::Item) -> fmt::Result {
1016 match item.doc_value() {
1018 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1025 fn item_module(w: &mut Writer, cx: &Context,
1026 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1027 try!(document(w, item));
1028 debug!("{:?}", items);
1029 let mut indices = slice::from_fn(items.len(), |i| i);
1031 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering {
1032 if shortty(i1) == shortty(i2) {
1033 return i1.name.cmp(&i2.name);
1035 match (&i1.inner, &i2.inner) {
1036 (&clean::ViewItemItem(ref a), &clean::ViewItemItem(ref b)) => {
1037 match (&a.inner, &b.inner) {
1038 (&clean::ExternCrate(..), _) => Less,
1039 (_, &clean::ExternCrate(..)) => Greater,
1040 _ => idx1.cmp(&idx2),
1043 (&clean::ViewItemItem(..), _) => Less,
1044 (_, &clean::ViewItemItem(..)) => Greater,
1045 (&clean::ModuleItem(..), _) => Less,
1046 (_, &clean::ModuleItem(..)) => Greater,
1047 (&clean::MacroItem(..), _) => Less,
1048 (_, &clean::MacroItem(..)) => Greater,
1049 (&clean::StructItem(..), _) => Less,
1050 (_, &clean::StructItem(..)) => Greater,
1051 (&clean::EnumItem(..), _) => Less,
1052 (_, &clean::EnumItem(..)) => Greater,
1053 (&clean::StaticItem(..), _) => Less,
1054 (_, &clean::StaticItem(..)) => Greater,
1055 (&clean::ForeignFunctionItem(..), _) => Less,
1056 (_, &clean::ForeignFunctionItem(..)) => Greater,
1057 (&clean::ForeignStaticItem(..), _) => Less,
1058 (_, &clean::ForeignStaticItem(..)) => Greater,
1059 (&clean::TraitItem(..), _) => Less,
1060 (_, &clean::TraitItem(..)) => Greater,
1061 (&clean::FunctionItem(..), _) => Less,
1062 (_, &clean::FunctionItem(..)) => Greater,
1063 (&clean::TypedefItem(..), _) => Less,
1064 (_, &clean::TypedefItem(..)) => Greater,
1065 _ => idx1.cmp(&idx2),
1069 debug!("{:?}", indices);
1070 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1072 debug!("{:?}", indices);
1074 for &idx in indices.iter() {
1075 let myitem = &items[idx];
1077 let myty = shortty(myitem);
1080 try!(write!(w, "</table>"));
1083 let (short, name) = match myitem.inner {
1084 clean::ModuleItem(..) => ("modules", "Modules"),
1085 clean::StructItem(..) => ("structs", "Structs"),
1086 clean::EnumItem(..) => ("enums", "Enums"),
1087 clean::FunctionItem(..) => ("functions", "Functions"),
1088 clean::TypedefItem(..) => ("types", "Type Definitions"),
1089 clean::StaticItem(..) => ("statics", "Statics"),
1090 clean::TraitItem(..) => ("traits", "Traits"),
1091 clean::ImplItem(..) => ("impls", "Implementations"),
1092 clean::ViewItemItem(..) => ("reexports", "Reexports"),
1093 clean::TyMethodItem(..) => ("tymethods", "Type Methods"),
1094 clean::MethodItem(..) => ("methods", "Methods"),
1095 clean::StructFieldItem(..) => ("fields", "Struct Fields"),
1096 clean::VariantItem(..) => ("variants", "Variants"),
1097 clean::ForeignFunctionItem(..) => ("ffi-fns", "Foreign Functions"),
1098 clean::ForeignStaticItem(..) => ("ffi-statics", "Foreign Statics"),
1099 clean::MacroItem(..) => ("macros", "Macros"),
1102 "<h2 id='{id}' class='section-link'>\
1103 <a href=\"\\#{id}\">{name}</a></h2>\n<table>",
1104 id = short, name = name));
1107 match myitem.inner {
1108 clean::StaticItem(ref s) | clean::ForeignStaticItem(ref s) => {
1109 struct Initializer<'a>(&'a str);
1110 impl<'a> fmt::Show for Initializer<'a> {
1111 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1112 let Initializer(s) = *self;
1113 if s.len() == 0 { return Ok(()); }
1114 try!(write!(f.buf, "<code> = </code>"));
1115 let tag = if s.contains("\n") { "pre" } else { "code" };
1116 try!(write!(f.buf, "<{tag}>{}</{tag}>",
1117 s.as_slice(), tag=tag));
1124 <td><code>{}static {}: {}</code>{}</td>
1125 <td class='docblock'>{} </td>
1128 VisSpace(myitem.visibility),
1129 *myitem.name.get_ref(),
1131 Initializer(s.expr),
1132 Markdown(blank(myitem.doc_value()))));
1135 clean::ViewItemItem(ref item) => {
1137 clean::ExternCrate(ref name, ref src, _) => {
1138 try!(write!(w, "<tr><td><code>extern crate {}",
1141 Some(ref src) => try!(write!(w, " = \"{}\"",
1145 try!(write!(w, ";</code></td></tr>"));
1148 clean::Import(ref imports) => {
1149 for import in imports.iter() {
1150 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1151 VisSpace(myitem.visibility),
1160 if myitem.name.is_none() { continue }
1163 <td><a class='{class}' href='{href}'
1164 title='{title}'>{}</a></td>
1165 <td class='docblock short'>{}</td>
1168 *myitem.name.get_ref(),
1169 Markdown(shorter(myitem.doc_value())),
1170 class = shortty(myitem),
1171 href = item_path(myitem),
1172 title = full_path(cx, myitem)));
1176 write!(w, "</table>")
1179 fn item_function(w: &mut Writer, it: &clean::Item,
1180 f: &clean::Function) -> fmt::Result {
1181 try!(write!(w, "<pre class='rust fn'>{vis}{purity}fn \
1182 {name}{generics}{decl}</pre>",
1183 vis = VisSpace(it.visibility),
1184 purity = PuritySpace(f.purity),
1185 name = it.name.get_ref().as_slice(),
1186 generics = f.generics,
1191 fn item_trait(w: &mut Writer, it: &clean::Item,
1192 t: &clean::Trait) -> fmt::Result {
1193 let mut parents = ~"";
1194 if t.parents.len() > 0 {
1195 parents.push_str(": ");
1196 for (i, p) in t.parents.iter().enumerate() {
1197 if i > 0 { parents.push_str(" + "); }
1198 parents.push_str(format!("{}", *p));
1202 // Output the trait definition
1203 try!(write!(w, "<pre class='rust trait'>{}trait {}{}{} ",
1204 VisSpace(it.visibility),
1205 it.name.get_ref().as_slice(),
1208 let required = t.methods.iter().filter(|m| m.is_req()).collect::<~[&clean::TraitMethod]>();
1209 let provided = t.methods.iter().filter(|m| !m.is_req()).collect::<~[&clean::TraitMethod]>();
1211 if t.methods.len() == 0 {
1212 try!(write!(w, "\\{ \\}"));
1214 try!(write!(w, "\\{\n"));
1215 for m in required.iter() {
1216 try!(write!(w, " "));
1217 try!(render_method(w, m.item()));
1218 try!(write!(w, ";\n"));
1220 if required.len() > 0 && provided.len() > 0 {
1221 try!(w.write("\n".as_bytes()));
1223 for m in provided.iter() {
1224 try!(write!(w, " "));
1225 try!(render_method(w, m.item()));
1226 try!(write!(w, " \\{ ... \\}\n"));
1228 try!(write!(w, "\\}"));
1230 try!(write!(w, "</pre>"));
1232 // Trait documentation
1233 try!(document(w, it));
1235 fn meth(w: &mut Writer, m: &clean::TraitMethod) -> fmt::Result {
1236 try!(write!(w, "<h3 id='{}.{}' class='method'><code>",
1238 *m.item().name.get_ref()));
1239 try!(render_method(w, m.item()));
1240 try!(write!(w, "</code></h3>"));
1241 try!(document(w, m.item()));
1245 // Output the documentation for each function individually
1246 if required.len() > 0 {
1248 <h2 id='required-methods'>Required Methods</h2>
1249 <div class='methods'>
1251 for m in required.iter() {
1254 try!(write!(w, "</div>"));
1256 if provided.len() > 0 {
1258 <h2 id='provided-methods'>Provided Methods</h2>
1259 <div class='methods'>
1261 for m in provided.iter() {
1264 try!(write!(w, "</div>"));
1267 local_data::get(cache_key, |cache| {
1268 let cache = cache.unwrap().get();
1269 match cache.implementors.find(&it.id) {
1270 Some(implementors) => {
1272 <h2 id='implementors'>Implementors</h2>
1273 <ul class='item-list'>
1275 for i in implementors.iter() {
1277 PathType(ref ty) => {
1278 try!(write!(w, "<li><code>{}</code></li>", *ty));
1280 OtherType(ref generics, ref trait_, ref for_) => {
1281 try!(write!(w, "<li><code>impl{} {} for {}</code></li>",
1282 *generics, *trait_, *for_));
1286 try!(write!(w, "</ul>"));
1294 fn render_method(w: &mut Writer, meth: &clean::Item) -> fmt::Result {
1295 fn fun(w: &mut Writer, it: &clean::Item, purity: ast::Purity,
1296 g: &clean::Generics, selfty: &clean::SelfTy,
1297 d: &clean::FnDecl) -> fmt::Result {
1298 write!(w, "{}fn <a href='\\#{ty}.{name}' class='fnname'>{name}</a>\
1301 ast::UnsafeFn => "unsafe ",
1305 name = it.name.get_ref().as_slice(),
1307 decl = Method(selfty, d))
1310 clean::TyMethodItem(ref m) => {
1311 fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl)
1313 clean::MethodItem(ref m) => {
1314 fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl)
1320 fn item_struct(w: &mut Writer, it: &clean::Item,
1321 s: &clean::Struct) -> fmt::Result {
1322 try!(write!(w, "<pre class='rust struct'>"));
1323 try!(render_struct(w,
1327 s.fields.as_slice(),
1331 try!(write!(w, "</pre>"));
1333 try!(document(w, it));
1334 match s.struct_type {
1335 doctree::Plain if s.fields.len() > 0 => {
1336 try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
1337 for field in s.fields.iter() {
1338 try!(write!(w, "<tr><td id='structfield.{name}'>\
1339 <code>{name}</code></td><td>",
1340 name = field.name.get_ref().as_slice()));
1341 try!(document(w, field));
1342 try!(write!(w, "</td></tr>"));
1344 try!(write!(w, "</table>"));
1348 render_methods(w, it)
1351 fn item_enum(w: &mut Writer, it: &clean::Item, e: &clean::Enum) -> fmt::Result {
1352 try!(write!(w, "<pre class='rust enum'>{}enum {}{}",
1353 VisSpace(it.visibility),
1354 it.name.get_ref().as_slice(),
1356 if e.variants.len() == 0 && !e.variants_stripped {
1357 try!(write!(w, " \\{\\}"));
1359 try!(write!(w, " \\{\n"));
1360 for v in e.variants.iter() {
1361 try!(write!(w, " "));
1362 let name = v.name.get_ref().as_slice();
1364 clean::VariantItem(ref var) => {
1366 clean::CLikeVariant => try!(write!(w, "{}", name)),
1367 clean::TupleVariant(ref tys) => {
1368 try!(write!(w, "{}(", name));
1369 for (i, ty) in tys.iter().enumerate() {
1371 try!(write!(w, ", "))
1373 try!(write!(w, "{}", *ty));
1375 try!(write!(w, ")"));
1377 clean::StructVariant(ref s) => {
1378 try!(render_struct(w,
1382 s.fields.as_slice(),
1391 try!(write!(w, ",\n"));
1394 if e.variants_stripped {
1395 try!(write!(w, " // some variants omitted\n"));
1397 try!(write!(w, "\\}"));
1399 try!(write!(w, "</pre>"));
1401 try!(document(w, it));
1402 if e.variants.len() > 0 {
1403 try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
1404 for variant in e.variants.iter() {
1405 try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
1406 name = variant.name.get_ref().as_slice()));
1407 try!(document(w, variant));
1408 match variant.inner {
1409 clean::VariantItem(ref var) => {
1411 clean::StructVariant(ref s) => {
1412 try!(write!(w, "<h3 class='fields'>Fields</h3>\n
1414 for field in s.fields.iter() {
1415 try!(write!(w, "<tr><td \
1416 id='variant.{v}.field.{f}'>\
1417 <code>{f}</code></td><td>",
1418 v = variant.name.get_ref().as_slice(),
1419 f = field.name.get_ref().as_slice()));
1420 try!(document(w, field));
1421 try!(write!(w, "</td></tr>"));
1423 try!(write!(w, "</table>"));
1430 try!(write!(w, "</td></tr>"));
1432 try!(write!(w, "</table>"));
1435 try!(render_methods(w, it));
1439 fn render_struct(w: &mut Writer, it: &clean::Item,
1440 g: Option<&clean::Generics>,
1441 ty: doctree::StructType,
1442 fields: &[clean::Item],
1443 fields_stripped: bool,
1445 structhead: bool) -> fmt::Result {
1446 try!(write!(w, "{}{}{}",
1447 VisSpace(it.visibility),
1448 if structhead {"struct "} else {""},
1449 it.name.get_ref().as_slice()));
1451 Some(g) => try!(write!(w, "{}", *g)),
1456 try!(write!(w, " \\{\n{}", tab));
1457 for field in fields.iter() {
1459 clean::StructFieldItem(ref ty) => {
1460 try!(write!(w, " {}{}: {},\n{}",
1461 VisSpace(field.visibility),
1462 field.name.get_ref().as_slice(),
1470 if fields_stripped {
1471 try!(write!(w, " // some fields omitted\n{}", tab));
1473 try!(write!(w, "\\}"));
1475 doctree::Tuple | doctree::Newtype => {
1476 try!(write!(w, "("));
1477 for (i, field) in fields.iter().enumerate() {
1479 try!(write!(w, ", "));
1482 clean::StructFieldItem(ref field) => {
1483 try!(write!(w, "{}", field.type_));
1488 try!(write!(w, ");"));
1491 try!(write!(w, ";"));
1497 fn render_methods(w: &mut Writer, it: &clean::Item) -> fmt::Result {
1498 local_data::get(cache_key, |cache| {
1499 let c = cache.unwrap().get();
1500 match c.impls.find(&it.id) {
1502 let mut non_trait = v.iter().filter(|p| {
1503 p.ref0().trait_.is_none()
1505 let non_trait = non_trait.collect::<~[&(clean::Impl, Option<~str>)]>();
1506 let mut traits = v.iter().filter(|p| {
1507 p.ref0().trait_.is_some()
1509 let traits = traits.collect::<~[&(clean::Impl, Option<~str>)]>();
1511 if non_trait.len() > 0 {
1512 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
1513 for &(ref i, ref dox) in non_trait.move_iter() {
1514 try!(render_impl(w, i, dox));
1517 if traits.len() > 0 {
1518 try!(write!(w, "<h2 id='implementations'>Trait \
1519 Implementations</h2>"));
1520 for &(ref i, ref dox) in traits.move_iter() {
1521 try!(render_impl(w, i, dox));
1531 fn render_impl(w: &mut Writer, i: &clean::Impl,
1532 dox: &Option<~str>) -> fmt::Result {
1533 try!(write!(w, "<h3 class='impl'><code>impl{} ", i.generics));
1534 let trait_id = match i.trait_ {
1536 try!(write!(w, "{} for ", *ty));
1538 clean::ResolvedPath { id, .. } => Some(id),
1544 try!(write!(w, "{}</code></h3>", i.for_));
1547 try!(write!(w, "<div class='docblock'>{}</div>",
1548 Markdown(dox.as_slice())));
1553 fn docmeth(w: &mut Writer, item: &clean::Item) -> io::IoResult<bool> {
1554 try!(write!(w, "<h4 id='method.{}' class='method'><code>",
1555 *item.name.get_ref()));
1556 try!(render_method(w, item));
1557 try!(write!(w, "</code></h4>\n"));
1558 match item.doc_value() {
1560 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1567 try!(write!(w, "<div class='methods'>"));
1568 for meth in i.methods.iter() {
1569 if try!(docmeth(w, meth)) {
1573 // No documentation? Attempt to slurp in the trait's documentation
1574 let trait_id = match trait_id {
1578 try!(local_data::get(cache_key, |cache| {
1579 let cache = cache.unwrap().get();
1580 match cache.traits.find(&trait_id) {
1582 let name = meth.name.clone();
1583 match t.methods.iter().find(|t| t.item().name == name) {
1585 match method.item().doc_value() {
1588 "<div class='docblock'>{}</div>",
1603 // If we've implemented a trait, then also emit documentation for all
1604 // default methods which weren't overridden in the implementation block.
1608 try!(local_data::get(cache_key, |cache| {
1609 let cache = cache.unwrap().get();
1610 match cache.traits.find(&id) {
1612 for method in t.methods.iter() {
1613 let n = method.item().name.clone();
1614 match i.methods.iter().find(|m| m.name == n) {
1615 Some(..) => continue,
1619 try!(docmeth(w, method.item()));
1628 try!(write!(w, "</div>"));
1632 fn item_typedef(w: &mut Writer, it: &clean::Item,
1633 t: &clean::Typedef) -> fmt::Result {
1634 try!(write!(w, "<pre class='rust typedef'>type {}{} = {};</pre>",
1635 it.name.get_ref().as_slice(),
1642 impl<'a> fmt::Show for Sidebar<'a> {
1643 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1646 try!(write!(fmt.buf, "<p class='location'>"));
1647 let len = cx.current.len() - if it.is_mod() {1} else {0};
1648 for (i, name) in cx.current.iter().take(len).enumerate() {
1650 try!(write!(fmt.buf, "&\\#8203;::"));
1652 try!(write!(fmt.buf, "<a href='{}index.html'>{}</a>",
1653 cx.root_path.slice_to((cx.current.len() - i - 1) * 3),
1656 try!(write!(fmt.buf, "</p>"));
1658 fn block(w: &mut Writer, short: &str, longty: &str,
1659 cur: &clean::Item, cx: &Context) -> fmt::Result {
1660 let items = match cx.sidebar.find_equiv(&short) {
1661 Some(items) => items.as_slice(),
1662 None => return Ok(())
1664 try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
1665 for item in items.iter() {
1666 let class = if cur.name.get_ref() == item &&
1667 short == shortty(cur) { "current" } else { "" };
1668 try!(write!(w, "<a class='{ty} {class}' href='{curty, select,
1672 mod{{name}/index.html}
1673 other{#.{name}.html}
1674 }'>{name}</a><br/>",
1678 curty = shortty(cur),
1679 name = item.as_slice()));
1681 try!(write!(w, "</div>"));
1685 try!(block(fmt.buf, "mod", "Modules", it, cx));
1686 try!(block(fmt.buf, "struct", "Structs", it, cx));
1687 try!(block(fmt.buf, "enum", "Enums", it, cx));
1688 try!(block(fmt.buf, "trait", "Traits", it, cx));
1689 try!(block(fmt.buf, "fn", "Functions", it, cx));
1694 fn build_sidebar(m: &clean::Module) -> HashMap<~str, Vec<~str> > {
1695 let mut map = HashMap::new();
1696 for item in m.items.iter() {
1697 let short = shortty(item);
1698 let myname = match item.name {
1700 Some(ref s) => s.to_owned(),
1702 let v = map.find_or_insert_with(short.to_owned(), |_| Vec::new());
1706 for (_, items) in map.mut_iter() {
1707 items.as_mut_slice().sort();
1712 impl<'a> fmt::Show for Source<'a> {
1713 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1714 let Source(s) = *self;
1715 let lines = s.lines().len();
1717 let mut tmp = lines;
1722 try!(write!(fmt.buf, "<pre class='line-numbers'>"));
1723 for i in range(1, lines + 1) {
1724 try!(write!(fmt.buf, "<span id='{0:u}'>{0:1$u}</span>\n", i, cols));
1726 try!(write!(fmt.buf, "</pre>"));
1727 try!(write!(fmt.buf, "{}", highlight::highlight(s.as_slice(), None)));
1732 fn item_macro(w: &mut Writer, it: &clean::Item,
1733 t: &clean::Macro) -> fmt::Result {
1734 try!(w.write_str(highlight::highlight(t.source, Some("macro"))));