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