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