]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render.rs
auto merge of #13440 : huonw/rust/strbuf, r=alexcrichton
[rust.git] / src / librustdoc / html / render.rs
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.
4 //
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.
10
11 //! Rustdoc's HTML Rendering module
12 //!
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.
17 //!
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
24 //! rendered.
25 //!
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).
30 //!
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.
35
36 use collections::{HashMap, HashSet};
37 use std::fmt;
38 use std::io::{fs, File, BufferedWriter, MemWriter, BufferedReader};
39 use std::io;
40 use std::local_data;
41 use std::slice;
42 use std::str;
43 use std::strbuf::StrBuf;
44
45 use sync::Arc;
46 use serialize::json::ToJson;
47 use syntax::ast;
48 use syntax::attr;
49 use syntax::parse::token::InternedString;
50 use rustc::util::nodemap::NodeSet;
51
52 use clean;
53 use doctree;
54 use fold::DocFolder;
55 use html::format::{VisSpace, Method, FnStyleSpace};
56 use html::layout;
57 use html::markdown;
58 use html::markdown::Markdown;
59 use html::highlight;
60
61 /// Major driving force in all rustdoc rendering. This contains information
62 /// about where in the tree-like hierarchy rendering is occurring and controls
63 /// how the current page is being rendered.
64 ///
65 /// It is intended that this context is a lightweight object which can be fairly
66 /// easily cloned because it is cloned per work-job (about once per item in the
67 /// rustdoc tree).
68 #[deriving(Clone)]
69 pub struct Context {
70     /// Current hierarchy of components leading down to what's currently being
71     /// rendered
72     pub current: Vec<~str> ,
73     /// String representation of how to get back to the root path of the 'doc/'
74     /// folder in terms of a relative URL.
75     pub root_path: StrBuf,
76     /// The current destination folder of where HTML artifacts should be placed.
77     /// This changes as the context descends into the module hierarchy.
78     pub dst: Path,
79     /// This describes the layout of each page, and is not modified after
80     /// creation of the context (contains info like the favicon)
81     pub layout: layout::Layout,
82     /// This map is a list of what should be displayed on the sidebar of the
83     /// current page. The key is the section header (traits, modules,
84     /// functions), and the value is the list of containers belonging to this
85     /// header. This map will change depending on the surrounding context of the
86     /// page.
87     pub sidebar: HashMap<~str, Vec<~str> >,
88     /// This flag indicates whether [src] links should be generated or not. If
89     /// the source files are present in the html rendering, then this will be
90     /// `true`.
91     pub include_sources: bool,
92 }
93
94 /// Indicates where an external crate can be found.
95 pub enum ExternalLocation {
96     /// Remote URL root of the external crate
97     Remote(~str),
98     /// This external crate can be found in the local doc/ folder
99     Local,
100     /// The external crate could not be found.
101     Unknown,
102 }
103
104 /// Different ways an implementor of a trait can be rendered.
105 pub enum Implementor {
106     /// Paths are displayed specially by omitting the `impl XX for` cruft
107     PathType(clean::Type),
108     /// This is the generic representation of a trait implementor, used for
109     /// primitive types and otherwise non-path types.
110     OtherType(clean::Generics, /* trait */ clean::Type, /* for */ clean::Type),
111 }
112
113 /// This cache is used to store information about the `clean::Crate` being
114 /// rendered in order to provide more useful documentation. This contains
115 /// information like all implementors of a trait, all traits a type implements,
116 /// documentation for all known traits, etc.
117 ///
118 /// This structure purposefully does not implement `Clone` because it's intended
119 /// to be a fairly large and expensive structure to clone. Instead this adheres
120 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
121 /// rendering tasks.
122 pub struct Cache {
123     /// Mapping of typaram ids to the name of the type parameter. This is used
124     /// when pretty-printing a type (so pretty printing doesn't have to
125     /// painfully maintain a context like this)
126     pub typarams: HashMap<ast::NodeId, ~str>,
127
128     /// Maps a type id to all known implementations for that type. This is only
129     /// recognized for intra-crate `ResolvedPath` types, and is used to print
130     /// out extra documentation on the page of an enum/struct.
131     ///
132     /// The values of the map are a list of implementations and documentation
133     /// found on that implementation.
134     pub impls: HashMap<ast::NodeId, Vec<(clean::Impl, Option<~str>)> >,
135
136     /// Maintains a mapping of local crate node ids to the fully qualified name
137     /// and "short type description" of that node. This is used when generating
138     /// URLs when a type is being linked to. External paths are not located in
139     /// this map because the `External` type itself has all the information
140     /// necessary.
141     pub paths: HashMap<ast::NodeId, (Vec<~str> , &'static str)>,
142
143     /// This map contains information about all known traits of this crate.
144     /// Implementations of a crate should inherit the documentation of the
145     /// parent trait if no extra documentation is specified, and default methods
146     /// should show up in documentation about trait implementations.
147     pub traits: HashMap<ast::NodeId, clean::Trait>,
148
149     /// When rendering traits, it's often useful to be able to list all
150     /// implementors of the trait, and this mapping is exactly, that: a mapping
151     /// of trait ids to the list of known implementors of the trait
152     pub implementors: HashMap<ast::NodeId, Vec<Implementor> >,
153
154     /// Cache of where external crate documentation can be found.
155     pub extern_locations: HashMap<ast::CrateNum, ExternalLocation>,
156
157     // Private fields only used when initially crawling a crate to build a cache
158
159     stack: Vec<~str> ,
160     parent_stack: Vec<ast::NodeId> ,
161     search_index: Vec<IndexItem> ,
162     privmod: bool,
163     public_items: NodeSet,
164
165     // In rare case where a structure is defined in one module but implemented
166     // in another, if the implementing module is parsed before defining module,
167     // then the fully qualified name of the structure isn't presented in `paths`
168     // yet when its implementation methods are being indexed. Caches such methods
169     // and their parent id here and indexes them at the end of crate parsing.
170     orphan_methods: Vec<(ast::NodeId, clean::Item)>,
171 }
172
173 /// Helper struct to render all source code to HTML pages
174 struct SourceCollector<'a> {
175     cx: &'a mut Context,
176
177     /// Processed source-file paths
178     seen: HashSet<~str>,
179     /// Root destination to place all HTML output into
180     dst: Path,
181 }
182
183 /// Wrapper struct to render the source code of a file. This will do things like
184 /// adding line numbers to the left-hand side.
185 struct Source<'a>(&'a str);
186
187 // Helper structs for rendering items/sidebars and carrying along contextual
188 // information
189
190 struct Item<'a> { cx: &'a Context, item: &'a clean::Item, }
191 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
192
193 /// Struct representing one entry in the JS search index. These are all emitted
194 /// by hand to a large JS file at the end of cache-creation.
195 struct IndexItem {
196     ty: &'static str,
197     name: ~str,
198     path: ~str,
199     desc: ~str,
200     parent: Option<ast::NodeId>,
201 }
202
203 // TLS keys used to carry information around during rendering.
204
205 local_data_key!(pub cache_key: Arc<Cache>)
206 local_data_key!(pub current_location_key: Vec<~str> )
207
208 /// Generates the documentation for `crate` into the directory `dst`
209 pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> {
210     let mut cx = Context {
211         dst: dst,
212         current: Vec::new(),
213         root_path: StrBuf::new(),
214         sidebar: HashMap::new(),
215         layout: layout::Layout {
216             logo: ~"",
217             favicon: ~"",
218             krate: krate.name.clone(),
219         },
220         include_sources: true,
221     };
222     try!(mkdir(&cx.dst));
223
224     match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(&[])) {
225         Some(attrs) => {
226             for attr in attrs.iter() {
227                 match *attr {
228                     clean::NameValue(ref x, ref s) if "html_favicon_url" == *x => {
229                         cx.layout.favicon = s.to_owned();
230                     }
231                     clean::NameValue(ref x, ref s) if "html_logo_url" == *x => {
232                         cx.layout.logo = s.to_owned();
233                     }
234                     clean::Word(ref x) if "html_no_source" == *x => {
235                         cx.include_sources = false;
236                     }
237                     _ => {}
238                 }
239             }
240         }
241         None => {}
242     }
243
244     // Crawl the crate to build various caches used for the output
245     let mut cache = local_data::get(::analysiskey, |analysis| {
246         let public_items = analysis.map(|a| a.public_items.clone());
247         let public_items = public_items.unwrap_or(NodeSet::new());
248         Cache {
249             impls: HashMap::new(),
250             typarams: HashMap::new(),
251             paths: HashMap::new(),
252             traits: HashMap::new(),
253             implementors: HashMap::new(),
254             stack: Vec::new(),
255             parent_stack: Vec::new(),
256             search_index: Vec::new(),
257             extern_locations: HashMap::new(),
258             privmod: false,
259             public_items: public_items,
260             orphan_methods: Vec::new(),
261         }
262     });
263     cache.stack.push(krate.name.clone());
264     krate = cache.fold_crate(krate);
265     {
266         let Cache { search_index: ref mut index,
267                     orphan_methods: ref meths, paths: ref mut paths, ..} = cache;
268
269         // Attach all orphan methods to the type's definition if the type
270         // has since been learned.
271         for &(ref pid, ref item) in meths.iter() {
272             match paths.find(pid) {
273                 Some(&(ref fqp, _)) => {
274                     index.push(IndexItem {
275                         ty: shortty(item),
276                         name: item.name.clone().unwrap(),
277                         path: fqp.slice_to(fqp.len() - 1).connect("::"),
278                         desc: shorter(item.doc_value()).to_owned(),
279                         parent: Some(*pid),
280                     });
281                 },
282                 None => {}
283             }
284         };
285
286         // Prune the paths that do not appear in the index.
287         let mut unseen: HashSet<ast::NodeId> = paths.keys().map(|&id| id).collect();
288         for item in index.iter() {
289             match item.parent {
290                 Some(ref pid) => { unseen.remove(pid); }
291                 None => {}
292             }
293         }
294         for pid in unseen.iter() {
295             paths.remove(pid);
296         }
297     }
298
299     // Publish the search index
300     let index = {
301         let mut w = MemWriter::new();
302         try!(write!(&mut w, "searchIndex['{}'] = [", krate.name));
303         for (i, item) in cache.search_index.iter().enumerate() {
304             if i > 0 {
305                 try!(write!(&mut w, ","));
306             }
307             try!(write!(&mut w, "\\{ty:\"{}\",name:\"{}\",path:\"{}\",desc:{}",
308                         item.ty, item.name, item.path,
309                         item.desc.to_json().to_str()));
310             match item.parent {
311                 Some(id) => {
312                     try!(write!(&mut w, ",parent:'{}'", id));
313                 }
314                 None => {}
315             }
316             try!(write!(&mut w, "\\}"));
317         }
318         try!(write!(&mut w, "];"));
319         try!(write!(&mut w, "allPaths['{}'] = \\{", krate.name));
320         for (i, (&id, &(ref fqp, short))) in cache.paths.iter().enumerate() {
321             if i > 0 {
322                 try!(write!(&mut w, ","));
323             }
324             try!(write!(&mut w, "'{}':\\{type:'{}',name:'{}'\\}",
325                         id, short, *fqp.last().unwrap()));
326         }
327         try!(write!(&mut w, "\\};"));
328
329         str::from_utf8(w.unwrap().as_slice()).unwrap().to_owned()
330     };
331
332     // Write out the shared files. Note that these are shared among all rustdoc
333     // docs placed in the output directory, so this needs to be a synchronized
334     // operation with respect to all other rustdocs running around.
335     {
336         try!(mkdir(&cx.dst));
337         let _lock = ::flock::Lock::new(&cx.dst.join(".lock"));
338
339         // Add all the static files. These may already exist, but we just
340         // overwrite them anyway to make sure that they're fresh and up-to-date.
341         try!(write(cx.dst.join("jquery.js"),
342                    include_str!("static/jquery-2.1.0.min.js")));
343         try!(write(cx.dst.join("main.js"), include_str!("static/main.js")));
344         try!(write(cx.dst.join("main.css"), include_str!("static/main.css")));
345         try!(write(cx.dst.join("normalize.css"),
346                    include_str!("static/normalize.css")));
347
348         // Update the search index
349         let dst = cx.dst.join("search-index.js");
350         let mut all_indexes = Vec::new();
351         all_indexes.push(index);
352         if dst.exists() {
353             for line in BufferedReader::new(File::open(&dst)).lines() {
354                 let line = try!(line);
355                 if !line.starts_with("searchIndex") { continue }
356                 if line.starts_with(format!("searchIndex['{}']", krate.name)) {
357                     continue
358                 }
359                 all_indexes.push(line);
360             }
361         }
362         let mut w = try!(File::create(&dst));
363         try!(writeln!(&mut w, r"var searchIndex = \{\}; var allPaths = \{\};"));
364         for index in all_indexes.iter() {
365             try!(writeln!(&mut w, "{}", *index));
366         }
367         try!(writeln!(&mut w, "initSearch(searchIndex);"));
368     }
369
370     // Render all source files (this may turn into a giant no-op)
371     {
372         info!("emitting source files");
373         let dst = cx.dst.join("src");
374         try!(mkdir(&dst));
375         let dst = dst.join(krate.name.as_slice());
376         try!(mkdir(&dst));
377         let mut folder = SourceCollector {
378             dst: dst,
379             seen: HashSet::new(),
380             cx: &mut cx,
381         };
382         krate = folder.fold_crate(krate);
383     }
384
385     for &(n, ref e) in krate.externs.iter() {
386         cache.extern_locations.insert(n, extern_location(e, &cx.dst));
387     }
388
389     // And finally render the whole crate's documentation
390     cx.krate(krate, cache)
391 }
392
393 /// Writes the entire contents of a string to a destination, not attempting to
394 /// catch any errors.
395 fn write(dst: Path, contents: &str) -> io::IoResult<()> {
396     File::create(&dst).write(contents.as_bytes())
397 }
398
399 /// Makes a directory on the filesystem, failing the task if an error occurs and
400 /// skipping if the directory already exists.
401 fn mkdir(path: &Path) -> io::IoResult<()> {
402     if !path.exists() {
403         fs::mkdir(path, io::UserRWX)
404     } else {
405         Ok(())
406     }
407 }
408
409 /// Takes a path to a source file and cleans the path to it. This canonicalizes
410 /// things like ".." to components which preserve the "top down" hierarchy of a
411 /// static HTML tree.
412 // FIXME (#9639): The closure should deal with &[u8] instead of &str
413 fn clean_srcpath(src: &[u8], f: |&str|) {
414     let p = Path::new(src);
415     if p.as_vec() != bytes!(".") {
416         for c in p.str_components().map(|x|x.unwrap()) {
417             if ".." == c {
418                 f("up");
419             } else {
420                 f(c.as_slice())
421             }
422         }
423     }
424 }
425
426 /// Attempts to find where an external crate is located, given that we're
427 /// rendering in to the specified source destination.
428 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
429     // See if there's documentation generated into the local directory
430     let local_location = dst.join(e.name.as_slice());
431     if local_location.is_dir() {
432         return Local;
433     }
434
435     // Failing that, see if there's an attribute specifying where to find this
436     // external crate
437     for attr in e.attrs.iter() {
438         match *attr {
439             clean::List(ref x, ref list) if "doc" == *x => {
440                 for attr in list.iter() {
441                     match *attr {
442                         clean::NameValue(ref x, ref s) if "html_root_url" == *x => {
443                             if s.ends_with("/") {
444                                 return Remote(s.to_owned());
445                             }
446                             return Remote(*s + "/");
447                         }
448                         _ => {}
449                     }
450                 }
451             }
452             _ => {}
453         }
454     }
455
456     // Well, at least we tried.
457     return Unknown;
458 }
459
460 impl<'a> DocFolder for SourceCollector<'a> {
461     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
462         // If we're including source files, and we haven't seen this file yet,
463         // then we need to render it out to the filesystem
464         if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
465
466             // If it turns out that we couldn't read this file, then we probably
467             // can't read any of the files (generating html output from json or
468             // something like that), so just don't include sources for the
469             // entire crate. The other option is maintaining this mapping on a
470             // per-file basis, but that's probably not worth it...
471             self.cx.include_sources = match self.emit_source(item.source.filename) {
472                 Ok(()) => true,
473                 Err(e) => {
474                     println!("warning: source code was requested to be rendered, \
475                               but processing `{}` had an error: {}",
476                              item.source.filename, e);
477                     println!("         skipping rendering of source code");
478                     false
479                 }
480             };
481             self.seen.insert(item.source.filename.clone());
482         }
483
484         self.fold_item_recur(item)
485     }
486 }
487
488 impl<'a> SourceCollector<'a> {
489     /// Renders the given filename into its corresponding HTML source file.
490     fn emit_source(&mut self, filename: &str) -> io::IoResult<()> {
491         let p = Path::new(filename);
492
493         // If we couldn't open this file, then just returns because it
494         // probably means that it's some standard library macro thing and we
495         // can't have the source to it anyway.
496         let contents = match File::open(&p).read_to_end() {
497             Ok(r) => r,
498             // macros from other libraries get special filenames which we can
499             // safely ignore
500             Err(..) if filename.starts_with("<") &&
501                        filename.ends_with("macros>") => return Ok(()),
502             Err(e) => return Err(e)
503         };
504         let contents = str::from_utf8(contents.as_slice()).unwrap();
505
506         // Remove the utf-8 BOM if any
507         let contents = if contents.starts_with("\ufeff") {
508             contents.as_slice().slice_from(3)
509         } else {
510             contents.as_slice()
511         };
512
513         // Create the intermediate directories
514         let mut cur = self.dst.clone();
515         let mut root_path = StrBuf::from_str("../../");
516         clean_srcpath(p.dirname(), |component| {
517             cur.push(component);
518             mkdir(&cur).unwrap();
519             root_path.push_str("../");
520         });
521
522         cur.push(p.filename().expect("source has no filename") + bytes!(".html"));
523         let mut w = BufferedWriter::new(try!(File::create(&cur)));
524
525         let title = format!("{} -- source", cur.filename_display());
526         let page = layout::Page {
527             title: title,
528             ty: "source",
529             root_path: root_path.as_slice(),
530         };
531         try!(layout::render(&mut w as &mut Writer, &self.cx.layout,
532                               &page, &(""), &Source(contents)));
533         try!(w.flush());
534         return Ok(());
535     }
536 }
537
538 impl DocFolder for Cache {
539     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
540         // If this is a private module, we don't want it in the search index.
541         let orig_privmod = match item.inner {
542             clean::ModuleItem(..) => {
543                 let prev = self.privmod;
544                 self.privmod = prev || item.visibility != Some(ast::Public);
545                 prev
546             }
547             _ => self.privmod,
548         };
549
550         // Register any generics to their corresponding string. This is used
551         // when pretty-printing types
552         match item.inner {
553             clean::StructItem(ref s)          => self.generics(&s.generics),
554             clean::EnumItem(ref e)            => self.generics(&e.generics),
555             clean::FunctionItem(ref f)        => self.generics(&f.generics),
556             clean::TypedefItem(ref t)         => self.generics(&t.generics),
557             clean::TraitItem(ref t)           => self.generics(&t.generics),
558             clean::ImplItem(ref i)            => self.generics(&i.generics),
559             clean::TyMethodItem(ref i)        => self.generics(&i.generics),
560             clean::MethodItem(ref i)          => self.generics(&i.generics),
561             clean::ForeignFunctionItem(ref f) => self.generics(&f.generics),
562             _ => {}
563         }
564
565         // Propagate a trait methods' documentation to all implementors of the
566         // trait
567         match item.inner {
568             clean::TraitItem(ref t) => {
569                 self.traits.insert(item.id, t.clone());
570             }
571             _ => {}
572         }
573
574         // Collect all the implementors of traits.
575         match item.inner {
576             clean::ImplItem(ref i) => {
577                 match i.trait_ {
578                     Some(clean::ResolvedPath{ id, .. }) => {
579                         let v = self.implementors.find_or_insert_with(id, |_|{
580                             Vec::new()
581                         });
582                         match i.for_ {
583                             clean::ResolvedPath{..} => {
584                                 v.unshift(PathType(i.for_.clone()));
585                             }
586                             _ => {
587                                 v.push(OtherType(i.generics.clone(),
588                                                  i.trait_.get_ref().clone(),
589                                                  i.for_.clone()));
590                             }
591                         }
592                     }
593                     Some(..) | None => {}
594                 }
595             }
596             _ => {}
597         }
598
599         // Index this method for searching later on
600         match item.name {
601             Some(ref s) => {
602                 let parent = match item.inner {
603                     clean::TyMethodItem(..) |
604                     clean::StructFieldItem(..) |
605                     clean::VariantItem(..) => {
606                         (Some(*self.parent_stack.last().unwrap()),
607                          Some(self.stack.slice_to(self.stack.len() - 1)))
608
609                     }
610                     clean::MethodItem(..) => {
611                         if self.parent_stack.len() == 0 {
612                             (None, None)
613                         } else {
614                             let last = self.parent_stack.last().unwrap();
615                             let path = match self.paths.find(last) {
616                                 Some(&(_, "trait")) =>
617                                     Some(self.stack.slice_to(self.stack.len() - 1)),
618                                 // The current stack not necessarily has correlation for
619                                 // where the type was defined. On the other hand,
620                                 // `paths` always has the right information if present.
621                                 Some(&(ref fqp, "struct")) | Some(&(ref fqp, "enum")) =>
622                                     Some(fqp.slice_to(fqp.len() - 1)),
623                                 Some(..) => Some(self.stack.as_slice()),
624                                 None => None
625                             };
626                             (Some(*last), path)
627                         }
628                     }
629                     _ => (None, Some(self.stack.as_slice()))
630                 };
631                 match parent {
632                     (parent, Some(path)) if !self.privmod => {
633                         self.search_index.push(IndexItem {
634                             ty: shortty(&item),
635                             name: s.to_owned(),
636                             path: path.connect("::"),
637                             desc: shorter(item.doc_value()).to_owned(),
638                             parent: parent,
639                         });
640                     }
641                     (Some(parent), None) if !self.privmod => {
642                         // We have a parent, but we don't know where they're
643                         // defined yet. Wait for later to index this item.
644                         self.orphan_methods.push((parent, item.clone()))
645                     }
646                     _ => {}
647                 }
648             }
649             None => {}
650         }
651
652         // Keep track of the fully qualified path for this item.
653         let pushed = if item.name.is_some() {
654             let n = item.name.get_ref();
655             if n.len() > 0 {
656                 self.stack.push(n.to_owned());
657                 true
658             } else { false }
659         } else { false };
660         match item.inner {
661             clean::StructItem(..) | clean::EnumItem(..) |
662             clean::TypedefItem(..) | clean::TraitItem(..) |
663             clean::FunctionItem(..) | clean::ModuleItem(..) |
664             clean::ForeignFunctionItem(..) => {
665                 // Reexported items mean that the same id can show up twice in
666                 // the rustdoc ast that we're looking at. We know, however, that
667                 // a reexported item doesn't show up in the `public_items` map,
668                 // so we can skip inserting into the paths map if there was
669                 // already an entry present and we're not a public item.
670                 if !self.paths.contains_key(&item.id) ||
671                    self.public_items.contains(&item.id) {
672                     self.paths.insert(item.id,
673                                       (self.stack.clone(), shortty(&item)));
674                 }
675             }
676             // link variants to their parent enum because pages aren't emitted
677             // for each variant
678             clean::VariantItem(..) => {
679                 let mut stack = self.stack.clone();
680                 stack.pop();
681                 self.paths.insert(item.id, (stack, "enum"));
682             }
683             _ => {}
684         }
685
686         // Maintain the parent stack
687         let parent_pushed = match item.inner {
688             clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
689                 self.parent_stack.push(item.id); true
690             }
691             clean::ImplItem(ref i) => {
692                 match i.for_ {
693                     clean::ResolvedPath{ id, .. } => {
694                         self.parent_stack.push(id); true
695                     }
696                     _ => false
697                 }
698             }
699             _ => false
700         };
701
702         // Once we've recursively found all the generics, then hoard off all the
703         // implementations elsewhere
704         let ret = match self.fold_item_recur(item) {
705             Some(item) => {
706                 match item {
707                     clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
708                         match i.for_ {
709                             clean::ResolvedPath { id, .. } => {
710                                 let v = self.impls.find_or_insert_with(id, |_| {
711                                     Vec::new()
712                                 });
713                                 // extract relevant documentation for this impl
714                                 match attrs.move_iter().find(|a| {
715                                     match *a {
716                                         clean::NameValue(ref x, _) if "doc" == *x => true,
717                                         _ => false
718                                     }
719                                 }) {
720                                     Some(clean::NameValue(_, dox)) => {
721                                         v.push((i, Some(dox)));
722                                     }
723                                     Some(..) | None => {
724                                         v.push((i, None));
725                                     }
726                                 }
727                             }
728                             _ => {}
729                         }
730                         None
731                     }
732                     // Private modules may survive the strip-private pass if
733                     // they contain impls for public types, but those will get
734                     // stripped here
735                     clean::Item { inner: clean::ModuleItem(ref m),
736                                   visibility, .. }
737                             if (m.items.len() == 0 &&
738                                 item.doc_value().is_none()) ||
739                                visibility != Some(ast::Public) => None,
740
741                     i => Some(i),
742                 }
743             }
744             i => i,
745         };
746
747         if pushed { self.stack.pop().unwrap(); }
748         if parent_pushed { self.parent_stack.pop().unwrap(); }
749         self.privmod = orig_privmod;
750         return ret;
751     }
752 }
753
754 impl<'a> Cache {
755     fn generics(&mut self, generics: &clean::Generics) {
756         for typ in generics.type_params.iter() {
757             self.typarams.insert(typ.id, typ.name.clone());
758         }
759     }
760 }
761
762 impl Context {
763     /// Recurse in the directory structure and change the "root path" to make
764     /// sure it always points to the top (relatively)
765     fn recurse<T>(&mut self, s: ~str, f: |&mut Context| -> T) -> T {
766         if s.len() == 0 {
767             fail!("what {:?}", self);
768         }
769         let prev = self.dst.clone();
770         self.dst.push(s.as_slice());
771         self.root_path.push_str("../");
772         self.current.push(s);
773
774         info!("Recursing into {}", self.dst.display());
775
776         mkdir(&self.dst).unwrap();
777         let ret = f(self);
778
779         info!("Recursed; leaving {}", self.dst.display());
780
781         // Go back to where we were at
782         self.dst = prev;
783         let len = self.root_path.len();
784         self.root_path.truncate(len - 3);
785         self.current.pop().unwrap();
786
787         return ret;
788     }
789
790     /// Main method for rendering a crate.
791     ///
792     /// This currently isn't parallelized, but it'd be pretty easy to add
793     /// parallelization to this function.
794     fn krate(self, mut krate: clean::Crate, cache: Cache) -> io::IoResult<()> {
795         let mut item = match krate.module.take() {
796             Some(i) => i,
797             None => return Ok(())
798         };
799         item.name = Some(krate.name);
800
801         // using a rwarc makes this parallelizable in the future
802         local_data::set(cache_key, Arc::new(cache));
803
804         let mut work = vec!((self, item));
805         loop {
806             match work.pop() {
807                 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
808                     work.push((cx.clone(), item));
809                 })),
810                 None => break,
811             }
812         }
813         Ok(())
814     }
815
816     /// Non-parellelized version of rendering an item. This will take the input
817     /// item, render its contents, and then invoke the specified closure with
818     /// all sub-items which need to be rendered.
819     ///
820     /// The rendering driver uses this closure to queue up more work.
821     fn item(&mut self, item: clean::Item,
822             f: |&mut Context, clean::Item|) -> io::IoResult<()> {
823         fn render(w: io::File, cx: &mut Context, it: &clean::Item,
824                   pushname: bool) -> io::IoResult<()> {
825             info!("Rendering an item to {}", w.path().display());
826             // A little unfortunate that this is done like this, but it sure
827             // does make formatting *a lot* nicer.
828             local_data::set(current_location_key, cx.current.clone());
829
830             let mut title = StrBuf::from_str(cx.current.connect("::"));
831             if pushname {
832                 if title.len() > 0 {
833                     title.push_str("::");
834                 }
835                 title.push_str(*it.name.get_ref());
836             }
837             title.push_str(" - Rust");
838             let page = layout::Page {
839                 ty: shortty(it),
840                 root_path: cx.root_path.as_slice(),
841                 title: title.as_slice(),
842             };
843
844             markdown::reset_headers();
845
846             // We have a huge number of calls to write, so try to alleviate some
847             // of the pain by using a buffered writer instead of invoking the
848             // write sycall all the time.
849             let mut writer = BufferedWriter::new(w);
850             try!(layout::render(&mut writer as &mut Writer, &cx.layout, &page,
851                                   &Sidebar{ cx: cx, item: it },
852                                   &Item{ cx: cx, item: it }));
853             writer.flush()
854         }
855
856         match item.inner {
857             // modules are special because they add a namespace. We also need to
858             // recurse into the items of the module as well.
859             clean::ModuleItem(..) => {
860                 let name = item.name.get_ref().to_owned();
861                 let mut item = Some(item);
862                 self.recurse(name, |this| {
863                     let item = item.take_unwrap();
864                     let dst = this.dst.join("index.html");
865                     let dst = try!(File::create(&dst));
866                     try!(render(dst, this, &item, false));
867
868                     let m = match item.inner {
869                         clean::ModuleItem(m) => m,
870                         _ => unreachable!()
871                     };
872                     this.sidebar = build_sidebar(&m);
873                     for item in m.items.move_iter() {
874                         f(this,item);
875                     }
876                     Ok(())
877                 })
878             }
879
880             // Things which don't have names (like impls) don't get special
881             // pages dedicated to them.
882             _ if item.name.is_some() => {
883                 let dst = self.dst.join(item_path(&item));
884                 let dst = try!(File::create(&dst));
885                 render(dst, self, &item, true)
886             }
887
888             _ => Ok(())
889         }
890     }
891 }
892
893 fn shortty(item: &clean::Item) -> &'static str {
894     match item.inner {
895         clean::ModuleItem(..)          => "mod",
896         clean::StructItem(..)          => "struct",
897         clean::EnumItem(..)            => "enum",
898         clean::FunctionItem(..)        => "fn",
899         clean::TypedefItem(..)         => "typedef",
900         clean::StaticItem(..)          => "static",
901         clean::TraitItem(..)           => "trait",
902         clean::ImplItem(..)            => "impl",
903         clean::ViewItemItem(..)        => "viewitem",
904         clean::TyMethodItem(..)        => "tymethod",
905         clean::MethodItem(..)          => "method",
906         clean::StructFieldItem(..)     => "structfield",
907         clean::VariantItem(..)         => "variant",
908         clean::ForeignFunctionItem(..) => "ffi",
909         clean::ForeignStaticItem(..)   => "ffs",
910         clean::MacroItem(..)           => "macro",
911     }
912 }
913
914 impl<'a> Item<'a> {
915     fn ismodule(&self) -> bool {
916         match self.item.inner {
917             clean::ModuleItem(..) => true, _ => false
918         }
919     }
920 }
921
922 impl<'a> fmt::Show for Item<'a> {
923     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
924         match attr::find_stability(self.item.attrs.iter()) {
925             Some(ref stability) => {
926                 try!(write!(fmt.buf,
927                        "<a class='stability {lvl}' title='{reason}'>{lvl}</a>",
928                        lvl = stability.level.to_str(),
929                        reason = match stability.text {
930                            Some(ref s) => (*s).clone(),
931                            None => InternedString::new(""),
932                        }));
933             }
934             None => {}
935         }
936
937         if self.cx.include_sources {
938             let mut path = Vec::new();
939             clean_srcpath(self.item.source.filename.as_bytes(), |component| {
940                 path.push(component.to_owned());
941             });
942             let href = if self.item.source.loline == self.item.source.hiline {
943                 format!("{}", self.item.source.loline)
944             } else {
945                 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
946             };
947             try!(write!(fmt.buf,
948                           "<a class='source'
949                               href='{root}src/{krate}/{path}.html\\#{href}'>\
950                               [src]</a>",
951                           root = self.cx.root_path,
952                           krate = self.cx.layout.krate,
953                           path = path.connect("/"),
954                           href = href));
955         }
956
957         // Write the breadcrumb trail header for the top
958         try!(write!(fmt.buf, "<h1 class='fqn'>"));
959         match self.item.inner {
960             clean::ModuleItem(ref m) => if m.is_crate {
961                     try!(write!(fmt.buf, "Crate "));
962                 } else {
963                     try!(write!(fmt.buf, "Module "));
964                 },
965             clean::FunctionItem(..) => try!(write!(fmt.buf, "Function ")),
966             clean::TraitItem(..) => try!(write!(fmt.buf, "Trait ")),
967             clean::StructItem(..) => try!(write!(fmt.buf, "Struct ")),
968             clean::EnumItem(..) => try!(write!(fmt.buf, "Enum ")),
969             _ => {}
970         }
971         let cur = self.cx.current.as_slice();
972         let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
973         for (i, component) in cur.iter().enumerate().take(amt) {
974             let mut trail = StrBuf::new();
975             for _ in range(0, cur.len() - i - 1) {
976                 trail.push_str("../");
977             }
978             try!(write!(fmt.buf, "<a href='{}index.html'>{}</a>::",
979                           trail, component.as_slice()));
980         }
981         try!(write!(fmt.buf, "<a class='{}' href=''>{}</a></h1>",
982                       shortty(self.item), self.item.name.get_ref().as_slice()));
983
984         match self.item.inner {
985             clean::ModuleItem(ref m) => {
986                 item_module(fmt.buf, self.cx, self.item, m.items.as_slice())
987             }
988             clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
989                 item_function(fmt.buf, self.item, f),
990             clean::TraitItem(ref t) => item_trait(fmt.buf, self.item, t),
991             clean::StructItem(ref s) => item_struct(fmt.buf, self.item, s),
992             clean::EnumItem(ref e) => item_enum(fmt.buf, self.item, e),
993             clean::TypedefItem(ref t) => item_typedef(fmt.buf, self.item, t),
994             clean::MacroItem(ref m) => item_macro(fmt.buf, self.item, m),
995             _ => Ok(())
996         }
997     }
998 }
999
1000 fn item_path(item: &clean::Item) -> ~str {
1001     match item.inner {
1002         clean::ModuleItem(..) => *item.name.get_ref() + "/index.html",
1003         _ => shortty(item) + "." + *item.name.get_ref() + ".html"
1004     }
1005 }
1006
1007 fn full_path(cx: &Context, item: &clean::Item) -> ~str {
1008     let mut s = StrBuf::from_str(cx.current.connect("::"));
1009     s.push_str("::");
1010     s.push_str(item.name.get_ref().as_slice());
1011     return s.into_owned();
1012 }
1013
1014 fn blank<'a>(s: Option<&'a str>) -> &'a str {
1015     match s {
1016         Some(s) => s,
1017         None => ""
1018     }
1019 }
1020
1021 fn shorter<'a>(s: Option<&'a str>) -> &'a str {
1022     match s {
1023         Some(s) => match s.find_str("\n\n") {
1024             Some(pos) => s.slice_to(pos),
1025             None => s,
1026         },
1027         None => ""
1028     }
1029 }
1030
1031 fn document(w: &mut Writer, item: &clean::Item) -> fmt::Result {
1032     match item.doc_value() {
1033         Some(s) => {
1034             try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1035         }
1036         None => {}
1037     }
1038     Ok(())
1039 }
1040
1041 fn item_module(w: &mut Writer, cx: &Context,
1042                item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1043     try!(document(w, item));
1044     debug!("{:?}", items);
1045     let mut indices = slice::from_fn(items.len(), |i| i);
1046
1047     fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering {
1048         if shortty(i1) == shortty(i2) {
1049             return i1.name.cmp(&i2.name);
1050         }
1051         match (&i1.inner, &i2.inner) {
1052             (&clean::ViewItemItem(ref a), &clean::ViewItemItem(ref b)) => {
1053                 match (&a.inner, &b.inner) {
1054                     (&clean::ExternCrate(..), _) => Less,
1055                     (_, &clean::ExternCrate(..)) => Greater,
1056                     _ => idx1.cmp(&idx2),
1057                 }
1058             }
1059             (&clean::ViewItemItem(..), _) => Less,
1060             (_, &clean::ViewItemItem(..)) => Greater,
1061             (&clean::ModuleItem(..), _) => Less,
1062             (_, &clean::ModuleItem(..)) => Greater,
1063             (&clean::MacroItem(..), _) => Less,
1064             (_, &clean::MacroItem(..)) => Greater,
1065             (&clean::StructItem(..), _) => Less,
1066             (_, &clean::StructItem(..)) => Greater,
1067             (&clean::EnumItem(..), _) => Less,
1068             (_, &clean::EnumItem(..)) => Greater,
1069             (&clean::StaticItem(..), _) => Less,
1070             (_, &clean::StaticItem(..)) => Greater,
1071             (&clean::ForeignFunctionItem(..), _) => Less,
1072             (_, &clean::ForeignFunctionItem(..)) => Greater,
1073             (&clean::ForeignStaticItem(..), _) => Less,
1074             (_, &clean::ForeignStaticItem(..)) => Greater,
1075             (&clean::TraitItem(..), _) => Less,
1076             (_, &clean::TraitItem(..)) => Greater,
1077             (&clean::FunctionItem(..), _) => Less,
1078             (_, &clean::FunctionItem(..)) => Greater,
1079             (&clean::TypedefItem(..), _) => Less,
1080             (_, &clean::TypedefItem(..)) => Greater,
1081             _ => idx1.cmp(&idx2),
1082         }
1083     }
1084
1085     debug!("{:?}", indices);
1086     indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1087
1088     debug!("{:?}", indices);
1089     let mut curty = "";
1090     for &idx in indices.iter() {
1091         let myitem = &items[idx];
1092
1093         let myty = shortty(myitem);
1094         if myty != curty {
1095             if curty != "" {
1096                 try!(write!(w, "</table>"));
1097             }
1098             curty = myty;
1099             let (short, name) = match myitem.inner {
1100                 clean::ModuleItem(..)          => ("modules", "Modules"),
1101                 clean::StructItem(..)          => ("structs", "Structs"),
1102                 clean::EnumItem(..)            => ("enums", "Enums"),
1103                 clean::FunctionItem(..)        => ("functions", "Functions"),
1104                 clean::TypedefItem(..)         => ("types", "Type Definitions"),
1105                 clean::StaticItem(..)          => ("statics", "Statics"),
1106                 clean::TraitItem(..)           => ("traits", "Traits"),
1107                 clean::ImplItem(..)            => ("impls", "Implementations"),
1108                 clean::ViewItemItem(..)        => ("reexports", "Reexports"),
1109                 clean::TyMethodItem(..)        => ("tymethods", "Type Methods"),
1110                 clean::MethodItem(..)          => ("methods", "Methods"),
1111                 clean::StructFieldItem(..)     => ("fields", "Struct Fields"),
1112                 clean::VariantItem(..)         => ("variants", "Variants"),
1113                 clean::ForeignFunctionItem(..) => ("ffi-fns", "Foreign Functions"),
1114                 clean::ForeignStaticItem(..)   => ("ffi-statics", "Foreign Statics"),
1115                 clean::MacroItem(..)           => ("macros", "Macros"),
1116             };
1117             try!(write!(w,
1118                         "<h2 id='{id}' class='section-link'>\
1119                         <a href=\"\\#{id}\">{name}</a></h2>\n<table>",
1120                         id = short, name = name));
1121         }
1122
1123         match myitem.inner {
1124             clean::StaticItem(ref s) | clean::ForeignStaticItem(ref s) => {
1125                 struct Initializer<'a>(&'a str);
1126                 impl<'a> fmt::Show for Initializer<'a> {
1127                     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1128                         let Initializer(s) = *self;
1129                         if s.len() == 0 { return Ok(()); }
1130                         try!(write!(f.buf, "<code> = </code>"));
1131                         let tag = if s.contains("\n") { "pre" } else { "code" };
1132                         try!(write!(f.buf, "<{tag}>{}</{tag}>",
1133                                       s.as_slice(), tag=tag));
1134                         Ok(())
1135                     }
1136                 }
1137
1138                 try!(write!(w, "
1139                     <tr>
1140                         <td><code>{}static {}: {}</code>{}</td>
1141                         <td class='docblock'>{}&nbsp;</td>
1142                     </tr>
1143                 ",
1144                 VisSpace(myitem.visibility),
1145                 *myitem.name.get_ref(),
1146                 s.type_,
1147                 Initializer(s.expr),
1148                 Markdown(blank(myitem.doc_value()))));
1149             }
1150
1151             clean::ViewItemItem(ref item) => {
1152                 match item.inner {
1153                     clean::ExternCrate(ref name, ref src, _) => {
1154                         try!(write!(w, "<tr><td><code>extern crate {}",
1155                                       name.as_slice()));
1156                         match *src {
1157                             Some(ref src) => try!(write!(w, " = \"{}\"",
1158                                                            src.as_slice())),
1159                             None => {}
1160                         }
1161                         try!(write!(w, ";</code></td></tr>"));
1162                     }
1163
1164                     clean::Import(ref imports) => {
1165                         for import in imports.iter() {
1166                             try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1167                                           VisSpace(myitem.visibility),
1168                                           *import));
1169                         }
1170                     }
1171                 }
1172
1173             }
1174
1175             _ => {
1176                 if myitem.name.is_none() { continue }
1177                 try!(write!(w, "
1178                     <tr>
1179                         <td><a class='{class}' href='{href}'
1180                                title='{title}'>{}</a></td>
1181                         <td class='docblock short'>{}</td>
1182                     </tr>
1183                 ",
1184                 *myitem.name.get_ref(),
1185                 Markdown(shorter(myitem.doc_value())),
1186                 class = shortty(myitem),
1187                 href = item_path(myitem),
1188                 title = full_path(cx, myitem)));
1189             }
1190         }
1191     }
1192     write!(w, "</table>")
1193 }
1194
1195 fn item_function(w: &mut Writer, it: &clean::Item,
1196                  f: &clean::Function) -> fmt::Result {
1197     try!(write!(w, "<pre class='rust fn'>{vis}{fn_style}fn \
1198                     {name}{generics}{decl}</pre>",
1199            vis = VisSpace(it.visibility),
1200            fn_style = FnStyleSpace(f.fn_style),
1201            name = it.name.get_ref().as_slice(),
1202            generics = f.generics,
1203            decl = f.decl));
1204     document(w, it)
1205 }
1206
1207 fn item_trait(w: &mut Writer, it: &clean::Item,
1208               t: &clean::Trait) -> fmt::Result {
1209     let mut parents = StrBuf::new();
1210     if t.parents.len() > 0 {
1211         parents.push_str(": ");
1212         for (i, p) in t.parents.iter().enumerate() {
1213             if i > 0 { parents.push_str(" + "); }
1214             parents.push_str(format!("{}", *p));
1215         }
1216     }
1217
1218     // Output the trait definition
1219     try!(write!(w, "<pre class='rust trait'>{}trait {}{}{} ",
1220                   VisSpace(it.visibility),
1221                   it.name.get_ref().as_slice(),
1222                   t.generics,
1223                   parents));
1224     let required = t.methods.iter().filter(|m| m.is_req()).collect::<Vec<&clean::TraitMethod>>();
1225     let provided = t.methods.iter().filter(|m| !m.is_req()).collect::<Vec<&clean::TraitMethod>>();
1226
1227     if t.methods.len() == 0 {
1228         try!(write!(w, "\\{ \\}"));
1229     } else {
1230         try!(write!(w, "\\{\n"));
1231         for m in required.iter() {
1232             try!(write!(w, "    "));
1233             try!(render_method(w, m.item()));
1234             try!(write!(w, ";\n"));
1235         }
1236         if required.len() > 0 && provided.len() > 0 {
1237             try!(w.write("\n".as_bytes()));
1238         }
1239         for m in provided.iter() {
1240             try!(write!(w, "    "));
1241             try!(render_method(w, m.item()));
1242             try!(write!(w, " \\{ ... \\}\n"));
1243         }
1244         try!(write!(w, "\\}"));
1245     }
1246     try!(write!(w, "</pre>"));
1247
1248     // Trait documentation
1249     try!(document(w, it));
1250
1251     fn meth(w: &mut Writer, m: &clean::TraitMethod) -> fmt::Result {
1252         try!(write!(w, "<h3 id='{}.{}' class='method'><code>",
1253                       shortty(m.item()),
1254                       *m.item().name.get_ref()));
1255         try!(render_method(w, m.item()));
1256         try!(write!(w, "</code></h3>"));
1257         try!(document(w, m.item()));
1258         Ok(())
1259     }
1260
1261     // Output the documentation for each function individually
1262     if required.len() > 0 {
1263         try!(write!(w, "
1264             <h2 id='required-methods'>Required Methods</h2>
1265             <div class='methods'>
1266         "));
1267         for m in required.iter() {
1268             try!(meth(w, *m));
1269         }
1270         try!(write!(w, "</div>"));
1271     }
1272     if provided.len() > 0 {
1273         try!(write!(w, "
1274             <h2 id='provided-methods'>Provided Methods</h2>
1275             <div class='methods'>
1276         "));
1277         for m in provided.iter() {
1278             try!(meth(w, *m));
1279         }
1280         try!(write!(w, "</div>"));
1281     }
1282
1283     local_data::get(cache_key, |cache| {
1284         let cache = cache.unwrap();
1285         match cache.implementors.find(&it.id) {
1286             Some(implementors) => {
1287                 try!(write!(w, "
1288                     <h2 id='implementors'>Implementors</h2>
1289                     <ul class='item-list'>
1290                 "));
1291                 for i in implementors.iter() {
1292                     match *i {
1293                         PathType(ref ty) => {
1294                             try!(write!(w, "<li><code>{}</code></li>", *ty));
1295                         }
1296                         OtherType(ref generics, ref trait_, ref for_) => {
1297                             try!(write!(w, "<li><code>impl{} {} for {}</code></li>",
1298                                           *generics, *trait_, *for_));
1299                         }
1300                     }
1301                 }
1302                 try!(write!(w, "</ul>"));
1303             }
1304             None => {}
1305         }
1306         Ok(())
1307     })
1308 }
1309
1310 fn render_method(w: &mut Writer, meth: &clean::Item) -> fmt::Result {
1311     fn fun(w: &mut Writer, it: &clean::Item, fn_style: ast::FnStyle,
1312            g: &clean::Generics, selfty: &clean::SelfTy,
1313            d: &clean::FnDecl) -> fmt::Result {
1314         write!(w, "{}fn <a href='\\#{ty}.{name}' class='fnname'>{name}</a>\
1315                    {generics}{decl}",
1316                match fn_style {
1317                    ast::UnsafeFn => "unsafe ",
1318                    _ => "",
1319                },
1320                ty = shortty(it),
1321                name = it.name.get_ref().as_slice(),
1322                generics = *g,
1323                decl = Method(selfty, d))
1324     }
1325     match meth.inner {
1326         clean::TyMethodItem(ref m) => {
1327             fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
1328         }
1329         clean::MethodItem(ref m) => {
1330             fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
1331         }
1332         _ => unreachable!()
1333     }
1334 }
1335
1336 fn item_struct(w: &mut Writer, it: &clean::Item,
1337                s: &clean::Struct) -> fmt::Result {
1338     try!(write!(w, "<pre class='rust struct'>"));
1339     try!(render_struct(w,
1340                        it,
1341                        Some(&s.generics),
1342                        s.struct_type,
1343                        s.fields.as_slice(),
1344                        s.fields_stripped,
1345                        "",
1346                        true));
1347     try!(write!(w, "</pre>"));
1348
1349     try!(document(w, it));
1350     match s.struct_type {
1351         doctree::Plain if s.fields.len() > 0 => {
1352             try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
1353             for field in s.fields.iter() {
1354                 try!(write!(w, "<tr><td id='structfield.{name}'>\
1355                                   <code>{name}</code></td><td>",
1356                               name = field.name.get_ref().as_slice()));
1357                 try!(document(w, field));
1358                 try!(write!(w, "</td></tr>"));
1359             }
1360             try!(write!(w, "</table>"));
1361         }
1362         _ => {}
1363     }
1364     render_methods(w, it)
1365 }
1366
1367 fn item_enum(w: &mut Writer, it: &clean::Item, e: &clean::Enum) -> fmt::Result {
1368     try!(write!(w, "<pre class='rust enum'>{}enum {}{}",
1369                   VisSpace(it.visibility),
1370                   it.name.get_ref().as_slice(),
1371                   e.generics));
1372     if e.variants.len() == 0 && !e.variants_stripped {
1373         try!(write!(w, " \\{\\}"));
1374     } else {
1375         try!(write!(w, " \\{\n"));
1376         for v in e.variants.iter() {
1377             try!(write!(w, "    "));
1378             let name = v.name.get_ref().as_slice();
1379             match v.inner {
1380                 clean::VariantItem(ref var) => {
1381                     match var.kind {
1382                         clean::CLikeVariant => try!(write!(w, "{}", name)),
1383                         clean::TupleVariant(ref tys) => {
1384                             try!(write!(w, "{}(", name));
1385                             for (i, ty) in tys.iter().enumerate() {
1386                                 if i > 0 {
1387                                     try!(write!(w, ", "))
1388                                 }
1389                                 try!(write!(w, "{}", *ty));
1390                             }
1391                             try!(write!(w, ")"));
1392                         }
1393                         clean::StructVariant(ref s) => {
1394                             try!(render_struct(w,
1395                                                v,
1396                                                None,
1397                                                s.struct_type,
1398                                                s.fields.as_slice(),
1399                                                s.fields_stripped,
1400                                                "    ",
1401                                                false));
1402                         }
1403                     }
1404                 }
1405                 _ => unreachable!()
1406             }
1407             try!(write!(w, ",\n"));
1408         }
1409
1410         if e.variants_stripped {
1411             try!(write!(w, "    // some variants omitted\n"));
1412         }
1413         try!(write!(w, "\\}"));
1414     }
1415     try!(write!(w, "</pre>"));
1416
1417     try!(document(w, it));
1418     if e.variants.len() > 0 {
1419         try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
1420         for variant in e.variants.iter() {
1421             try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
1422                           name = variant.name.get_ref().as_slice()));
1423             try!(document(w, variant));
1424             match variant.inner {
1425                 clean::VariantItem(ref var) => {
1426                     match var.kind {
1427                         clean::StructVariant(ref s) => {
1428                             try!(write!(w, "<h3 class='fields'>Fields</h3>\n
1429                                               <table>"));
1430                             for field in s.fields.iter() {
1431                                 try!(write!(w, "<tr><td \
1432                                                   id='variant.{v}.field.{f}'>\
1433                                                   <code>{f}</code></td><td>",
1434                                               v = variant.name.get_ref().as_slice(),
1435                                               f = field.name.get_ref().as_slice()));
1436                                 try!(document(w, field));
1437                                 try!(write!(w, "</td></tr>"));
1438                             }
1439                             try!(write!(w, "</table>"));
1440                         }
1441                         _ => ()
1442                     }
1443                 }
1444                 _ => ()
1445             }
1446             try!(write!(w, "</td></tr>"));
1447         }
1448         try!(write!(w, "</table>"));
1449
1450     }
1451     try!(render_methods(w, it));
1452     Ok(())
1453 }
1454
1455 fn render_struct(w: &mut Writer, it: &clean::Item,
1456                  g: Option<&clean::Generics>,
1457                  ty: doctree::StructType,
1458                  fields: &[clean::Item],
1459                  fields_stripped: bool,
1460                  tab: &str,
1461                  structhead: bool) -> fmt::Result {
1462     try!(write!(w, "{}{}{}",
1463                   VisSpace(it.visibility),
1464                   if structhead {"struct "} else {""},
1465                   it.name.get_ref().as_slice()));
1466     match g {
1467         Some(g) => try!(write!(w, "{}", *g)),
1468         None => {}
1469     }
1470     match ty {
1471         doctree::Plain => {
1472             try!(write!(w, " \\{\n{}", tab));
1473             for field in fields.iter() {
1474                 match field.inner {
1475                     clean::StructFieldItem(ref ty) => {
1476                         try!(write!(w, "    {}{}: {},\n{}",
1477                                       VisSpace(field.visibility),
1478                                       field.name.get_ref().as_slice(),
1479                                       ty.type_,
1480                                       tab));
1481                     }
1482                     _ => unreachable!()
1483                 }
1484             }
1485
1486             if fields_stripped {
1487                 try!(write!(w, "    // some fields omitted\n{}", tab));
1488             }
1489             try!(write!(w, "\\}"));
1490         }
1491         doctree::Tuple | doctree::Newtype => {
1492             try!(write!(w, "("));
1493             for (i, field) in fields.iter().enumerate() {
1494                 if i > 0 {
1495                     try!(write!(w, ", "));
1496                 }
1497                 match field.inner {
1498                     clean::StructFieldItem(ref field) => {
1499                         try!(write!(w, "{}", field.type_));
1500                     }
1501                     _ => unreachable!()
1502                 }
1503             }
1504             try!(write!(w, ");"));
1505         }
1506         doctree::Unit => {
1507             try!(write!(w, ";"));
1508         }
1509     }
1510     Ok(())
1511 }
1512
1513 fn render_methods(w: &mut Writer, it: &clean::Item) -> fmt::Result {
1514     local_data::get(cache_key, |cache| {
1515         let c = cache.unwrap();
1516         match c.impls.find(&it.id) {
1517             Some(v) => {
1518                 let mut non_trait = v.iter().filter(|p| {
1519                     p.ref0().trait_.is_none()
1520                 });
1521                 let non_trait = non_trait.collect::<Vec<&(clean::Impl, Option<~str>)>>();
1522                 let mut traits = v.iter().filter(|p| {
1523                     p.ref0().trait_.is_some()
1524                 });
1525                 let traits = traits.collect::<Vec<&(clean::Impl, Option<~str>)>>();
1526
1527                 if non_trait.len() > 0 {
1528                     try!(write!(w, "<h2 id='methods'>Methods</h2>"));
1529                     for &(ref i, ref dox) in non_trait.move_iter() {
1530                         try!(render_impl(w, i, dox));
1531                     }
1532                 }
1533                 if traits.len() > 0 {
1534                     try!(write!(w, "<h2 id='implementations'>Trait \
1535                                       Implementations</h2>"));
1536                     let mut any_derived = false;
1537                     for & &(ref i, ref dox) in traits.iter() {
1538                         if !i.derived {
1539                             try!(render_impl(w, i, dox));
1540                         } else {
1541                             any_derived = true;
1542                         }
1543                     }
1544                     if any_derived {
1545                         try!(write!(w, "<h3 id='derived_implementations'>Derived Implementations \
1546                                     </h3>"));
1547                         for &(ref i, ref dox) in traits.move_iter() {
1548                             if i.derived {
1549                                 try!(render_impl(w, i, dox));
1550                             }
1551                         }
1552                     }
1553                 }
1554             }
1555             None => {}
1556         }
1557         Ok(())
1558     })
1559 }
1560
1561 fn render_impl(w: &mut Writer, i: &clean::Impl,
1562                dox: &Option<~str>) -> fmt::Result {
1563     try!(write!(w, "<h3 class='impl'><code>impl{} ", i.generics));
1564     let trait_id = match i.trait_ {
1565         Some(ref ty) => {
1566             try!(write!(w, "{} for ", *ty));
1567             match *ty {
1568                 clean::ResolvedPath { id, .. } => Some(id),
1569                 _ => None,
1570             }
1571         }
1572         None => None
1573     };
1574     try!(write!(w, "{}</code></h3>", i.for_));
1575     match *dox {
1576         Some(ref dox) => {
1577             try!(write!(w, "<div class='docblock'>{}</div>",
1578                           Markdown(dox.as_slice())));
1579         }
1580         None => {}
1581     }
1582
1583     fn docmeth(w: &mut Writer, item: &clean::Item) -> io::IoResult<bool> {
1584         try!(write!(w, "<h4 id='method.{}' class='method'><code>",
1585                       *item.name.get_ref()));
1586         try!(render_method(w, item));
1587         try!(write!(w, "</code></h4>\n"));
1588         match item.doc_value() {
1589             Some(s) => {
1590                 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1591                 Ok(true)
1592             }
1593             None => Ok(false)
1594         }
1595     }
1596
1597     try!(write!(w, "<div class='methods'>"));
1598     for meth in i.methods.iter() {
1599         if try!(docmeth(w, meth)) {
1600             continue
1601         }
1602
1603         // No documentation? Attempt to slurp in the trait's documentation
1604         let trait_id = match trait_id {
1605             None => continue,
1606             Some(id) => id,
1607         };
1608         try!(local_data::get(cache_key, |cache| {
1609             let cache = cache.unwrap();
1610             match cache.traits.find(&trait_id) {
1611                 Some(t) => {
1612                     let name = meth.name.clone();
1613                     match t.methods.iter().find(|t| t.item().name == name) {
1614                         Some(method) => {
1615                             match method.item().doc_value() {
1616                                 Some(s) => {
1617                                     try!(write!(w,
1618                                                   "<div class='docblock'>{}</div>",
1619                                                   Markdown(s)));
1620                                 }
1621                                 None => {}
1622                             }
1623                         }
1624                         None => {}
1625                     }
1626                 }
1627                 None => {}
1628             }
1629             Ok(())
1630         }))
1631     }
1632
1633     // If we've implemented a trait, then also emit documentation for all
1634     // default methods which weren't overridden in the implementation block.
1635     match trait_id {
1636         None => {}
1637         Some(id) => {
1638             try!(local_data::get(cache_key, |cache| {
1639                 let cache = cache.unwrap();
1640                 match cache.traits.find(&id) {
1641                     Some(t) => {
1642                         for method in t.methods.iter() {
1643                             let n = method.item().name.clone();
1644                             match i.methods.iter().find(|m| m.name == n) {
1645                                 Some(..) => continue,
1646                                 None => {}
1647                             }
1648
1649                             try!(docmeth(w, method.item()));
1650                         }
1651                     }
1652                     None => {}
1653                 }
1654                 Ok(())
1655             }))
1656         }
1657     }
1658     try!(write!(w, "</div>"));
1659     Ok(())
1660 }
1661
1662 fn item_typedef(w: &mut Writer, it: &clean::Item,
1663                 t: &clean::Typedef) -> fmt::Result {
1664     try!(write!(w, "<pre class='rust typedef'>type {}{} = {};</pre>",
1665                   it.name.get_ref().as_slice(),
1666                   t.generics,
1667                   t.type_));
1668
1669     document(w, it)
1670 }
1671
1672 impl<'a> fmt::Show for Sidebar<'a> {
1673     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1674         let cx = self.cx;
1675         let it = self.item;
1676         try!(write!(fmt.buf, "<p class='location'>"));
1677         let len = cx.current.len() - if it.is_mod() {1} else {0};
1678         for (i, name) in cx.current.iter().take(len).enumerate() {
1679             if i > 0 {
1680                 try!(write!(fmt.buf, "&\\#8203;::"));
1681             }
1682             try!(write!(fmt.buf, "<a href='{}index.html'>{}</a>",
1683                           cx.root_path
1684                             .as_slice()
1685                             .slice_to((cx.current.len() - i - 1) * 3),
1686                           *name));
1687         }
1688         try!(write!(fmt.buf, "</p>"));
1689
1690         fn block(w: &mut Writer, short: &str, longty: &str,
1691                  cur: &clean::Item, cx: &Context) -> fmt::Result {
1692             let items = match cx.sidebar.find_equiv(&short) {
1693                 Some(items) => items.as_slice(),
1694                 None => return Ok(())
1695             };
1696             try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
1697             for item in items.iter() {
1698                 let class = if cur.name.get_ref() == item &&
1699                                short == shortty(cur) { "current" } else { "" };
1700                 try!(write!(w, "<a class='{ty} {class}' href='{curty, select,
1701                                 mod{../}
1702                                 other{}
1703                            }{tysel, select,
1704                                 mod{{name}/index.html}
1705                                 other{#.{name}.html}
1706                            }'>{name}</a><br/>",
1707                        ty = short,
1708                        tysel = short,
1709                        class = class,
1710                        curty = shortty(cur),
1711                        name = item.as_slice()));
1712             }
1713             try!(write!(w, "</div>"));
1714             Ok(())
1715         }
1716
1717         try!(block(fmt.buf, "mod", "Modules", it, cx));
1718         try!(block(fmt.buf, "struct", "Structs", it, cx));
1719         try!(block(fmt.buf, "enum", "Enums", it, cx));
1720         try!(block(fmt.buf, "trait", "Traits", it, cx));
1721         try!(block(fmt.buf, "fn", "Functions", it, cx));
1722         Ok(())
1723     }
1724 }
1725
1726 fn build_sidebar(m: &clean::Module) -> HashMap<~str, Vec<~str> > {
1727     let mut map = HashMap::new();
1728     for item in m.items.iter() {
1729         let short = shortty(item);
1730         let myname = match item.name {
1731             None => continue,
1732             Some(ref s) => s.to_owned(),
1733         };
1734         let v = map.find_or_insert_with(short.to_owned(), |_| Vec::new());
1735         v.push(myname);
1736     }
1737
1738     for (_, items) in map.mut_iter() {
1739         items.as_mut_slice().sort();
1740     }
1741     return map;
1742 }
1743
1744 impl<'a> fmt::Show for Source<'a> {
1745     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1746         let Source(s) = *self;
1747         let lines = s.lines().len();
1748         let mut cols = 0;
1749         let mut tmp = lines;
1750         while tmp > 0 {
1751             cols += 1;
1752             tmp /= 10;
1753         }
1754         try!(write!(fmt.buf, "<pre class='line-numbers'>"));
1755         for i in range(1, lines + 1) {
1756             try!(write!(fmt.buf, "<span id='{0:u}'>{0:1$u}</span>\n", i, cols));
1757         }
1758         try!(write!(fmt.buf, "</pre>"));
1759         try!(write!(fmt.buf, "{}", highlight::highlight(s.as_slice(), None)));
1760         Ok(())
1761     }
1762 }
1763
1764 fn item_macro(w: &mut Writer, it: &clean::Item,
1765               t: &clean::Macro) -> fmt::Result {
1766     try!(w.write_str(highlight::highlight(t.source, Some("macro"))));
1767     document(w, it)
1768 }