]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
auto merge of #14481 : alexcrichton/rust/no-format-strbuf, r=sfackler
[rust.git] / src / librustdoc / clean / mod.rs
1 // Copyright 2012-2013 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 //! This module contains the "cleaned" pieces of the AST, and the functions
12 //! that clean them.
13
14 use syntax;
15 use syntax::ast;
16 use syntax::ast_util;
17 use syntax::attr;
18 use syntax::attr::{AttributeMethods, AttrMetaMethods};
19 use syntax::codemap::Pos;
20 use syntax::parse::token::InternedString;
21 use syntax::parse::token;
22
23 use rustc::back::link;
24 use rustc::driver::driver;
25 use rustc::metadata::cstore;
26 use rustc::metadata::csearch;
27 use rustc::metadata::decoder;
28 use rustc::middle::ty;
29
30 use std::rc::Rc;
31
32 use core;
33 use doctree;
34 use visit_ast;
35
36 /// A stable identifier to the particular version of JSON output.
37 /// Increment this when the `Crate` and related structures change.
38 pub static SCHEMA_VERSION: &'static str = "0.8.2";
39
40 mod inline;
41
42 pub trait Clean<T> {
43     fn clean(&self) -> T;
44 }
45
46 impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
47     fn clean(&self) -> Vec<U> {
48         self.iter().map(|x| x.clean()).collect()
49     }
50 }
51
52 impl<T: Clean<U>, U> Clean<U> for @T {
53     fn clean(&self) -> U {
54         (**self).clean()
55     }
56 }
57
58 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
59     fn clean(&self) -> U {
60         (**self).clean()
61     }
62 }
63
64 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
65     fn clean(&self) -> Option<U> {
66         match self {
67             &None => None,
68             &Some(ref v) => Some(v.clean())
69         }
70     }
71 }
72
73 impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
74     fn clean(&self) -> Vec<U> {
75         self.iter().map(|x| x.clean()).collect()
76     }
77 }
78
79 #[deriving(Clone, Encodable, Decodable)]
80 pub struct Crate {
81     pub name: String,
82     pub module: Option<Item>,
83     pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
84 }
85
86 impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> {
87     fn clean(&self) -> Crate {
88         let cx = super::ctxtkey.get().unwrap();
89
90         let mut externs = Vec::new();
91         cx.sess().cstore.iter_crate_data(|n, meta| {
92             externs.push((n, meta.clean()));
93         });
94
95         let input = driver::FileInput(cx.src.clone());
96         let t_outputs = driver::build_output_filenames(&input,
97                                                        &None,
98                                                        &None,
99                                                        self.attrs.as_slice(),
100                                                        cx.sess());
101         let id = link::find_crate_id(self.attrs.as_slice(),
102                                      t_outputs.out_filestem.as_slice());
103         Crate {
104             name: id.name.to_string(),
105             module: Some(self.module.clean()),
106             externs: externs,
107         }
108     }
109 }
110
111 #[deriving(Clone, Encodable, Decodable)]
112 pub struct ExternalCrate {
113     pub name: String,
114     pub attrs: Vec<Attribute>,
115 }
116
117 impl Clean<ExternalCrate> for cstore::crate_metadata {
118     fn clean(&self) -> ExternalCrate {
119         ExternalCrate {
120             name: self.name.to_string(),
121             attrs: decoder::get_crate_attributes(self.data()).clean()
122                                                              .move_iter()
123                                                              .collect(),
124         }
125     }
126 }
127
128 /// Anything with a source location and set of attributes and, optionally, a
129 /// name. That is, anything that can be documented. This doesn't correspond
130 /// directly to the AST's concept of an item; it's a strict superset.
131 #[deriving(Clone, Encodable, Decodable)]
132 pub struct Item {
133     /// Stringified span
134     pub source: Span,
135     /// Not everything has a name. E.g., impls
136     pub name: Option<String>,
137     pub attrs: Vec<Attribute> ,
138     pub inner: ItemEnum,
139     pub visibility: Option<Visibility>,
140     pub def_id: ast::DefId,
141 }
142
143 impl Item {
144     /// Finds the `doc` attribute as a List and returns the list of attributes
145     /// nested inside.
146     pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
147         for attr in self.attrs.iter() {
148             match *attr {
149                 List(ref x, ref list) if "doc" == x.as_slice() => {
150                     return Some(list.as_slice());
151                 }
152                 _ => {}
153             }
154         }
155         return None;
156     }
157
158     /// Finds the `doc` attribute as a NameValue and returns the corresponding
159     /// value found.
160     pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
161         for attr in self.attrs.iter() {
162             match *attr {
163                 NameValue(ref x, ref v) if "doc" == x.as_slice() => {
164                     return Some(v.as_slice());
165                 }
166                 _ => {}
167             }
168         }
169         return None;
170     }
171
172     pub fn is_hidden_from_doc(&self) -> bool {
173         match self.doc_list() {
174             Some(ref l) => {
175                 for innerattr in l.iter() {
176                     match *innerattr {
177                         Word(ref s) if "hidden" == s.as_slice() => {
178                             return true
179                         }
180                         _ => (),
181                     }
182                 }
183             },
184             None => ()
185         }
186         return false;
187     }
188
189     pub fn is_mod(&self) -> bool {
190         match self.inner { ModuleItem(..) => true, _ => false }
191     }
192     pub fn is_trait(&self) -> bool {
193         match self.inner { TraitItem(..) => true, _ => false }
194     }
195     pub fn is_struct(&self) -> bool {
196         match self.inner { StructItem(..) => true, _ => false }
197     }
198     pub fn is_enum(&self) -> bool {
199         match self.inner { EnumItem(..) => true, _ => false }
200     }
201     pub fn is_fn(&self) -> bool {
202         match self.inner { FunctionItem(..) => true, _ => false }
203     }
204 }
205
206 #[deriving(Clone, Encodable, Decodable)]
207 pub enum ItemEnum {
208     StructItem(Struct),
209     EnumItem(Enum),
210     FunctionItem(Function),
211     ModuleItem(Module),
212     TypedefItem(Typedef),
213     StaticItem(Static),
214     TraitItem(Trait),
215     ImplItem(Impl),
216     /// `use` and `extern crate`
217     ViewItemItem(ViewItem),
218     /// A method signature only. Used for required methods in traits (ie,
219     /// non-default-methods).
220     TyMethodItem(TyMethod),
221     /// A method with a body.
222     MethodItem(Method),
223     StructFieldItem(StructField),
224     VariantItem(Variant),
225     /// `fn`s from an extern block
226     ForeignFunctionItem(Function),
227     /// `static`s from an extern block
228     ForeignStaticItem(Static),
229     MacroItem(Macro),
230 }
231
232 #[deriving(Clone, Encodable, Decodable)]
233 pub struct Module {
234     pub items: Vec<Item>,
235     pub is_crate: bool,
236 }
237
238 impl Clean<Item> for doctree::Module {
239     fn clean(&self) -> Item {
240         let name = if self.name.is_some() {
241             self.name.unwrap().clean()
242         } else {
243             "".to_string()
244         };
245         let mut foreigns = Vec::new();
246         for subforeigns in self.foreigns.clean().move_iter() {
247             for foreign in subforeigns.move_iter() {
248                 foreigns.push(foreign)
249             }
250         }
251         let items: Vec<Vec<Item> > = vec!(
252             self.structs.clean().move_iter().collect(),
253             self.enums.clean().move_iter().collect(),
254             self.fns.clean().move_iter().collect(),
255             foreigns,
256             self.mods.clean().move_iter().collect(),
257             self.typedefs.clean().move_iter().collect(),
258             self.statics.clean().move_iter().collect(),
259             self.traits.clean().move_iter().collect(),
260             self.impls.clean().move_iter().collect(),
261             self.view_items.clean().move_iter()
262                            .flat_map(|s| s.move_iter()).collect(),
263             self.macros.clean().move_iter().collect()
264         );
265
266         // determine if we should display the inner contents or
267         // the outer `mod` item for the source code.
268         let where = {
269             let ctxt = super::ctxtkey.get().unwrap();
270             let cm = ctxt.sess().codemap();
271             let outer = cm.lookup_char_pos(self.where_outer.lo);
272             let inner = cm.lookup_char_pos(self.where_inner.lo);
273             if outer.file.start_pos == inner.file.start_pos {
274                 // mod foo { ... }
275                 self.where_outer
276             } else {
277                 // mod foo; (and a separate FileMap for the contents)
278                 self.where_inner
279             }
280         };
281
282         Item {
283             name: Some(name),
284             attrs: self.attrs.clean(),
285             source: where.clean(),
286             visibility: self.vis.clean(),
287             def_id: ast_util::local_def(self.id),
288             inner: ModuleItem(Module {
289                is_crate: self.is_crate,
290                items: items.iter()
291                            .flat_map(|x| x.iter().map(|x| (*x).clone()))
292                            .collect(),
293             })
294         }
295     }
296 }
297
298 #[deriving(Clone, Encodable, Decodable)]
299 pub enum Attribute {
300     Word(String),
301     List(String, Vec<Attribute> ),
302     NameValue(String, String)
303 }
304
305 impl Clean<Attribute> for ast::MetaItem {
306     fn clean(&self) -> Attribute {
307         match self.node {
308             ast::MetaWord(ref s) => Word(s.get().to_string()),
309             ast::MetaList(ref s, ref l) => {
310                 List(s.get().to_string(), l.clean().move_iter().collect())
311             }
312             ast::MetaNameValue(ref s, ref v) => {
313                 NameValue(s.get().to_string(), lit_to_str(v))
314             }
315         }
316     }
317 }
318
319 impl Clean<Attribute> for ast::Attribute {
320     fn clean(&self) -> Attribute {
321         self.desugar_doc().node.value.clean()
322     }
323 }
324
325 // This is a rough approximation that gets us what we want.
326 impl attr::AttrMetaMethods for Attribute {
327     fn name(&self) -> InternedString {
328         match *self {
329             Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
330                 token::intern_and_get_ident(n.as_slice())
331             }
332         }
333     }
334
335     fn value_str(&self) -> Option<InternedString> {
336         match *self {
337             NameValue(_, ref v) => {
338                 Some(token::intern_and_get_ident(v.as_slice()))
339             }
340             _ => None,
341         }
342     }
343     fn meta_item_list<'a>(&'a self) -> Option<&'a [@ast::MetaItem]> { None }
344     fn name_str_pair(&self) -> Option<(InternedString, InternedString)> {
345         None
346     }
347 }
348 impl<'a> attr::AttrMetaMethods for &'a Attribute {
349     fn name(&self) -> InternedString { (**self).name() }
350     fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
351     fn meta_item_list<'a>(&'a self) -> Option<&'a [@ast::MetaItem]> { None }
352     fn name_str_pair(&self) -> Option<(InternedString, InternedString)> {
353         None
354     }
355 }
356
357 #[deriving(Clone, Encodable, Decodable)]
358 pub struct TyParam {
359     pub name: String,
360     pub did: ast::DefId,
361     pub bounds: Vec<TyParamBound>,
362 }
363
364 impl Clean<TyParam> for ast::TyParam {
365     fn clean(&self) -> TyParam {
366         TyParam {
367             name: self.ident.clean(),
368             did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
369             bounds: self.bounds.clean().move_iter().collect(),
370         }
371     }
372 }
373
374 impl Clean<TyParam> for ty::TypeParameterDef {
375     fn clean(&self) -> TyParam {
376         let cx = super::ctxtkey.get().unwrap();
377         cx.external_typarams.borrow_mut().get_mut_ref().insert(self.def_id,
378                                                                self.ident.clean());
379         TyParam {
380             name: self.ident.clean(),
381             did: self.def_id,
382             bounds: self.bounds.clean(),
383         }
384     }
385 }
386
387 #[deriving(Clone, Encodable, Decodable)]
388 pub enum TyParamBound {
389     RegionBound,
390     TraitBound(Type)
391 }
392
393 impl Clean<TyParamBound> for ast::TyParamBound {
394     fn clean(&self) -> TyParamBound {
395         match *self {
396             ast::StaticRegionTyParamBound => RegionBound,
397             ast::OtherRegionTyParamBound(_) => RegionBound,
398             ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
399         }
400     }
401 }
402
403 fn external_path(name: &str) -> Path {
404     Path {
405         global: false,
406         segments: vec![PathSegment {
407             name: name.to_string(),
408             lifetimes: Vec::new(),
409             types: Vec::new(),
410         }]
411     }
412 }
413
414 impl Clean<TyParamBound> for ty::BuiltinBound {
415     fn clean(&self) -> TyParamBound {
416         let cx = super::ctxtkey.get().unwrap();
417         let tcx = match cx.maybe_typed {
418             core::Typed(ref tcx) => tcx,
419             core::NotTyped(_) => return RegionBound,
420         };
421         let (did, path) = match *self {
422             ty::BoundStatic => return RegionBound,
423             ty::BoundSend =>
424                 (tcx.lang_items.send_trait().unwrap(), external_path("Send")),
425             ty::BoundSized =>
426                 (tcx.lang_items.sized_trait().unwrap(), external_path("Sized")),
427             ty::BoundCopy =>
428                 (tcx.lang_items.copy_trait().unwrap(), external_path("Copy")),
429             ty::BoundShare =>
430                 (tcx.lang_items.share_trait().unwrap(), external_path("Share")),
431         };
432         let fqn = csearch::get_item_path(tcx, did);
433         let fqn = fqn.move_iter().map(|i| i.to_str().to_string()).collect();
434         cx.external_paths.borrow_mut().get_mut_ref().insert(did,
435                                                             (fqn, TypeTrait));
436         TraitBound(ResolvedPath {
437             path: path,
438             typarams: None,
439             did: did,
440         })
441     }
442 }
443
444 impl Clean<TyParamBound> for ty::TraitRef {
445     fn clean(&self) -> TyParamBound {
446         let cx = super::ctxtkey.get().unwrap();
447         let tcx = match cx.maybe_typed {
448             core::Typed(ref tcx) => tcx,
449             core::NotTyped(_) => return RegionBound,
450         };
451         let fqn = csearch::get_item_path(tcx, self.def_id);
452         let fqn = fqn.move_iter().map(|i| i.to_str().to_string())
453                      .collect::<Vec<String>>();
454         let path = external_path(fqn.last().unwrap().as_slice());
455         cx.external_paths.borrow_mut().get_mut_ref().insert(self.def_id,
456                                                             (fqn, TypeTrait));
457         TraitBound(ResolvedPath {
458             path: path,
459             typarams: None,
460             did: self.def_id,
461         })
462     }
463 }
464
465 impl Clean<Vec<TyParamBound>> for ty::ParamBounds {
466     fn clean(&self) -> Vec<TyParamBound> {
467         let mut v = Vec::new();
468         for b in self.builtin_bounds.iter() {
469             if b != ty::BoundSized {
470                 v.push(b.clean());
471             }
472         }
473         for t in self.trait_bounds.iter() {
474             v.push(t.clean());
475         }
476         return v;
477     }
478 }
479
480 impl Clean<Option<Vec<TyParamBound>>> for ty::substs {
481     fn clean(&self) -> Option<Vec<TyParamBound>> {
482         let mut v = Vec::new();
483         match self.regions {
484             ty::NonerasedRegions(..) => v.push(RegionBound),
485             ty::ErasedRegions => {}
486         }
487         v.extend(self.tps.iter().map(|t| TraitBound(t.clean())));
488
489         if v.len() > 0 {Some(v)} else {None}
490     }
491 }
492
493 #[deriving(Clone, Encodable, Decodable, Eq)]
494 pub struct Lifetime(String);
495
496 impl Lifetime {
497     pub fn get_ref<'a>(&'a self) -> &'a str {
498         let Lifetime(ref s) = *self;
499         let s: &'a str = s.as_slice();
500         return s;
501     }
502 }
503
504 impl Clean<Lifetime> for ast::Lifetime {
505     fn clean(&self) -> Lifetime {
506         Lifetime(token::get_name(self.name).get().to_string())
507     }
508 }
509
510 impl Clean<Lifetime> for ty::RegionParameterDef {
511     fn clean(&self) -> Lifetime {
512         Lifetime(token::get_name(self.name).get().to_string())
513     }
514 }
515
516 impl Clean<Option<Lifetime>> for ty::Region {
517     fn clean(&self) -> Option<Lifetime> {
518         match *self {
519             ty::ReStatic => Some(Lifetime("static".to_string())),
520             ty::ReLateBound(_, ty::BrNamed(_, name)) =>
521                 Some(Lifetime(token::get_name(name).get().to_string())),
522
523             ty::ReLateBound(..) |
524             ty::ReEarlyBound(..) |
525             ty::ReFree(..) |
526             ty::ReScope(..) |
527             ty::ReInfer(..) |
528             ty::ReEmpty(..) => None
529         }
530     }
531 }
532
533 // maybe use a Generic enum and use ~[Generic]?
534 #[deriving(Clone, Encodable, Decodable)]
535 pub struct Generics {
536     pub lifetimes: Vec<Lifetime>,
537     pub type_params: Vec<TyParam>,
538 }
539
540 impl Clean<Generics> for ast::Generics {
541     fn clean(&self) -> Generics {
542         Generics {
543             lifetimes: self.lifetimes.clean().move_iter().collect(),
544             type_params: self.ty_params.clean().move_iter().collect(),
545         }
546     }
547 }
548
549 impl Clean<Generics> for ty::Generics {
550     fn clean(&self) -> Generics {
551         Generics {
552             lifetimes: self.region_param_defs.clean(),
553             type_params: self.type_param_defs.clean(),
554         }
555     }
556 }
557
558 #[deriving(Clone, Encodable, Decodable)]
559 pub struct Method {
560     pub generics: Generics,
561     pub self_: SelfTy,
562     pub fn_style: ast::FnStyle,
563     pub decl: FnDecl,
564 }
565
566 impl Clean<Item> for ast::Method {
567     fn clean(&self) -> Item {
568         let inputs = match self.explicit_self.node {
569             ast::SelfStatic => self.decl.inputs.as_slice(),
570             _ => self.decl.inputs.slice_from(1)
571         };
572         let decl = FnDecl {
573             inputs: Arguments {
574                 values: inputs.iter().map(|x| x.clean()).collect(),
575             },
576             output: (self.decl.output.clean()),
577             cf: self.decl.cf.clean(),
578             attrs: Vec::new()
579         };
580         Item {
581             name: Some(self.ident.clean()),
582             attrs: self.attrs.clean().move_iter().collect(),
583             source: self.span.clean(),
584             def_id: ast_util::local_def(self.id.clone()),
585             visibility: self.vis.clean(),
586             inner: MethodItem(Method {
587                 generics: self.generics.clean(),
588                 self_: self.explicit_self.node.clean(),
589                 fn_style: self.fn_style.clone(),
590                 decl: decl,
591             }),
592         }
593     }
594 }
595
596 #[deriving(Clone, Encodable, Decodable)]
597 pub struct TyMethod {
598     pub fn_style: ast::FnStyle,
599     pub decl: FnDecl,
600     pub generics: Generics,
601     pub self_: SelfTy,
602 }
603
604 impl Clean<Item> for ast::TypeMethod {
605     fn clean(&self) -> Item {
606         let inputs = match self.explicit_self.node {
607             ast::SelfStatic => self.decl.inputs.as_slice(),
608             _ => self.decl.inputs.slice_from(1)
609         };
610         let decl = FnDecl {
611             inputs: Arguments {
612                 values: inputs.iter().map(|x| x.clean()).collect(),
613             },
614             output: (self.decl.output.clean()),
615             cf: self.decl.cf.clean(),
616             attrs: Vec::new()
617         };
618         Item {
619             name: Some(self.ident.clean()),
620             attrs: self.attrs.clean().move_iter().collect(),
621             source: self.span.clean(),
622             def_id: ast_util::local_def(self.id),
623             visibility: None,
624             inner: TyMethodItem(TyMethod {
625                 fn_style: self.fn_style.clone(),
626                 decl: decl,
627                 self_: self.explicit_self.node.clean(),
628                 generics: self.generics.clean(),
629             }),
630         }
631     }
632 }
633
634 #[deriving(Clone, Encodable, Decodable, Eq)]
635 pub enum SelfTy {
636     SelfStatic,
637     SelfValue,
638     SelfBorrowed(Option<Lifetime>, Mutability),
639     SelfOwned,
640 }
641
642 impl Clean<SelfTy> for ast::ExplicitSelf_ {
643     fn clean(&self) -> SelfTy {
644         match *self {
645             ast::SelfStatic => SelfStatic,
646             ast::SelfValue => SelfValue,
647             ast::SelfUniq => SelfOwned,
648             ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()),
649         }
650     }
651 }
652
653 #[deriving(Clone, Encodable, Decodable)]
654 pub struct Function {
655     pub decl: FnDecl,
656     pub generics: Generics,
657     pub fn_style: ast::FnStyle,
658 }
659
660 impl Clean<Item> for doctree::Function {
661     fn clean(&self) -> Item {
662         Item {
663             name: Some(self.name.clean()),
664             attrs: self.attrs.clean(),
665             source: self.where.clean(),
666             visibility: self.vis.clean(),
667             def_id: ast_util::local_def(self.id),
668             inner: FunctionItem(Function {
669                 decl: self.decl.clean(),
670                 generics: self.generics.clean(),
671                 fn_style: self.fn_style,
672             }),
673         }
674     }
675 }
676
677 #[deriving(Clone, Encodable, Decodable)]
678 pub struct ClosureDecl {
679     pub lifetimes: Vec<Lifetime>,
680     pub decl: FnDecl,
681     pub onceness: ast::Onceness,
682     pub fn_style: ast::FnStyle,
683     pub bounds: Vec<TyParamBound>,
684 }
685
686 impl Clean<ClosureDecl> for ast::ClosureTy {
687     fn clean(&self) -> ClosureDecl {
688         ClosureDecl {
689             lifetimes: self.lifetimes.clean(),
690             decl: self.decl.clean(),
691             onceness: self.onceness,
692             fn_style: self.fn_style,
693             bounds: match self.bounds {
694                 Some(ref x) => x.clean().move_iter().collect(),
695                 None        => Vec::new()
696             },
697         }
698     }
699 }
700
701 #[deriving(Clone, Encodable, Decodable)]
702 pub struct FnDecl {
703     pub inputs: Arguments,
704     pub output: Type,
705     pub cf: RetStyle,
706     pub attrs: Vec<Attribute>,
707 }
708
709 #[deriving(Clone, Encodable, Decodable)]
710 pub struct Arguments {
711     pub values: Vec<Argument>,
712 }
713
714 impl Clean<FnDecl> for ast::FnDecl {
715     fn clean(&self) -> FnDecl {
716         FnDecl {
717             inputs: Arguments {
718                 values: self.inputs.iter().map(|x| x.clean()).collect(),
719             },
720             output: (self.output.clean()),
721             cf: self.cf.clean(),
722             attrs: Vec::new()
723         }
724     }
725 }
726
727 impl<'a> Clean<FnDecl> for (ast::DefId, &'a ty::FnSig) {
728     fn clean(&self) -> FnDecl {
729         let cx = super::ctxtkey.get().unwrap();
730         let tcx = match cx.maybe_typed {
731             core::Typed(ref tcx) => tcx,
732             core::NotTyped(_) => unreachable!(),
733         };
734         let (did, sig) = *self;
735         let mut names = if did.node != 0 {
736             csearch::get_method_arg_names(&tcx.sess.cstore, did).move_iter()
737         } else {
738             Vec::new().move_iter()
739         }.peekable();
740         if names.peek().map(|s| s.as_slice()) == Some("self") {
741             let _ = names.next();
742         }
743         FnDecl {
744             output: sig.output.clean(),
745             cf: Return,
746             attrs: Vec::new(),
747             inputs: Arguments {
748                 values: sig.inputs.iter().map(|t| {
749                     Argument {
750                         type_: t.clean(),
751                         id: 0,
752                         name: names.next().unwrap_or("".to_string()),
753                     }
754                 }).collect(),
755             },
756         }
757     }
758 }
759
760 #[deriving(Clone, Encodable, Decodable)]
761 pub struct Argument {
762     pub type_: Type,
763     pub name: String,
764     pub id: ast::NodeId,
765 }
766
767 impl Clean<Argument> for ast::Arg {
768     fn clean(&self) -> Argument {
769         Argument {
770             name: name_from_pat(self.pat),
771             type_: (self.ty.clean()),
772             id: self.id
773         }
774     }
775 }
776
777 #[deriving(Clone, Encodable, Decodable)]
778 pub enum RetStyle {
779     NoReturn,
780     Return
781 }
782
783 impl Clean<RetStyle> for ast::RetStyle {
784     fn clean(&self) -> RetStyle {
785         match *self {
786             ast::Return => Return,
787             ast::NoReturn => NoReturn
788         }
789     }
790 }
791
792 #[deriving(Clone, Encodable, Decodable)]
793 pub struct Trait {
794     pub methods: Vec<TraitMethod>,
795     pub generics: Generics,
796     pub parents: Vec<Type>,
797 }
798
799 impl Clean<Item> for doctree::Trait {
800     fn clean(&self) -> Item {
801         Item {
802             name: Some(self.name.clean()),
803             attrs: self.attrs.clean(),
804             source: self.where.clean(),
805             def_id: ast_util::local_def(self.id),
806             visibility: self.vis.clean(),
807             inner: TraitItem(Trait {
808                 methods: self.methods.clean(),
809                 generics: self.generics.clean(),
810                 parents: self.parents.clean(),
811             }),
812         }
813     }
814 }
815
816 impl Clean<Type> for ast::TraitRef {
817     fn clean(&self) -> Type {
818         resolve_type(self.path.clean(), None, self.ref_id)
819     }
820 }
821
822 #[deriving(Clone, Encodable, Decodable)]
823 pub enum TraitMethod {
824     Required(Item),
825     Provided(Item),
826 }
827
828 impl TraitMethod {
829     pub fn is_req(&self) -> bool {
830         match self {
831             &Required(..) => true,
832             _ => false,
833         }
834     }
835     pub fn is_def(&self) -> bool {
836         match self {
837             &Provided(..) => true,
838             _ => false,
839         }
840     }
841     pub fn item<'a>(&'a self) -> &'a Item {
842         match *self {
843             Required(ref item) => item,
844             Provided(ref item) => item,
845         }
846     }
847 }
848
849 impl Clean<TraitMethod> for ast::TraitMethod {
850     fn clean(&self) -> TraitMethod {
851         match self {
852             &ast::Required(ref t) => Required(t.clean()),
853             &ast::Provided(ref t) => Provided(t.clean()),
854         }
855     }
856 }
857
858 impl Clean<TraitMethod> for ty::Method {
859     fn clean(&self) -> TraitMethod {
860         let m = if self.provided_source.is_some() {Provided} else {Required};
861         let cx = super::ctxtkey.get().unwrap();
862         let tcx = match cx.maybe_typed {
863             core::Typed(ref tcx) => tcx,
864             core::NotTyped(_) => unreachable!(),
865         };
866         let (self_, sig) = match self.explicit_self {
867             ast::SelfStatic => (ast::SelfStatic.clean(), self.fty.sig.clone()),
868             s => {
869                 let sig = ty::FnSig {
870                     inputs: Vec::from_slice(self.fty.sig.inputs.slice_from(1)),
871                     ..self.fty.sig.clone()
872                 };
873                 let s = match s {
874                     ast::SelfRegion(..) => {
875                         match ty::get(*self.fty.sig.inputs.get(0)).sty {
876                             ty::ty_rptr(r, mt) => {
877                                 SelfBorrowed(r.clean(), mt.mutbl.clean())
878                             }
879                             _ => s.clean(),
880                         }
881                     }
882                     s => s.clean(),
883                 };
884                 (s, sig)
885             }
886         };
887
888         m(Item {
889             name: Some(self.ident.clean()),
890             visibility: Some(ast::Inherited),
891             def_id: self.def_id,
892             attrs: inline::load_attrs(tcx, self.def_id),
893             source: Span::empty(),
894             inner: TyMethodItem(TyMethod {
895                 fn_style: self.fty.fn_style,
896                 generics: self.generics.clean(),
897                 self_: self_,
898                 decl: (self.def_id, &sig).clean(),
899             })
900         })
901     }
902 }
903
904 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
905 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
906 /// it does not preserve mutability or boxes.
907 #[deriving(Clone, Encodable, Decodable)]
908 pub enum Type {
909     /// structs/enums/traits (anything that'd be an ast::TyPath)
910     ResolvedPath {
911         pub path: Path,
912         pub typarams: Option<Vec<TyParamBound>>,
913         pub did: ast::DefId,
914     },
915     // I have no idea how to usefully use this.
916     TyParamBinder(ast::NodeId),
917     /// For parameterized types, so the consumer of the JSON don't go looking
918     /// for types which don't exist anywhere.
919     Generic(ast::DefId),
920     /// For references to self
921     Self(ast::DefId),
922     /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
923     Primitive(ast::PrimTy),
924     Closure(Box<ClosureDecl>, Option<Lifetime>),
925     Proc(Box<ClosureDecl>),
926     /// extern "ABI" fn
927     BareFunction(Box<BareFunctionDecl>),
928     Tuple(Vec<Type>),
929     Vector(Box<Type>),
930     FixedVector(Box<Type>, String),
931     String,
932     Bool,
933     /// aka TyNil
934     Unit,
935     /// aka TyBot
936     Bottom,
937     Unique(Box<Type>),
938     Managed(Box<Type>),
939     RawPointer(Mutability, Box<Type>),
940     BorrowedRef {
941         pub lifetime: Option<Lifetime>,
942         pub mutability: Mutability,
943         pub type_: Box<Type>,
944     },
945     // region, raw, other boxes, mutable
946 }
947
948 #[deriving(Clone, Encodable, Decodable)]
949 pub enum TypeKind {
950     TypeEnum,
951     TypeFunction,
952     TypeModule,
953     TypeStatic,
954     TypeStruct,
955     TypeTrait,
956     TypeVariant,
957 }
958
959 impl Clean<Type> for ast::Ty {
960     fn clean(&self) -> Type {
961         use syntax::ast::*;
962         match self.node {
963             TyNil => Unit,
964             TyPtr(ref m) => RawPointer(m.mutbl.clean(), box m.ty.clean()),
965             TyRptr(ref l, ref m) =>
966                 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
967                              type_: box m.ty.clean()},
968             TyBox(ty) => Managed(box ty.clean()),
969             TyUniq(ty) => Unique(box ty.clean()),
970             TyVec(ty) => Vector(box ty.clean()),
971             TyFixedLengthVec(ty, ref e) => FixedVector(box ty.clean(),
972                                                        e.span.to_src()),
973             TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
974             TyPath(ref p, ref tpbs, id) => {
975                 resolve_type(p.clean(),
976                              tpbs.clean().map(|x| x.move_iter().collect()),
977                              id)
978             }
979             TyClosure(ref c, region) => Closure(box c.clean(), region.clean()),
980             TyProc(ref c) => Proc(box c.clean()),
981             TyBareFn(ref barefn) => BareFunction(box barefn.clean()),
982             TyBot => Bottom,
983             ref x => fail!("Unimplemented type {:?}", x),
984         }
985     }
986 }
987
988 impl Clean<Type> for ty::t {
989     fn clean(&self) -> Type {
990         match ty::get(*self).sty {
991             ty::ty_nil => Unit,
992             ty::ty_bot => Bottom,
993             ty::ty_bool => Bool,
994             ty::ty_char => Primitive(ast::TyChar),
995             ty::ty_int(t) => Primitive(ast::TyInt(t)),
996             ty::ty_uint(u) => Primitive(ast::TyUint(u)),
997             ty::ty_float(f) => Primitive(ast::TyFloat(f)),
998             ty::ty_box(t) => Managed(box t.clean()),
999             ty::ty_uniq(t) => Unique(box t.clean()),
1000             ty::ty_str => String,
1001             ty::ty_vec(mt, None) => Vector(box mt.ty.clean()),
1002             ty::ty_vec(mt, Some(i)) => FixedVector(box mt.ty.clean(),
1003                                                    format!("{}", i)),
1004             ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(), box mt.ty.clean()),
1005             ty::ty_rptr(r, mt) => BorrowedRef {
1006                 lifetime: r.clean(),
1007                 mutability: mt.mutbl.clean(),
1008                 type_: box mt.ty.clean(),
1009             },
1010             ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
1011                 fn_style: fty.fn_style,
1012                 generics: Generics {
1013                     lifetimes: Vec::new(), type_params: Vec::new()
1014                 },
1015                 decl: (ast_util::local_def(0), &fty.sig).clean(),
1016                 abi: fty.abi.to_str(),
1017             }),
1018             ty::ty_closure(ref fty) => {
1019                 let decl = box ClosureDecl {
1020                     lifetimes: Vec::new(), // FIXME: this looks wrong...
1021                     decl: (ast_util::local_def(0), &fty.sig).clean(),
1022                     onceness: fty.onceness,
1023                     fn_style: fty.fn_style,
1024                     bounds: fty.bounds.iter().map(|i| i.clean()).collect(),
1025                 };
1026                 match fty.store {
1027                     ty::UniqTraitStore => Proc(decl),
1028                     ty::RegionTraitStore(ref r, _) => Closure(decl, r.clean()),
1029                 }
1030             }
1031             ty::ty_struct(did, ref substs) |
1032             ty::ty_enum(did, ref substs) |
1033             ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1034                 let cx = super::ctxtkey.get().unwrap();
1035                 let tcx = match cx.maybe_typed {
1036                     core::Typed(ref tycx) => tycx,
1037                     core::NotTyped(_) => unreachable!(),
1038                 };
1039                 let fqn = csearch::get_item_path(tcx, did);
1040                 let fqn: Vec<String> = fqn.move_iter().map(|i| {
1041                     i.to_str().to_string()
1042                 }).collect();
1043                 let mut path = external_path(fqn.last()
1044                                                 .unwrap()
1045                                                 .to_str()
1046                                                 .as_slice());
1047                 let kind = match ty::get(*self).sty {
1048                     ty::ty_struct(..) => TypeStruct,
1049                     ty::ty_trait(..) => TypeTrait,
1050                     _ => TypeEnum,
1051                 };
1052                 path.segments.get_mut(0).lifetimes = match substs.regions {
1053                     ty::ErasedRegions => Vec::new(),
1054                     ty::NonerasedRegions(ref v) => {
1055                         v.iter().filter_map(|v| v.clean()).collect()
1056                     }
1057                 };
1058                 path.segments.get_mut(0).types = substs.tps.clean();
1059                 cx.external_paths.borrow_mut().get_mut_ref().insert(did,
1060                                                                     (fqn, kind));
1061                 ResolvedPath {
1062                     path: path,
1063                     typarams: None,
1064                     did: did,
1065                 }
1066             }
1067             ty::ty_tup(ref t) => Tuple(t.iter().map(|t| t.clean()).collect()),
1068
1069             ty::ty_param(ref p) => Generic(p.def_id),
1070             ty::ty_self(did) => Self(did),
1071
1072             ty::ty_infer(..) => fail!("ty_infer"),
1073             ty::ty_err => fail!("ty_err"),
1074         }
1075     }
1076 }
1077
1078 #[deriving(Clone, Encodable, Decodable)]
1079 pub enum StructField {
1080     HiddenStructField, // inserted later by strip passes
1081     TypedStructField(Type),
1082 }
1083
1084 impl Clean<Item> for ast::StructField {
1085     fn clean(&self) -> Item {
1086         let (name, vis) = match self.node.kind {
1087             ast::NamedField(id, vis) => (Some(id), vis),
1088             ast::UnnamedField(vis) => (None, vis)
1089         };
1090         Item {
1091             name: name.clean(),
1092             attrs: self.node.attrs.clean().move_iter().collect(),
1093             source: self.span.clean(),
1094             visibility: Some(vis),
1095             def_id: ast_util::local_def(self.node.id),
1096             inner: StructFieldItem(TypedStructField(self.node.ty.clean())),
1097         }
1098     }
1099 }
1100
1101 impl Clean<Item> for ty::field_ty {
1102     fn clean(&self) -> Item {
1103         use syntax::parse::token::special_idents::unnamed_field;
1104         let name = if self.name == unnamed_field.name {
1105             None
1106         } else {
1107             Some(self.name)
1108         };
1109         let cx = super::ctxtkey.get().unwrap();
1110         let tcx = match cx.maybe_typed {
1111             core::Typed(ref tycx) => tycx,
1112             core::NotTyped(_) => unreachable!(),
1113         };
1114         let ty = ty::lookup_item_type(tcx, self.id);
1115         Item {
1116             name: name.clean(),
1117             attrs: inline::load_attrs(tcx, self.id),
1118             source: Span::empty(),
1119             visibility: Some(self.vis),
1120             def_id: self.id,
1121             inner: StructFieldItem(TypedStructField(ty.ty.clean())),
1122         }
1123     }
1124 }
1125
1126 pub type Visibility = ast::Visibility;
1127
1128 impl Clean<Option<Visibility>> for ast::Visibility {
1129     fn clean(&self) -> Option<Visibility> {
1130         Some(*self)
1131     }
1132 }
1133
1134 #[deriving(Clone, Encodable, Decodable)]
1135 pub struct Struct {
1136     pub struct_type: doctree::StructType,
1137     pub generics: Generics,
1138     pub fields: Vec<Item>,
1139     pub fields_stripped: bool,
1140 }
1141
1142 impl Clean<Item> for doctree::Struct {
1143     fn clean(&self) -> Item {
1144         Item {
1145             name: Some(self.name.clean()),
1146             attrs: self.attrs.clean(),
1147             source: self.where.clean(),
1148             def_id: ast_util::local_def(self.id),
1149             visibility: self.vis.clean(),
1150             inner: StructItem(Struct {
1151                 struct_type: self.struct_type,
1152                 generics: self.generics.clean(),
1153                 fields: self.fields.clean(),
1154                 fields_stripped: false,
1155             }),
1156         }
1157     }
1158 }
1159
1160 /// This is a more limited form of the standard Struct, different in that
1161 /// it lacks the things most items have (name, id, parameterization). Found
1162 /// only as a variant in an enum.
1163 #[deriving(Clone, Encodable, Decodable)]
1164 pub struct VariantStruct {
1165     pub struct_type: doctree::StructType,
1166     pub fields: Vec<Item>,
1167     pub fields_stripped: bool,
1168 }
1169
1170 impl Clean<VariantStruct> for syntax::ast::StructDef {
1171     fn clean(&self) -> VariantStruct {
1172         VariantStruct {
1173             struct_type: doctree::struct_type_from_def(self),
1174             fields: self.fields.clean().move_iter().collect(),
1175             fields_stripped: false,
1176         }
1177     }
1178 }
1179
1180 #[deriving(Clone, Encodable, Decodable)]
1181 pub struct Enum {
1182     pub variants: Vec<Item>,
1183     pub generics: Generics,
1184     pub variants_stripped: bool,
1185 }
1186
1187 impl Clean<Item> for doctree::Enum {
1188     fn clean(&self) -> Item {
1189         Item {
1190             name: Some(self.name.clean()),
1191             attrs: self.attrs.clean(),
1192             source: self.where.clean(),
1193             def_id: ast_util::local_def(self.id),
1194             visibility: self.vis.clean(),
1195             inner: EnumItem(Enum {
1196                 variants: self.variants.clean(),
1197                 generics: self.generics.clean(),
1198                 variants_stripped: false,
1199             }),
1200         }
1201     }
1202 }
1203
1204 #[deriving(Clone, Encodable, Decodable)]
1205 pub struct Variant {
1206     pub kind: VariantKind,
1207 }
1208
1209 impl Clean<Item> for doctree::Variant {
1210     fn clean(&self) -> Item {
1211         Item {
1212             name: Some(self.name.clean()),
1213             attrs: self.attrs.clean(),
1214             source: self.where.clean(),
1215             visibility: self.vis.clean(),
1216             def_id: ast_util::local_def(self.id),
1217             inner: VariantItem(Variant {
1218                 kind: self.kind.clean(),
1219             }),
1220         }
1221     }
1222 }
1223
1224 impl Clean<Item> for ty::VariantInfo {
1225     fn clean(&self) -> Item {
1226         // use syntax::parse::token::special_idents::unnamed_field;
1227         let cx = super::ctxtkey.get().unwrap();
1228         let tcx = match cx.maybe_typed {
1229             core::Typed(ref tycx) => tycx,
1230             core::NotTyped(_) => fail!("tcx not present"),
1231         };
1232         let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1233             None | Some([]) if self.args.len() == 0 => CLikeVariant,
1234             None | Some([]) => {
1235                 TupleVariant(self.args.iter().map(|t| t.clean()).collect())
1236             }
1237             Some(s) => {
1238                 StructVariant(VariantStruct {
1239                     struct_type: doctree::Plain,
1240                     fields_stripped: false,
1241                     fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1242                         Item {
1243                             source: Span::empty(),
1244                             name: Some(name.clean()),
1245                             attrs: Vec::new(),
1246                             visibility: Some(ast::Public),
1247                             // FIXME: this is not accurate, we need an id for
1248                             //        the specific field but we're using the id
1249                             //        for the whole variant. Nothing currently
1250                             //        uses this so we should be good for now.
1251                             def_id: self.id,
1252                             inner: StructFieldItem(
1253                                 TypedStructField(ty.clean())
1254                             )
1255                         }
1256                     }).collect()
1257                 })
1258             }
1259         };
1260         Item {
1261             name: Some(self.name.clean()),
1262             attrs: inline::load_attrs(tcx, self.id),
1263             source: Span::empty(),
1264             visibility: Some(ast::Public),
1265             def_id: self.id,
1266             inner: VariantItem(Variant { kind: kind }),
1267         }
1268     }
1269 }
1270
1271 #[deriving(Clone, Encodable, Decodable)]
1272 pub enum VariantKind {
1273     CLikeVariant,
1274     TupleVariant(Vec<Type>),
1275     StructVariant(VariantStruct),
1276 }
1277
1278 impl Clean<VariantKind> for ast::VariantKind {
1279     fn clean(&self) -> VariantKind {
1280         match self {
1281             &ast::TupleVariantKind(ref args) => {
1282                 if args.len() == 0 {
1283                     CLikeVariant
1284                 } else {
1285                     TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
1286                 }
1287             },
1288             &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
1289         }
1290     }
1291 }
1292
1293 #[deriving(Clone, Encodable, Decodable)]
1294 pub struct Span {
1295     pub filename: String,
1296     pub loline: uint,
1297     pub locol: uint,
1298     pub hiline: uint,
1299     pub hicol: uint,
1300 }
1301
1302 impl Span {
1303     fn empty() -> Span {
1304         Span {
1305             filename: "".to_string(),
1306             loline: 0, locol: 0,
1307             hiline: 0, hicol: 0,
1308         }
1309     }
1310 }
1311
1312 impl Clean<Span> for syntax::codemap::Span {
1313     fn clean(&self) -> Span {
1314         let ctxt = super::ctxtkey.get().unwrap();
1315         let cm = ctxt.sess().codemap();
1316         let filename = cm.span_to_filename(*self);
1317         let lo = cm.lookup_char_pos(self.lo);
1318         let hi = cm.lookup_char_pos(self.hi);
1319         Span {
1320             filename: filename.to_string(),
1321             loline: lo.line,
1322             locol: lo.col.to_uint(),
1323             hiline: hi.line,
1324             hicol: hi.col.to_uint(),
1325         }
1326     }
1327 }
1328
1329 #[deriving(Clone, Encodable, Decodable)]
1330 pub struct Path {
1331     pub global: bool,
1332     pub segments: Vec<PathSegment>,
1333 }
1334
1335 impl Clean<Path> for ast::Path {
1336     fn clean(&self) -> Path {
1337         Path {
1338             global: self.global,
1339             segments: self.segments.clean().move_iter().collect(),
1340         }
1341     }
1342 }
1343
1344 #[deriving(Clone, Encodable, Decodable)]
1345 pub struct PathSegment {
1346     pub name: String,
1347     pub lifetimes: Vec<Lifetime>,
1348     pub types: Vec<Type>,
1349 }
1350
1351 impl Clean<PathSegment> for ast::PathSegment {
1352     fn clean(&self) -> PathSegment {
1353         PathSegment {
1354             name: self.identifier.clean(),
1355             lifetimes: self.lifetimes.clean().move_iter().collect(),
1356             types: self.types.clean().move_iter().collect()
1357         }
1358     }
1359 }
1360
1361 fn path_to_str(p: &ast::Path) -> String {
1362     use syntax::parse::token;
1363
1364     let mut s = String::new();
1365     let mut first = true;
1366     for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1367         if !first || p.global {
1368             s.push_str("::");
1369         } else {
1370             first = false;
1371         }
1372         s.push_str(i.get());
1373     }
1374     s
1375 }
1376
1377 impl Clean<String> for ast::Ident {
1378     fn clean(&self) -> String {
1379         token::get_ident(*self).get().to_string()
1380     }
1381 }
1382
1383 impl Clean<String> for ast::Name {
1384     fn clean(&self) -> String {
1385         token::get_name(*self).get().to_string()
1386     }
1387 }
1388
1389 #[deriving(Clone, Encodable, Decodable)]
1390 pub struct Typedef {
1391     pub type_: Type,
1392     pub generics: Generics,
1393 }
1394
1395 impl Clean<Item> for doctree::Typedef {
1396     fn clean(&self) -> Item {
1397         Item {
1398             name: Some(self.name.clean()),
1399             attrs: self.attrs.clean(),
1400             source: self.where.clean(),
1401             def_id: ast_util::local_def(self.id.clone()),
1402             visibility: self.vis.clean(),
1403             inner: TypedefItem(Typedef {
1404                 type_: self.ty.clean(),
1405                 generics: self.gen.clean(),
1406             }),
1407         }
1408     }
1409 }
1410
1411 #[deriving(Clone, Encodable, Decodable)]
1412 pub struct BareFunctionDecl {
1413     pub fn_style: ast::FnStyle,
1414     pub generics: Generics,
1415     pub decl: FnDecl,
1416     pub abi: String,
1417 }
1418
1419 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1420     fn clean(&self) -> BareFunctionDecl {
1421         BareFunctionDecl {
1422             fn_style: self.fn_style,
1423             generics: Generics {
1424                 lifetimes: self.lifetimes.clean().move_iter().collect(),
1425                 type_params: Vec::new(),
1426             },
1427             decl: self.decl.clean(),
1428             abi: self.abi.to_str().to_string(),
1429         }
1430     }
1431 }
1432
1433 #[deriving(Clone, Encodable, Decodable)]
1434 pub struct Static {
1435     pub type_: Type,
1436     pub mutability: Mutability,
1437     /// It's useful to have the value of a static documented, but I have no
1438     /// desire to represent expressions (that'd basically be all of the AST,
1439     /// which is huge!). So, have a string.
1440     pub expr: String,
1441 }
1442
1443 impl Clean<Item> for doctree::Static {
1444     fn clean(&self) -> Item {
1445         debug!("claning static {}: {:?}", self.name.clean(), self);
1446         Item {
1447             name: Some(self.name.clean()),
1448             attrs: self.attrs.clean(),
1449             source: self.where.clean(),
1450             def_id: ast_util::local_def(self.id),
1451             visibility: self.vis.clean(),
1452             inner: StaticItem(Static {
1453                 type_: self.type_.clean(),
1454                 mutability: self.mutability.clean(),
1455                 expr: self.expr.span.to_src(),
1456             }),
1457         }
1458     }
1459 }
1460
1461 #[deriving(Show, Clone, Encodable, Decodable, Eq)]
1462 pub enum Mutability {
1463     Mutable,
1464     Immutable,
1465 }
1466
1467 impl Clean<Mutability> for ast::Mutability {
1468     fn clean(&self) -> Mutability {
1469         match self {
1470             &ast::MutMutable => Mutable,
1471             &ast::MutImmutable => Immutable,
1472         }
1473     }
1474 }
1475
1476 #[deriving(Clone, Encodable, Decodable)]
1477 pub struct Impl {
1478     pub generics: Generics,
1479     pub trait_: Option<Type>,
1480     pub for_: Type,
1481     pub methods: Vec<Item>,
1482     pub derived: bool,
1483 }
1484
1485 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1486     attr::contains_name(attrs, "automatically_derived")
1487 }
1488
1489 impl Clean<Item> for doctree::Impl {
1490     fn clean(&self) -> Item {
1491         Item {
1492             name: None,
1493             attrs: self.attrs.clean(),
1494             source: self.where.clean(),
1495             def_id: ast_util::local_def(self.id),
1496             visibility: self.vis.clean(),
1497             inner: ImplItem(Impl {
1498                 generics: self.generics.clean(),
1499                 trait_: self.trait_.clean(),
1500                 for_: self.for_.clean(),
1501                 methods: self.methods.clean(),
1502                 derived: detect_derived(self.attrs.as_slice()),
1503             }),
1504         }
1505     }
1506 }
1507
1508 #[deriving(Clone, Encodable, Decodable)]
1509 pub struct ViewItem {
1510     pub inner: ViewItemInner,
1511 }
1512
1513 impl Clean<Vec<Item>> for ast::ViewItem {
1514     fn clean(&self) -> Vec<Item> {
1515         // We consider inlining the documentation of `pub use` statments, but we
1516         // forcefully don't inline if this is not public or if the
1517         // #[doc(no_inline)] attribute is present.
1518         let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1519             a.name().get() == "doc" && match a.meta_item_list() {
1520                 Some(l) => attr::contains_name(l, "no_inline"),
1521                 None => false,
1522             }
1523         });
1524         let convert = |node: &ast::ViewItem_| {
1525             Item {
1526                 name: None,
1527                 attrs: self.attrs.clean().move_iter().collect(),
1528                 source: self.span.clean(),
1529                 def_id: ast_util::local_def(0),
1530                 visibility: self.vis.clean(),
1531                 inner: ViewItemItem(ViewItem { inner: node.clean() }),
1532             }
1533         };
1534         let mut ret = Vec::new();
1535         match self.node {
1536             ast::ViewItemUse(ref path) if !denied => {
1537                 match path.node {
1538                     ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
1539                     ast::ViewPathList(ref a, ref list, ref b) => {
1540                         // Attempt to inline all reexported items, but be sure
1541                         // to keep any non-inlineable reexports so they can be
1542                         // listed in the documentation.
1543                         let remaining = list.iter().filter(|path| {
1544                             match inline::try_inline(path.node.id) {
1545                                 Some(items) => {
1546                                     ret.extend(items.move_iter()); false
1547                                 }
1548                                 None => true,
1549                             }
1550                         }).map(|a| a.clone()).collect::<Vec<ast::PathListIdent>>();
1551                         if remaining.len() > 0 {
1552                             let path = ast::ViewPathList(a.clone(),
1553                                                          remaining,
1554                                                          b.clone());
1555                             let path = syntax::codemap::dummy_spanned(path);
1556                             ret.push(convert(&ast::ViewItemUse(@path)));
1557                         }
1558                     }
1559                     ast::ViewPathSimple(_, _, id) => {
1560                         match inline::try_inline(id) {
1561                             Some(items) => ret.extend(items.move_iter()),
1562                             None => ret.push(convert(&self.node)),
1563                         }
1564                     }
1565                 }
1566             }
1567             ref n => ret.push(convert(n)),
1568         }
1569         return ret;
1570     }
1571 }
1572
1573 #[deriving(Clone, Encodable, Decodable)]
1574 pub enum ViewItemInner {
1575     ExternCrate(String, Option<String>, ast::NodeId),
1576     Import(ViewPath)
1577 }
1578
1579 impl Clean<ViewItemInner> for ast::ViewItem_ {
1580     fn clean(&self) -> ViewItemInner {
1581         match self {
1582             &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1583                 let string = match *p {
1584                     None => None,
1585                     Some((ref x, _)) => Some(x.get().to_string()),
1586                 };
1587                 ExternCrate(i.clean(), string, *id)
1588             }
1589             &ast::ViewItemUse(ref vp) => {
1590                 Import(vp.clean())
1591             }
1592         }
1593     }
1594 }
1595
1596 #[deriving(Clone, Encodable, Decodable)]
1597 pub enum ViewPath {
1598     // use str = source;
1599     SimpleImport(String, ImportSource),
1600     // use source::*;
1601     GlobImport(ImportSource),
1602     // use source::{a, b, c};
1603     ImportList(ImportSource, Vec<ViewListIdent>),
1604 }
1605
1606 #[deriving(Clone, Encodable, Decodable)]
1607 pub struct ImportSource {
1608     pub path: Path,
1609     pub did: Option<ast::DefId>,
1610 }
1611
1612 impl Clean<ViewPath> for ast::ViewPath {
1613     fn clean(&self) -> ViewPath {
1614         match self.node {
1615             ast::ViewPathSimple(ref i, ref p, id) =>
1616                 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1617             ast::ViewPathGlob(ref p, id) =>
1618                 GlobImport(resolve_use_source(p.clean(), id)),
1619             ast::ViewPathList(ref p, ref pl, id) => {
1620                 ImportList(resolve_use_source(p.clean(), id),
1621                            pl.clean().move_iter().collect())
1622             }
1623         }
1624     }
1625 }
1626
1627 #[deriving(Clone, Encodable, Decodable)]
1628 pub struct ViewListIdent {
1629     pub name: String,
1630     pub source: Option<ast::DefId>,
1631 }
1632
1633 impl Clean<ViewListIdent> for ast::PathListIdent {
1634     fn clean(&self) -> ViewListIdent {
1635         ViewListIdent {
1636             name: self.node.name.clean(),
1637             source: resolve_def(self.node.id),
1638         }
1639     }
1640 }
1641
1642 impl Clean<Vec<Item>> for ast::ForeignMod {
1643     fn clean(&self) -> Vec<Item> {
1644         self.items.clean()
1645     }
1646 }
1647
1648 impl Clean<Item> for ast::ForeignItem {
1649     fn clean(&self) -> Item {
1650         let inner = match self.node {
1651             ast::ForeignItemFn(ref decl, ref generics) => {
1652                 ForeignFunctionItem(Function {
1653                     decl: decl.clean(),
1654                     generics: generics.clean(),
1655                     fn_style: ast::UnsafeFn,
1656                 })
1657             }
1658             ast::ForeignItemStatic(ref ty, mutbl) => {
1659                 ForeignStaticItem(Static {
1660                     type_: ty.clean(),
1661                     mutability: if mutbl {Mutable} else {Immutable},
1662                     expr: "".to_string(),
1663                 })
1664             }
1665         };
1666         Item {
1667             name: Some(self.ident.clean()),
1668             attrs: self.attrs.clean().move_iter().collect(),
1669             source: self.span.clean(),
1670             def_id: ast_util::local_def(self.id),
1671             visibility: self.vis.clean(),
1672             inner: inner,
1673         }
1674     }
1675 }
1676
1677 // Utilities
1678
1679 trait ToSource {
1680     fn to_src(&self) -> String;
1681 }
1682
1683 impl ToSource for syntax::codemap::Span {
1684     fn to_src(&self) -> String {
1685         debug!("converting span {:?} to snippet", self.clean());
1686         let ctxt = super::ctxtkey.get().unwrap();
1687         let cm = ctxt.sess().codemap().clone();
1688         let sn = match cm.span_to_snippet(*self) {
1689             Some(x) => x.to_string(),
1690             None    => "".to_string()
1691         };
1692         debug!("got snippet {}", sn);
1693         sn
1694     }
1695 }
1696
1697 fn lit_to_str(lit: &ast::Lit) -> String {
1698     match lit.node {
1699         ast::LitStr(ref st, _) => st.get().to_string(),
1700         ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1701         ast::LitChar(c) => format!("'{}'", c),
1702         ast::LitInt(i, _t) => i.to_str().to_string(),
1703         ast::LitUint(u, _t) => u.to_str().to_string(),
1704         ast::LitIntUnsuffixed(i) => i.to_str().to_string(),
1705         ast::LitFloat(ref f, _t) => f.get().to_string(),
1706         ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1707         ast::LitBool(b) => b.to_str().to_string(),
1708         ast::LitNil => "".to_string(),
1709     }
1710 }
1711
1712 fn name_from_pat(p: &ast::Pat) -> String {
1713     use syntax::ast::*;
1714     debug!("Trying to get a name from pattern: {:?}", p);
1715
1716     match p.node {
1717         PatWild => "_".to_string(),
1718         PatWildMulti => "..".to_string(),
1719         PatIdent(_, ref p, _) => path_to_str(p),
1720         PatEnum(ref p, _) => path_to_str(p),
1721         PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1722                                 which is not allowed in function arguments"),
1723         PatTup(..) => "(tuple arg NYI)".to_string(),
1724         PatUniq(p) => name_from_pat(p),
1725         PatRegion(p) => name_from_pat(p),
1726         PatLit(..) => {
1727             warn!("tried to get argument name from PatLit, \
1728                   which is silly in function arguments");
1729             "()".to_string()
1730         },
1731         PatRange(..) => fail!("tried to get argument name from PatRange, \
1732                               which is not allowed in function arguments"),
1733         PatVec(..) => fail!("tried to get argument name from pat_vec, \
1734                              which is not allowed in function arguments"),
1735         PatMac(..) => {
1736             warn!("can't document the name of a function argument \
1737                    produced by a pattern macro");
1738             "(argument produced by macro)".to_string()
1739         }
1740     }
1741 }
1742
1743 /// Given a Type, resolve it using the def_map
1744 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound>>,
1745                 id: ast::NodeId) -> Type {
1746     let cx = super::ctxtkey.get().unwrap();
1747     let tycx = match cx.maybe_typed {
1748         core::Typed(ref tycx) => tycx,
1749         // If we're extracting tests, this return value doesn't matter.
1750         core::NotTyped(_) => return Bool
1751     };
1752     debug!("searching for {:?} in defmap", id);
1753     let def = match tycx.def_map.borrow().find(&id) {
1754         Some(&k) => k,
1755         None => fail!("unresolved id not in defmap")
1756     };
1757
1758     match def {
1759         ast::DefSelfTy(i) => return Self(ast_util::local_def(i)),
1760         ast::DefPrimTy(p) => match p {
1761             ast::TyStr => return String,
1762             ast::TyBool => return Bool,
1763             _ => return Primitive(p)
1764         },
1765         ast::DefTyParam(i, _) => return Generic(i),
1766         ast::DefTyParamBinder(i) => return TyParamBinder(i),
1767         _ => {}
1768     };
1769     let did = register_def(&**cx, def);
1770     ResolvedPath { path: path, typarams: tpbs, did: did }
1771 }
1772
1773 fn register_def(cx: &core::DocContext, def: ast::Def) -> ast::DefId {
1774     let (did, kind) = match def {
1775         ast::DefFn(i, _) => (i, TypeFunction),
1776         ast::DefTy(i) => (i, TypeEnum),
1777         ast::DefTrait(i) => (i, TypeTrait),
1778         ast::DefStruct(i) => (i, TypeStruct),
1779         ast::DefMod(i) => (i, TypeModule),
1780         ast::DefStatic(i, _) => (i, TypeStatic),
1781         ast::DefVariant(i, _, _) => (i, TypeEnum),
1782         _ => return ast_util::def_id_of_def(def),
1783     };
1784     if ast_util::is_local(did) { return did }
1785     let tcx = match cx.maybe_typed {
1786         core::Typed(ref t) => t,
1787         core::NotTyped(_) => return did
1788     };
1789     inline::record_extern_fqn(cx, did, kind);
1790     match kind {
1791         TypeTrait => {
1792             let t = inline::build_external_trait(tcx, did);
1793             cx.external_traits.borrow_mut().get_mut_ref().insert(did, t);
1794         }
1795         _ => {}
1796     }
1797     return did;
1798 }
1799
1800 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
1801     ImportSource {
1802         path: path,
1803         did: resolve_def(id),
1804     }
1805 }
1806
1807 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
1808     let cx = super::ctxtkey.get().unwrap();
1809     match cx.maybe_typed {
1810         core::Typed(ref tcx) => {
1811             tcx.def_map.borrow().find(&id).map(|&def| register_def(&**cx, def))
1812         }
1813         core::NotTyped(_) => None
1814     }
1815 }
1816
1817 #[deriving(Clone, Encodable, Decodable)]
1818 pub struct Macro {
1819     pub source: String,
1820 }
1821
1822 impl Clean<Item> for doctree::Macro {
1823     fn clean(&self) -> Item {
1824         Item {
1825             name: Some(format!("{}!", self.name.clean())),
1826             attrs: self.attrs.clean(),
1827             source: self.where.clean(),
1828             visibility: ast::Public.clean(),
1829             def_id: ast_util::local_def(self.id),
1830             inner: MacroItem(Macro {
1831                 source: self.where.to_src(),
1832             }),
1833         }
1834     }
1835 }