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.
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.
11 //! This module contains the "cleaned" pieces of the AST, and the functions
18 use syntax::attr::AttributeMethods;
19 use syntax::codemap::Pos;
20 use syntax::parse::token::InternedString;
21 use syntax::parse::token;
23 use rustc::metadata::cstore;
24 use rustc::metadata::csearch;
25 use rustc::metadata::decoder;
28 use std::strbuf::StrBuf;
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()
45 impl<T: Clean<U>, U> Clean<U> for @T {
46 fn clean(&self) -> U {
51 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
52 fn clean(&self) -> Option<U> {
55 &Some(ref v) => Some(v.clean())
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()
66 #[deriving(Clone, Encodable, Decodable)]
69 pub module: Option<Item>,
70 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
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());
78 let mut externs = Vec::new();
79 cx.sess().cstore.iter_crate_data(|n, meta| {
80 externs.push((n, meta.clean()));
84 name: match find_crateid(self.attrs.as_slice()) {
86 None => fail!("rustdoc requires a `crate_id` crate attribute"),
88 module: Some(self.module.clean()),
94 #[deriving(Clone, Encodable, Decodable)]
95 pub struct ExternalCrate {
97 pub attrs: Vec<Attribute>,
100 impl Clean<ExternalCrate> for cstore::crate_metadata {
101 fn clean(&self) -> ExternalCrate {
103 name: self.name.to_owned(),
104 attrs: decoder::get_crate_attributes(self.data()).clean()
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)]
118 /// Not everything has a name. E.g., impls
119 pub name: Option<~str>,
120 pub attrs: Vec<Attribute> ,
122 pub visibility: Option<Visibility>,
127 /// Finds the `doc` attribute as a List and returns the list of attributes
129 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
130 for attr in self.attrs.iter() {
132 List(ref x, ref list) if "doc" == *x => { return Some(list.as_slice()); }
139 /// Finds the `doc` attribute as a NameValue and returns the corresponding
141 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
142 for attr in self.attrs.iter() {
144 NameValue(ref x, ref v) if "doc" == *x => { return Some(v.as_slice()); }
151 pub fn is_mod(&self) -> bool {
152 match self.inner { ModuleItem(..) => true, _ => false }
154 pub fn is_trait(&self) -> bool {
155 match self.inner { TraitItem(..) => true, _ => false }
157 pub fn is_struct(&self) -> bool {
158 match self.inner { StructItem(..) => true, _ => false }
160 pub fn is_enum(&self) -> bool {
161 match self.inner { EnumItem(..) => true, _ => false }
163 pub fn is_fn(&self) -> bool {
164 match self.inner { FunctionItem(..) => true, _ => false }
168 #[deriving(Clone, Encodable, Decodable)]
172 FunctionItem(Function),
174 TypedefItem(Typedef),
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.
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),
194 #[deriving(Clone, Encodable, Decodable)]
196 pub items: Vec<Item>,
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()
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)
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(),
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()
228 attrs: self.attrs.clean(),
229 source: self.where.clean(),
230 visibility: self.vis.clean(),
232 inner: ModuleItem(Module {
233 is_crate: self.is_crate,
235 .flat_map(|x| x.iter().map(|x| (*x).clone()))
242 #[deriving(Clone, Encodable, Decodable)]
245 List(~str, Vec<Attribute> ),
246 NameValue(~str, ~str)
249 impl Clean<Attribute> for ast::MetaItem {
250 fn clean(&self) -> Attribute {
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())
256 ast::MetaNameValue(ref s, ref v) => {
257 NameValue(s.get().to_owned(), lit_to_str(v))
263 impl Clean<Attribute> for ast::Attribute {
264 fn clean(&self) -> Attribute {
265 self.desugar_doc().node.value.clean()
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 {
273 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
274 token::intern_and_get_ident(*n)
279 fn value_str(&self) -> Option<InternedString> {
281 NameValue(_, ref v) => Some(token::intern_and_get_ident(*v)),
285 fn meta_item_list<'a>(&'a self) -> Option<&'a [@ast::MetaItem]> { None }
286 fn name_str_pair(&self) -> Option<(InternedString, InternedString)> {
291 #[deriving(Clone, Encodable, Decodable)]
295 pub bounds: Vec<TyParamBound>,
298 impl Clean<TyParam> for ast::TyParam {
299 fn clean(&self) -> TyParam {
301 name: self.ident.clean(),
303 bounds: self.bounds.clean().move_iter().collect(),
308 #[deriving(Clone, Encodable, Decodable)]
309 pub enum TyParamBound {
314 impl Clean<TyParamBound> for ast::TyParamBound {
315 fn clean(&self) -> TyParamBound {
317 ast::RegionTyParamBound => RegionBound,
318 ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
323 #[deriving(Clone, Encodable, Decodable)]
324 pub struct Lifetime(~str);
327 pub fn get_ref<'a>(&'a self) -> &'a str {
328 let Lifetime(ref s) = *self;
334 impl Clean<Lifetime> for ast::Lifetime {
335 fn clean(&self) -> Lifetime {
336 Lifetime(token::get_name(self.name).get().to_owned())
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>,
347 impl Clean<Generics> for ast::Generics {
348 fn clean(&self) -> Generics {
350 lifetimes: self.lifetimes.clean().move_iter().collect(),
351 type_params: self.ty_params.clean().move_iter().collect(),
356 #[deriving(Clone, Encodable, Decodable)]
358 pub generics: Generics,
360 pub fn_style: ast::FnStyle,
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)
372 values: inputs.iter().map(|x| x.clean()).collect(),
374 output: (self.decl.output.clean()),
375 cf: self.decl.cf.clean(),
379 name: Some(self.ident.clean()),
380 attrs: self.attrs.clean().move_iter().collect(),
381 source: self.span.clean(),
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(),
394 #[deriving(Clone, Encodable, Decodable)]
395 pub struct TyMethod {
396 pub fn_style: ast::FnStyle,
398 pub generics: Generics,
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)
410 values: inputs.iter().map(|x| x.clean()).collect(),
412 output: (self.decl.output.clean()),
413 cf: self.decl.cf.clean(),
417 name: Some(self.ident.clean()),
418 attrs: self.attrs.clean().move_iter().collect(),
419 source: self.span.clean(),
422 inner: TyMethodItem(TyMethod {
423 fn_style: self.fn_style.clone(),
425 self_: self.explicit_self.clean(),
426 generics: self.generics.clean(),
432 #[deriving(Clone, Encodable, Decodable)]
436 SelfBorrowed(Option<Lifetime>, Mutability),
440 impl Clean<SelfTy> for ast::ExplicitSelf {
441 fn clean(&self) -> SelfTy {
443 ast::SelfStatic => SelfStatic,
444 ast::SelfValue => SelfValue,
445 ast::SelfUniq => SelfOwned,
446 ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()),
451 #[deriving(Clone, Encodable, Decodable)]
452 pub struct Function {
454 pub generics: Generics,
455 pub fn_style: ast::FnStyle,
458 impl Clean<Item> for doctree::Function {
459 fn clean(&self) -> Item {
461 name: Some(self.name.clean()),
462 attrs: self.attrs.clean(),
463 source: self.where.clean(),
464 visibility: self.vis.clean(),
466 inner: FunctionItem(Function {
467 decl: self.decl.clean(),
468 generics: self.generics.clean(),
469 fn_style: self.fn_style,
475 #[deriving(Clone, Encodable, Decodable)]
476 pub struct ClosureDecl {
477 pub lifetimes: Vec<Lifetime>,
479 pub onceness: ast::Onceness,
480 pub fn_style: ast::FnStyle,
481 pub bounds: Vec<TyParamBound>,
484 impl Clean<ClosureDecl> for ast::ClosureTy {
485 fn clean(&self) -> 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(),
499 #[deriving(Clone, Encodable, Decodable)]
501 pub inputs: Arguments,
504 pub attrs: Vec<Attribute>,
507 #[deriving(Clone, Encodable, Decodable)]
508 pub struct Arguments {
509 pub values: Vec<Argument>,
512 impl Clean<FnDecl> for ast::FnDecl {
513 fn clean(&self) -> FnDecl {
516 values: self.inputs.iter().map(|x| x.clean()).collect(),
518 output: (self.output.clean()),
525 #[deriving(Clone, Encodable, Decodable)]
526 pub struct Argument {
532 impl Clean<Argument> for ast::Arg {
533 fn clean(&self) -> Argument {
535 name: name_from_pat(self.pat),
536 type_: (self.ty.clean()),
542 #[deriving(Clone, Encodable, Decodable)]
548 impl Clean<RetStyle> for ast::RetStyle {
549 fn clean(&self) -> RetStyle {
551 ast::Return => Return,
552 ast::NoReturn => NoReturn
557 #[deriving(Clone, Encodable, Decodable)]
559 pub methods: Vec<TraitMethod>,
560 pub generics: Generics,
561 pub parents: Vec<Type>,
564 impl Clean<Item> for doctree::Trait {
565 fn clean(&self) -> Item {
567 name: Some(self.name.clean()),
568 attrs: self.attrs.clean(),
569 source: self.where.clean(),
571 visibility: self.vis.clean(),
572 inner: TraitItem(Trait {
573 methods: self.methods.clean(),
574 generics: self.generics.clean(),
575 parents: self.parents.clean(),
581 impl Clean<Type> for ast::TraitRef {
582 fn clean(&self) -> Type {
583 resolve_type(self.path.clean(), None, self.ref_id)
587 #[deriving(Clone, Encodable, Decodable)]
588 pub enum TraitMethod {
594 pub fn is_req(&self) -> bool {
596 &Required(..) => true,
600 pub fn is_def(&self) -> bool {
602 &Provided(..) => true,
606 pub fn item<'a>(&'a self) -> &'a Item {
608 Required(ref item) => item,
609 Provided(ref item) => item,
614 impl Clean<TraitMethod> for ast::TraitMethod {
615 fn clean(&self) -> TraitMethod {
617 &ast::Required(ref t) => Required(t.clean()),
618 &ast::Provided(ref t) => Provided(t.clean()),
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)]
628 /// structs/enums/traits (anything that'd be an ast::TyPath)
631 pub typarams: Option<Vec<TyParamBound>>,
634 /// Same as above, but only external variants
637 pub typarams: Option<Vec<TyParamBound>>,
640 pub krate: ast::CrateNum,
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
649 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
650 Primitive(ast::PrimTy),
651 Closure(~ClosureDecl, Option<Lifetime>),
654 BareFunction(~BareFunctionDecl),
657 FixedVector(~Type, ~str),
666 RawPointer(Mutability, ~Type),
668 pub lifetime: Option<Lifetime>,
669 pub mutability: Mutability,
672 // region, raw, other boxes, mutable
675 #[deriving(Clone, Encodable, Decodable)]
683 impl Clean<Type> for ast::Ty {
684 fn clean(&self) -> Type {
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));
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(),
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()),
706 TyClosure(ref c, region) => Closure(~c.clean(), region.clean()),
707 TyProc(ref c) => Proc(~c.clean()),
708 TyBareFn(ref barefn) => BareFunction(~barefn.clean()),
710 ref x => fail!("Unimplemented type {:?}", x),
715 #[deriving(Clone, Encodable, Decodable)]
716 pub enum StructField {
718 TypedStructField(Type),
721 impl Clean<Item> for ast::StructField {
722 fn clean(&self) -> Item {
723 let (name, vis) = match self.node.kind {
724 ast::NamedField(id, vis) => (Some(id), vis),
725 ast::UnnamedField(vis) => (None, vis)
729 attrs: self.node.attrs.clean().move_iter().collect(),
730 source: self.span.clean(),
731 visibility: Some(vis),
733 inner: StructFieldItem(TypedStructField(self.node.ty.clean())),
738 pub type Visibility = ast::Visibility;
740 impl Clean<Option<Visibility>> for ast::Visibility {
741 fn clean(&self) -> Option<Visibility> {
746 #[deriving(Clone, Encodable, Decodable)]
748 pub struct_type: doctree::StructType,
749 pub generics: Generics,
750 pub fields: Vec<Item>,
751 pub fields_stripped: bool,
754 impl Clean<Item> for doctree::Struct {
755 fn clean(&self) -> Item {
757 name: Some(self.name.clean()),
758 attrs: self.attrs.clean(),
759 source: self.where.clean(),
761 visibility: self.vis.clean(),
762 inner: StructItem(Struct {
763 struct_type: self.struct_type,
764 generics: self.generics.clean(),
765 fields: self.fields.clean(),
766 fields_stripped: false,
772 /// This is a more limited form of the standard Struct, different in that
773 /// it lacks the things most items have (name, id, parameterization). Found
774 /// only as a variant in an enum.
775 #[deriving(Clone, Encodable, Decodable)]
776 pub struct VariantStruct {
777 pub struct_type: doctree::StructType,
778 pub fields: Vec<Item>,
779 pub fields_stripped: bool,
782 impl Clean<VariantStruct> for syntax::ast::StructDef {
783 fn clean(&self) -> VariantStruct {
785 struct_type: doctree::struct_type_from_def(self),
786 fields: self.fields.clean().move_iter().collect(),
787 fields_stripped: false,
792 #[deriving(Clone, Encodable, Decodable)]
794 pub variants: Vec<Item>,
795 pub generics: Generics,
796 pub variants_stripped: bool,
799 impl Clean<Item> for doctree::Enum {
800 fn clean(&self) -> Item {
802 name: Some(self.name.clean()),
803 attrs: self.attrs.clean(),
804 source: self.where.clean(),
806 visibility: self.vis.clean(),
807 inner: EnumItem(Enum {
808 variants: self.variants.clean(),
809 generics: self.generics.clean(),
810 variants_stripped: false,
816 #[deriving(Clone, Encodable, Decodable)]
818 pub kind: VariantKind,
821 impl Clean<Item> for doctree::Variant {
822 fn clean(&self) -> Item {
824 name: Some(self.name.clean()),
825 attrs: self.attrs.clean(),
826 source: self.where.clean(),
827 visibility: self.vis.clean(),
829 inner: VariantItem(Variant {
830 kind: self.kind.clean(),
836 #[deriving(Clone, Encodable, Decodable)]
837 pub enum VariantKind {
839 TupleVariant(Vec<Type>),
840 StructVariant(VariantStruct),
843 impl Clean<VariantKind> for ast::VariantKind {
844 fn clean(&self) -> VariantKind {
846 &ast::TupleVariantKind(ref args) => {
850 TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
853 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
858 #[deriving(Clone, Encodable, Decodable)]
867 impl Clean<Span> for syntax::codemap::Span {
868 fn clean(&self) -> Span {
869 let cm = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess().codemap();
870 let filename = cm.span_to_filename(*self);
871 let lo = cm.lookup_char_pos(self.lo);
872 let hi = cm.lookup_char_pos(self.hi);
874 filename: filename.to_owned(),
876 locol: lo.col.to_uint(),
878 hicol: hi.col.to_uint(),
883 #[deriving(Clone, Encodable, Decodable)]
886 pub segments: Vec<PathSegment>,
889 impl Clean<Path> for ast::Path {
890 fn clean(&self) -> Path {
893 segments: self.segments.clean().move_iter().collect(),
898 #[deriving(Clone, Encodable, Decodable)]
899 pub struct PathSegment {
901 pub lifetimes: Vec<Lifetime>,
902 pub types: Vec<Type>,
905 impl Clean<PathSegment> for ast::PathSegment {
906 fn clean(&self) -> PathSegment {
908 name: self.identifier.clean(),
909 lifetimes: self.lifetimes.clean().move_iter().collect(),
910 types: self.types.clean().move_iter().collect()
915 fn path_to_str(p: &ast::Path) -> ~str {
916 use syntax::parse::token;
918 let mut s = StrBuf::new();
919 let mut first = true;
920 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
921 if !first || p.global {
931 impl Clean<~str> for ast::Ident {
932 fn clean(&self) -> ~str {
933 token::get_ident(*self).get().to_owned()
937 #[deriving(Clone, Encodable, Decodable)]
940 pub generics: Generics,
943 impl Clean<Item> for doctree::Typedef {
944 fn clean(&self) -> Item {
946 name: Some(self.name.clean()),
947 attrs: self.attrs.clean(),
948 source: self.where.clean(),
950 visibility: self.vis.clean(),
951 inner: TypedefItem(Typedef {
952 type_: self.ty.clean(),
953 generics: self.gen.clean(),
959 #[deriving(Clone, Encodable, Decodable)]
960 pub struct BareFunctionDecl {
961 pub fn_style: ast::FnStyle,
962 pub generics: Generics,
967 impl Clean<BareFunctionDecl> for ast::BareFnTy {
968 fn clean(&self) -> BareFunctionDecl {
970 fn_style: self.fn_style,
972 lifetimes: self.lifetimes.clean().move_iter().collect(),
973 type_params: Vec::new(),
975 decl: self.decl.clean(),
976 abi: self.abi.to_str(),
981 #[deriving(Clone, Encodable, Decodable)]
984 pub mutability: Mutability,
985 /// It's useful to have the value of a static documented, but I have no
986 /// desire to represent expressions (that'd basically be all of the AST,
987 /// which is huge!). So, have a string.
991 impl Clean<Item> for doctree::Static {
992 fn clean(&self) -> Item {
993 debug!("claning static {}: {:?}", self.name.clean(), self);
995 name: Some(self.name.clean()),
996 attrs: self.attrs.clean(),
997 source: self.where.clean(),
999 visibility: self.vis.clean(),
1000 inner: StaticItem(Static {
1001 type_: self.type_.clean(),
1002 mutability: self.mutability.clean(),
1003 expr: self.expr.span.to_src(),
1009 #[deriving(Show, Clone, Encodable, Decodable)]
1010 pub enum Mutability {
1015 impl Clean<Mutability> for ast::Mutability {
1016 fn clean(&self) -> Mutability {
1018 &ast::MutMutable => Mutable,
1019 &ast::MutImmutable => Immutable,
1024 #[deriving(Clone, Encodable, Decodable)]
1026 pub generics: Generics,
1027 pub trait_: Option<Type>,
1029 pub methods: Vec<Item>,
1033 impl Clean<Item> for doctree::Impl {
1034 fn clean(&self) -> Item {
1035 let mut derived = false;
1036 for attr in self.attrs.iter() {
1037 match attr.node.value.node {
1038 ast::MetaWord(ref s) => {
1039 if s.get() == "automatically_derived" {
1048 attrs: self.attrs.clean(),
1049 source: self.where.clean(),
1051 visibility: self.vis.clean(),
1052 inner: ImplItem(Impl {
1053 generics: self.generics.clean(),
1054 trait_: self.trait_.clean(),
1055 for_: self.for_.clean(),
1056 methods: self.methods.clean(),
1063 #[deriving(Clone, Encodable, Decodable)]
1064 pub struct ViewItem {
1065 pub inner: ViewItemInner,
1068 impl Clean<Item> for ast::ViewItem {
1069 fn clean(&self) -> Item {
1072 attrs: self.attrs.clean().move_iter().collect(),
1073 source: self.span.clean(),
1075 visibility: self.vis.clean(),
1076 inner: ViewItemItem(ViewItem {
1077 inner: self.node.clean()
1083 #[deriving(Clone, Encodable, Decodable)]
1084 pub enum ViewItemInner {
1085 ExternCrate(~str, Option<~str>, ast::NodeId),
1086 Import(Vec<ViewPath>)
1089 impl Clean<ViewItemInner> for ast::ViewItem_ {
1090 fn clean(&self) -> ViewItemInner {
1092 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1093 let string = match *p {
1095 Some((ref x, _)) => Some(x.get().to_owned()),
1097 ExternCrate(i.clean(), string, *id)
1099 &ast::ViewItemUse(ref vp) => {
1100 Import(vp.clean().move_iter().collect())
1106 #[deriving(Clone, Encodable, Decodable)]
1108 // use str = source;
1109 SimpleImport(~str, ImportSource),
1111 GlobImport(ImportSource),
1112 // use source::{a, b, c};
1113 ImportList(ImportSource, Vec<ViewListIdent> ),
1116 #[deriving(Clone, Encodable, Decodable)]
1117 pub struct ImportSource {
1119 pub did: Option<ast::DefId>,
1122 impl Clean<ViewPath> for ast::ViewPath {
1123 fn clean(&self) -> ViewPath {
1125 ast::ViewPathSimple(ref i, ref p, id) =>
1126 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1127 ast::ViewPathGlob(ref p, id) =>
1128 GlobImport(resolve_use_source(p.clean(), id)),
1129 ast::ViewPathList(ref p, ref pl, id) => {
1130 ImportList(resolve_use_source(p.clean(), id),
1131 pl.clean().move_iter().collect())
1137 #[deriving(Clone, Encodable, Decodable)]
1138 pub struct ViewListIdent {
1140 pub source: Option<ast::DefId>,
1143 impl Clean<ViewListIdent> for ast::PathListIdent {
1144 fn clean(&self) -> ViewListIdent {
1146 name: self.node.name.clean(),
1147 source: resolve_def(self.node.id),
1152 impl Clean<Vec<Item>> for ast::ForeignMod {
1153 fn clean(&self) -> Vec<Item> {
1158 impl Clean<Item> for ast::ForeignItem {
1159 fn clean(&self) -> Item {
1160 let inner = match self.node {
1161 ast::ForeignItemFn(ref decl, ref generics) => {
1162 ForeignFunctionItem(Function {
1164 generics: generics.clean(),
1165 fn_style: ast::ExternFn,
1168 ast::ForeignItemStatic(ref ty, mutbl) => {
1169 ForeignStaticItem(Static {
1171 mutability: if mutbl {Mutable} else {Immutable},
1172 expr: "".to_owned(),
1177 name: Some(self.ident.clean()),
1178 attrs: self.attrs.clean().move_iter().collect(),
1179 source: self.span.clean(),
1181 visibility: self.vis.clean(),
1190 fn to_src(&self) -> ~str;
1193 impl ToSource for syntax::codemap::Span {
1194 fn to_src(&self) -> ~str {
1195 debug!("converting span {:?} to snippet", self.clean());
1196 let cm = local_data::get(super::ctxtkey, |x| x.unwrap().clone()).sess().codemap().clone();
1197 let sn = match cm.span_to_snippet(*self) {
1199 None => "".to_owned()
1201 debug!("got snippet {}", sn);
1206 fn lit_to_str(lit: &ast::Lit) -> ~str {
1208 ast::LitStr(ref st, _) => st.get().to_owned(),
1209 ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1210 ast::LitChar(c) => "'".to_owned() + std::char::from_u32(c).unwrap().to_str() + "'",
1211 ast::LitInt(i, _t) => i.to_str(),
1212 ast::LitUint(u, _t) => u.to_str(),
1213 ast::LitIntUnsuffixed(i) => i.to_str(),
1214 ast::LitFloat(ref f, _t) => f.get().to_str(),
1215 ast::LitFloatUnsuffixed(ref f) => f.get().to_str(),
1216 ast::LitBool(b) => b.to_str(),
1217 ast::LitNil => "".to_owned(),
1221 fn name_from_pat(p: &ast::Pat) -> ~str {
1223 debug!("Trying to get a name from pattern: {:?}", p);
1226 PatWild => "_".to_owned(),
1227 PatWildMulti => "..".to_owned(),
1228 PatIdent(_, ref p, _) => path_to_str(p),
1229 PatEnum(ref p, _) => path_to_str(p),
1230 PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1231 which is not allowed in function arguments"),
1232 PatTup(..) => "(tuple arg NYI)".to_owned(),
1233 PatUniq(p) => name_from_pat(p),
1234 PatRegion(p) => name_from_pat(p),
1236 warn!("tried to get argument name from PatLit, \
1237 which is silly in function arguments");
1240 PatRange(..) => fail!("tried to get argument name from PatRange, \
1241 which is not allowed in function arguments"),
1242 PatVec(..) => fail!("tried to get argument name from pat_vec, \
1243 which is not allowed in function arguments")
1247 /// Given a Type, resolve it using the def_map
1248 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound> >,
1249 id: ast::NodeId) -> Type {
1250 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1251 let tycx = match cx.maybe_typed {
1252 core::Typed(ref tycx) => tycx,
1253 // If we're extracting tests, this return value doesn't matter.
1254 core::NotTyped(_) => return Bool
1256 debug!("searching for {:?} in defmap", id);
1257 let d = match tycx.def_map.borrow().find(&id) {
1260 debug!("could not find {:?} in defmap (`{}`)", id, tycx.map.node_to_str(id));
1261 fail!("Unexpected failure: unresolved id not in defmap (this is a bug!)")
1265 let (def_id, kind) = match d {
1266 ast::DefFn(i, _) => (i, TypeFunction),
1267 ast::DefSelfTy(i) => return Self(i),
1268 ast::DefTy(i) => (i, TypeEnum),
1269 ast::DefTrait(i) => {
1270 debug!("saw DefTrait in def_to_id");
1273 ast::DefPrimTy(p) => match p {
1274 ast::TyStr => return String,
1275 ast::TyBool => return Bool,
1276 _ => return Primitive(p)
1278 ast::DefTyParam(i, _) => return Generic(i.node),
1279 ast::DefStruct(i) => (i, TypeStruct),
1280 ast::DefTyParamBinder(i) => {
1281 debug!("found a typaram_binder, what is it? {}", i);
1282 return TyParamBinder(i);
1284 x => fail!("resolved type maps to a weird def {:?}", x),
1286 if ast_util::is_local(def_id) {
1287 ResolvedPath{ path: path, typarams: tpbs, id: def_id.node }
1289 let fqn = csearch::get_item_path(tycx, def_id);
1290 let fqn = fqn.move_iter().map(|i| i.to_str()).collect();
1296 krate: def_id.krate,
1301 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
1304 did: resolve_def(id),
1308 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
1309 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1310 match cx.maybe_typed {
1311 core::Typed(ref tcx) => {
1312 tcx.def_map.borrow().find(&id).map(|&d| ast_util::def_id_of_def(d))
1314 core::NotTyped(_) => None
1318 #[deriving(Clone, Encodable, Decodable)]
1323 impl Clean<Item> for doctree::Macro {
1324 fn clean(&self) -> Item {
1326 name: Some(self.name.clean()),
1327 attrs: self.attrs.clean(),
1328 source: self.where.clean(),
1329 visibility: ast::Public.clean(),
1331 inner: MacroItem(Macro {
1332 source: self.where.to_src(),