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, ~[~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 both `Send` and `Freeze` so it may be stored in a `Arc` instance and
120 /// shared among the various rendering tasks.
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, ~[(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, (~[~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, ~[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
159 priv parent_stack: ~[ast::NodeId],
160 priv search_index: ~[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: ~[~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(),
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 = ~[(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 {
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) => item_module(fmt.buf, self.cx,
971 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
972 item_function(fmt.buf, self.item, f),
973 clean::TraitItem(ref t) => item_trait(fmt.buf, self.item, t),
974 clean::StructItem(ref s) => item_struct(fmt.buf, self.item, s),
975 clean::EnumItem(ref e) => item_enum(fmt.buf, self.item, e),
976 clean::TypedefItem(ref t) => item_typedef(fmt.buf, self.item, t),
977 clean::MacroItem(ref m) => item_macro(fmt.buf, self.item, m),
983 fn item_path(item: &clean::Item) -> ~str {
985 clean::ModuleItem(..) => *item.name.get_ref() + "/index.html",
986 _ => shortty(item) + "." + *item.name.get_ref() + ".html"
990 fn full_path(cx: &Context, item: &clean::Item) -> ~str {
991 let mut s = cx.current.connect("::");
993 s.push_str(item.name.get_ref().as_slice());
997 fn blank<'a>(s: Option<&'a str>) -> &'a str {
1004 fn shorter<'a>(s: Option<&'a str>) -> &'a str {
1006 Some(s) => match s.find_str("\n\n") {
1007 Some(pos) => s.slice_to(pos),
1014 fn document(w: &mut Writer, item: &clean::Item) -> fmt::Result {
1015 match item.doc_value() {
1017 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1024 fn item_module(w: &mut Writer, cx: &Context,
1025 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1026 try!(document(w, item));
1027 debug!("{:?}", items);
1028 let mut indices = slice::from_fn(items.len(), |i| i);
1030 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering {
1031 if shortty(i1) == shortty(i2) {
1032 return i1.name.cmp(&i2.name);
1034 match (&i1.inner, &i2.inner) {
1035 (&clean::ViewItemItem(ref a), &clean::ViewItemItem(ref b)) => {
1036 match (&a.inner, &b.inner) {
1037 (&clean::ExternCrate(..), _) => Less,
1038 (_, &clean::ExternCrate(..)) => Greater,
1039 _ => idx1.cmp(&idx2),
1042 (&clean::ViewItemItem(..), _) => Less,
1043 (_, &clean::ViewItemItem(..)) => Greater,
1044 (&clean::ModuleItem(..), _) => Less,
1045 (_, &clean::ModuleItem(..)) => Greater,
1046 (&clean::MacroItem(..), _) => Less,
1047 (_, &clean::MacroItem(..)) => Greater,
1048 (&clean::StructItem(..), _) => Less,
1049 (_, &clean::StructItem(..)) => Greater,
1050 (&clean::EnumItem(..), _) => Less,
1051 (_, &clean::EnumItem(..)) => Greater,
1052 (&clean::StaticItem(..), _) => Less,
1053 (_, &clean::StaticItem(..)) => Greater,
1054 (&clean::ForeignFunctionItem(..), _) => Less,
1055 (_, &clean::ForeignFunctionItem(..)) => Greater,
1056 (&clean::ForeignStaticItem(..), _) => Less,
1057 (_, &clean::ForeignStaticItem(..)) => Greater,
1058 (&clean::TraitItem(..), _) => Less,
1059 (_, &clean::TraitItem(..)) => Greater,
1060 (&clean::FunctionItem(..), _) => Less,
1061 (_, &clean::FunctionItem(..)) => Greater,
1062 (&clean::TypedefItem(..), _) => Less,
1063 (_, &clean::TypedefItem(..)) => Greater,
1064 _ => idx1.cmp(&idx2),
1068 debug!("{:?}", indices);
1069 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1071 debug!("{:?}", indices);
1073 for &idx in indices.iter() {
1074 let myitem = &items[idx];
1076 let myty = shortty(myitem);
1079 try!(write!(w, "</table>"));
1082 let (short, name) = match myitem.inner {
1083 clean::ModuleItem(..) => ("modules", "Modules"),
1084 clean::StructItem(..) => ("structs", "Structs"),
1085 clean::EnumItem(..) => ("enums", "Enums"),
1086 clean::FunctionItem(..) => ("functions", "Functions"),
1087 clean::TypedefItem(..) => ("types", "Type Definitions"),
1088 clean::StaticItem(..) => ("statics", "Statics"),
1089 clean::TraitItem(..) => ("traits", "Traits"),
1090 clean::ImplItem(..) => ("impls", "Implementations"),
1091 clean::ViewItemItem(..) => ("reexports", "Reexports"),
1092 clean::TyMethodItem(..) => ("tymethods", "Type Methods"),
1093 clean::MethodItem(..) => ("methods", "Methods"),
1094 clean::StructFieldItem(..) => ("fields", "Struct Fields"),
1095 clean::VariantItem(..) => ("variants", "Variants"),
1096 clean::ForeignFunctionItem(..) => ("ffi-fns", "Foreign Functions"),
1097 clean::ForeignStaticItem(..) => ("ffi-statics", "Foreign Statics"),
1098 clean::MacroItem(..) => ("macros", "Macros"),
1101 "<h2 id='{id}' class='section-link'>\
1102 <a href=\"\\#{id}\">{name}</a></h2>\n<table>",
1103 id = short, name = name));
1106 match myitem.inner {
1107 clean::StaticItem(ref s) | clean::ForeignStaticItem(ref s) => {
1108 struct Initializer<'a>(&'a str);
1109 impl<'a> fmt::Show for Initializer<'a> {
1110 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1111 let Initializer(s) = *self;
1112 if s.len() == 0 { return Ok(()); }
1113 try!(write!(f.buf, "<code> = </code>"));
1114 let tag = if s.contains("\n") { "pre" } else { "code" };
1115 try!(write!(f.buf, "<{tag}>{}</{tag}>",
1116 s.as_slice(), tag=tag));
1123 <td><code>{}static {}: {}</code>{}</td>
1124 <td class='docblock'>{} </td>
1127 VisSpace(myitem.visibility),
1128 *myitem.name.get_ref(),
1130 Initializer(s.expr),
1131 Markdown(blank(myitem.doc_value()))));
1134 clean::ViewItemItem(ref item) => {
1136 clean::ExternCrate(ref name, ref src, _) => {
1137 try!(write!(w, "<tr><td><code>extern crate {}",
1140 Some(ref src) => try!(write!(w, " = \"{}\"",
1144 try!(write!(w, ";</code></td></tr>"));
1147 clean::Import(ref imports) => {
1148 for import in imports.iter() {
1149 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1150 VisSpace(myitem.visibility),
1159 if myitem.name.is_none() { continue }
1162 <td><a class='{class}' href='{href}'
1163 title='{title}'>{}</a></td>
1164 <td class='docblock short'>{}</td>
1167 *myitem.name.get_ref(),
1168 Markdown(shorter(myitem.doc_value())),
1169 class = shortty(myitem),
1170 href = item_path(myitem),
1171 title = full_path(cx, myitem)));
1175 write!(w, "</table>")
1178 fn item_function(w: &mut Writer, it: &clean::Item,
1179 f: &clean::Function) -> fmt::Result {
1180 try!(write!(w, "<pre class='rust fn'>{vis}{purity}fn \
1181 {name}{generics}{decl}</pre>",
1182 vis = VisSpace(it.visibility),
1183 purity = PuritySpace(f.purity),
1184 name = it.name.get_ref().as_slice(),
1185 generics = f.generics,
1190 fn item_trait(w: &mut Writer, it: &clean::Item,
1191 t: &clean::Trait) -> fmt::Result {
1192 let mut parents = ~"";
1193 if t.parents.len() > 0 {
1194 parents.push_str(": ");
1195 for (i, p) in t.parents.iter().enumerate() {
1196 if i > 0 { parents.push_str(" + "); }
1197 parents.push_str(format!("{}", *p));
1201 // Output the trait definition
1202 try!(write!(w, "<pre class='rust trait'>{}trait {}{}{} ",
1203 VisSpace(it.visibility),
1204 it.name.get_ref().as_slice(),
1207 let required = t.methods.iter().filter(|m| m.is_req()).to_owned_vec();
1208 let provided = t.methods.iter().filter(|m| !m.is_req()).to_owned_vec();
1210 if t.methods.len() == 0 {
1211 try!(write!(w, "\\{ \\}"));
1213 try!(write!(w, "\\{\n"));
1214 for m in required.iter() {
1215 try!(write!(w, " "));
1216 try!(render_method(w, m.item()));
1217 try!(write!(w, ";\n"));
1219 if required.len() > 0 && provided.len() > 0 {
1220 try!(w.write("\n".as_bytes()));
1222 for m in provided.iter() {
1223 try!(write!(w, " "));
1224 try!(render_method(w, m.item()));
1225 try!(write!(w, " \\{ ... \\}\n"));
1227 try!(write!(w, "\\}"));
1229 try!(write!(w, "</pre>"));
1231 // Trait documentation
1232 try!(document(w, it));
1234 fn meth(w: &mut Writer, m: &clean::TraitMethod) -> fmt::Result {
1235 try!(write!(w, "<h3 id='{}.{}' class='method'><code>",
1237 *m.item().name.get_ref()));
1238 try!(render_method(w, m.item()));
1239 try!(write!(w, "</code></h3>"));
1240 try!(document(w, m.item()));
1244 // Output the documentation for each function individually
1245 if required.len() > 0 {
1247 <h2 id='required-methods'>Required Methods</h2>
1248 <div class='methods'>
1250 for m in required.iter() {
1253 try!(write!(w, "</div>"));
1255 if provided.len() > 0 {
1257 <h2 id='provided-methods'>Provided Methods</h2>
1258 <div class='methods'>
1260 for m in provided.iter() {
1263 try!(write!(w, "</div>"));
1266 local_data::get(cache_key, |cache| {
1267 let cache = cache.unwrap().get();
1268 match cache.implementors.find(&it.id) {
1269 Some(implementors) => {
1271 <h2 id='implementors'>Implementors</h2>
1272 <ul class='item-list'>
1274 for i in implementors.iter() {
1276 PathType(ref ty) => {
1277 try!(write!(w, "<li><code>{}</code></li>", *ty));
1279 OtherType(ref generics, ref trait_, ref for_) => {
1280 try!(write!(w, "<li><code>impl{} {} for {}</code></li>",
1281 *generics, *trait_, *for_));
1285 try!(write!(w, "</ul>"));
1293 fn render_method(w: &mut Writer, meth: &clean::Item) -> fmt::Result {
1294 fn fun(w: &mut Writer, it: &clean::Item, purity: ast::Purity,
1295 g: &clean::Generics, selfty: &clean::SelfTy,
1296 d: &clean::FnDecl) -> fmt::Result {
1297 write!(w, "{}fn <a href='\\#{ty}.{name}' class='fnname'>{name}</a>\
1300 ast::UnsafeFn => "unsafe ",
1304 name = it.name.get_ref().as_slice(),
1306 decl = Method(selfty, d))
1309 clean::TyMethodItem(ref m) => {
1310 fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl)
1312 clean::MethodItem(ref m) => {
1313 fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl)
1319 fn item_struct(w: &mut Writer, it: &clean::Item,
1320 s: &clean::Struct) -> fmt::Result {
1321 try!(write!(w, "<pre class='rust struct'>"));
1322 try!(render_struct(w, it, Some(&s.generics), s.struct_type, s.fields,
1323 s.fields_stripped, "", true));
1324 try!(write!(w, "</pre>"));
1326 try!(document(w, it));
1327 match s.struct_type {
1328 doctree::Plain if s.fields.len() > 0 => {
1329 try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
1330 for field in s.fields.iter() {
1331 try!(write!(w, "<tr><td id='structfield.{name}'>\
1332 <code>{name}</code></td><td>",
1333 name = field.name.get_ref().as_slice()));
1334 try!(document(w, field));
1335 try!(write!(w, "</td></tr>"));
1337 try!(write!(w, "</table>"));
1341 render_methods(w, it)
1344 fn item_enum(w: &mut Writer, it: &clean::Item, e: &clean::Enum) -> fmt::Result {
1345 try!(write!(w, "<pre class='rust enum'>{}enum {}{}",
1346 VisSpace(it.visibility),
1347 it.name.get_ref().as_slice(),
1349 if e.variants.len() == 0 && !e.variants_stripped {
1350 try!(write!(w, " \\{\\}"));
1352 try!(write!(w, " \\{\n"));
1353 for v in e.variants.iter() {
1354 try!(write!(w, " "));
1355 let name = v.name.get_ref().as_slice();
1357 clean::VariantItem(ref var) => {
1359 clean::CLikeVariant => try!(write!(w, "{}", name)),
1360 clean::TupleVariant(ref tys) => {
1361 try!(write!(w, "{}(", name));
1362 for (i, ty) in tys.iter().enumerate() {
1364 try!(write!(w, ", "))
1366 try!(write!(w, "{}", *ty));
1368 try!(write!(w, ")"));
1370 clean::StructVariant(ref s) => {
1371 try!(render_struct(w, v, None, s.struct_type,
1372 s.fields, s.fields_stripped,
1379 try!(write!(w, ",\n"));
1382 if e.variants_stripped {
1383 try!(write!(w, " // some variants omitted\n"));
1385 try!(write!(w, "\\}"));
1387 try!(write!(w, "</pre>"));
1389 try!(document(w, it));
1390 if e.variants.len() > 0 {
1391 try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
1392 for variant in e.variants.iter() {
1393 try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
1394 name = variant.name.get_ref().as_slice()));
1395 try!(document(w, variant));
1396 match variant.inner {
1397 clean::VariantItem(ref var) => {
1399 clean::StructVariant(ref s) => {
1400 try!(write!(w, "<h3 class='fields'>Fields</h3>\n
1402 for field in s.fields.iter() {
1403 try!(write!(w, "<tr><td \
1404 id='variant.{v}.field.{f}'>\
1405 <code>{f}</code></td><td>",
1406 v = variant.name.get_ref().as_slice(),
1407 f = field.name.get_ref().as_slice()));
1408 try!(document(w, field));
1409 try!(write!(w, "</td></tr>"));
1411 try!(write!(w, "</table>"));
1418 try!(write!(w, "</td></tr>"));
1420 try!(write!(w, "</table>"));
1423 try!(render_methods(w, it));
1427 fn render_struct(w: &mut Writer, it: &clean::Item,
1428 g: Option<&clean::Generics>,
1429 ty: doctree::StructType,
1430 fields: &[clean::Item],
1431 fields_stripped: bool,
1433 structhead: bool) -> fmt::Result {
1434 try!(write!(w, "{}{}{}",
1435 VisSpace(it.visibility),
1436 if structhead {"struct "} else {""},
1437 it.name.get_ref().as_slice()));
1439 Some(g) => try!(write!(w, "{}", *g)),
1444 try!(write!(w, " \\{\n{}", tab));
1445 for field in fields.iter() {
1447 clean::StructFieldItem(ref ty) => {
1448 try!(write!(w, " {}{}: {},\n{}",
1449 VisSpace(field.visibility),
1450 field.name.get_ref().as_slice(),
1458 if fields_stripped {
1459 try!(write!(w, " // some fields omitted\n{}", tab));
1461 try!(write!(w, "\\}"));
1463 doctree::Tuple | doctree::Newtype => {
1464 try!(write!(w, "("));
1465 for (i, field) in fields.iter().enumerate() {
1467 try!(write!(w, ", "));
1470 clean::StructFieldItem(ref field) => {
1471 try!(write!(w, "{}", field.type_));
1476 try!(write!(w, ");"));
1479 try!(write!(w, ";"));
1485 fn render_methods(w: &mut Writer, it: &clean::Item) -> fmt::Result {
1486 local_data::get(cache_key, |cache| {
1487 let c = cache.unwrap().get();
1488 match c.impls.find(&it.id) {
1490 let mut non_trait = v.iter().filter(|p| {
1491 p.ref0().trait_.is_none()
1493 let non_trait = non_trait.to_owned_vec();
1494 let mut traits = v.iter().filter(|p| {
1495 p.ref0().trait_.is_some()
1497 let traits = traits.to_owned_vec();
1499 if non_trait.len() > 0 {
1500 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
1501 for &(ref i, ref dox) in non_trait.move_iter() {
1502 try!(render_impl(w, i, dox));
1505 if traits.len() > 0 {
1506 try!(write!(w, "<h2 id='implementations'>Trait \
1507 Implementations</h2>"));
1508 for &(ref i, ref dox) in traits.move_iter() {
1509 try!(render_impl(w, i, dox));
1519 fn render_impl(w: &mut Writer, i: &clean::Impl,
1520 dox: &Option<~str>) -> fmt::Result {
1521 try!(write!(w, "<h3 class='impl'><code>impl{} ", i.generics));
1522 let trait_id = match i.trait_ {
1524 try!(write!(w, "{} for ", *ty));
1526 clean::ResolvedPath { id, .. } => Some(id),
1532 try!(write!(w, "{}</code></h3>", i.for_));
1535 try!(write!(w, "<div class='docblock'>{}</div>",
1536 Markdown(dox.as_slice())));
1541 fn docmeth(w: &mut Writer, item: &clean::Item) -> io::IoResult<bool> {
1542 try!(write!(w, "<h4 id='method.{}' class='method'><code>",
1543 *item.name.get_ref()));
1544 try!(render_method(w, item));
1545 try!(write!(w, "</code></h4>\n"));
1546 match item.doc_value() {
1548 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1555 try!(write!(w, "<div class='methods'>"));
1556 for meth in i.methods.iter() {
1557 if try!(docmeth(w, meth)) {
1561 // No documentation? Attempt to slurp in the trait's documentation
1562 let trait_id = match trait_id {
1566 try!(local_data::get(cache_key, |cache| {
1567 let cache = cache.unwrap().get();
1568 match cache.traits.find(&trait_id) {
1570 let name = meth.name.clone();
1571 match t.methods.iter().find(|t| t.item().name == name) {
1573 match method.item().doc_value() {
1576 "<div class='docblock'>{}</div>",
1591 // If we've implemented a trait, then also emit documentation for all
1592 // default methods which weren't overridden in the implementation block.
1596 try!(local_data::get(cache_key, |cache| {
1597 let cache = cache.unwrap().get();
1598 match cache.traits.find(&id) {
1600 for method in t.methods.iter() {
1601 let n = method.item().name.clone();
1602 match i.methods.iter().find(|m| m.name == n) {
1603 Some(..) => continue,
1607 try!(docmeth(w, method.item()));
1616 try!(write!(w, "</div>"));
1620 fn item_typedef(w: &mut Writer, it: &clean::Item,
1621 t: &clean::Typedef) -> fmt::Result {
1622 try!(write!(w, "<pre class='rust typedef'>type {}{} = {};</pre>",
1623 it.name.get_ref().as_slice(),
1630 impl<'a> fmt::Show for Sidebar<'a> {
1631 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1634 try!(write!(fmt.buf, "<p class='location'>"));
1635 let len = cx.current.len() - if it.is_mod() {1} else {0};
1636 for (i, name) in cx.current.iter().take(len).enumerate() {
1638 try!(write!(fmt.buf, "&\\#8203;::"));
1640 try!(write!(fmt.buf, "<a href='{}index.html'>{}</a>",
1641 cx.root_path.slice_to((cx.current.len() - i - 1) * 3),
1644 try!(write!(fmt.buf, "</p>"));
1646 fn block(w: &mut Writer, short: &str, longty: &str,
1647 cur: &clean::Item, cx: &Context) -> fmt::Result {
1648 let items = match cx.sidebar.find_equiv(&short) {
1649 Some(items) => items.as_slice(),
1650 None => return Ok(())
1652 try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
1653 for item in items.iter() {
1654 let class = if cur.name.get_ref() == item &&
1655 short == shortty(cur) { "current" } else { "" };
1656 try!(write!(w, "<a class='{ty} {class}' href='{curty, select,
1660 mod{{name}/index.html}
1661 other{#.{name}.html}
1662 }'>{name}</a><br/>",
1666 curty = shortty(cur),
1667 name = item.as_slice()));
1669 try!(write!(w, "</div>"));
1673 try!(block(fmt.buf, "mod", "Modules", it, cx));
1674 try!(block(fmt.buf, "struct", "Structs", it, cx));
1675 try!(block(fmt.buf, "enum", "Enums", it, cx));
1676 try!(block(fmt.buf, "trait", "Traits", it, cx));
1677 try!(block(fmt.buf, "fn", "Functions", it, cx));
1682 fn build_sidebar(m: &clean::Module) -> HashMap<~str, ~[~str]> {
1683 let mut map = HashMap::new();
1684 for item in m.items.iter() {
1685 let short = shortty(item);
1686 let myname = match item.name {
1688 Some(ref s) => s.to_owned(),
1690 let v = map.find_or_insert_with(short.to_owned(), |_| ~[]);
1694 for (_, items) in map.mut_iter() {
1700 impl<'a> fmt::Show for Source<'a> {
1701 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1702 let Source(s) = *self;
1703 let lines = s.lines().len();
1705 let mut tmp = lines;
1710 try!(write!(fmt.buf, "<pre class='line-numbers'>"));
1711 for i in range(1, lines + 1) {
1712 try!(write!(fmt.buf, "<span id='{0:u}'>{0:1$u}</span>\n", i, cols));
1714 try!(write!(fmt.buf, "</pre>"));
1715 try!(write!(fmt.buf, "{}", highlight::highlight(s.as_slice(), None)));
1720 fn item_macro(w: &mut Writer, it: &clean::Item,
1721 t: &clean::Macro) -> fmt::Result {
1722 try!(w.write_str(highlight::highlight(t.source, Some("macro"))));