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;
38 impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
39 fn clean(&self) -> Vec<U> {
40 self.iter().map(|x| x.clean()).collect()
44 impl<T: Clean<U>, U> Clean<U> for @T {
45 fn clean(&self) -> U {
50 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
51 fn clean(&self) -> Option<U> {
54 &Some(ref v) => Some(v.clean())
59 impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
60 fn clean(&self) -> Vec<U> {
61 self.iter().map(|x| x.clean()).collect()
65 #[deriving(Clone, Encodable, Decodable)]
68 pub module: Option<Item>,
69 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
72 impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> {
73 fn clean(&self) -> Crate {
74 use syntax::attr::find_crateid;
75 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
77 let mut externs = Vec::new();
78 cx.sess().cstore.iter_crate_data(|n, meta| {
79 externs.push((n, meta.clean()));
83 name: match find_crateid(self.attrs.as_slice()) {
85 None => fail!("rustdoc requires a `crate_id` crate attribute"),
87 module: Some(self.module.clean()),
93 #[deriving(Clone, Encodable, Decodable)]
94 pub struct ExternalCrate {
96 pub attrs: Vec<Attribute>,
99 impl Clean<ExternalCrate> for cstore::crate_metadata {
100 fn clean(&self) -> ExternalCrate {
102 name: self.name.to_owned(),
103 attrs: decoder::get_crate_attributes(self.data()).clean()
110 /// Anything with a source location and set of attributes and, optionally, a
111 /// name. That is, anything that can be documented. This doesn't correspond
112 /// directly to the AST's concept of an item; it's a strict superset.
113 #[deriving(Clone, Encodable, Decodable)]
117 /// Not everything has a name. E.g., impls
118 pub name: Option<~str>,
119 pub attrs: Vec<Attribute> ,
121 pub visibility: Option<Visibility>,
126 /// Finds the `doc` attribute as a List and returns the list of attributes
128 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
129 for attr in self.attrs.iter() {
131 List(ref x, ref list) if "doc" == *x => { return Some(list.as_slice()); }
138 /// Finds the `doc` attribute as a NameValue and returns the corresponding
140 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
141 for attr in self.attrs.iter() {
143 NameValue(ref x, ref v) if "doc" == *x => { return Some(v.as_slice()); }
150 pub fn is_mod(&self) -> bool {
151 match self.inner { ModuleItem(..) => true, _ => false }
153 pub fn is_trait(&self) -> bool {
154 match self.inner { TraitItem(..) => true, _ => false }
156 pub fn is_struct(&self) -> bool {
157 match self.inner { StructItem(..) => true, _ => false }
159 pub fn is_enum(&self) -> bool {
160 match self.inner { EnumItem(..) => true, _ => false }
162 pub fn is_fn(&self) -> bool {
163 match self.inner { FunctionItem(..) => true, _ => false }
167 #[deriving(Clone, Encodable, Decodable)]
171 FunctionItem(Function),
173 TypedefItem(Typedef),
177 /// `use` and `extern crate`
178 ViewItemItem(ViewItem),
179 /// A method signature only. Used for required methods in traits (ie,
180 /// non-default-methods).
181 TyMethodItem(TyMethod),
182 /// A method with a body.
184 StructFieldItem(StructField),
185 VariantItem(Variant),
186 /// `fn`s from an extern block
187 ForeignFunctionItem(Function),
188 /// `static`s from an extern block
189 ForeignStaticItem(Static),
193 #[deriving(Clone, Encodable, Decodable)]
195 pub items: Vec<Item>,
199 impl Clean<Item> for doctree::Module {
200 fn clean(&self) -> Item {
201 let name = if self.name.is_some() {
202 self.name.unwrap().clean()
206 let mut foreigns = Vec::new();
207 for subforeigns in self.foreigns.clean().move_iter() {
208 for foreign in subforeigns.move_iter() {
209 foreigns.push(foreign)
212 let items: Vec<Vec<Item> > = vec!(
213 self.structs.clean().move_iter().collect(),
214 self.enums.clean().move_iter().collect(),
215 self.fns.clean().move_iter().collect(),
217 self.mods.clean().move_iter().collect(),
218 self.typedefs.clean().move_iter().collect(),
219 self.statics.clean().move_iter().collect(),
220 self.traits.clean().move_iter().collect(),
221 self.impls.clean().move_iter().collect(),
222 self.view_items.clean().move_iter().collect(),
223 self.macros.clean().move_iter().collect()
227 attrs: self.attrs.clean(),
228 source: self.where.clean(),
229 visibility: self.vis.clean(),
231 inner: ModuleItem(Module {
232 is_crate: self.is_crate,
234 .flat_map(|x| x.iter().map(|x| (*x).clone()))
241 #[deriving(Clone, Encodable, Decodable)]
244 List(~str, Vec<Attribute> ),
245 NameValue(~str, ~str)
248 impl Clean<Attribute> for ast::MetaItem {
249 fn clean(&self) -> Attribute {
251 ast::MetaWord(ref s) => Word(s.get().to_owned()),
252 ast::MetaList(ref s, ref l) => {
253 List(s.get().to_owned(), l.clean().move_iter().collect())
255 ast::MetaNameValue(ref s, ref v) => {
256 NameValue(s.get().to_owned(), lit_to_str(v))
262 impl Clean<Attribute> for ast::Attribute {
263 fn clean(&self) -> Attribute {
264 self.desugar_doc().node.value.clean()
268 // This is a rough approximation that gets us what we want.
269 impl<'a> attr::AttrMetaMethods for &'a Attribute {
270 fn name(&self) -> InternedString {
272 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
273 token::intern_and_get_ident(*n)
278 fn value_str(&self) -> Option<InternedString> {
280 NameValue(_, ref v) => Some(token::intern_and_get_ident(*v)),
284 fn meta_item_list<'a>(&'a self) -> Option<&'a [@ast::MetaItem]> { None }
285 fn name_str_pair(&self) -> Option<(InternedString, InternedString)> {
290 #[deriving(Clone, Encodable, Decodable)]
294 pub bounds: Vec<TyParamBound>,
297 impl Clean<TyParam> for ast::TyParam {
298 fn clean(&self) -> TyParam {
300 name: self.ident.clean(),
302 bounds: self.bounds.clean().move_iter().collect(),
307 #[deriving(Clone, Encodable, Decodable)]
308 pub enum TyParamBound {
313 impl Clean<TyParamBound> for ast::TyParamBound {
314 fn clean(&self) -> TyParamBound {
316 ast::RegionTyParamBound => RegionBound,
317 ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
322 #[deriving(Clone, Encodable, Decodable)]
323 pub struct Lifetime(~str);
326 pub fn get_ref<'a>(&'a self) -> &'a str {
327 let Lifetime(ref s) = *self;
333 impl Clean<Lifetime> for ast::Lifetime {
334 fn clean(&self) -> Lifetime {
335 Lifetime(token::get_name(self.name).get().to_owned())
339 // maybe use a Generic enum and use ~[Generic]?
340 #[deriving(Clone, Encodable, Decodable)]
341 pub struct Generics {
342 pub lifetimes: Vec<Lifetime>,
343 pub type_params: Vec<TyParam>,
346 impl Clean<Generics> for ast::Generics {
347 fn clean(&self) -> Generics {
349 lifetimes: self.lifetimes.clean().move_iter().collect(),
350 type_params: self.ty_params.clean().move_iter().collect(),
355 #[deriving(Clone, Encodable, Decodable)]
357 pub generics: Generics,
359 pub fn_style: ast::FnStyle,
363 impl Clean<Item> for ast::Method {
364 fn clean(&self) -> Item {
365 let inputs = match self.explicit_self.node {
366 ast::SelfStatic => self.decl.inputs.as_slice(),
367 _ => self.decl.inputs.slice_from(1)
371 values: inputs.iter().map(|x| x.clean()).collect(),
373 output: (self.decl.output.clean()),
374 cf: self.decl.cf.clean(),
378 name: Some(self.ident.clean()),
379 attrs: self.attrs.clean().move_iter().collect(),
380 source: self.span.clean(),
382 visibility: self.vis.clean(),
383 inner: MethodItem(Method {
384 generics: self.generics.clean(),
385 self_: self.explicit_self.clean(),
386 fn_style: self.fn_style.clone(),
393 #[deriving(Clone, Encodable, Decodable)]
394 pub struct TyMethod {
395 pub fn_style: ast::FnStyle,
397 pub generics: Generics,
401 impl Clean<Item> for ast::TypeMethod {
402 fn clean(&self) -> Item {
403 let inputs = match self.explicit_self.node {
404 ast::SelfStatic => self.decl.inputs.as_slice(),
405 _ => self.decl.inputs.slice_from(1)
409 values: inputs.iter().map(|x| x.clean()).collect(),
411 output: (self.decl.output.clean()),
412 cf: self.decl.cf.clean(),
416 name: Some(self.ident.clean()),
417 attrs: self.attrs.clean().move_iter().collect(),
418 source: self.span.clean(),
421 inner: TyMethodItem(TyMethod {
422 fn_style: self.fn_style.clone(),
424 self_: self.explicit_self.clean(),
425 generics: self.generics.clean(),
431 #[deriving(Clone, Encodable, Decodable)]
435 SelfBorrowed(Option<Lifetime>, Mutability),
439 impl Clean<SelfTy> for ast::ExplicitSelf {
440 fn clean(&self) -> SelfTy {
442 ast::SelfStatic => SelfStatic,
443 ast::SelfValue => SelfValue,
444 ast::SelfUniq => SelfOwned,
445 ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()),
450 #[deriving(Clone, Encodable, Decodable)]
451 pub struct Function {
453 pub generics: Generics,
454 pub fn_style: ast::FnStyle,
457 impl Clean<Item> for doctree::Function {
458 fn clean(&self) -> Item {
460 name: Some(self.name.clean()),
461 attrs: self.attrs.clean(),
462 source: self.where.clean(),
463 visibility: self.vis.clean(),
465 inner: FunctionItem(Function {
466 decl: self.decl.clean(),
467 generics: self.generics.clean(),
468 fn_style: self.fn_style,
474 #[deriving(Clone, Encodable, Decodable)]
475 pub struct ClosureDecl {
476 pub sigil: ast::Sigil,
477 pub region: Option<Lifetime>,
478 pub lifetimes: Vec<Lifetime>,
480 pub onceness: ast::Onceness,
481 pub fn_style: ast::FnStyle,
482 pub bounds: Vec<TyParamBound>,
485 impl Clean<ClosureDecl> for ast::ClosureTy {
486 fn clean(&self) -> ClosureDecl {
489 region: self.region.clean(),
490 lifetimes: self.lifetimes.clean().move_iter().collect(),
491 decl: self.decl.clean(),
492 onceness: self.onceness,
493 fn_style: self.fn_style,
494 bounds: match self.bounds {
495 Some(ref x) => x.clean().move_iter().collect(),
502 #[deriving(Clone, Encodable, Decodable)]
504 pub inputs: Arguments,
507 pub attrs: Vec<Attribute>,
510 #[deriving(Clone, Encodable, Decodable)]
511 pub struct Arguments {
512 pub values: Vec<Argument>,
515 impl Clean<FnDecl> for ast::FnDecl {
516 fn clean(&self) -> FnDecl {
519 values: self.inputs.iter().map(|x| x.clean()).collect(),
521 output: (self.output.clean()),
528 #[deriving(Clone, Encodable, Decodable)]
529 pub struct Argument {
535 impl Clean<Argument> for ast::Arg {
536 fn clean(&self) -> Argument {
538 name: name_from_pat(self.pat),
539 type_: (self.ty.clean()),
545 #[deriving(Clone, Encodable, Decodable)]
551 impl Clean<RetStyle> for ast::RetStyle {
552 fn clean(&self) -> RetStyle {
554 ast::Return => Return,
555 ast::NoReturn => NoReturn
560 #[deriving(Clone, Encodable, Decodable)]
562 pub methods: Vec<TraitMethod>,
563 pub generics: Generics,
564 pub parents: Vec<Type>,
567 impl Clean<Item> for doctree::Trait {
568 fn clean(&self) -> Item {
570 name: Some(self.name.clean()),
571 attrs: self.attrs.clean(),
572 source: self.where.clean(),
574 visibility: self.vis.clean(),
575 inner: TraitItem(Trait {
576 methods: self.methods.clean(),
577 generics: self.generics.clean(),
578 parents: self.parents.clean(),
584 impl Clean<Type> for ast::TraitRef {
585 fn clean(&self) -> Type {
586 resolve_type(self.path.clean(), None, self.ref_id)
590 #[deriving(Clone, Encodable, Decodable)]
591 pub enum TraitMethod {
597 pub fn is_req(&self) -> bool {
599 &Required(..) => true,
603 pub fn is_def(&self) -> bool {
605 &Provided(..) => true,
609 pub fn item<'a>(&'a self) -> &'a Item {
611 Required(ref item) => item,
612 Provided(ref item) => item,
617 impl Clean<TraitMethod> for ast::TraitMethod {
618 fn clean(&self) -> TraitMethod {
620 &ast::Required(ref t) => Required(t.clean()),
621 &ast::Provided(ref t) => Provided(t.clean()),
626 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
627 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
628 /// it does not preserve mutability or boxes.
629 #[deriving(Clone, Encodable, Decodable)]
631 /// structs/enums/traits (anything that'd be an ast::TyPath)
634 pub typarams: Option<Vec<TyParamBound>>,
637 /// Same as above, but only external variants
640 pub typarams: Option<Vec<TyParamBound>>,
643 pub krate: ast::CrateNum,
645 // I have no idea how to usefully use this.
646 TyParamBinder(ast::NodeId),
647 /// For parameterized types, so the consumer of the JSON don't go looking
648 /// for types which don't exist anywhere.
649 Generic(ast::NodeId),
650 /// For references to self
652 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
653 Primitive(ast::PrimTy),
654 Closure(~ClosureDecl),
656 BareFunction(~BareFunctionDecl),
659 FixedVector(~Type, ~str),
668 RawPointer(Mutability, ~Type),
670 pub lifetime: Option<Lifetime>,
671 pub mutability: Mutability,
674 // region, raw, other boxes, mutable
677 #[deriving(Clone, Encodable, Decodable)]
685 impl Clean<Type> for ast::Ty {
686 fn clean(&self) -> Type {
688 debug!("cleaning type `{:?}`", self);
689 let codemap = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess().codemap();
690 debug!("span corresponds to `{}`", codemap.span_to_str(self.span));
693 TyPtr(ref m) => RawPointer(m.mutbl.clean(), ~m.ty.clean()),
694 TyRptr(ref l, ref m) =>
695 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
696 type_: ~m.ty.clean()},
697 TyBox(ty) => Managed(~ty.clean()),
698 TyUniq(ty) => Unique(~ty.clean()),
699 TyVec(ty) => Vector(~ty.clean()),
700 TyFixedLengthVec(ty, ref e) => FixedVector(~ty.clean(),
702 TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
703 TyPath(ref p, ref tpbs, id) => {
704 resolve_type(p.clean(),
705 tpbs.clean().map(|x| x.move_iter().collect()),
708 TyClosure(ref c) => Closure(~c.clean()),
709 TyBareFn(ref barefn) => BareFunction(~barefn.clean()),
711 ref x => fail!("Unimplemented type {:?}", x),
716 #[deriving(Clone, Encodable, Decodable)]
717 pub struct StructField {
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), Some(vis)),
729 attrs: self.node.attrs.clean().move_iter().collect(),
730 source: self.span.clean(),
733 inner: StructFieldItem(StructField {
734 type_: self.node.ty.clean(),
740 pub type Visibility = ast::Visibility;
742 impl Clean<Option<Visibility>> for ast::Visibility {
743 fn clean(&self) -> Option<Visibility> {
748 #[deriving(Clone, Encodable, Decodable)]
750 pub struct_type: doctree::StructType,
751 pub generics: Generics,
752 pub fields: Vec<Item>,
753 pub fields_stripped: bool,
756 impl Clean<Item> for doctree::Struct {
757 fn clean(&self) -> Item {
759 name: Some(self.name.clean()),
760 attrs: self.attrs.clean(),
761 source: self.where.clean(),
763 visibility: self.vis.clean(),
764 inner: StructItem(Struct {
765 struct_type: self.struct_type,
766 generics: self.generics.clean(),
767 fields: self.fields.clean(),
768 fields_stripped: false,
774 /// This is a more limited form of the standard Struct, different in that
775 /// it lacks the things most items have (name, id, parameterization). Found
776 /// only as a variant in an enum.
777 #[deriving(Clone, Encodable, Decodable)]
778 pub struct VariantStruct {
779 pub struct_type: doctree::StructType,
780 pub fields: Vec<Item>,
781 pub fields_stripped: bool,
784 impl Clean<VariantStruct> for syntax::ast::StructDef {
785 fn clean(&self) -> VariantStruct {
787 struct_type: doctree::struct_type_from_def(self),
788 fields: self.fields.clean().move_iter().collect(),
789 fields_stripped: false,
794 #[deriving(Clone, Encodable, Decodable)]
796 pub variants: Vec<Item>,
797 pub generics: Generics,
798 pub variants_stripped: bool,
801 impl Clean<Item> for doctree::Enum {
802 fn clean(&self) -> Item {
804 name: Some(self.name.clean()),
805 attrs: self.attrs.clean(),
806 source: self.where.clean(),
808 visibility: self.vis.clean(),
809 inner: EnumItem(Enum {
810 variants: self.variants.clean(),
811 generics: self.generics.clean(),
812 variants_stripped: false,
818 #[deriving(Clone, Encodable, Decodable)]
820 pub kind: VariantKind,
823 impl Clean<Item> for doctree::Variant {
824 fn clean(&self) -> Item {
826 name: Some(self.name.clean()),
827 attrs: self.attrs.clean(),
828 source: self.where.clean(),
829 visibility: self.vis.clean(),
831 inner: VariantItem(Variant {
832 kind: self.kind.clean(),
838 #[deriving(Clone, Encodable, Decodable)]
839 pub enum VariantKind {
841 TupleVariant(Vec<Type> ),
842 StructVariant(VariantStruct),
845 impl Clean<VariantKind> for ast::VariantKind {
846 fn clean(&self) -> VariantKind {
848 &ast::TupleVariantKind(ref args) => {
852 TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
855 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
860 #[deriving(Clone, Encodable, Decodable)]
869 impl Clean<Span> for syntax::codemap::Span {
870 fn clean(&self) -> Span {
871 let cm = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess().codemap();
872 let filename = cm.span_to_filename(*self);
873 let lo = cm.lookup_char_pos(self.lo);
874 let hi = cm.lookup_char_pos(self.hi);
876 filename: filename.to_owned(),
878 locol: lo.col.to_uint(),
880 hicol: hi.col.to_uint(),
885 #[deriving(Clone, Encodable, Decodable)]
888 pub segments: Vec<PathSegment>,
891 impl Clean<Path> for ast::Path {
892 fn clean(&self) -> Path {
895 segments: self.segments.clean().move_iter().collect(),
900 #[deriving(Clone, Encodable, Decodable)]
901 pub struct PathSegment {
903 pub lifetimes: Vec<Lifetime>,
904 pub types: Vec<Type>,
907 impl Clean<PathSegment> for ast::PathSegment {
908 fn clean(&self) -> PathSegment {
910 name: self.identifier.clean(),
911 lifetimes: self.lifetimes.clean().move_iter().collect(),
912 types: self.types.clean().move_iter().collect()
917 fn path_to_str(p: &ast::Path) -> ~str {
918 use syntax::parse::token;
921 let mut first = true;
922 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
923 if !first || p.global {
933 impl Clean<~str> for ast::Ident {
934 fn clean(&self) -> ~str {
935 token::get_ident(*self).get().to_owned()
939 #[deriving(Clone, Encodable, Decodable)]
942 pub generics: Generics,
945 impl Clean<Item> for doctree::Typedef {
946 fn clean(&self) -> Item {
948 name: Some(self.name.clean()),
949 attrs: self.attrs.clean(),
950 source: self.where.clean(),
952 visibility: self.vis.clean(),
953 inner: TypedefItem(Typedef {
954 type_: self.ty.clean(),
955 generics: self.gen.clean(),
961 #[deriving(Clone, Encodable, Decodable)]
962 pub struct BareFunctionDecl {
963 pub fn_style: ast::FnStyle,
964 pub generics: Generics,
969 impl Clean<BareFunctionDecl> for ast::BareFnTy {
970 fn clean(&self) -> BareFunctionDecl {
972 fn_style: self.fn_style,
974 lifetimes: self.lifetimes.clean().move_iter().collect(),
975 type_params: Vec::new(),
977 decl: self.decl.clean(),
978 abi: self.abi.to_str(),
983 #[deriving(Clone, Encodable, Decodable)]
986 pub mutability: Mutability,
987 /// It's useful to have the value of a static documented, but I have no
988 /// desire to represent expressions (that'd basically be all of the AST,
989 /// which is huge!). So, have a string.
993 impl Clean<Item> for doctree::Static {
994 fn clean(&self) -> Item {
995 debug!("claning static {}: {:?}", self.name.clean(), self);
997 name: Some(self.name.clean()),
998 attrs: self.attrs.clean(),
999 source: self.where.clean(),
1001 visibility: self.vis.clean(),
1002 inner: StaticItem(Static {
1003 type_: self.type_.clean(),
1004 mutability: self.mutability.clean(),
1005 expr: self.expr.span.to_src(),
1011 #[deriving(Show, Clone, Encodable, Decodable)]
1012 pub enum Mutability {
1017 impl Clean<Mutability> for ast::Mutability {
1018 fn clean(&self) -> Mutability {
1020 &ast::MutMutable => Mutable,
1021 &ast::MutImmutable => Immutable,
1026 #[deriving(Clone, Encodable, Decodable)]
1028 pub generics: Generics,
1029 pub trait_: Option<Type>,
1031 pub methods: Vec<Item>,
1035 impl Clean<Item> for doctree::Impl {
1036 fn clean(&self) -> Item {
1037 let mut derived = false;
1038 for attr in self.attrs.iter() {
1039 match attr.node.value.node {
1040 ast::MetaWord(ref s) => {
1041 if s.get() == "automatically_derived" {
1050 attrs: self.attrs.clean(),
1051 source: self.where.clean(),
1053 visibility: self.vis.clean(),
1054 inner: ImplItem(Impl {
1055 generics: self.generics.clean(),
1056 trait_: self.trait_.clean(),
1057 for_: self.for_.clean(),
1058 methods: self.methods.clean(),
1065 #[deriving(Clone, Encodable, Decodable)]
1066 pub struct ViewItem {
1067 pub inner: ViewItemInner,
1070 impl Clean<Item> for ast::ViewItem {
1071 fn clean(&self) -> Item {
1074 attrs: self.attrs.clean().move_iter().collect(),
1075 source: self.span.clean(),
1077 visibility: self.vis.clean(),
1078 inner: ViewItemItem(ViewItem {
1079 inner: self.node.clean()
1085 #[deriving(Clone, Encodable, Decodable)]
1086 pub enum ViewItemInner {
1087 ExternCrate(~str, Option<~str>, ast::NodeId),
1088 Import(Vec<ViewPath>)
1091 impl Clean<ViewItemInner> for ast::ViewItem_ {
1092 fn clean(&self) -> ViewItemInner {
1094 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1095 let string = match *p {
1097 Some((ref x, _)) => Some(x.get().to_owned()),
1099 ExternCrate(i.clean(), string, *id)
1101 &ast::ViewItemUse(ref vp) => {
1102 Import(vp.clean().move_iter().collect())
1108 #[deriving(Clone, Encodable, Decodable)]
1110 // use str = source;
1111 SimpleImport(~str, ImportSource),
1113 GlobImport(ImportSource),
1114 // use source::{a, b, c};
1115 ImportList(ImportSource, Vec<ViewListIdent> ),
1118 #[deriving(Clone, Encodable, Decodable)]
1119 pub struct ImportSource {
1121 pub did: Option<ast::DefId>,
1124 impl Clean<ViewPath> for ast::ViewPath {
1125 fn clean(&self) -> ViewPath {
1127 ast::ViewPathSimple(ref i, ref p, id) =>
1128 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1129 ast::ViewPathGlob(ref p, id) =>
1130 GlobImport(resolve_use_source(p.clean(), id)),
1131 ast::ViewPathList(ref p, ref pl, id) => {
1132 ImportList(resolve_use_source(p.clean(), id),
1133 pl.clean().move_iter().collect())
1139 #[deriving(Clone, Encodable, Decodable)]
1140 pub struct ViewListIdent {
1142 pub source: Option<ast::DefId>,
1145 impl Clean<ViewListIdent> for ast::PathListIdent {
1146 fn clean(&self) -> ViewListIdent {
1148 name: self.node.name.clean(),
1149 source: resolve_def(self.node.id),
1154 impl Clean<Vec<Item>> for ast::ForeignMod {
1155 fn clean(&self) -> Vec<Item> {
1160 impl Clean<Item> for ast::ForeignItem {
1161 fn clean(&self) -> Item {
1162 let inner = match self.node {
1163 ast::ForeignItemFn(ref decl, ref generics) => {
1164 ForeignFunctionItem(Function {
1166 generics: generics.clean(),
1167 fn_style: ast::ExternFn,
1170 ast::ForeignItemStatic(ref ty, mutbl) => {
1171 ForeignStaticItem(Static {
1173 mutability: if mutbl {Mutable} else {Immutable},
1179 name: Some(self.ident.clean()),
1180 attrs: self.attrs.clean().move_iter().collect(),
1181 source: self.span.clean(),
1183 visibility: self.vis.clean(),
1192 fn to_src(&self) -> ~str;
1195 impl ToSource for syntax::codemap::Span {
1196 fn to_src(&self) -> ~str {
1197 debug!("converting span {:?} to snippet", self.clean());
1198 let cm = local_data::get(super::ctxtkey, |x| x.unwrap().clone()).sess().codemap().clone();
1199 let sn = match cm.span_to_snippet(*self) {
1203 debug!("got snippet {}", sn);
1208 fn lit_to_str(lit: &ast::Lit) -> ~str {
1210 ast::LitStr(ref st, _) => st.get().to_owned(),
1211 ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1212 ast::LitChar(c) => ~"'" + std::char::from_u32(c).unwrap().to_str() + "'",
1213 ast::LitInt(i, _t) => i.to_str(),
1214 ast::LitUint(u, _t) => u.to_str(),
1215 ast::LitIntUnsuffixed(i) => i.to_str(),
1216 ast::LitFloat(ref f, _t) => f.get().to_str(),
1217 ast::LitFloatUnsuffixed(ref f) => f.get().to_str(),
1218 ast::LitBool(b) => b.to_str(),
1223 fn name_from_pat(p: &ast::Pat) -> ~str {
1225 debug!("Trying to get a name from pattern: {:?}", p);
1229 PatWildMulti => ~"..",
1230 PatIdent(_, ref p, _) => path_to_str(p),
1231 PatEnum(ref p, _) => path_to_str(p),
1232 PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1233 which is not allowed in function arguments"),
1234 PatTup(..) => ~"(tuple arg NYI)",
1235 PatUniq(p) => name_from_pat(p),
1236 PatRegion(p) => name_from_pat(p),
1238 warn!("tried to get argument name from PatLit, \
1239 which is silly in function arguments");
1242 PatRange(..) => fail!("tried to get argument name from PatRange, \
1243 which is not allowed in function arguments"),
1244 PatVec(..) => fail!("tried to get argument name from pat_vec, \
1245 which is not allowed in function arguments")
1249 /// Given a Type, resolve it using the def_map
1250 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound> >,
1251 id: ast::NodeId) -> Type {
1252 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1253 let tycx = match cx.maybe_typed {
1254 core::Typed(ref tycx) => tycx,
1255 // If we're extracting tests, this return value doesn't matter.
1256 core::NotTyped(_) => return Bool
1258 debug!("searching for {:?} in defmap", id);
1259 let d = match tycx.def_map.borrow().find(&id) {
1262 debug!("could not find {:?} in defmap (`{}`)", id, tycx.map.node_to_str(id));
1263 fail!("Unexpected failure: unresolved id not in defmap (this is a bug!)")
1267 let (def_id, kind) = match d {
1268 ast::DefFn(i, _) => (i, TypeFunction),
1269 ast::DefSelfTy(i) => return Self(i),
1270 ast::DefTy(i) => (i, TypeEnum),
1271 ast::DefTrait(i) => {
1272 debug!("saw DefTrait in def_to_id");
1275 ast::DefPrimTy(p) => match p {
1276 ast::TyStr => return String,
1277 ast::TyBool => return Bool,
1278 _ => return Primitive(p)
1280 ast::DefTyParam(i, _) => return Generic(i.node),
1281 ast::DefStruct(i) => (i, TypeStruct),
1282 ast::DefTyParamBinder(i) => {
1283 debug!("found a typaram_binder, what is it? {}", i);
1284 return TyParamBinder(i);
1286 x => fail!("resolved type maps to a weird def {:?}", x),
1288 if ast_util::is_local(def_id) {
1289 ResolvedPath{ path: path, typarams: tpbs, id: def_id.node }
1291 let fqn = csearch::get_item_path(tycx, def_id);
1292 let fqn = fqn.move_iter().map(|i| i.to_str()).collect();
1298 krate: def_id.krate,
1303 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
1306 did: resolve_def(id),
1310 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
1311 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1312 match cx.maybe_typed {
1313 core::Typed(ref tcx) => {
1314 tcx.def_map.borrow().find(&id).map(|&d| ast_util::def_id_of_def(d))
1316 core::NotTyped(_) => None
1320 #[deriving(Clone, Encodable, Decodable)]
1325 impl Clean<Item> for doctree::Macro {
1326 fn clean(&self) -> Item {
1328 name: Some(self.name.clean()),
1329 attrs: self.attrs.clean(),
1330 source: self.where.clean(),
1331 visibility: ast::Public.clean(),
1333 inner: MacroItem(Macro {
1334 source: self.where.to_src(),