]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean.rs
auto merge of #13452 : Ryman/rust/fix_uint_as_u, r=alexcrichton
[rust.git] / src / librustdoc / clean.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;
19 use syntax::codemap::Pos;
20 use syntax::parse::token::InternedString;
21 use syntax::parse::token;
22
23 use rustc::metadata::cstore;
24 use rustc::metadata::csearch;
25 use rustc::metadata::decoder;
26
27 use std::local_data;
28 use std::strbuf::StrBuf;
29 use std;
30
31 use core;
32 use doctree;
33 use visit_ast;
34
35 pub trait Clean<T> {
36     fn clean(&self) -> T;
37 }
38
39 impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
40     fn clean(&self) -> Vec<U> {
41         self.iter().map(|x| x.clean()).collect()
42     }
43 }
44
45 impl<T: Clean<U>, U> Clean<U> for @T {
46     fn clean(&self) -> U {
47         (**self).clean()
48     }
49 }
50
51 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
52     fn clean(&self) -> Option<U> {
53         match self {
54             &None => None,
55             &Some(ref v) => Some(v.clean())
56         }
57     }
58 }
59
60 impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
61     fn clean(&self) -> Vec<U> {
62         self.iter().map(|x| x.clean()).collect()
63     }
64 }
65
66 #[deriving(Clone, Encodable, Decodable)]
67 pub struct Crate {
68     pub name: ~str,
69     pub module: Option<Item>,
70     pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
71 }
72
73 impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> {
74     fn clean(&self) -> Crate {
75         use syntax::attr::find_crateid;
76         let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
77
78         let mut externs = Vec::new();
79         cx.sess().cstore.iter_crate_data(|n, meta| {
80             externs.push((n, meta.clean()));
81         });
82
83         Crate {
84             name: match find_crateid(self.attrs.as_slice()) {
85                 Some(n) => n.name,
86                 None => fail!("rustdoc requires a `crate_id` crate attribute"),
87             },
88             module: Some(self.module.clean()),
89             externs: externs,
90         }
91     }
92 }
93
94 #[deriving(Clone, Encodable, Decodable)]
95 pub struct ExternalCrate {
96     pub name: ~str,
97     pub attrs: Vec<Attribute>,
98 }
99
100 impl Clean<ExternalCrate> for cstore::crate_metadata {
101     fn clean(&self) -> ExternalCrate {
102         ExternalCrate {
103             name: self.name.to_owned(),
104             attrs: decoder::get_crate_attributes(self.data()).clean()
105                                                              .move_iter()
106                                                              .collect(),
107         }
108     }
109 }
110
111 /// Anything with a source location and set of attributes and, optionally, a
112 /// name. That is, anything that can be documented. This doesn't correspond
113 /// directly to the AST's concept of an item; it's a strict superset.
114 #[deriving(Clone, Encodable, Decodable)]
115 pub struct Item {
116     /// Stringified span
117     pub source: Span,
118     /// Not everything has a name. E.g., impls
119     pub name: Option<~str>,
120     pub attrs: Vec<Attribute> ,
121     pub inner: ItemEnum,
122     pub visibility: Option<Visibility>,
123     pub id: ast::NodeId,
124 }
125
126 impl Item {
127     /// Finds the `doc` attribute as a List and returns the list of attributes
128     /// nested inside.
129     pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
130         for attr in self.attrs.iter() {
131             match *attr {
132                 List(ref x, ref list) if "doc" == *x => { return Some(list.as_slice()); }
133                 _ => {}
134             }
135         }
136         return None;
137     }
138
139     /// Finds the `doc` attribute as a NameValue and returns the corresponding
140     /// value found.
141     pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
142         for attr in self.attrs.iter() {
143             match *attr {
144                 NameValue(ref x, ref v) if "doc" == *x => { return Some(v.as_slice()); }
145                 _ => {}
146             }
147         }
148         return None;
149     }
150
151     pub fn is_mod(&self) -> bool {
152         match self.inner { ModuleItem(..) => true, _ => false }
153     }
154     pub fn is_trait(&self) -> bool {
155         match self.inner { TraitItem(..) => true, _ => false }
156     }
157     pub fn is_struct(&self) -> bool {
158         match self.inner { StructItem(..) => true, _ => false }
159     }
160     pub fn is_enum(&self) -> bool {
161         match self.inner { EnumItem(..) => true, _ => false }
162     }
163     pub fn is_fn(&self) -> bool {
164         match self.inner { FunctionItem(..) => true, _ => false }
165     }
166 }
167
168 #[deriving(Clone, Encodable, Decodable)]
169 pub enum ItemEnum {
170     StructItem(Struct),
171     EnumItem(Enum),
172     FunctionItem(Function),
173     ModuleItem(Module),
174     TypedefItem(Typedef),
175     StaticItem(Static),
176     TraitItem(Trait),
177     ImplItem(Impl),
178     /// `use` and `extern crate`
179     ViewItemItem(ViewItem),
180     /// A method signature only. Used for required methods in traits (ie,
181     /// non-default-methods).
182     TyMethodItem(TyMethod),
183     /// A method with a body.
184     MethodItem(Method),
185     StructFieldItem(StructField),
186     VariantItem(Variant),
187     /// `fn`s from an extern block
188     ForeignFunctionItem(Function),
189     /// `static`s from an extern block
190     ForeignStaticItem(Static),
191     MacroItem(Macro),
192 }
193
194 #[deriving(Clone, Encodable, Decodable)]
195 pub struct Module {
196     pub items: Vec<Item>,
197     pub is_crate: bool,
198 }
199
200 impl Clean<Item> for doctree::Module {
201     fn clean(&self) -> Item {
202         let name = if self.name.is_some() {
203             self.name.unwrap().clean()
204         } else {
205             ~""
206         };
207         let mut foreigns = Vec::new();
208         for subforeigns in self.foreigns.clean().move_iter() {
209             for foreign in subforeigns.move_iter() {
210                 foreigns.push(foreign)
211             }
212         }
213         let items: Vec<Vec<Item> > = vec!(
214             self.structs.clean().move_iter().collect(),
215             self.enums.clean().move_iter().collect(),
216             self.fns.clean().move_iter().collect(),
217             foreigns,
218             self.mods.clean().move_iter().collect(),
219             self.typedefs.clean().move_iter().collect(),
220             self.statics.clean().move_iter().collect(),
221             self.traits.clean().move_iter().collect(),
222             self.impls.clean().move_iter().collect(),
223             self.view_items.clean().move_iter().collect(),
224             self.macros.clean().move_iter().collect()
225         );
226         Item {
227             name: Some(name),
228             attrs: self.attrs.clean(),
229             source: self.where.clean(),
230             visibility: self.vis.clean(),
231             id: self.id,
232             inner: ModuleItem(Module {
233                is_crate: self.is_crate,
234                items: items.iter()
235                            .flat_map(|x| x.iter().map(|x| (*x).clone()))
236                            .collect(),
237             })
238         }
239     }
240 }
241
242 #[deriving(Clone, Encodable, Decodable)]
243 pub enum Attribute {
244     Word(~str),
245     List(~str, Vec<Attribute> ),
246     NameValue(~str, ~str)
247 }
248
249 impl Clean<Attribute> for ast::MetaItem {
250     fn clean(&self) -> Attribute {
251         match self.node {
252             ast::MetaWord(ref s) => Word(s.get().to_owned()),
253             ast::MetaList(ref s, ref l) => {
254                 List(s.get().to_owned(), l.clean().move_iter().collect())
255             }
256             ast::MetaNameValue(ref s, ref v) => {
257                 NameValue(s.get().to_owned(), lit_to_str(v))
258             }
259         }
260     }
261 }
262
263 impl Clean<Attribute> for ast::Attribute {
264     fn clean(&self) -> Attribute {
265         self.desugar_doc().node.value.clean()
266     }
267 }
268
269 // This is a rough approximation that gets us what we want.
270 impl<'a> attr::AttrMetaMethods for &'a Attribute {
271     fn name(&self) -> InternedString {
272         match **self {
273             Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
274                 token::intern_and_get_ident(*n)
275             }
276         }
277     }
278
279     fn value_str(&self) -> Option<InternedString> {
280         match **self {
281             NameValue(_, ref v) => Some(token::intern_and_get_ident(*v)),
282             _ => None,
283         }
284     }
285     fn meta_item_list<'a>(&'a self) -> Option<&'a [@ast::MetaItem]> { None }
286     fn name_str_pair(&self) -> Option<(InternedString, InternedString)> {
287         None
288     }
289 }
290
291 #[deriving(Clone, Encodable, Decodable)]
292 pub struct TyParam {
293     pub name: ~str,
294     pub id: ast::NodeId,
295     pub bounds: Vec<TyParamBound>,
296 }
297
298 impl Clean<TyParam> for ast::TyParam {
299     fn clean(&self) -> TyParam {
300         TyParam {
301             name: self.ident.clean(),
302             id: self.id,
303             bounds: self.bounds.clean().move_iter().collect(),
304         }
305     }
306 }
307
308 #[deriving(Clone, Encodable, Decodable)]
309 pub enum TyParamBound {
310     RegionBound,
311     TraitBound(Type)
312 }
313
314 impl Clean<TyParamBound> for ast::TyParamBound {
315     fn clean(&self) -> TyParamBound {
316         match *self {
317             ast::RegionTyParamBound => RegionBound,
318             ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
319         }
320     }
321 }
322
323 #[deriving(Clone, Encodable, Decodable)]
324 pub struct Lifetime(~str);
325
326 impl Lifetime {
327     pub fn get_ref<'a>(&'a self) -> &'a str {
328         let Lifetime(ref s) = *self;
329         let s: &'a str = *s;
330         return s;
331     }
332 }
333
334 impl Clean<Lifetime> for ast::Lifetime {
335     fn clean(&self) -> Lifetime {
336         Lifetime(token::get_name(self.name).get().to_owned())
337     }
338 }
339
340 // maybe use a Generic enum and use ~[Generic]?
341 #[deriving(Clone, Encodable, Decodable)]
342 pub struct Generics {
343     pub lifetimes: Vec<Lifetime>,
344     pub type_params: Vec<TyParam>,
345 }
346
347 impl Clean<Generics> for ast::Generics {
348     fn clean(&self) -> Generics {
349         Generics {
350             lifetimes: self.lifetimes.clean().move_iter().collect(),
351             type_params: self.ty_params.clean().move_iter().collect(),
352         }
353     }
354 }
355
356 #[deriving(Clone, Encodable, Decodable)]
357 pub struct Method {
358     pub generics: Generics,
359     pub self_: SelfTy,
360     pub fn_style: ast::FnStyle,
361     pub decl: FnDecl,
362 }
363
364 impl Clean<Item> for ast::Method {
365     fn clean(&self) -> Item {
366         let inputs = match self.explicit_self.node {
367             ast::SelfStatic => self.decl.inputs.as_slice(),
368             _ => self.decl.inputs.slice_from(1)
369         };
370         let decl = FnDecl {
371             inputs: Arguments {
372                 values: inputs.iter().map(|x| x.clean()).collect(),
373             },
374             output: (self.decl.output.clean()),
375             cf: self.decl.cf.clean(),
376             attrs: Vec::new()
377         };
378         Item {
379             name: Some(self.ident.clean()),
380             attrs: self.attrs.clean().move_iter().collect(),
381             source: self.span.clean(),
382             id: self.id.clone(),
383             visibility: self.vis.clean(),
384             inner: MethodItem(Method {
385                 generics: self.generics.clean(),
386                 self_: self.explicit_self.clean(),
387                 fn_style: self.fn_style.clone(),
388                 decl: decl,
389             }),
390         }
391     }
392 }
393
394 #[deriving(Clone, Encodable, Decodable)]
395 pub struct TyMethod {
396     pub fn_style: ast::FnStyle,
397     pub decl: FnDecl,
398     pub generics: Generics,
399     pub self_: SelfTy,
400 }
401
402 impl Clean<Item> for ast::TypeMethod {
403     fn clean(&self) -> Item {
404         let inputs = match self.explicit_self.node {
405             ast::SelfStatic => self.decl.inputs.as_slice(),
406             _ => self.decl.inputs.slice_from(1)
407         };
408         let decl = FnDecl {
409             inputs: Arguments {
410                 values: inputs.iter().map(|x| x.clean()).collect(),
411             },
412             output: (self.decl.output.clean()),
413             cf: self.decl.cf.clean(),
414             attrs: Vec::new()
415         };
416         Item {
417             name: Some(self.ident.clean()),
418             attrs: self.attrs.clean().move_iter().collect(),
419             source: self.span.clean(),
420             id: self.id,
421             visibility: None,
422             inner: TyMethodItem(TyMethod {
423                 fn_style: self.fn_style.clone(),
424                 decl: decl,
425                 self_: self.explicit_self.clean(),
426                 generics: self.generics.clean(),
427             }),
428         }
429     }
430 }
431
432 #[deriving(Clone, Encodable, Decodable)]
433 pub enum SelfTy {
434     SelfStatic,
435     SelfValue,
436     SelfBorrowed(Option<Lifetime>, Mutability),
437     SelfOwned,
438 }
439
440 impl Clean<SelfTy> for ast::ExplicitSelf {
441     fn clean(&self) -> SelfTy {
442         match self.node {
443             ast::SelfStatic => SelfStatic,
444             ast::SelfValue => SelfValue,
445             ast::SelfUniq => SelfOwned,
446             ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()),
447         }
448     }
449 }
450
451 #[deriving(Clone, Encodable, Decodable)]
452 pub struct Function {
453     pub decl: FnDecl,
454     pub generics: Generics,
455     pub fn_style: ast::FnStyle,
456 }
457
458 impl Clean<Item> for doctree::Function {
459     fn clean(&self) -> Item {
460         Item {
461             name: Some(self.name.clean()),
462             attrs: self.attrs.clean(),
463             source: self.where.clean(),
464             visibility: self.vis.clean(),
465             id: self.id,
466             inner: FunctionItem(Function {
467                 decl: self.decl.clean(),
468                 generics: self.generics.clean(),
469                 fn_style: self.fn_style,
470             }),
471         }
472     }
473 }
474
475 #[deriving(Clone, Encodable, Decodable)]
476 pub struct ClosureDecl {
477     pub lifetimes: Vec<Lifetime>,
478     pub decl: FnDecl,
479     pub onceness: ast::Onceness,
480     pub fn_style: ast::FnStyle,
481     pub bounds: Vec<TyParamBound>,
482 }
483
484 impl Clean<ClosureDecl> for ast::ClosureTy {
485     fn clean(&self) -> ClosureDecl {
486         ClosureDecl {
487             lifetimes: self.lifetimes.clean().move_iter().collect(),
488             decl: self.decl.clean(),
489             onceness: self.onceness,
490             fn_style: self.fn_style,
491             bounds: match self.bounds {
492                 Some(ref x) => x.clean().move_iter().collect(),
493                 None        => Vec::new()
494             },
495         }
496     }
497 }
498
499 #[deriving(Clone, Encodable, Decodable)]
500 pub struct FnDecl {
501     pub inputs: Arguments,
502     pub output: Type,
503     pub cf: RetStyle,
504     pub attrs: Vec<Attribute>,
505 }
506
507 #[deriving(Clone, Encodable, Decodable)]
508 pub struct Arguments {
509     pub values: Vec<Argument>,
510 }
511
512 impl Clean<FnDecl> for ast::FnDecl {
513     fn clean(&self) -> FnDecl {
514         FnDecl {
515             inputs: Arguments {
516                 values: self.inputs.iter().map(|x| x.clean()).collect(),
517             },
518             output: (self.output.clean()),
519             cf: self.cf.clean(),
520             attrs: Vec::new()
521         }
522     }
523 }
524
525 #[deriving(Clone, Encodable, Decodable)]
526 pub struct Argument {
527     pub type_: Type,
528     pub name: ~str,
529     pub id: ast::NodeId,
530 }
531
532 impl Clean<Argument> for ast::Arg {
533     fn clean(&self) -> Argument {
534         Argument {
535             name: name_from_pat(self.pat),
536             type_: (self.ty.clean()),
537             id: self.id
538         }
539     }
540 }
541
542 #[deriving(Clone, Encodable, Decodable)]
543 pub enum RetStyle {
544     NoReturn,
545     Return
546 }
547
548 impl Clean<RetStyle> for ast::RetStyle {
549     fn clean(&self) -> RetStyle {
550         match *self {
551             ast::Return => Return,
552             ast::NoReturn => NoReturn
553         }
554     }
555 }
556
557 #[deriving(Clone, Encodable, Decodable)]
558 pub struct Trait {
559     pub methods: Vec<TraitMethod>,
560     pub generics: Generics,
561     pub parents: Vec<Type>,
562 }
563
564 impl Clean<Item> for doctree::Trait {
565     fn clean(&self) -> Item {
566         Item {
567             name: Some(self.name.clean()),
568             attrs: self.attrs.clean(),
569             source: self.where.clean(),
570             id: self.id,
571             visibility: self.vis.clean(),
572             inner: TraitItem(Trait {
573                 methods: self.methods.clean(),
574                 generics: self.generics.clean(),
575                 parents: self.parents.clean(),
576             }),
577         }
578     }
579 }
580
581 impl Clean<Type> for ast::TraitRef {
582     fn clean(&self) -> Type {
583         resolve_type(self.path.clean(), None, self.ref_id)
584     }
585 }
586
587 #[deriving(Clone, Encodable, Decodable)]
588 pub enum TraitMethod {
589     Required(Item),
590     Provided(Item),
591 }
592
593 impl TraitMethod {
594     pub fn is_req(&self) -> bool {
595         match self {
596             &Required(..) => true,
597             _ => false,
598         }
599     }
600     pub fn is_def(&self) -> bool {
601         match self {
602             &Provided(..) => true,
603             _ => false,
604         }
605     }
606     pub fn item<'a>(&'a self) -> &'a Item {
607         match *self {
608             Required(ref item) => item,
609             Provided(ref item) => item,
610         }
611     }
612 }
613
614 impl Clean<TraitMethod> for ast::TraitMethod {
615     fn clean(&self) -> TraitMethod {
616         match self {
617             &ast::Required(ref t) => Required(t.clean()),
618             &ast::Provided(ref t) => Provided(t.clean()),
619         }
620     }
621 }
622
623 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
624 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
625 /// it does not preserve mutability or boxes.
626 #[deriving(Clone, Encodable, Decodable)]
627 pub enum Type {
628     /// structs/enums/traits (anything that'd be an ast::TyPath)
629     ResolvedPath {
630         pub path: Path,
631         pub typarams: Option<Vec<TyParamBound>>,
632         pub id: ast::NodeId,
633     },
634     /// Same as above, but only external variants
635     ExternalPath {
636         pub path: Path,
637         pub typarams: Option<Vec<TyParamBound>>,
638         pub fqn: Vec<~str>,
639         pub kind: TypeKind,
640         pub krate: ast::CrateNum,
641     },
642     // I have no idea how to usefully use this.
643     TyParamBinder(ast::NodeId),
644     /// For parameterized types, so the consumer of the JSON don't go looking
645     /// for types which don't exist anywhere.
646     Generic(ast::NodeId),
647     /// For references to self
648     Self(ast::NodeId),
649     /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
650     Primitive(ast::PrimTy),
651     Closure(~ClosureDecl, Option<Lifetime>),
652     Proc(~ClosureDecl),
653     /// extern "ABI" fn
654     BareFunction(~BareFunctionDecl),
655     Tuple(Vec<Type> ),
656     Vector(~Type),
657     FixedVector(~Type, ~str),
658     String,
659     Bool,
660     /// aka TyNil
661     Unit,
662     /// aka TyBot
663     Bottom,
664     Unique(~Type),
665     Managed(~Type),
666     RawPointer(Mutability, ~Type),
667     BorrowedRef {
668         pub lifetime: Option<Lifetime>,
669         pub mutability: Mutability,
670         pub type_: ~Type,
671     },
672     // region, raw, other boxes, mutable
673 }
674
675 #[deriving(Clone, Encodable, Decodable)]
676 pub enum TypeKind {
677     TypeStruct,
678     TypeEnum,
679     TypeTrait,
680     TypeFunction,
681 }
682
683 impl Clean<Type> for ast::Ty {
684     fn clean(&self) -> Type {
685         use syntax::ast::*;
686         debug!("cleaning type `{:?}`", self);
687         let codemap = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess().codemap();
688         debug!("span corresponds to `{}`", codemap.span_to_str(self.span));
689         match self.node {
690             TyNil => Unit,
691             TyPtr(ref m) => RawPointer(m.mutbl.clean(), ~m.ty.clean()),
692             TyRptr(ref l, ref m) =>
693                 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
694                              type_: ~m.ty.clean()},
695             TyBox(ty) => Managed(~ty.clean()),
696             TyUniq(ty) => Unique(~ty.clean()),
697             TyVec(ty) => Vector(~ty.clean()),
698             TyFixedLengthVec(ty, ref e) => FixedVector(~ty.clean(),
699                                                        e.span.to_src()),
700             TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
701             TyPath(ref p, ref tpbs, id) => {
702                 resolve_type(p.clean(),
703                              tpbs.clean().map(|x| x.move_iter().collect()),
704                              id)
705             }
706             TyClosure(ref c, region) => Closure(~c.clean(), region.clean()),
707             TyProc(ref c) => Proc(~c.clean()),
708             TyBareFn(ref barefn) => BareFunction(~barefn.clean()),
709             TyBot => Bottom,
710             ref x => fail!("Unimplemented type {:?}", x),
711         }
712     }
713 }
714
715 #[deriving(Clone, Encodable, Decodable)]
716 pub struct StructField {
717     pub type_: Type,
718 }
719
720 impl Clean<Item> for ast::StructField {
721     fn clean(&self) -> Item {
722         let (name, vis) = match self.node.kind {
723             ast::NamedField(id, vis) => (Some(id), Some(vis)),
724             _ => (None, None)
725         };
726         Item {
727             name: name.clean(),
728             attrs: self.node.attrs.clean().move_iter().collect(),
729             source: self.span.clean(),
730             visibility: vis,
731             id: self.node.id,
732             inner: StructFieldItem(StructField {
733                 type_: self.node.ty.clean(),
734             }),
735         }
736     }
737 }
738
739 pub type Visibility = ast::Visibility;
740
741 impl Clean<Option<Visibility>> for ast::Visibility {
742     fn clean(&self) -> Option<Visibility> {
743         Some(*self)
744     }
745 }
746
747 #[deriving(Clone, Encodable, Decodable)]
748 pub struct Struct {
749     pub struct_type: doctree::StructType,
750     pub generics: Generics,
751     pub fields: Vec<Item>,
752     pub fields_stripped: bool,
753 }
754
755 impl Clean<Item> for doctree::Struct {
756     fn clean(&self) -> Item {
757         Item {
758             name: Some(self.name.clean()),
759             attrs: self.attrs.clean(),
760             source: self.where.clean(),
761             id: self.id,
762             visibility: self.vis.clean(),
763             inner: StructItem(Struct {
764                 struct_type: self.struct_type,
765                 generics: self.generics.clean(),
766                 fields: self.fields.clean(),
767                 fields_stripped: false,
768             }),
769         }
770     }
771 }
772
773 /// This is a more limited form of the standard Struct, different in that
774 /// it lacks the things most items have (name, id, parameterization). Found
775 /// only as a variant in an enum.
776 #[deriving(Clone, Encodable, Decodable)]
777 pub struct VariantStruct {
778     pub struct_type: doctree::StructType,
779     pub fields: Vec<Item>,
780     pub fields_stripped: bool,
781 }
782
783 impl Clean<VariantStruct> for syntax::ast::StructDef {
784     fn clean(&self) -> VariantStruct {
785         VariantStruct {
786             struct_type: doctree::struct_type_from_def(self),
787             fields: self.fields.clean().move_iter().collect(),
788             fields_stripped: false,
789         }
790     }
791 }
792
793 #[deriving(Clone, Encodable, Decodable)]
794 pub struct Enum {
795     pub variants: Vec<Item>,
796     pub generics: Generics,
797     pub variants_stripped: bool,
798 }
799
800 impl Clean<Item> for doctree::Enum {
801     fn clean(&self) -> Item {
802         Item {
803             name: Some(self.name.clean()),
804             attrs: self.attrs.clean(),
805             source: self.where.clean(),
806             id: self.id,
807             visibility: self.vis.clean(),
808             inner: EnumItem(Enum {
809                 variants: self.variants.clean(),
810                 generics: self.generics.clean(),
811                 variants_stripped: false,
812             }),
813         }
814     }
815 }
816
817 #[deriving(Clone, Encodable, Decodable)]
818 pub struct Variant {
819     pub kind: VariantKind,
820 }
821
822 impl Clean<Item> for doctree::Variant {
823     fn clean(&self) -> Item {
824         Item {
825             name: Some(self.name.clean()),
826             attrs: self.attrs.clean(),
827             source: self.where.clean(),
828             visibility: self.vis.clean(),
829             id: self.id,
830             inner: VariantItem(Variant {
831                 kind: self.kind.clean(),
832             }),
833         }
834     }
835 }
836
837 #[deriving(Clone, Encodable, Decodable)]
838 pub enum VariantKind {
839     CLikeVariant,
840     TupleVariant(Vec<Type> ),
841     StructVariant(VariantStruct),
842 }
843
844 impl Clean<VariantKind> for ast::VariantKind {
845     fn clean(&self) -> VariantKind {
846         match self {
847             &ast::TupleVariantKind(ref args) => {
848                 if args.len() == 0 {
849                     CLikeVariant
850                 } else {
851                     TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
852                 }
853             },
854             &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
855         }
856     }
857 }
858
859 #[deriving(Clone, Encodable, Decodable)]
860 pub struct Span {
861     pub filename: ~str,
862     pub loline: uint,
863     pub locol: uint,
864     pub hiline: uint,
865     pub hicol: uint,
866 }
867
868 impl Clean<Span> for syntax::codemap::Span {
869     fn clean(&self) -> Span {
870         let cm = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess().codemap();
871         let filename = cm.span_to_filename(*self);
872         let lo = cm.lookup_char_pos(self.lo);
873         let hi = cm.lookup_char_pos(self.hi);
874         Span {
875             filename: filename.to_owned(),
876             loline: lo.line,
877             locol: lo.col.to_uint(),
878             hiline: hi.line,
879             hicol: hi.col.to_uint(),
880         }
881     }
882 }
883
884 #[deriving(Clone, Encodable, Decodable)]
885 pub struct Path {
886     pub global: bool,
887     pub segments: Vec<PathSegment>,
888 }
889
890 impl Clean<Path> for ast::Path {
891     fn clean(&self) -> Path {
892         Path {
893             global: self.global,
894             segments: self.segments.clean().move_iter().collect(),
895         }
896     }
897 }
898
899 #[deriving(Clone, Encodable, Decodable)]
900 pub struct PathSegment {
901     pub name: ~str,
902     pub lifetimes: Vec<Lifetime>,
903     pub types: Vec<Type>,
904 }
905
906 impl Clean<PathSegment> for ast::PathSegment {
907     fn clean(&self) -> PathSegment {
908         PathSegment {
909             name: self.identifier.clean(),
910             lifetimes: self.lifetimes.clean().move_iter().collect(),
911             types: self.types.clean().move_iter().collect()
912         }
913     }
914 }
915
916 fn path_to_str(p: &ast::Path) -> ~str {
917     use syntax::parse::token;
918
919     let mut s = StrBuf::new();
920     let mut first = true;
921     for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
922         if !first || p.global {
923             s.push_str("::");
924         } else {
925             first = false;
926         }
927         s.push_str(i.get());
928     }
929     s.into_owned()
930 }
931
932 impl Clean<~str> for ast::Ident {
933     fn clean(&self) -> ~str {
934         token::get_ident(*self).get().to_owned()
935     }
936 }
937
938 #[deriving(Clone, Encodable, Decodable)]
939 pub struct Typedef {
940     pub type_: Type,
941     pub generics: Generics,
942 }
943
944 impl Clean<Item> for doctree::Typedef {
945     fn clean(&self) -> Item {
946         Item {
947             name: Some(self.name.clean()),
948             attrs: self.attrs.clean(),
949             source: self.where.clean(),
950             id: self.id.clone(),
951             visibility: self.vis.clean(),
952             inner: TypedefItem(Typedef {
953                 type_: self.ty.clean(),
954                 generics: self.gen.clean(),
955             }),
956         }
957     }
958 }
959
960 #[deriving(Clone, Encodable, Decodable)]
961 pub struct BareFunctionDecl {
962     pub fn_style: ast::FnStyle,
963     pub generics: Generics,
964     pub decl: FnDecl,
965     pub abi: ~str,
966 }
967
968 impl Clean<BareFunctionDecl> for ast::BareFnTy {
969     fn clean(&self) -> BareFunctionDecl {
970         BareFunctionDecl {
971             fn_style: self.fn_style,
972             generics: Generics {
973                 lifetimes: self.lifetimes.clean().move_iter().collect(),
974                 type_params: Vec::new(),
975             },
976             decl: self.decl.clean(),
977             abi: self.abi.to_str(),
978         }
979     }
980 }
981
982 #[deriving(Clone, Encodable, Decodable)]
983 pub struct Static {
984     pub type_: Type,
985     pub mutability: Mutability,
986     /// It's useful to have the value of a static documented, but I have no
987     /// desire to represent expressions (that'd basically be all of the AST,
988     /// which is huge!). So, have a string.
989     pub expr: ~str,
990 }
991
992 impl Clean<Item> for doctree::Static {
993     fn clean(&self) -> Item {
994         debug!("claning static {}: {:?}", self.name.clean(), self);
995         Item {
996             name: Some(self.name.clean()),
997             attrs: self.attrs.clean(),
998             source: self.where.clean(),
999             id: self.id,
1000             visibility: self.vis.clean(),
1001             inner: StaticItem(Static {
1002                 type_: self.type_.clean(),
1003                 mutability: self.mutability.clean(),
1004                 expr: self.expr.span.to_src(),
1005             }),
1006         }
1007     }
1008 }
1009
1010 #[deriving(Show, Clone, Encodable, Decodable)]
1011 pub enum Mutability {
1012     Mutable,
1013     Immutable,
1014 }
1015
1016 impl Clean<Mutability> for ast::Mutability {
1017     fn clean(&self) -> Mutability {
1018         match self {
1019             &ast::MutMutable => Mutable,
1020             &ast::MutImmutable => Immutable,
1021         }
1022     }
1023 }
1024
1025 #[deriving(Clone, Encodable, Decodable)]
1026 pub struct Impl {
1027     pub generics: Generics,
1028     pub trait_: Option<Type>,
1029     pub for_: Type,
1030     pub methods: Vec<Item>,
1031     pub derived: bool,
1032 }
1033
1034 impl Clean<Item> for doctree::Impl {
1035     fn clean(&self) -> Item {
1036         let mut derived = false;
1037         for attr in self.attrs.iter() {
1038             match attr.node.value.node {
1039                 ast::MetaWord(ref s) => {
1040                     if s.get() == "automatically_derived" {
1041                         derived = true;
1042                     }
1043                 }
1044                 _ => {}
1045             }
1046         }
1047         Item {
1048             name: None,
1049             attrs: self.attrs.clean(),
1050             source: self.where.clean(),
1051             id: self.id,
1052             visibility: self.vis.clean(),
1053             inner: ImplItem(Impl {
1054                 generics: self.generics.clean(),
1055                 trait_: self.trait_.clean(),
1056                 for_: self.for_.clean(),
1057                 methods: self.methods.clean(),
1058                 derived: derived,
1059             }),
1060         }
1061     }
1062 }
1063
1064 #[deriving(Clone, Encodable, Decodable)]
1065 pub struct ViewItem {
1066     pub inner: ViewItemInner,
1067 }
1068
1069 impl Clean<Item> for ast::ViewItem {
1070     fn clean(&self) -> Item {
1071         Item {
1072             name: None,
1073             attrs: self.attrs.clean().move_iter().collect(),
1074             source: self.span.clean(),
1075             id: 0,
1076             visibility: self.vis.clean(),
1077             inner: ViewItemItem(ViewItem {
1078                 inner: self.node.clean()
1079             }),
1080         }
1081     }
1082 }
1083
1084 #[deriving(Clone, Encodable, Decodable)]
1085 pub enum ViewItemInner {
1086     ExternCrate(~str, Option<~str>, ast::NodeId),
1087     Import(Vec<ViewPath>)
1088 }
1089
1090 impl Clean<ViewItemInner> for ast::ViewItem_ {
1091     fn clean(&self) -> ViewItemInner {
1092         match self {
1093             &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1094                 let string = match *p {
1095                     None => None,
1096                     Some((ref x, _)) => Some(x.get().to_owned()),
1097                 };
1098                 ExternCrate(i.clean(), string, *id)
1099             }
1100             &ast::ViewItemUse(ref vp) => {
1101                 Import(vp.clean().move_iter().collect())
1102             }
1103         }
1104     }
1105 }
1106
1107 #[deriving(Clone, Encodable, Decodable)]
1108 pub enum ViewPath {
1109     // use str = source;
1110     SimpleImport(~str, ImportSource),
1111     // use source::*;
1112     GlobImport(ImportSource),
1113     // use source::{a, b, c};
1114     ImportList(ImportSource, Vec<ViewListIdent> ),
1115 }
1116
1117 #[deriving(Clone, Encodable, Decodable)]
1118 pub struct ImportSource {
1119     pub path: Path,
1120     pub did: Option<ast::DefId>,
1121 }
1122
1123 impl Clean<ViewPath> for ast::ViewPath {
1124     fn clean(&self) -> ViewPath {
1125         match self.node {
1126             ast::ViewPathSimple(ref i, ref p, id) =>
1127                 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1128             ast::ViewPathGlob(ref p, id) =>
1129                 GlobImport(resolve_use_source(p.clean(), id)),
1130             ast::ViewPathList(ref p, ref pl, id) => {
1131                 ImportList(resolve_use_source(p.clean(), id),
1132                            pl.clean().move_iter().collect())
1133             }
1134         }
1135     }
1136 }
1137
1138 #[deriving(Clone, Encodable, Decodable)]
1139 pub struct ViewListIdent {
1140     pub name: ~str,
1141     pub source: Option<ast::DefId>,
1142 }
1143
1144 impl Clean<ViewListIdent> for ast::PathListIdent {
1145     fn clean(&self) -> ViewListIdent {
1146         ViewListIdent {
1147             name: self.node.name.clean(),
1148             source: resolve_def(self.node.id),
1149         }
1150     }
1151 }
1152
1153 impl Clean<Vec<Item>> for ast::ForeignMod {
1154     fn clean(&self) -> Vec<Item> {
1155         self.items.clean()
1156     }
1157 }
1158
1159 impl Clean<Item> for ast::ForeignItem {
1160     fn clean(&self) -> Item {
1161         let inner = match self.node {
1162             ast::ForeignItemFn(ref decl, ref generics) => {
1163                 ForeignFunctionItem(Function {
1164                     decl: decl.clean(),
1165                     generics: generics.clean(),
1166                     fn_style: ast::ExternFn,
1167                 })
1168             }
1169             ast::ForeignItemStatic(ref ty, mutbl) => {
1170                 ForeignStaticItem(Static {
1171                     type_: ty.clean(),
1172                     mutability: if mutbl {Mutable} else {Immutable},
1173                     expr: ~"",
1174                 })
1175             }
1176         };
1177         Item {
1178             name: Some(self.ident.clean()),
1179             attrs: self.attrs.clean().move_iter().collect(),
1180             source: self.span.clean(),
1181             id: self.id,
1182             visibility: self.vis.clean(),
1183             inner: inner,
1184         }
1185     }
1186 }
1187
1188 // Utilities
1189
1190 trait ToSource {
1191     fn to_src(&self) -> ~str;
1192 }
1193
1194 impl ToSource for syntax::codemap::Span {
1195     fn to_src(&self) -> ~str {
1196         debug!("converting span {:?} to snippet", self.clean());
1197         let cm = local_data::get(super::ctxtkey, |x| x.unwrap().clone()).sess().codemap().clone();
1198         let sn = match cm.span_to_snippet(*self) {
1199             Some(x) => x,
1200             None    => ~""
1201         };
1202         debug!("got snippet {}", sn);
1203         sn
1204     }
1205 }
1206
1207 fn lit_to_str(lit: &ast::Lit) -> ~str {
1208     match lit.node {
1209         ast::LitStr(ref st, _) => st.get().to_owned(),
1210         ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1211         ast::LitChar(c) => ~"'" + std::char::from_u32(c).unwrap().to_str() + "'",
1212         ast::LitInt(i, _t) => i.to_str(),
1213         ast::LitUint(u, _t) => u.to_str(),
1214         ast::LitIntUnsuffixed(i) => i.to_str(),
1215         ast::LitFloat(ref f, _t) => f.get().to_str(),
1216         ast::LitFloatUnsuffixed(ref f) => f.get().to_str(),
1217         ast::LitBool(b) => b.to_str(),
1218         ast::LitNil => ~"",
1219     }
1220 }
1221
1222 fn name_from_pat(p: &ast::Pat) -> ~str {
1223     use syntax::ast::*;
1224     debug!("Trying to get a name from pattern: {:?}", p);
1225
1226     match p.node {
1227         PatWild => ~"_",
1228         PatWildMulti => ~"..",
1229         PatIdent(_, ref p, _) => path_to_str(p),
1230         PatEnum(ref p, _) => path_to_str(p),
1231         PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1232                                 which is not allowed in function arguments"),
1233         PatTup(..) => ~"(tuple arg NYI)",
1234         PatUniq(p) => name_from_pat(p),
1235         PatRegion(p) => name_from_pat(p),
1236         PatLit(..) => {
1237             warn!("tried to get argument name from PatLit, \
1238                   which is silly in function arguments");
1239             ~"()"
1240         },
1241         PatRange(..) => fail!("tried to get argument name from PatRange, \
1242                               which is not allowed in function arguments"),
1243         PatVec(..) => fail!("tried to get argument name from pat_vec, \
1244                              which is not allowed in function arguments")
1245     }
1246 }
1247
1248 /// Given a Type, resolve it using the def_map
1249 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound> >,
1250                 id: ast::NodeId) -> Type {
1251     let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1252     let tycx = match cx.maybe_typed {
1253         core::Typed(ref tycx) => tycx,
1254         // If we're extracting tests, this return value doesn't matter.
1255         core::NotTyped(_) => return Bool
1256     };
1257     debug!("searching for {:?} in defmap", id);
1258     let d = match tycx.def_map.borrow().find(&id) {
1259         Some(&k) => k,
1260         None => {
1261             debug!("could not find {:?} in defmap (`{}`)", id, tycx.map.node_to_str(id));
1262             fail!("Unexpected failure: unresolved id not in defmap (this is a bug!)")
1263         }
1264     };
1265
1266     let (def_id, kind) = match d {
1267         ast::DefFn(i, _) => (i, TypeFunction),
1268         ast::DefSelfTy(i) => return Self(i),
1269         ast::DefTy(i) => (i, TypeEnum),
1270         ast::DefTrait(i) => {
1271             debug!("saw DefTrait in def_to_id");
1272             (i, TypeTrait)
1273         },
1274         ast::DefPrimTy(p) => match p {
1275             ast::TyStr => return String,
1276             ast::TyBool => return Bool,
1277             _ => return Primitive(p)
1278         },
1279         ast::DefTyParam(i, _) => return Generic(i.node),
1280         ast::DefStruct(i) => (i, TypeStruct),
1281         ast::DefTyParamBinder(i) => {
1282             debug!("found a typaram_binder, what is it? {}", i);
1283             return TyParamBinder(i);
1284         },
1285         x => fail!("resolved type maps to a weird def {:?}", x),
1286     };
1287     if ast_util::is_local(def_id) {
1288         ResolvedPath{ path: path, typarams: tpbs, id: def_id.node }
1289     } else {
1290         let fqn = csearch::get_item_path(tycx, def_id);
1291         let fqn = fqn.move_iter().map(|i| i.to_str()).collect();
1292         ExternalPath {
1293             path: path,
1294             typarams: tpbs,
1295             fqn: fqn,
1296             kind: kind,
1297             krate: def_id.krate,
1298         }
1299     }
1300 }
1301
1302 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
1303     ImportSource {
1304         path: path,
1305         did: resolve_def(id),
1306     }
1307 }
1308
1309 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
1310     let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1311     match cx.maybe_typed {
1312         core::Typed(ref tcx) => {
1313             tcx.def_map.borrow().find(&id).map(|&d| ast_util::def_id_of_def(d))
1314         }
1315         core::NotTyped(_) => None
1316     }
1317 }
1318
1319 #[deriving(Clone, Encodable, Decodable)]
1320 pub struct Macro {
1321     pub source: ~str,
1322 }
1323
1324 impl Clean<Item> for doctree::Macro {
1325     fn clean(&self) -> Item {
1326         Item {
1327             name: Some(self.name.clean()),
1328             attrs: self.attrs.clean(),
1329             source: self.where.clean(),
1330             visibility: ast::Public.clean(),
1331             id: self.id,
1332             inner: MacroItem(Macro {
1333                 source: self.where.to_src(),
1334             }),
1335         }
1336     }
1337 }