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