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