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::opt_vec::OptVec<T> {
60 fn clean(&self) -> Vec<U> {
62 &syntax::opt_vec::Empty => Vec::new(),
63 &syntax::opt_vec::Vec(ref v) => v.clean()
68 #[deriving(Clone, Encodable, Decodable)]
72 externs: Vec<(ast::CrateNum, ExternalCrate)> ,
75 impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> {
76 fn clean(&self) -> Crate {
77 use syntax::attr::find_crateid;
78 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
80 let mut externs = Vec::new();
81 cx.sess().cstore.iter_crate_data(|n, meta| {
82 externs.push((n, meta.clean()));
86 name: match find_crateid(self.attrs.as_slice()) {
88 None => fail!("rustdoc requires a `crate_id` crate attribute"),
90 module: Some(self.module.clean()),
96 #[deriving(Clone, Encodable, Decodable)]
97 pub struct ExternalCrate {
99 attrs: Vec<Attribute> ,
102 impl Clean<ExternalCrate> for cstore::crate_metadata {
103 fn clean(&self) -> ExternalCrate {
105 name: self.name.to_owned(),
106 attrs: decoder::get_crate_attributes(self.data()).clean()
113 /// Anything with a source location and set of attributes and, optionally, a
114 /// name. That is, anything that can be documented. This doesn't correspond
115 /// directly to the AST's concept of an item; it's a strict superset.
116 #[deriving(Clone, Encodable, Decodable)]
120 /// Not everything has a name. E.g., impls
122 attrs: Vec<Attribute> ,
124 visibility: Option<Visibility>,
129 /// Finds the `doc` attribute as a List and returns the list of attributes
131 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
132 for attr in self.attrs.iter() {
134 List(ref x, ref list) if "doc" == *x => { return Some(list.as_slice()); }
141 /// Finds the `doc` attribute as a NameValue and returns the corresponding
143 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
144 for attr in self.attrs.iter() {
146 NameValue(ref x, ref v) if "doc" == *x => { return Some(v.as_slice()); }
153 pub fn is_mod(&self) -> bool {
154 match self.inner { ModuleItem(..) => true, _ => false }
156 pub fn is_trait(&self) -> bool {
157 match self.inner { TraitItem(..) => true, _ => false }
159 pub fn is_struct(&self) -> bool {
160 match self.inner { StructItem(..) => true, _ => false }
162 pub fn is_enum(&self) -> bool {
163 match self.inner { EnumItem(..) => true, _ => false }
165 pub fn is_fn(&self) -> bool {
166 match self.inner { FunctionItem(..) => true, _ => false }
170 #[deriving(Clone, Encodable, Decodable)]
174 FunctionItem(Function),
176 TypedefItem(Typedef),
180 ViewItemItem(ViewItem),
181 TyMethodItem(TyMethod),
183 StructFieldItem(StructField),
184 VariantItem(Variant),
185 ForeignFunctionItem(Function),
186 ForeignStaticItem(Static),
190 #[deriving(Clone, Encodable, Decodable)]
196 impl Clean<Item> for doctree::Module {
197 fn clean(&self) -> Item {
198 let name = if self.name.is_some() {
199 self.name.unwrap().clean()
203 let mut foreigns = Vec::new();
204 for subforeigns in self.foreigns.clean().move_iter() {
205 for foreign in subforeigns.move_iter() {
206 foreigns.push(foreign)
209 let items: Vec<Vec<Item> > = vec!(
210 self.structs.clean().move_iter().collect(),
211 self.enums.clean().move_iter().collect(),
212 self.fns.clean().move_iter().collect(),
214 self.mods.clean().move_iter().collect(),
215 self.typedefs.clean().move_iter().collect(),
216 self.statics.clean().move_iter().collect(),
217 self.traits.clean().move_iter().collect(),
218 self.impls.clean().move_iter().collect(),
219 self.view_items.clean().move_iter().collect(),
220 self.macros.clean().move_iter().collect()
224 attrs: self.attrs.clean(),
225 source: self.where.clean(),
226 visibility: self.vis.clean(),
228 inner: ModuleItem(Module {
229 is_crate: self.is_crate,
231 .flat_map(|x| x.iter().map(|x| (*x).clone()))
238 #[deriving(Clone, Encodable, Decodable)]
241 List(~str, Vec<Attribute> ),
242 NameValue(~str, ~str)
245 impl Clean<Attribute> for ast::MetaItem {
246 fn clean(&self) -> Attribute {
248 ast::MetaWord(ref s) => Word(s.get().to_owned()),
249 ast::MetaList(ref s, ref l) => {
250 List(s.get().to_owned(), l.clean().move_iter().collect())
252 ast::MetaNameValue(ref s, ref v) => {
253 NameValue(s.get().to_owned(), lit_to_str(v))
259 impl Clean<Attribute> for ast::Attribute {
260 fn clean(&self) -> Attribute {
261 self.desugar_doc().node.value.clean()
265 // This is a rough approximation that gets us what we want.
266 impl<'a> attr::AttrMetaMethods for &'a Attribute {
267 fn name(&self) -> InternedString {
269 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
270 token::intern_and_get_ident(*n)
275 fn value_str(&self) -> Option<InternedString> {
277 NameValue(_, ref v) => Some(token::intern_and_get_ident(*v)),
281 fn meta_item_list<'a>(&'a self) -> Option<&'a [@ast::MetaItem]> { None }
282 fn name_str_pair(&self) -> Option<(InternedString, InternedString)> {
287 #[deriving(Clone, Encodable, Decodable)]
291 bounds: Vec<TyParamBound> }
293 impl Clean<TyParam> for ast::TyParam {
294 fn clean(&self) -> TyParam {
296 name: self.ident.clean(),
298 bounds: self.bounds.clean().move_iter().collect(),
303 #[deriving(Clone, Encodable, Decodable)]
304 pub enum TyParamBound {
309 impl Clean<TyParamBound> for ast::TyParamBound {
310 fn clean(&self) -> TyParamBound {
312 ast::RegionTyParamBound => RegionBound,
313 ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
318 #[deriving(Clone, Encodable, Decodable)]
319 pub struct Lifetime(~str);
322 pub fn get_ref<'a>(&'a self) -> &'a str {
323 let Lifetime(ref s) = *self;
329 impl Clean<Lifetime> for ast::Lifetime {
330 fn clean(&self) -> Lifetime {
331 Lifetime(token::get_name(self.name).get().to_owned())
335 // maybe use a Generic enum and use ~[Generic]?
336 #[deriving(Clone, Encodable, Decodable)]
337 pub struct Generics {
338 lifetimes: Vec<Lifetime> ,
339 type_params: Vec<TyParam> }
341 impl Clean<Generics> for ast::Generics {
342 fn clean(&self) -> Generics {
344 lifetimes: self.lifetimes.clean().move_iter().collect(),
345 type_params: self.ty_params.clean().move_iter().collect(),
350 #[deriving(Clone, Encodable, Decodable)]
358 impl Clean<Item> for ast::Method {
359 fn clean(&self) -> Item {
360 let inputs = match self.explicit_self.node {
361 ast::SelfStatic => self.decl.inputs.as_slice(),
362 _ => self.decl.inputs.slice_from(1)
366 values: inputs.iter().map(|x| x.clean()).collect(),
368 output: (self.decl.output.clean()),
369 cf: self.decl.cf.clean(),
373 name: Some(self.ident.clean()),
374 attrs: self.attrs.clean().move_iter().collect(),
375 source: self.span.clean(),
377 visibility: self.vis.clean(),
378 inner: MethodItem(Method {
379 generics: self.generics.clean(),
380 self_: self.explicit_self.clean(),
381 purity: self.purity.clone(),
388 #[deriving(Clone, Encodable, Decodable)]
389 pub struct TyMethod {
396 impl Clean<Item> for ast::TypeMethod {
397 fn clean(&self) -> Item {
398 let inputs = match self.explicit_self.node {
399 ast::SelfStatic => self.decl.inputs.as_slice(),
400 _ => self.decl.inputs.slice_from(1)
404 values: inputs.iter().map(|x| x.clean()).collect(),
406 output: (self.decl.output.clean()),
407 cf: self.decl.cf.clean(),
411 name: Some(self.ident.clean()),
412 attrs: self.attrs.clean().move_iter().collect(),
413 source: self.span.clean(),
416 inner: TyMethodItem(TyMethod {
417 purity: self.purity.clone(),
419 self_: self.explicit_self.clean(),
420 generics: self.generics.clean(),
426 #[deriving(Clone, Encodable, Decodable)]
430 SelfBorrowed(Option<Lifetime>, Mutability),
434 impl Clean<SelfTy> for ast::ExplicitSelf {
435 fn clean(&self) -> SelfTy {
437 ast::SelfStatic => SelfStatic,
438 ast::SelfValue => SelfValue,
439 ast::SelfUniq => SelfOwned,
440 ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()),
445 #[deriving(Clone, Encodable, Decodable)]
446 pub struct Function {
452 impl Clean<Item> for doctree::Function {
453 fn clean(&self) -> Item {
455 name: Some(self.name.clean()),
456 attrs: self.attrs.clean(),
457 source: self.where.clean(),
458 visibility: self.vis.clean(),
460 inner: FunctionItem(Function {
461 decl: self.decl.clean(),
462 generics: self.generics.clean(),
469 #[deriving(Clone, Encodable, Decodable)]
470 pub struct ClosureDecl {
472 region: Option<Lifetime>,
473 lifetimes: Vec<Lifetime> ,
475 onceness: ast::Onceness,
477 bounds: Vec<TyParamBound> }
479 impl Clean<ClosureDecl> for ast::ClosureTy {
480 fn clean(&self) -> ClosureDecl {
483 region: self.region.clean(),
484 lifetimes: self.lifetimes.clean().move_iter().collect(),
485 decl: self.decl.clean(),
486 onceness: self.onceness,
488 bounds: match self.bounds {
489 Some(ref x) => x.clean().move_iter().collect(),
496 #[deriving(Clone, Encodable, Decodable)]
501 attrs: Vec<Attribute> }
503 #[deriving(Clone, Encodable, Decodable)]
504 pub struct Arguments {
505 values: Vec<Argument> ,
508 impl Clean<FnDecl> for ast::FnDecl {
509 fn clean(&self) -> FnDecl {
512 values: self.inputs.iter().map(|x| x.clean()).collect(),
514 output: (self.output.clean()),
521 #[deriving(Clone, Encodable, Decodable)]
522 pub struct Argument {
528 impl Clean<Argument> for ast::Arg {
529 fn clean(&self) -> Argument {
531 name: name_from_pat(self.pat),
532 type_: (self.ty.clean()),
538 #[deriving(Clone, Encodable, Decodable)]
544 impl Clean<RetStyle> for ast::RetStyle {
545 fn clean(&self) -> RetStyle {
547 ast::Return => Return,
548 ast::NoReturn => NoReturn
553 #[deriving(Clone, Encodable, Decodable)]
555 methods: Vec<TraitMethod> ,
560 impl Clean<Item> for doctree::Trait {
561 fn clean(&self) -> Item {
563 name: Some(self.name.clean()),
564 attrs: self.attrs.clean(),
565 source: self.where.clean(),
567 visibility: self.vis.clean(),
568 inner: TraitItem(Trait {
569 methods: self.methods.clean(),
570 generics: self.generics.clean(),
571 parents: self.parents.clean(),
577 impl Clean<Type> for ast::TraitRef {
578 fn clean(&self) -> Type {
579 resolve_type(self.path.clean(), None, self.ref_id)
583 #[deriving(Clone, Encodable, Decodable)]
584 pub enum TraitMethod {
590 pub fn is_req(&self) -> bool {
592 &Required(..) => true,
596 pub fn is_def(&self) -> bool {
598 &Provided(..) => true,
602 pub fn item<'a>(&'a self) -> &'a Item {
604 Required(ref item) => item,
605 Provided(ref item) => item,
610 impl Clean<TraitMethod> for ast::TraitMethod {
611 fn clean(&self) -> TraitMethod {
613 &ast::Required(ref t) => Required(t.clean()),
614 &ast::Provided(ref t) => Provided(t.clean()),
619 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
620 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
621 /// it does not preserve mutability or boxes.
622 #[deriving(Clone, Encodable, Decodable)]
624 /// structs/enums/traits (anything that'd be an ast::TyPath)
627 typarams: Option<Vec<TyParamBound> >,
630 /// Same as above, but only external variants
633 typarams: Option<Vec<TyParamBound> >,
636 krate: ast::CrateNum,
638 // I have no idea how to usefully use this.
639 TyParamBinder(ast::NodeId),
640 /// For parameterized types, so the consumer of the JSON don't go looking
641 /// for types which don't exist anywhere.
642 Generic(ast::NodeId),
643 /// For references to self
645 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
646 Primitive(ast::PrimTy),
647 Closure(~ClosureDecl),
649 BareFunction(~BareFunctionDecl),
652 FixedVector(~Type, ~str),
661 RawPointer(Mutability, ~Type),
662 BorrowedRef { lifetime: Option<Lifetime>, mutability: Mutability, type_: ~Type},
663 // region, raw, other boxes, mutable
666 #[deriving(Clone, Encodable, Decodable)]
674 impl Clean<Type> for ast::Ty {
675 fn clean(&self) -> Type {
677 debug!("cleaning type `{:?}`", self);
678 let codemap = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess().codemap();
679 debug!("span corresponds to `{}`", codemap.span_to_str(self.span));
682 TyPtr(ref m) => RawPointer(m.mutbl.clean(), ~m.ty.clean()),
683 TyRptr(ref l, ref m) =>
684 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
685 type_: ~m.ty.clean()},
686 TyBox(ty) => Managed(~ty.clean()),
687 TyUniq(ty) => Unique(~ty.clean()),
688 TyVec(ty) => Vector(~ty.clean()),
689 TyFixedLengthVec(ty, ref e) => FixedVector(~ty.clean(),
691 TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
692 TyPath(ref p, ref tpbs, id) => {
693 resolve_type(p.clean(),
694 tpbs.clean().map(|x| x.move_iter().collect()),
697 TyClosure(ref c) => Closure(~c.clean()),
698 TyBareFn(ref barefn) => BareFunction(~barefn.clean()),
700 ref x => fail!("Unimplemented type {:?}", x),
705 #[deriving(Clone, Encodable, Decodable)]
706 pub struct StructField {
710 impl Clean<Item> for ast::StructField {
711 fn clean(&self) -> Item {
712 let (name, vis) = match self.node.kind {
713 ast::NamedField(id, vis) => (Some(id), Some(vis)),
718 attrs: self.node.attrs.clean().move_iter().collect(),
719 source: self.span.clean(),
722 inner: StructFieldItem(StructField {
723 type_: self.node.ty.clean(),
729 pub type Visibility = ast::Visibility;
731 impl Clean<Option<Visibility>> for ast::Visibility {
732 fn clean(&self) -> Option<Visibility> {
737 #[deriving(Clone, Encodable, Decodable)]
739 struct_type: doctree::StructType,
742 fields_stripped: bool,
745 impl Clean<Item> for doctree::Struct {
746 fn clean(&self) -> Item {
748 name: Some(self.name.clean()),
749 attrs: self.attrs.clean(),
750 source: self.where.clean(),
752 visibility: self.vis.clean(),
753 inner: StructItem(Struct {
754 struct_type: self.struct_type,
755 generics: self.generics.clean(),
756 fields: self.fields.clean(),
757 fields_stripped: false,
763 /// This is a more limited form of the standard Struct, different in that
764 /// it lacks the things most items have (name, id, parameterization). Found
765 /// only as a variant in an enum.
766 #[deriving(Clone, Encodable, Decodable)]
767 pub struct VariantStruct {
768 struct_type: doctree::StructType,
770 fields_stripped: bool,
773 impl Clean<VariantStruct> for syntax::ast::StructDef {
774 fn clean(&self) -> VariantStruct {
776 struct_type: doctree::struct_type_from_def(self),
777 fields: self.fields.clean().move_iter().collect(),
778 fields_stripped: false,
783 #[deriving(Clone, Encodable, Decodable)]
785 variants: Vec<Item> ,
787 variants_stripped: bool,
790 impl Clean<Item> for doctree::Enum {
791 fn clean(&self) -> Item {
793 name: Some(self.name.clean()),
794 attrs: self.attrs.clean(),
795 source: self.where.clean(),
797 visibility: self.vis.clean(),
798 inner: EnumItem(Enum {
799 variants: self.variants.clean(),
800 generics: self.generics.clean(),
801 variants_stripped: false,
807 #[deriving(Clone, Encodable, Decodable)]
812 impl Clean<Item> for doctree::Variant {
813 fn clean(&self) -> Item {
815 name: Some(self.name.clean()),
816 attrs: self.attrs.clean(),
817 source: self.where.clean(),
818 visibility: self.vis.clean(),
820 inner: VariantItem(Variant {
821 kind: self.kind.clean(),
827 #[deriving(Clone, Encodable, Decodable)]
828 pub enum VariantKind {
830 TupleVariant(Vec<Type> ),
831 StructVariant(VariantStruct),
834 impl Clean<VariantKind> for ast::VariantKind {
835 fn clean(&self) -> VariantKind {
837 &ast::TupleVariantKind(ref args) => {
841 TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
844 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
849 #[deriving(Clone, Encodable, Decodable)]
858 impl Clean<Span> for syntax::codemap::Span {
859 fn clean(&self) -> Span {
860 let cm = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess().codemap();
861 let filename = cm.span_to_filename(*self);
862 let lo = cm.lookup_char_pos(self.lo);
863 let hi = cm.lookup_char_pos(self.hi);
865 filename: filename.to_owned(),
867 locol: lo.col.to_uint(),
869 hicol: hi.col.to_uint(),
874 #[deriving(Clone, Encodable, Decodable)]
877 segments: Vec<PathSegment> ,
880 impl Clean<Path> for ast::Path {
881 fn clean(&self) -> Path {
884 segments: self.segments.clean().move_iter().collect(),
889 #[deriving(Clone, Encodable, Decodable)]
890 pub struct PathSegment {
892 lifetimes: Vec<Lifetime> ,
896 impl Clean<PathSegment> for ast::PathSegment {
897 fn clean(&self) -> PathSegment {
899 name: self.identifier.clean(),
900 lifetimes: self.lifetimes.clean().move_iter().collect(),
901 types: self.types.clean().move_iter().collect()
906 fn path_to_str(p: &ast::Path) -> ~str {
907 use syntax::parse::token;
910 let mut first = true;
911 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
912 if !first || p.global {
922 impl Clean<~str> for ast::Ident {
923 fn clean(&self) -> ~str {
924 token::get_ident(*self).get().to_owned()
928 #[deriving(Clone, Encodable, Decodable)]
934 impl Clean<Item> for doctree::Typedef {
935 fn clean(&self) -> Item {
937 name: Some(self.name.clean()),
938 attrs: self.attrs.clean(),
939 source: self.where.clean(),
941 visibility: self.vis.clean(),
942 inner: TypedefItem(Typedef {
943 type_: self.ty.clean(),
944 generics: self.gen.clean(),
950 #[deriving(Clone, Encodable, Decodable)]
951 pub struct BareFunctionDecl {
958 impl Clean<BareFunctionDecl> for ast::BareFnTy {
959 fn clean(&self) -> BareFunctionDecl {
963 lifetimes: self.lifetimes.clean().move_iter().collect(),
964 type_params: Vec::new(),
966 decl: self.decl.clean(),
967 abi: self.abis.to_str(),
972 #[deriving(Clone, Encodable, Decodable)]
975 mutability: Mutability,
976 /// It's useful to have the value of a static documented, but I have no
977 /// desire to represent expressions (that'd basically be all of the AST,
978 /// which is huge!). So, have a string.
982 impl Clean<Item> for doctree::Static {
983 fn clean(&self) -> Item {
984 debug!("claning static {}: {:?}", self.name.clean(), self);
986 name: Some(self.name.clean()),
987 attrs: self.attrs.clean(),
988 source: self.where.clean(),
990 visibility: self.vis.clean(),
991 inner: StaticItem(Static {
992 type_: self.type_.clean(),
993 mutability: self.mutability.clean(),
994 expr: self.expr.span.to_src(),
1000 #[deriving(Show, Clone, Encodable, Decodable)]
1001 pub enum Mutability {
1006 impl Clean<Mutability> for ast::Mutability {
1007 fn clean(&self) -> Mutability {
1009 &ast::MutMutable => Mutable,
1010 &ast::MutImmutable => Immutable,
1015 #[deriving(Clone, Encodable, Decodable)]
1018 trait_: Option<Type>,
1020 methods: Vec<Item> ,
1023 impl Clean<Item> for doctree::Impl {
1024 fn clean(&self) -> Item {
1027 attrs: self.attrs.clean(),
1028 source: self.where.clean(),
1030 visibility: self.vis.clean(),
1031 inner: ImplItem(Impl {
1032 generics: self.generics.clean(),
1033 trait_: self.trait_.clean(),
1034 for_: self.for_.clean(),
1035 methods: self.methods.clean(),
1041 #[deriving(Clone, Encodable, Decodable)]
1042 pub struct ViewItem {
1043 inner: ViewItemInner
1046 impl Clean<Item> for ast::ViewItem {
1047 fn clean(&self) -> Item {
1050 attrs: self.attrs.clean().move_iter().collect(),
1051 source: self.span.clean(),
1053 visibility: self.vis.clean(),
1054 inner: ViewItemItem(ViewItem {
1055 inner: self.node.clean()
1061 #[deriving(Clone, Encodable, Decodable)]
1062 pub enum ViewItemInner {
1063 ExternCrate(~str, Option<~str>, ast::NodeId),
1064 Import(Vec<ViewPath>)
1067 impl Clean<ViewItemInner> for ast::ViewItem_ {
1068 fn clean(&self) -> ViewItemInner {
1070 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1071 let string = match *p {
1073 Some((ref x, _)) => Some(x.get().to_owned()),
1075 ExternCrate(i.clean(), string, *id)
1077 &ast::ViewItemUse(ref vp) => {
1078 Import(vp.clean().move_iter().collect())
1084 #[deriving(Clone, Encodable, Decodable)]
1086 // use str = source;
1087 SimpleImport(~str, ImportSource),
1089 GlobImport(ImportSource),
1090 // use source::{a, b, c};
1091 ImportList(ImportSource, Vec<ViewListIdent> ),
1094 #[deriving(Clone, Encodable, Decodable)]
1095 pub struct ImportSource {
1097 did: Option<ast::DefId>,
1100 impl Clean<ViewPath> for ast::ViewPath {
1101 fn clean(&self) -> ViewPath {
1103 ast::ViewPathSimple(ref i, ref p, id) =>
1104 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1105 ast::ViewPathGlob(ref p, id) =>
1106 GlobImport(resolve_use_source(p.clean(), id)),
1107 ast::ViewPathList(ref p, ref pl, id) => {
1108 ImportList(resolve_use_source(p.clean(), id),
1109 pl.clean().move_iter().collect())
1115 #[deriving(Clone, Encodable, Decodable)]
1116 pub struct ViewListIdent {
1118 source: Option<ast::DefId>,
1121 impl Clean<ViewListIdent> for ast::PathListIdent {
1122 fn clean(&self) -> ViewListIdent {
1124 name: self.node.name.clean(),
1125 source: resolve_def(self.node.id),
1130 impl Clean<Vec<Item>> for ast::ForeignMod {
1131 fn clean(&self) -> Vec<Item> {
1136 impl Clean<Item> for ast::ForeignItem {
1137 fn clean(&self) -> Item {
1138 let inner = match self.node {
1139 ast::ForeignItemFn(ref decl, ref generics) => {
1140 ForeignFunctionItem(Function {
1142 generics: generics.clean(),
1143 purity: ast::ExternFn,
1146 ast::ForeignItemStatic(ref ty, mutbl) => {
1147 ForeignStaticItem(Static {
1149 mutability: if mutbl {Mutable} else {Immutable},
1155 name: Some(self.ident.clean()),
1156 attrs: self.attrs.clean().move_iter().collect(),
1157 source: self.span.clean(),
1159 visibility: self.vis.clean(),
1168 fn to_src(&self) -> ~str;
1171 impl ToSource for syntax::codemap::Span {
1172 fn to_src(&self) -> ~str {
1173 debug!("converting span {:?} to snippet", self.clean());
1174 let cm = local_data::get(super::ctxtkey, |x| x.unwrap().clone()).sess().codemap().clone();
1175 let sn = match cm.span_to_snippet(*self) {
1179 debug!("got snippet {}", sn);
1184 fn lit_to_str(lit: &ast::Lit) -> ~str {
1186 ast::LitStr(ref st, _) => st.get().to_owned(),
1187 ast::LitBinary(ref data) => format!("{:?}", data.deref().as_slice()),
1188 ast::LitChar(c) => ~"'" + std::char::from_u32(c).unwrap().to_str() + "'",
1189 ast::LitInt(i, _t) => i.to_str(),
1190 ast::LitUint(u, _t) => u.to_str(),
1191 ast::LitIntUnsuffixed(i) => i.to_str(),
1192 ast::LitFloat(ref f, _t) => f.get().to_str(),
1193 ast::LitFloatUnsuffixed(ref f) => f.get().to_str(),
1194 ast::LitBool(b) => b.to_str(),
1199 fn name_from_pat(p: &ast::Pat) -> ~str {
1201 debug!("Trying to get a name from pattern: {:?}", p);
1205 PatWildMulti => ~"..",
1206 PatIdent(_, ref p, _) => path_to_str(p),
1207 PatEnum(ref p, _) => path_to_str(p),
1208 PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1209 which is not allowed in function arguments"),
1210 PatTup(..) => ~"(tuple arg NYI)",
1211 PatUniq(p) => name_from_pat(p),
1212 PatRegion(p) => name_from_pat(p),
1214 warn!("tried to get argument name from PatLit, \
1215 which is silly in function arguments");
1218 PatRange(..) => fail!("tried to get argument name from PatRange, \
1219 which is not allowed in function arguments"),
1220 PatVec(..) => fail!("tried to get argument name from pat_vec, \
1221 which is not allowed in function arguments")
1225 /// Given a Type, resolve it using the def_map
1226 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound> >,
1227 id: ast::NodeId) -> Type {
1228 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1229 let tycx = match cx.maybe_typed {
1230 core::Typed(ref tycx) => tycx,
1231 // If we're extracting tests, this return value doesn't matter.
1232 core::NotTyped(_) => return Bool
1234 debug!("searching for {:?} in defmap", id);
1235 let def_map = tycx.def_map.borrow();
1236 let d = match def_map.get().find(&id) {
1239 debug!("could not find {:?} in defmap (`{}`)", id, tycx.map.node_to_str(id));
1240 fail!("Unexpected failure: unresolved id not in defmap (this is a bug!)")
1244 let (def_id, kind) = match *d {
1245 ast::DefFn(i, _) => (i, TypeFunction),
1246 ast::DefSelfTy(i) => return Self(i),
1247 ast::DefTy(i) => (i, TypeEnum),
1248 ast::DefTrait(i) => {
1249 debug!("saw DefTrait in def_to_id");
1252 ast::DefPrimTy(p) => match p {
1253 ast::TyStr => return String,
1254 ast::TyBool => return Bool,
1255 _ => return Primitive(p)
1257 ast::DefTyParam(i, _) => return Generic(i.node),
1258 ast::DefStruct(i) => (i, TypeStruct),
1259 ast::DefTyParamBinder(i) => {
1260 debug!("found a typaram_binder, what is it? {}", i);
1261 return TyParamBinder(i);
1263 x => fail!("resolved type maps to a weird def {:?}", x),
1265 if ast_util::is_local(def_id) {
1266 ResolvedPath{ path: path, typarams: tpbs, id: def_id.node }
1268 let fqn = csearch::get_item_path(tycx, def_id);
1269 let fqn = fqn.move_iter().map(|i| i.to_str()).collect();
1275 krate: def_id.krate,
1280 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
1283 did: resolve_def(id),
1287 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
1288 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1289 match cx.maybe_typed {
1290 core::Typed(ref tcx) => {
1291 let def_map = tcx.def_map.borrow();
1292 def_map.get().find(&id).map(|&d| ast_util::def_id_of_def(d))
1294 core::NotTyped(_) => None
1298 #[deriving(Clone, Encodable, Decodable)]
1303 impl Clean<Item> for doctree::Macro {
1304 fn clean(&self) -> Item {
1306 name: Some(self.name.clean()),
1307 attrs: self.attrs.clean(),
1308 source: self.where.clean(),
1309 visibility: ast::Public.clean(),
1311 inner: MacroItem(Macro {
1312 source: self.where.to_src(),