]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render.rs
6bbe22402d10c6dfb38a085d0d964da0c25d7ad4
[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: ~[~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, ~[~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, ~[(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, (~[~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, ~[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: ~[~str],
159     priv parent_stack: ~[ast::NodeId],
160     priv search_index: ~[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: ~[~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: ~[],
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: ~[],
254             parent_stack: ~[],
255             search_index: ~[],
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                             ~[]
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                                     ~[]
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 = ~[(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 = ~[];
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) => item_module(fmt.buf, self.cx,
970                                                     self.item, m.items),
971             clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
972                 item_function(fmt.buf, self.item, f),
973             clean::TraitItem(ref t) => item_trait(fmt.buf, self.item, t),
974             clean::StructItem(ref s) => item_struct(fmt.buf, self.item, s),
975             clean::EnumItem(ref e) => item_enum(fmt.buf, self.item, e),
976             clean::TypedefItem(ref t) => item_typedef(fmt.buf, self.item, t),
977             clean::MacroItem(ref m) => item_macro(fmt.buf, self.item, m),
978             _ => Ok(())
979         }
980     }
981 }
982
983 fn item_path(item: &clean::Item) -> ~str {
984     match item.inner {
985         clean::ModuleItem(..) => *item.name.get_ref() + "/index.html",
986         _ => shortty(item) + "." + *item.name.get_ref() + ".html"
987     }
988 }
989
990 fn full_path(cx: &Context, item: &clean::Item) -> ~str {
991     let mut s = cx.current.connect("::");
992     s.push_str("::");
993     s.push_str(item.name.get_ref().as_slice());
994     return s;
995 }
996
997 fn blank<'a>(s: Option<&'a str>) -> &'a str {
998     match s {
999         Some(s) => s,
1000         None => ""
1001     }
1002 }
1003
1004 fn shorter<'a>(s: Option<&'a str>) -> &'a str {
1005     match s {
1006         Some(s) => match s.find_str("\n\n") {
1007             Some(pos) => s.slice_to(pos),
1008             None => s,
1009         },
1010         None => ""
1011     }
1012 }
1013
1014 fn document(w: &mut Writer, item: &clean::Item) -> fmt::Result {
1015     match item.doc_value() {
1016         Some(s) => {
1017             try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1018         }
1019         None => {}
1020     }
1021     Ok(())
1022 }
1023
1024 fn item_module(w: &mut Writer, cx: &Context,
1025                item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1026     try!(document(w, item));
1027     debug!("{:?}", items);
1028     let mut indices = slice::from_fn(items.len(), |i| i);
1029
1030     fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering {
1031         if shortty(i1) == shortty(i2) {
1032             return i1.name.cmp(&i2.name);
1033         }
1034         match (&i1.inner, &i2.inner) {
1035             (&clean::ViewItemItem(ref a), &clean::ViewItemItem(ref b)) => {
1036                 match (&a.inner, &b.inner) {
1037                     (&clean::ExternCrate(..), _) => Less,
1038                     (_, &clean::ExternCrate(..)) => Greater,
1039                     _ => idx1.cmp(&idx2),
1040                 }
1041             }
1042             (&clean::ViewItemItem(..), _) => Less,
1043             (_, &clean::ViewItemItem(..)) => Greater,
1044             (&clean::ModuleItem(..), _) => Less,
1045             (_, &clean::ModuleItem(..)) => Greater,
1046             (&clean::MacroItem(..), _) => Less,
1047             (_, &clean::MacroItem(..)) => Greater,
1048             (&clean::StructItem(..), _) => Less,
1049             (_, &clean::StructItem(..)) => Greater,
1050             (&clean::EnumItem(..), _) => Less,
1051             (_, &clean::EnumItem(..)) => Greater,
1052             (&clean::StaticItem(..), _) => Less,
1053             (_, &clean::StaticItem(..)) => Greater,
1054             (&clean::ForeignFunctionItem(..), _) => Less,
1055             (_, &clean::ForeignFunctionItem(..)) => Greater,
1056             (&clean::ForeignStaticItem(..), _) => Less,
1057             (_, &clean::ForeignStaticItem(..)) => Greater,
1058             (&clean::TraitItem(..), _) => Less,
1059             (_, &clean::TraitItem(..)) => Greater,
1060             (&clean::FunctionItem(..), _) => Less,
1061             (_, &clean::FunctionItem(..)) => Greater,
1062             (&clean::TypedefItem(..), _) => Less,
1063             (_, &clean::TypedefItem(..)) => Greater,
1064             _ => idx1.cmp(&idx2),
1065         }
1066     }
1067
1068     debug!("{:?}", indices);
1069     indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1070
1071     debug!("{:?}", indices);
1072     let mut curty = "";
1073     for &idx in indices.iter() {
1074         let myitem = &items[idx];
1075
1076         let myty = shortty(myitem);
1077         if myty != curty {
1078             if curty != "" {
1079                 try!(write!(w, "</table>"));
1080             }
1081             curty = myty;
1082             let (short, name) = match myitem.inner {
1083                 clean::ModuleItem(..)          => ("modules", "Modules"),
1084                 clean::StructItem(..)          => ("structs", "Structs"),
1085                 clean::EnumItem(..)            => ("enums", "Enums"),
1086                 clean::FunctionItem(..)        => ("functions", "Functions"),
1087                 clean::TypedefItem(..)         => ("types", "Type Definitions"),
1088                 clean::StaticItem(..)          => ("statics", "Statics"),
1089                 clean::TraitItem(..)           => ("traits", "Traits"),
1090                 clean::ImplItem(..)            => ("impls", "Implementations"),
1091                 clean::ViewItemItem(..)        => ("reexports", "Reexports"),
1092                 clean::TyMethodItem(..)        => ("tymethods", "Type Methods"),
1093                 clean::MethodItem(..)          => ("methods", "Methods"),
1094                 clean::StructFieldItem(..)     => ("fields", "Struct Fields"),
1095                 clean::VariantItem(..)         => ("variants", "Variants"),
1096                 clean::ForeignFunctionItem(..) => ("ffi-fns", "Foreign Functions"),
1097                 clean::ForeignStaticItem(..)   => ("ffi-statics", "Foreign Statics"),
1098                 clean::MacroItem(..)           => ("macros", "Macros"),
1099             };
1100             try!(write!(w,
1101                         "<h2 id='{id}' class='section-link'>\
1102                         <a href=\"\\#{id}\">{name}</a></h2>\n<table>",
1103                         id = short, name = name));
1104         }
1105
1106         match myitem.inner {
1107             clean::StaticItem(ref s) | clean::ForeignStaticItem(ref s) => {
1108                 struct Initializer<'a>(&'a str);
1109                 impl<'a> fmt::Show for Initializer<'a> {
1110                     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1111                         let Initializer(s) = *self;
1112                         if s.len() == 0 { return Ok(()); }
1113                         try!(write!(f.buf, "<code> = </code>"));
1114                         let tag = if s.contains("\n") { "pre" } else { "code" };
1115                         try!(write!(f.buf, "<{tag}>{}</{tag}>",
1116                                       s.as_slice(), tag=tag));
1117                         Ok(())
1118                     }
1119                 }
1120
1121                 try!(write!(w, "
1122                     <tr>
1123                         <td><code>{}static {}: {}</code>{}</td>
1124                         <td class='docblock'>{}&nbsp;</td>
1125                     </tr>
1126                 ",
1127                 VisSpace(myitem.visibility),
1128                 *myitem.name.get_ref(),
1129                 s.type_,
1130                 Initializer(s.expr),
1131                 Markdown(blank(myitem.doc_value()))));
1132             }
1133
1134             clean::ViewItemItem(ref item) => {
1135                 match item.inner {
1136                     clean::ExternCrate(ref name, ref src, _) => {
1137                         try!(write!(w, "<tr><td><code>extern crate {}",
1138                                       name.as_slice()));
1139                         match *src {
1140                             Some(ref src) => try!(write!(w, " = \"{}\"",
1141                                                            src.as_slice())),
1142                             None => {}
1143                         }
1144                         try!(write!(w, ";</code></td></tr>"));
1145                     }
1146
1147                     clean::Import(ref imports) => {
1148                         for import in imports.iter() {
1149                             try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1150                                           VisSpace(myitem.visibility),
1151                                           *import));
1152                         }
1153                     }
1154                 }
1155
1156             }
1157
1158             _ => {
1159                 if myitem.name.is_none() { continue }
1160                 try!(write!(w, "
1161                     <tr>
1162                         <td><a class='{class}' href='{href}'
1163                                title='{title}'>{}</a></td>
1164                         <td class='docblock short'>{}</td>
1165                     </tr>
1166                 ",
1167                 *myitem.name.get_ref(),
1168                 Markdown(shorter(myitem.doc_value())),
1169                 class = shortty(myitem),
1170                 href = item_path(myitem),
1171                 title = full_path(cx, myitem)));
1172             }
1173         }
1174     }
1175     write!(w, "</table>")
1176 }
1177
1178 fn item_function(w: &mut Writer, it: &clean::Item,
1179                  f: &clean::Function) -> fmt::Result {
1180     try!(write!(w, "<pre class='rust fn'>{vis}{purity}fn \
1181                     {name}{generics}{decl}</pre>",
1182            vis = VisSpace(it.visibility),
1183            purity = PuritySpace(f.purity),
1184            name = it.name.get_ref().as_slice(),
1185            generics = f.generics,
1186            decl = f.decl));
1187     document(w, it)
1188 }
1189
1190 fn item_trait(w: &mut Writer, it: &clean::Item,
1191               t: &clean::Trait) -> fmt::Result {
1192     let mut parents = ~"";
1193     if t.parents.len() > 0 {
1194         parents.push_str(": ");
1195         for (i, p) in t.parents.iter().enumerate() {
1196             if i > 0 { parents.push_str(" + "); }
1197             parents.push_str(format!("{}", *p));
1198         }
1199     }
1200
1201     // Output the trait definition
1202     try!(write!(w, "<pre class='rust trait'>{}trait {}{}{} ",
1203                   VisSpace(it.visibility),
1204                   it.name.get_ref().as_slice(),
1205                   t.generics,
1206                   parents));
1207     let required = t.methods.iter().filter(|m| m.is_req()).to_owned_vec();
1208     let provided = t.methods.iter().filter(|m| !m.is_req()).to_owned_vec();
1209
1210     if t.methods.len() == 0 {
1211         try!(write!(w, "\\{ \\}"));
1212     } else {
1213         try!(write!(w, "\\{\n"));
1214         for m in required.iter() {
1215             try!(write!(w, "    "));
1216             try!(render_method(w, m.item()));
1217             try!(write!(w, ";\n"));
1218         }
1219         if required.len() > 0 && provided.len() > 0 {
1220             try!(w.write("\n".as_bytes()));
1221         }
1222         for m in provided.iter() {
1223             try!(write!(w, "    "));
1224             try!(render_method(w, m.item()));
1225             try!(write!(w, " \\{ ... \\}\n"));
1226         }
1227         try!(write!(w, "\\}"));
1228     }
1229     try!(write!(w, "</pre>"));
1230
1231     // Trait documentation
1232     try!(document(w, it));
1233
1234     fn meth(w: &mut Writer, m: &clean::TraitMethod) -> fmt::Result {
1235         try!(write!(w, "<h3 id='{}.{}' class='method'><code>",
1236                       shortty(m.item()),
1237                       *m.item().name.get_ref()));
1238         try!(render_method(w, m.item()));
1239         try!(write!(w, "</code></h3>"));
1240         try!(document(w, m.item()));
1241         Ok(())
1242     }
1243
1244     // Output the documentation for each function individually
1245     if required.len() > 0 {
1246         try!(write!(w, "
1247             <h2 id='required-methods'>Required Methods</h2>
1248             <div class='methods'>
1249         "));
1250         for m in required.iter() {
1251             try!(meth(w, *m));
1252         }
1253         try!(write!(w, "</div>"));
1254     }
1255     if provided.len() > 0 {
1256         try!(write!(w, "
1257             <h2 id='provided-methods'>Provided Methods</h2>
1258             <div class='methods'>
1259         "));
1260         for m in provided.iter() {
1261             try!(meth(w, *m));
1262         }
1263         try!(write!(w, "</div>"));
1264     }
1265
1266     local_data::get(cache_key, |cache| {
1267         let cache = cache.unwrap().get();
1268         match cache.implementors.find(&it.id) {
1269             Some(implementors) => {
1270                 try!(write!(w, "
1271                     <h2 id='implementors'>Implementors</h2>
1272                     <ul class='item-list'>
1273                 "));
1274                 for i in implementors.iter() {
1275                     match *i {
1276                         PathType(ref ty) => {
1277                             try!(write!(w, "<li><code>{}</code></li>", *ty));
1278                         }
1279                         OtherType(ref generics, ref trait_, ref for_) => {
1280                             try!(write!(w, "<li><code>impl{} {} for {}</code></li>",
1281                                           *generics, *trait_, *for_));
1282                         }
1283                     }
1284                 }
1285                 try!(write!(w, "</ul>"));
1286             }
1287             None => {}
1288         }
1289         Ok(())
1290     })
1291 }
1292
1293 fn render_method(w: &mut Writer, meth: &clean::Item) -> fmt::Result {
1294     fn fun(w: &mut Writer, it: &clean::Item, purity: ast::Purity,
1295            g: &clean::Generics, selfty: &clean::SelfTy,
1296            d: &clean::FnDecl) -> fmt::Result {
1297         write!(w, "{}fn <a href='\\#{ty}.{name}' class='fnname'>{name}</a>\
1298                    {generics}{decl}",
1299                match purity {
1300                    ast::UnsafeFn => "unsafe ",
1301                    _ => "",
1302                },
1303                ty = shortty(it),
1304                name = it.name.get_ref().as_slice(),
1305                generics = *g,
1306                decl = Method(selfty, d))
1307     }
1308     match meth.inner {
1309         clean::TyMethodItem(ref m) => {
1310             fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl)
1311         }
1312         clean::MethodItem(ref m) => {
1313             fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl)
1314         }
1315         _ => unreachable!()
1316     }
1317 }
1318
1319 fn item_struct(w: &mut Writer, it: &clean::Item,
1320                s: &clean::Struct) -> fmt::Result {
1321     try!(write!(w, "<pre class='rust struct'>"));
1322     try!(render_struct(w, it, Some(&s.generics), s.struct_type, s.fields,
1323                          s.fields_stripped, "", true));
1324     try!(write!(w, "</pre>"));
1325
1326     try!(document(w, it));
1327     match s.struct_type {
1328         doctree::Plain if s.fields.len() > 0 => {
1329             try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
1330             for field in s.fields.iter() {
1331                 try!(write!(w, "<tr><td id='structfield.{name}'>\
1332                                   <code>{name}</code></td><td>",
1333                               name = field.name.get_ref().as_slice()));
1334                 try!(document(w, field));
1335                 try!(write!(w, "</td></tr>"));
1336             }
1337             try!(write!(w, "</table>"));
1338         }
1339         _ => {}
1340     }
1341     render_methods(w, it)
1342 }
1343
1344 fn item_enum(w: &mut Writer, it: &clean::Item, e: &clean::Enum) -> fmt::Result {
1345     try!(write!(w, "<pre class='rust enum'>{}enum {}{}",
1346                   VisSpace(it.visibility),
1347                   it.name.get_ref().as_slice(),
1348                   e.generics));
1349     if e.variants.len() == 0 && !e.variants_stripped {
1350         try!(write!(w, " \\{\\}"));
1351     } else {
1352         try!(write!(w, " \\{\n"));
1353         for v in e.variants.iter() {
1354             try!(write!(w, "    "));
1355             let name = v.name.get_ref().as_slice();
1356             match v.inner {
1357                 clean::VariantItem(ref var) => {
1358                     match var.kind {
1359                         clean::CLikeVariant => try!(write!(w, "{}", name)),
1360                         clean::TupleVariant(ref tys) => {
1361                             try!(write!(w, "{}(", name));
1362                             for (i, ty) in tys.iter().enumerate() {
1363                                 if i > 0 {
1364                                     try!(write!(w, ", "))
1365                                 }
1366                                 try!(write!(w, "{}", *ty));
1367                             }
1368                             try!(write!(w, ")"));
1369                         }
1370                         clean::StructVariant(ref s) => {
1371                             try!(render_struct(w, v, None, s.struct_type,
1372                                                  s.fields, s.fields_stripped,
1373                                                  "    ", false));
1374                         }
1375                     }
1376                 }
1377                 _ => unreachable!()
1378             }
1379             try!(write!(w, ",\n"));
1380         }
1381
1382         if e.variants_stripped {
1383             try!(write!(w, "    // some variants omitted\n"));
1384         }
1385         try!(write!(w, "\\}"));
1386     }
1387     try!(write!(w, "</pre>"));
1388
1389     try!(document(w, it));
1390     if e.variants.len() > 0 {
1391         try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
1392         for variant in e.variants.iter() {
1393             try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
1394                           name = variant.name.get_ref().as_slice()));
1395             try!(document(w, variant));
1396             match variant.inner {
1397                 clean::VariantItem(ref var) => {
1398                     match var.kind {
1399                         clean::StructVariant(ref s) => {
1400                             try!(write!(w, "<h3 class='fields'>Fields</h3>\n
1401                                               <table>"));
1402                             for field in s.fields.iter() {
1403                                 try!(write!(w, "<tr><td \
1404                                                   id='variant.{v}.field.{f}'>\
1405                                                   <code>{f}</code></td><td>",
1406                                               v = variant.name.get_ref().as_slice(),
1407                                               f = field.name.get_ref().as_slice()));
1408                                 try!(document(w, field));
1409                                 try!(write!(w, "</td></tr>"));
1410                             }
1411                             try!(write!(w, "</table>"));
1412                         }
1413                         _ => ()
1414                     }
1415                 }
1416                 _ => ()
1417             }
1418             try!(write!(w, "</td></tr>"));
1419         }
1420         try!(write!(w, "</table>"));
1421
1422     }
1423     try!(render_methods(w, it));
1424     Ok(())
1425 }
1426
1427 fn render_struct(w: &mut Writer, it: &clean::Item,
1428                  g: Option<&clean::Generics>,
1429                  ty: doctree::StructType,
1430                  fields: &[clean::Item],
1431                  fields_stripped: bool,
1432                  tab: &str,
1433                  structhead: bool) -> fmt::Result {
1434     try!(write!(w, "{}{}{}",
1435                   VisSpace(it.visibility),
1436                   if structhead {"struct "} else {""},
1437                   it.name.get_ref().as_slice()));
1438     match g {
1439         Some(g) => try!(write!(w, "{}", *g)),
1440         None => {}
1441     }
1442     match ty {
1443         doctree::Plain => {
1444             try!(write!(w, " \\{\n{}", tab));
1445             for field in fields.iter() {
1446                 match field.inner {
1447                     clean::StructFieldItem(ref ty) => {
1448                         try!(write!(w, "    {}{}: {},\n{}",
1449                                       VisSpace(field.visibility),
1450                                       field.name.get_ref().as_slice(),
1451                                       ty.type_,
1452                                       tab));
1453                     }
1454                     _ => unreachable!()
1455                 }
1456             }
1457
1458             if fields_stripped {
1459                 try!(write!(w, "    // some fields omitted\n{}", tab));
1460             }
1461             try!(write!(w, "\\}"));
1462         }
1463         doctree::Tuple | doctree::Newtype => {
1464             try!(write!(w, "("));
1465             for (i, field) in fields.iter().enumerate() {
1466                 if i > 0 {
1467                     try!(write!(w, ", "));
1468                 }
1469                 match field.inner {
1470                     clean::StructFieldItem(ref field) => {
1471                         try!(write!(w, "{}", field.type_));
1472                     }
1473                     _ => unreachable!()
1474                 }
1475             }
1476             try!(write!(w, ");"));
1477         }
1478         doctree::Unit => {
1479             try!(write!(w, ";"));
1480         }
1481     }
1482     Ok(())
1483 }
1484
1485 fn render_methods(w: &mut Writer, it: &clean::Item) -> fmt::Result {
1486     local_data::get(cache_key, |cache| {
1487         let c = cache.unwrap().get();
1488         match c.impls.find(&it.id) {
1489             Some(v) => {
1490                 let mut non_trait = v.iter().filter(|p| {
1491                     p.ref0().trait_.is_none()
1492                 });
1493                 let non_trait = non_trait.to_owned_vec();
1494                 let mut traits = v.iter().filter(|p| {
1495                     p.ref0().trait_.is_some()
1496                 });
1497                 let traits = traits.to_owned_vec();
1498
1499                 if non_trait.len() > 0 {
1500                     try!(write!(w, "<h2 id='methods'>Methods</h2>"));
1501                     for &(ref i, ref dox) in non_trait.move_iter() {
1502                         try!(render_impl(w, i, dox));
1503                     }
1504                 }
1505                 if traits.len() > 0 {
1506                     try!(write!(w, "<h2 id='implementations'>Trait \
1507                                       Implementations</h2>"));
1508                     for &(ref i, ref dox) in traits.move_iter() {
1509                         try!(render_impl(w, i, dox));
1510                     }
1511                 }
1512             }
1513             None => {}
1514         }
1515         Ok(())
1516     })
1517 }
1518
1519 fn render_impl(w: &mut Writer, i: &clean::Impl,
1520                dox: &Option<~str>) -> fmt::Result {
1521     try!(write!(w, "<h3 class='impl'><code>impl{} ", i.generics));
1522     let trait_id = match i.trait_ {
1523         Some(ref ty) => {
1524             try!(write!(w, "{} for ", *ty));
1525             match *ty {
1526                 clean::ResolvedPath { id, .. } => Some(id),
1527                 _ => None,
1528             }
1529         }
1530         None => None
1531     };
1532     try!(write!(w, "{}</code></h3>", i.for_));
1533     match *dox {
1534         Some(ref dox) => {
1535             try!(write!(w, "<div class='docblock'>{}</div>",
1536                           Markdown(dox.as_slice())));
1537         }
1538         None => {}
1539     }
1540
1541     fn docmeth(w: &mut Writer, item: &clean::Item) -> io::IoResult<bool> {
1542         try!(write!(w, "<h4 id='method.{}' class='method'><code>",
1543                       *item.name.get_ref()));
1544         try!(render_method(w, item));
1545         try!(write!(w, "</code></h4>\n"));
1546         match item.doc_value() {
1547             Some(s) => {
1548                 try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1549                 Ok(true)
1550             }
1551             None => Ok(false)
1552         }
1553     }
1554
1555     try!(write!(w, "<div class='methods'>"));
1556     for meth in i.methods.iter() {
1557         if try!(docmeth(w, meth)) {
1558             continue
1559         }
1560
1561         // No documentation? Attempt to slurp in the trait's documentation
1562         let trait_id = match trait_id {
1563             None => continue,
1564             Some(id) => id,
1565         };
1566         try!(local_data::get(cache_key, |cache| {
1567             let cache = cache.unwrap().get();
1568             match cache.traits.find(&trait_id) {
1569                 Some(t) => {
1570                     let name = meth.name.clone();
1571                     match t.methods.iter().find(|t| t.item().name == name) {
1572                         Some(method) => {
1573                             match method.item().doc_value() {
1574                                 Some(s) => {
1575                                     try!(write!(w,
1576                                                   "<div class='docblock'>{}</div>",
1577                                                   Markdown(s)));
1578                                 }
1579                                 None => {}
1580                             }
1581                         }
1582                         None => {}
1583                     }
1584                 }
1585                 None => {}
1586             }
1587             Ok(())
1588         }))
1589     }
1590
1591     // If we've implemented a trait, then also emit documentation for all
1592     // default methods which weren't overridden in the implementation block.
1593     match trait_id {
1594         None => {}
1595         Some(id) => {
1596             try!(local_data::get(cache_key, |cache| {
1597                 let cache = cache.unwrap().get();
1598                 match cache.traits.find(&id) {
1599                     Some(t) => {
1600                         for method in t.methods.iter() {
1601                             let n = method.item().name.clone();
1602                             match i.methods.iter().find(|m| m.name == n) {
1603                                 Some(..) => continue,
1604                                 None => {}
1605                             }
1606
1607                             try!(docmeth(w, method.item()));
1608                         }
1609                     }
1610                     None => {}
1611                 }
1612                 Ok(())
1613             }))
1614         }
1615     }
1616     try!(write!(w, "</div>"));
1617     Ok(())
1618 }
1619
1620 fn item_typedef(w: &mut Writer, it: &clean::Item,
1621                 t: &clean::Typedef) -> fmt::Result {
1622     try!(write!(w, "<pre class='rust typedef'>type {}{} = {};</pre>",
1623                   it.name.get_ref().as_slice(),
1624                   t.generics,
1625                   t.type_));
1626
1627     document(w, it)
1628 }
1629
1630 impl<'a> fmt::Show for Sidebar<'a> {
1631     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1632         let cx = self.cx;
1633         let it = self.item;
1634         try!(write!(fmt.buf, "<p class='location'>"));
1635         let len = cx.current.len() - if it.is_mod() {1} else {0};
1636         for (i, name) in cx.current.iter().take(len).enumerate() {
1637             if i > 0 {
1638                 try!(write!(fmt.buf, "&\\#8203;::"));
1639             }
1640             try!(write!(fmt.buf, "<a href='{}index.html'>{}</a>",
1641                           cx.root_path.slice_to((cx.current.len() - i - 1) * 3),
1642                           *name));
1643         }
1644         try!(write!(fmt.buf, "</p>"));
1645
1646         fn block(w: &mut Writer, short: &str, longty: &str,
1647                  cur: &clean::Item, cx: &Context) -> fmt::Result {
1648             let items = match cx.sidebar.find_equiv(&short) {
1649                 Some(items) => items.as_slice(),
1650                 None => return Ok(())
1651             };
1652             try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
1653             for item in items.iter() {
1654                 let class = if cur.name.get_ref() == item &&
1655                                short == shortty(cur) { "current" } else { "" };
1656                 try!(write!(w, "<a class='{ty} {class}' href='{curty, select,
1657                                 mod{../}
1658                                 other{}
1659                            }{tysel, select,
1660                                 mod{{name}/index.html}
1661                                 other{#.{name}.html}
1662                            }'>{name}</a><br/>",
1663                        ty = short,
1664                        tysel = short,
1665                        class = class,
1666                        curty = shortty(cur),
1667                        name = item.as_slice()));
1668             }
1669             try!(write!(w, "</div>"));
1670             Ok(())
1671         }
1672
1673         try!(block(fmt.buf, "mod", "Modules", it, cx));
1674         try!(block(fmt.buf, "struct", "Structs", it, cx));
1675         try!(block(fmt.buf, "enum", "Enums", it, cx));
1676         try!(block(fmt.buf, "trait", "Traits", it, cx));
1677         try!(block(fmt.buf, "fn", "Functions", it, cx));
1678         Ok(())
1679     }
1680 }
1681
1682 fn build_sidebar(m: &clean::Module) -> HashMap<~str, ~[~str]> {
1683     let mut map = HashMap::new();
1684     for item in m.items.iter() {
1685         let short = shortty(item);
1686         let myname = match item.name {
1687             None => continue,
1688             Some(ref s) => s.to_owned(),
1689         };
1690         let v = map.find_or_insert_with(short.to_owned(), |_| ~[]);
1691         v.push(myname);
1692     }
1693
1694     for (_, items) in map.mut_iter() {
1695         items.sort();
1696     }
1697     return map;
1698 }
1699
1700 impl<'a> fmt::Show for Source<'a> {
1701     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1702         let Source(s) = *self;
1703         let lines = s.lines().len();
1704         let mut cols = 0;
1705         let mut tmp = lines;
1706         while tmp > 0 {
1707             cols += 1;
1708             tmp /= 10;
1709         }
1710         try!(write!(fmt.buf, "<pre class='line-numbers'>"));
1711         for i in range(1, lines + 1) {
1712             try!(write!(fmt.buf, "<span id='{0:u}'>{0:1$u}</span>\n", i, cols));
1713         }
1714         try!(write!(fmt.buf, "</pre>"));
1715         try!(write!(fmt.buf, "{}", highlight::highlight(s.as_slice(), None)));
1716         Ok(())
1717     }
1718 }
1719
1720 fn item_macro(w: &mut Writer, it: &clean::Item,
1721               t: &clean::Macro) -> fmt::Result {
1722     try!(w.write_str(highlight::highlight(t.source, Some("macro"))));
1723     document(w, it)
1724 }