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
19 use syntax::attr::AttributeMethods;
20 use syntax::codemap::Pos;
21 use syntax::parse::token::InternedString;
22 use syntax::parse::token;
24 use rustc::metadata::cstore;
25 use rustc::metadata::csearch;
26 use rustc::metadata::decoder;
29 use std::hashmap::HashMap;
39 impl<T: Clean<U>, U> Clean<~[U]> for ~[T] {
40 fn clean(&self) -> ~[U] {
41 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<~[U]> for syntax::opt_vec::OptVec<T> {
60 fn clean(&self) -> ~[U] {
62 &syntax::opt_vec::Empty => ~[],
63 &syntax::opt_vec::Vec(ref v) => v.clean()
68 #[deriving(Clone, Encodable, Decodable)]
72 externs: HashMap<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 = HashMap::new();
81 cx.sess.cstore.iter_crate_data(|n, meta| {
82 externs.insert(n, meta.clean());
86 name: match find_crateid(self.attrs) {
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 {
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()
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
122 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(~"doc", ref list) => { 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(~"doc", ref v) => { 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 ViewItemItem(ViewItem),
179 TyMethodItem(TyMethod),
181 StructFieldItem(StructField),
182 VariantItem(Variant),
183 ForeignFunctionItem(Function),
184 ForeignStaticItem(Static),
187 #[deriving(Clone, Encodable, Decodable)]
192 impl Clean<Item> for doctree::Module {
193 fn clean(&self) -> Item {
194 let name = if self.name.is_some() {
195 self.name.unwrap().clean()
201 attrs: self.attrs.clean(),
202 source: self.where.clean(),
203 visibility: self.vis.clean(),
205 inner: ModuleItem(Module {
206 items: [self.structs.clean(), self.enums.clean(),
207 self.fns.clean(), self.foreigns.clean().concat_vec(),
208 self.mods.clean(), self.typedefs.clean(),
209 self.statics.clean(), self.traits.clean(),
210 self.impls.clean(), self.view_items.clean()].concat_vec()
216 #[deriving(Clone, Encodable, Decodable)]
219 List(~str, ~[Attribute]),
220 NameValue(~str, ~str)
223 impl Clean<Attribute> for ast::MetaItem {
224 fn clean(&self) -> Attribute {
226 ast::MetaWord(ref s) => Word(s.get().to_owned()),
227 ast::MetaList(ref s, ref l) => {
228 List(s.get().to_owned(), l.clean())
230 ast::MetaNameValue(ref s, ref v) => {
231 NameValue(s.get().to_owned(), lit_to_str(v))
237 impl Clean<Attribute> for ast::Attribute {
238 fn clean(&self) -> Attribute {
239 self.desugar_doc().node.value.clean()
243 // This is a rough approximation that gets us what we want.
244 impl<'a> attr::AttrMetaMethods for &'a Attribute {
245 fn name(&self) -> InternedString {
247 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
248 token::intern_and_get_ident(*n)
253 fn value_str(&self) -> Option<InternedString> {
255 NameValue(_, ref v) => Some(token::intern_and_get_ident(*v)),
259 fn meta_item_list<'a>(&'a self) -> Option<&'a [@ast::MetaItem]> { None }
260 fn name_str_pair(&self) -> Option<(InternedString, InternedString)> {
265 #[deriving(Clone, Encodable, Decodable)]
269 bounds: ~[TyParamBound]
272 impl Clean<TyParam> for ast::TyParam {
273 fn clean(&self) -> TyParam {
275 name: self.ident.clean(),
277 bounds: self.bounds.clean(),
282 #[deriving(Clone, Encodable, Decodable)]
283 pub enum TyParamBound {
288 impl Clean<TyParamBound> for ast::TyParamBound {
289 fn clean(&self) -> TyParamBound {
291 ast::RegionTyParamBound => RegionBound,
292 ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
297 #[deriving(Clone, Encodable, Decodable)]
298 pub struct Lifetime(~str);
301 pub fn get_ref<'a>(&'a self) -> &'a str {
302 let Lifetime(ref s) = *self;
308 impl Clean<Lifetime> for ast::Lifetime {
309 fn clean(&self) -> Lifetime {
310 Lifetime(self.ident.clean())
314 // maybe use a Generic enum and use ~[Generic]?
315 #[deriving(Clone, Encodable, Decodable)]
316 pub struct Generics {
317 lifetimes: ~[Lifetime],
318 type_params: ~[TyParam]
321 impl Clean<Generics> for ast::Generics {
322 fn clean(&self) -> Generics {
324 lifetimes: self.lifetimes.clean(),
325 type_params: self.ty_params.clean(),
330 #[deriving(Clone, Encodable, Decodable)]
338 impl Clean<Item> for ast::Method {
339 fn clean(&self) -> Item {
340 let inputs = match self.explicit_self.node {
341 ast::SelfStatic => self.decl.inputs.as_slice(),
342 _ => self.decl.inputs.slice_from(1)
345 inputs: inputs.iter().map(|x| x.clean()).collect(),
346 output: (self.decl.output.clean()),
347 cf: self.decl.cf.clean(),
351 name: Some(self.ident.clean()),
352 attrs: self.attrs.clean(),
353 source: self.span.clean(),
355 visibility: self.vis.clean(),
356 inner: MethodItem(Method {
357 generics: self.generics.clean(),
358 self_: self.explicit_self.clean(),
359 purity: self.purity.clone(),
366 #[deriving(Clone, Encodable, Decodable)]
367 pub struct TyMethod {
374 impl Clean<Item> for ast::TypeMethod {
375 fn clean(&self) -> Item {
376 let inputs = match self.explicit_self.node {
377 ast::SelfStatic => self.decl.inputs.as_slice(),
378 _ => self.decl.inputs.slice_from(1)
381 inputs: inputs.iter().map(|x| x.clean()).collect(),
382 output: (self.decl.output.clean()),
383 cf: self.decl.cf.clean(),
387 name: Some(self.ident.clean()),
388 attrs: self.attrs.clean(),
389 source: self.span.clean(),
392 inner: TyMethodItem(TyMethod {
393 purity: self.purity.clone(),
395 self_: self.explicit_self.clean(),
396 generics: self.generics.clean(),
402 #[deriving(Clone, Encodable, Decodable)]
406 SelfBorrowed(Option<Lifetime>, Mutability),
411 impl Clean<SelfTy> for ast::ExplicitSelf {
412 fn clean(&self) -> SelfTy {
414 ast::SelfStatic => SelfStatic,
415 ast::SelfValue => SelfValue,
416 ast::SelfUniq => SelfOwned,
417 ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()),
418 ast::SelfBox => SelfManaged,
423 #[deriving(Clone, Encodable, Decodable)]
424 pub struct Function {
430 impl Clean<Item> for doctree::Function {
431 fn clean(&self) -> Item {
433 name: Some(self.name.clean()),
434 attrs: self.attrs.clean(),
435 source: self.where.clean(),
436 visibility: self.vis.clean(),
438 inner: FunctionItem(Function {
439 decl: self.decl.clean(),
440 generics: self.generics.clean(),
447 #[deriving(Clone, Encodable, Decodable)]
448 pub struct ClosureDecl {
450 region: Option<Lifetime>,
451 lifetimes: ~[Lifetime],
453 onceness: ast::Onceness,
455 bounds: ~[TyParamBound]
458 impl Clean<ClosureDecl> for ast::ClosureTy {
459 fn clean(&self) -> ClosureDecl {
462 region: self.region.clean(),
463 lifetimes: self.lifetimes.clean(),
464 decl: self.decl.clean(),
465 onceness: self.onceness,
467 bounds: match self.bounds {
468 Some(ref x) => x.clean(),
475 #[deriving(Clone, Encodable, Decodable)]
483 impl Clean<FnDecl> for ast::FnDecl {
484 fn clean(&self) -> FnDecl {
486 inputs: self.inputs.iter().map(|x| x.clean()).collect(),
487 output: (self.output.clean()),
494 #[deriving(Clone, Encodable, Decodable)]
495 pub struct Argument {
501 impl Clean<Argument> for ast::Arg {
502 fn clean(&self) -> Argument {
504 name: name_from_pat(self.pat),
505 type_: (self.ty.clean()),
511 #[deriving(Clone, Encodable, Decodable)]
517 impl Clean<RetStyle> for ast::RetStyle {
518 fn clean(&self) -> RetStyle {
520 ast::Return => Return,
521 ast::NoReturn => NoReturn
526 #[deriving(Clone, Encodable, Decodable)]
528 methods: ~[TraitMethod],
533 impl Clean<Item> for doctree::Trait {
534 fn clean(&self) -> Item {
536 name: Some(self.name.clean()),
537 attrs: self.attrs.clean(),
538 source: self.where.clean(),
540 visibility: self.vis.clean(),
541 inner: TraitItem(Trait {
542 methods: self.methods.clean(),
543 generics: self.generics.clean(),
544 parents: self.parents.clean(),
550 impl Clean<Type> for ast::TraitRef {
551 fn clean(&self) -> Type {
552 resolve_type(self.path.clean(), None, self.ref_id)
556 #[deriving(Clone, Encodable, Decodable)]
557 pub enum TraitMethod {
563 pub fn is_req(&self) -> bool {
565 &Required(..) => true,
569 pub fn is_def(&self) -> bool {
571 &Provided(..) => true,
575 pub fn item<'a>(&'a self) -> &'a Item {
577 Required(ref item) => item,
578 Provided(ref item) => item,
583 impl Clean<TraitMethod> for ast::TraitMethod {
584 fn clean(&self) -> TraitMethod {
586 &ast::Required(ref t) => Required(t.clean()),
587 &ast::Provided(ref t) => Provided(t.clean()),
592 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
593 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
594 /// it does not preserve mutability or boxes.
595 #[deriving(Clone, Encodable, Decodable)]
597 /// structs/enums/traits (anything that'd be an ast::TyPath)
600 typarams: Option<~[TyParamBound]>,
603 /// Same as above, but only external variants
606 typarams: Option<~[TyParamBound]>,
609 crate: ast::CrateNum,
611 // I have no idea how to usefully use this.
612 TyParamBinder(ast::NodeId),
613 /// For parameterized types, so the consumer of the JSON don't go looking
614 /// for types which don't exist anywhere.
615 Generic(ast::NodeId),
616 /// For references to self
618 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
619 Primitive(ast::PrimTy),
620 Closure(~ClosureDecl),
622 BareFunction(~BareFunctionDecl),
625 FixedVector(~Type, ~str),
634 RawPointer(Mutability, ~Type),
635 BorrowedRef { lifetime: Option<Lifetime>, mutability: Mutability, type_: ~Type},
636 // region, raw, other boxes, mutable
639 #[deriving(Clone, Encodable, Decodable)]
647 impl Clean<Type> for ast::Ty {
648 fn clean(&self) -> Type {
650 debug!("cleaning type `{:?}`", self);
651 let codemap = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess.codemap;
652 debug!("span corresponds to `{}`", codemap.span_to_str(self.span));
655 TyPtr(ref m) => RawPointer(m.mutbl.clean(), ~m.ty.clean()),
656 TyRptr(ref l, ref m) =>
657 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
658 type_: ~m.ty.clean()},
659 TyBox(ty) => Managed(~ty.clean()),
660 TyUniq(ty) => Unique(~ty.clean()),
661 TyVec(ty) => Vector(~ty.clean()),
662 TyFixedLengthVec(ty, ref e) => FixedVector(~ty.clean(),
664 TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
665 TyPath(ref p, ref tpbs, id) =>
666 resolve_type(p.clean(), tpbs.clean(), id),
667 TyClosure(ref c) => Closure(~c.clean()),
668 TyBareFn(ref barefn) => BareFunction(~barefn.clean()),
670 ref x => fail!("Unimplemented type {:?}", x),
675 #[deriving(Clone, Encodable, Decodable)]
676 pub struct StructField {
680 impl Clean<Item> for ast::StructField {
681 fn clean(&self) -> Item {
682 let (name, vis) = match self.node.kind {
683 ast::NamedField(id, vis) => (Some(id), Some(vis)),
688 attrs: self.node.attrs.clean(),
689 source: self.span.clean(),
692 inner: StructFieldItem(StructField {
693 type_: self.node.ty.clean(),
699 pub type Visibility = ast::Visibility;
701 impl Clean<Option<Visibility>> for ast::Visibility {
702 fn clean(&self) -> Option<Visibility> {
707 #[deriving(Clone, Encodable, Decodable)]
709 struct_type: doctree::StructType,
712 fields_stripped: bool,
715 impl Clean<Item> for doctree::Struct {
716 fn clean(&self) -> Item {
718 name: Some(self.name.clean()),
719 attrs: self.attrs.clean(),
720 source: self.where.clean(),
722 visibility: self.vis.clean(),
723 inner: StructItem(Struct {
724 struct_type: self.struct_type,
725 generics: self.generics.clean(),
726 fields: self.fields.clean(),
727 fields_stripped: false,
733 /// This is a more limited form of the standard Struct, different in that it
734 /// it lacks the things most items have (name, id, parameterization). Found
735 /// only as a variant in an enum.
736 #[deriving(Clone, Encodable, Decodable)]
737 pub struct VariantStruct {
738 struct_type: doctree::StructType,
740 fields_stripped: bool,
743 impl Clean<VariantStruct> for syntax::ast::StructDef {
744 fn clean(&self) -> VariantStruct {
746 struct_type: doctree::struct_type_from_def(self),
747 fields: self.fields.clean(),
748 fields_stripped: false,
753 #[deriving(Clone, Encodable, Decodable)]
757 variants_stripped: bool,
760 impl Clean<Item> for doctree::Enum {
761 fn clean(&self) -> Item {
763 name: Some(self.name.clean()),
764 attrs: self.attrs.clean(),
765 source: self.where.clean(),
767 visibility: self.vis.clean(),
768 inner: EnumItem(Enum {
769 variants: self.variants.clean(),
770 generics: self.generics.clean(),
771 variants_stripped: false,
777 #[deriving(Clone, Encodable, Decodable)]
782 impl Clean<Item> for doctree::Variant {
783 fn clean(&self) -> Item {
785 name: Some(self.name.clean()),
786 attrs: self.attrs.clean(),
787 source: self.where.clean(),
788 visibility: self.vis.clean(),
790 inner: VariantItem(Variant {
791 kind: self.kind.clean(),
797 #[deriving(Clone, Encodable, Decodable)]
798 pub enum VariantKind {
800 TupleVariant(~[Type]),
801 StructVariant(VariantStruct),
804 impl Clean<VariantKind> for ast::VariantKind {
805 fn clean(&self) -> VariantKind {
807 &ast::TupleVariantKind(ref args) => {
811 TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
814 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
819 #[deriving(Clone, Encodable, Decodable)]
828 impl Clean<Span> for syntax::codemap::Span {
829 fn clean(&self) -> Span {
830 let cm = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess.codemap;
831 let filename = cm.span_to_filename(*self);
832 let lo = cm.lookup_char_pos(self.lo);
833 let hi = cm.lookup_char_pos(self.hi);
835 filename: filename.to_owned(),
837 locol: lo.col.to_uint(),
839 hicol: hi.col.to_uint(),
844 #[deriving(Clone, Encodable, Decodable)]
847 segments: ~[PathSegment],
850 impl Clean<Path> for ast::Path {
851 fn clean(&self) -> Path {
854 segments: self.segments.clean()
859 #[deriving(Clone, Encodable, Decodable)]
860 pub struct PathSegment {
862 lifetimes: ~[Lifetime],
866 impl Clean<PathSegment> for ast::PathSegment {
867 fn clean(&self) -> PathSegment {
869 name: self.identifier.clean(),
870 lifetimes: self.lifetimes.clean(),
871 types: self.types.clean()
876 fn path_to_str(p: &ast::Path) -> ~str {
877 use syntax::parse::token::interner_get;
880 let mut first = true;
881 for i in p.segments.iter().map(|x| interner_get(x.identifier.name)) {
882 if !first || p.global {
892 impl Clean<~str> for ast::Ident {
893 fn clean(&self) -> ~str {
894 let string = token::get_ident(self.name);
895 string.get().to_owned()
899 #[deriving(Clone, Encodable, Decodable)]
905 impl Clean<Item> for doctree::Typedef {
906 fn clean(&self) -> Item {
908 name: Some(self.name.clean()),
909 attrs: self.attrs.clean(),
910 source: self.where.clean(),
912 visibility: self.vis.clean(),
913 inner: TypedefItem(Typedef {
914 type_: self.ty.clean(),
915 generics: self.gen.clean(),
921 #[deriving(Clone, Encodable, Decodable)]
922 pub struct BareFunctionDecl {
929 impl Clean<BareFunctionDecl> for ast::BareFnTy {
930 fn clean(&self) -> BareFunctionDecl {
934 lifetimes: self.lifetimes.clean(),
937 decl: self.decl.clean(),
938 abi: self.abis.to_str(),
943 #[deriving(Clone, Encodable, Decodable)]
946 mutability: Mutability,
947 /// It's useful to have the value of a static documented, but I have no
948 /// desire to represent expressions (that'd basically be all of the AST,
949 /// which is huge!). So, have a string.
953 impl Clean<Item> for doctree::Static {
954 fn clean(&self) -> Item {
955 debug!("claning static {}: {:?}", self.name.clean(), self);
957 name: Some(self.name.clean()),
958 attrs: self.attrs.clean(),
959 source: self.where.clean(),
961 visibility: self.vis.clean(),
962 inner: StaticItem(Static {
963 type_: self.type_.clean(),
964 mutability: self.mutability.clean(),
965 expr: self.expr.span.to_src(),
971 #[deriving(ToStr, Clone, Encodable, Decodable)]
972 pub enum Mutability {
977 impl Clean<Mutability> for ast::Mutability {
978 fn clean(&self) -> Mutability {
980 &ast::MutMutable => Mutable,
981 &ast::MutImmutable => Immutable,
986 #[deriving(Clone, Encodable, Decodable)]
989 trait_: Option<Type>,
994 impl Clean<Item> for doctree::Impl {
995 fn clean(&self) -> Item {
998 attrs: self.attrs.clean(),
999 source: self.where.clean(),
1001 visibility: self.vis.clean(),
1002 inner: ImplItem(Impl {
1003 generics: self.generics.clean(),
1004 trait_: self.trait_.clean(),
1005 for_: self.for_.clean(),
1006 methods: self.methods.clean(),
1012 #[deriving(Clone, Encodable, Decodable)]
1013 pub struct ViewItem {
1014 inner: ViewItemInner
1017 impl Clean<Item> for ast::ViewItem {
1018 fn clean(&self) -> Item {
1021 attrs: self.attrs.clean(),
1022 source: self.span.clean(),
1024 visibility: self.vis.clean(),
1025 inner: ViewItemItem(ViewItem {
1026 inner: self.node.clean()
1032 #[deriving(Clone, Encodable, Decodable)]
1033 pub enum ViewItemInner {
1034 ExternMod(~str, Option<~str>, ast::NodeId),
1038 impl Clean<ViewItemInner> for ast::ViewItem_ {
1039 fn clean(&self) -> ViewItemInner {
1041 &ast::ViewItemExternMod(ref i, ref p, ref id) => {
1042 let string = match *p {
1044 Some((ref x, _)) => Some(x.get().to_owned()),
1046 ExternMod(i.clean(), string, *id)
1048 &ast::ViewItemUse(ref vp) => Import(vp.clean())
1053 #[deriving(Clone, Encodable, Decodable)]
1055 // use str = source;
1056 SimpleImport(~str, ImportSource),
1058 GlobImport(ImportSource),
1059 // use source::{a, b, c};
1060 ImportList(ImportSource, ~[ViewListIdent]),
1063 #[deriving(Clone, Encodable, Decodable)]
1064 pub struct ImportSource {
1066 did: Option<ast::DefId>,
1069 impl Clean<ViewPath> for ast::ViewPath {
1070 fn clean(&self) -> ViewPath {
1072 ast::ViewPathSimple(ref i, ref p, id) =>
1073 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1074 ast::ViewPathGlob(ref p, id) =>
1075 GlobImport(resolve_use_source(p.clean(), id)),
1076 ast::ViewPathList(ref p, ref pl, id) =>
1077 ImportList(resolve_use_source(p.clean(), id), pl.clean()),
1082 #[deriving(Clone, Encodable, Decodable)]
1083 pub struct ViewListIdent {
1085 source: Option<ast::DefId>,
1088 impl Clean<ViewListIdent> for ast::PathListIdent {
1089 fn clean(&self) -> ViewListIdent {
1091 name: self.node.name.clean(),
1092 source: resolve_def(self.node.id),
1097 impl Clean<~[Item]> for ast::ForeignMod {
1098 fn clean(&self) -> ~[Item] {
1103 impl Clean<Item> for ast::ForeignItem {
1104 fn clean(&self) -> Item {
1105 let inner = match self.node {
1106 ast::ForeignItemFn(ref decl, ref generics) => {
1107 ForeignFunctionItem(Function {
1109 generics: generics.clean(),
1110 purity: ast::ExternFn,
1113 ast::ForeignItemStatic(ref ty, mutbl) => {
1114 ForeignStaticItem(Static {
1116 mutability: if mutbl {Mutable} else {Immutable},
1122 name: Some(self.ident.clean()),
1123 attrs: self.attrs.clean(),
1124 source: self.span.clean(),
1126 visibility: self.vis.clean(),
1135 fn to_src(&self) -> ~str;
1138 impl ToSource for syntax::codemap::Span {
1139 fn to_src(&self) -> ~str {
1140 debug!("converting span {:?} to snippet", self.clean());
1141 let cm = local_data::get(super::ctxtkey, |x| x.unwrap().clone()).sess.codemap.clone();
1142 let sn = match cm.span_to_snippet(*self) {
1146 debug!("got snippet {}", sn);
1151 fn lit_to_str(lit: &ast::Lit) -> ~str {
1153 ast::LitStr(ref st, _) => st.get().to_owned(),
1154 ast::LitBinary(data) => format!("{:?}", data.as_slice()),
1155 ast::LitChar(c) => ~"'" + std::char::from_u32(c).unwrap().to_str() + "'",
1156 ast::LitInt(i, _t) => i.to_str(),
1157 ast::LitUint(u, _t) => u.to_str(),
1158 ast::LitIntUnsuffixed(i) => i.to_str(),
1159 ast::LitFloat(ref f, _t) => f.get().to_str(),
1160 ast::LitFloatUnsuffixed(ref f) => f.get().to_str(),
1161 ast::LitBool(b) => b.to_str(),
1166 fn name_from_pat(p: &ast::Pat) -> ~str {
1168 debug!("Trying to get a name from pattern: {:?}", p);
1172 PatWildMulti => ~"..",
1173 PatIdent(_, ref p, _) => path_to_str(p),
1174 PatEnum(ref p, _) => path_to_str(p),
1175 PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1176 which is not allowed in function arguments"),
1177 PatTup(..) => ~"(tuple arg NYI)",
1178 PatUniq(p) => name_from_pat(p),
1179 PatRegion(p) => name_from_pat(p),
1181 warn!("tried to get argument name from PatLit, \
1182 which is silly in function arguments");
1185 PatRange(..) => fail!("tried to get argument name from PatRange, \
1186 which is not allowed in function arguments"),
1187 PatVec(..) => fail!("tried to get argument name from pat_vec, \
1188 which is not allowed in function arguments")
1192 /// Given a Type, resolve it using the def_map
1193 fn resolve_type(path: Path, tpbs: Option<~[TyParamBound]>,
1194 id: ast::NodeId) -> Type {
1195 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1196 let tycx = match cx.tycx {
1198 // If we're extracting tests, this return value doesn't matter.
1201 debug!("searching for {:?} in defmap", id);
1202 let def_map = tycx.def_map.borrow();
1203 let d = match def_map.get().find(&id) {
1206 debug!("could not find {:?} in defmap (`{}`)", id,
1207 syntax::ast_map::node_id_to_str(tycx.items, id, cx.sess.intr()));
1208 fail!("Unexpected failure: unresolved id not in defmap (this is a bug!)")
1212 let (def_id, kind) = match *d {
1213 ast::DefFn(i, _) => (i, TypeFunction),
1214 ast::DefSelfTy(i) => return Self(i),
1215 ast::DefTy(i) => (i, TypeEnum),
1216 ast::DefTrait(i) => {
1217 debug!("saw DefTrait in def_to_id");
1220 ast::DefPrimTy(p) => match p {
1221 ast::TyStr => return String,
1222 ast::TyBool => return Bool,
1223 _ => return Primitive(p)
1225 ast::DefTyParam(i, _) => return Generic(i.node),
1226 ast::DefStruct(i) => (i, TypeStruct),
1227 ast::DefTyParamBinder(i) => {
1228 debug!("found a typaram_binder, what is it? {}", i);
1229 return TyParamBinder(i);
1231 x => fail!("resolved type maps to a weird def {:?}", x),
1233 if ast_util::is_local(def_id) {
1234 ResolvedPath{ path: path, typarams: tpbs, id: def_id.node }
1236 let fqn = csearch::get_item_path(tycx, def_id);
1237 let fqn = fqn.move_iter().map(|i| {
1239 ast_map::PathMod(id) | ast_map::PathName(id) |
1240 ast_map::PathPrettyName(id, _) => id.clean()
1243 ExternalPath{ path: path, typarams: tpbs, fqn: fqn, kind: kind,
1244 crate: def_id.crate }
1248 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
1251 did: resolve_def(id),
1255 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
1256 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1259 let def_map = tcx.def_map.borrow();
1260 def_map.get().find(&id).map(|&d| ast_util::def_id_of_def(d))