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)]
69 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 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
119 attrs: Vec<Attribute> ,
121 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 ViewItemItem(ViewItem),
178 TyMethodItem(TyMethod),
180 StructFieldItem(StructField),
181 VariantItem(Variant),
182 ForeignFunctionItem(Function),
183 ForeignStaticItem(Static),
187 #[deriving(Clone, Encodable, Decodable)]
193 impl Clean<Item> for doctree::Module {
194 fn clean(&self) -> Item {
195 let name = if self.name.is_some() {
196 self.name.unwrap().clean()
200 let mut foreigns = Vec::new();
201 for subforeigns in self.foreigns.clean().move_iter() {
202 for foreign in subforeigns.move_iter() {
203 foreigns.push(foreign)
206 let items: Vec<Vec<Item> > = vec!(
207 self.structs.clean().move_iter().collect(),
208 self.enums.clean().move_iter().collect(),
209 self.fns.clean().move_iter().collect(),
211 self.mods.clean().move_iter().collect(),
212 self.typedefs.clean().move_iter().collect(),
213 self.statics.clean().move_iter().collect(),
214 self.traits.clean().move_iter().collect(),
215 self.impls.clean().move_iter().collect(),
216 self.view_items.clean().move_iter().collect(),
217 self.macros.clean().move_iter().collect()
221 attrs: self.attrs.clean(),
222 source: self.where.clean(),
223 visibility: self.vis.clean(),
225 inner: ModuleItem(Module {
226 is_crate: self.is_crate,
228 .flat_map(|x| x.iter().map(|x| (*x).clone()))
235 #[deriving(Clone, Encodable, Decodable)]
238 List(~str, Vec<Attribute> ),
239 NameValue(~str, ~str)
242 impl Clean<Attribute> for ast::MetaItem {
243 fn clean(&self) -> Attribute {
245 ast::MetaWord(ref s) => Word(s.get().to_owned()),
246 ast::MetaList(ref s, ref l) => {
247 List(s.get().to_owned(), l.clean().move_iter().collect())
249 ast::MetaNameValue(ref s, ref v) => {
250 NameValue(s.get().to_owned(), lit_to_str(v))
256 impl Clean<Attribute> for ast::Attribute {
257 fn clean(&self) -> Attribute {
258 self.desugar_doc().node.value.clean()
262 // This is a rough approximation that gets us what we want.
263 impl<'a> attr::AttrMetaMethods for &'a Attribute {
264 fn name(&self) -> InternedString {
266 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
267 token::intern_and_get_ident(*n)
272 fn value_str(&self) -> Option<InternedString> {
274 NameValue(_, ref v) => Some(token::intern_and_get_ident(*v)),
278 fn meta_item_list<'a>(&'a self) -> Option<&'a [@ast::MetaItem]> { None }
279 fn name_str_pair(&self) -> Option<(InternedString, InternedString)> {
284 #[deriving(Clone, Encodable, Decodable)]
288 bounds: Vec<TyParamBound> }
290 impl Clean<TyParam> for ast::TyParam {
291 fn clean(&self) -> TyParam {
293 name: self.ident.clean(),
295 bounds: self.bounds.clean().move_iter().collect(),
300 #[deriving(Clone, Encodable, Decodable)]
301 pub enum TyParamBound {
306 impl Clean<TyParamBound> for ast::TyParamBound {
307 fn clean(&self) -> TyParamBound {
309 ast::RegionTyParamBound => RegionBound,
310 ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
315 #[deriving(Clone, Encodable, Decodable)]
316 pub struct Lifetime(~str);
319 pub fn get_ref<'a>(&'a self) -> &'a str {
320 let Lifetime(ref s) = *self;
326 impl Clean<Lifetime> for ast::Lifetime {
327 fn clean(&self) -> Lifetime {
328 Lifetime(token::get_name(self.name).get().to_owned())
332 // maybe use a Generic enum and use ~[Generic]?
333 #[deriving(Clone, Encodable, Decodable)]
334 pub struct Generics {
335 lifetimes: Vec<Lifetime> ,
336 type_params: Vec<TyParam> }
338 impl Clean<Generics> for ast::Generics {
339 fn clean(&self) -> Generics {
341 lifetimes: self.lifetimes.clean().move_iter().collect(),
342 type_params: self.ty_params.clean().move_iter().collect(),
347 #[deriving(Clone, Encodable, Decodable)]
355 impl Clean<Item> for ast::Method {
356 fn clean(&self) -> Item {
357 let inputs = match self.explicit_self.node {
358 ast::SelfStatic => self.decl.inputs.as_slice(),
359 _ => self.decl.inputs.slice_from(1)
363 values: inputs.iter().map(|x| x.clean()).collect(),
365 output: (self.decl.output.clean()),
366 cf: self.decl.cf.clean(),
370 name: Some(self.ident.clean()),
371 attrs: self.attrs.clean().move_iter().collect(),
372 source: self.span.clean(),
374 visibility: self.vis.clean(),
375 inner: MethodItem(Method {
376 generics: self.generics.clean(),
377 self_: self.explicit_self.clean(),
378 purity: self.purity.clone(),
385 #[deriving(Clone, Encodable, Decodable)]
386 pub struct TyMethod {
393 impl Clean<Item> for ast::TypeMethod {
394 fn clean(&self) -> Item {
395 let inputs = match self.explicit_self.node {
396 ast::SelfStatic => self.decl.inputs.as_slice(),
397 _ => self.decl.inputs.slice_from(1)
401 values: inputs.iter().map(|x| x.clean()).collect(),
403 output: (self.decl.output.clean()),
404 cf: self.decl.cf.clean(),
408 name: Some(self.ident.clean()),
409 attrs: self.attrs.clean().move_iter().collect(),
410 source: self.span.clean(),
413 inner: TyMethodItem(TyMethod {
414 purity: self.purity.clone(),
416 self_: self.explicit_self.clean(),
417 generics: self.generics.clean(),
423 #[deriving(Clone, Encodable, Decodable)]
427 SelfBorrowed(Option<Lifetime>, Mutability),
431 impl Clean<SelfTy> for ast::ExplicitSelf {
432 fn clean(&self) -> SelfTy {
434 ast::SelfStatic => SelfStatic,
435 ast::SelfValue => SelfValue,
436 ast::SelfUniq => SelfOwned,
437 ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()),
442 #[deriving(Clone, Encodable, Decodable)]
443 pub struct Function {
449 impl Clean<Item> for doctree::Function {
450 fn clean(&self) -> Item {
452 name: Some(self.name.clean()),
453 attrs: self.attrs.clean(),
454 source: self.where.clean(),
455 visibility: self.vis.clean(),
457 inner: FunctionItem(Function {
458 decl: self.decl.clean(),
459 generics: self.generics.clean(),
466 #[deriving(Clone, Encodable, Decodable)]
467 pub struct ClosureDecl {
469 region: Option<Lifetime>,
470 lifetimes: Vec<Lifetime> ,
472 onceness: ast::Onceness,
474 bounds: Vec<TyParamBound> }
476 impl Clean<ClosureDecl> for ast::ClosureTy {
477 fn clean(&self) -> ClosureDecl {
480 region: self.region.clean(),
481 lifetimes: self.lifetimes.clean().move_iter().collect(),
482 decl: self.decl.clean(),
483 onceness: self.onceness,
485 bounds: match self.bounds {
486 Some(ref x) => x.clean().move_iter().collect(),
493 #[deriving(Clone, Encodable, Decodable)]
498 attrs: Vec<Attribute> }
500 #[deriving(Clone, Encodable, Decodable)]
501 pub struct Arguments {
502 values: Vec<Argument> ,
505 impl Clean<FnDecl> for ast::FnDecl {
506 fn clean(&self) -> FnDecl {
509 values: self.inputs.iter().map(|x| x.clean()).collect(),
511 output: (self.output.clean()),
518 #[deriving(Clone, Encodable, Decodable)]
519 pub struct Argument {
525 impl Clean<Argument> for ast::Arg {
526 fn clean(&self) -> Argument {
528 name: name_from_pat(self.pat),
529 type_: (self.ty.clean()),
535 #[deriving(Clone, Encodable, Decodable)]
541 impl Clean<RetStyle> for ast::RetStyle {
542 fn clean(&self) -> RetStyle {
544 ast::Return => Return,
545 ast::NoReturn => NoReturn
550 #[deriving(Clone, Encodable, Decodable)]
552 methods: Vec<TraitMethod> ,
557 impl Clean<Item> for doctree::Trait {
558 fn clean(&self) -> Item {
560 name: Some(self.name.clean()),
561 attrs: self.attrs.clean(),
562 source: self.where.clean(),
564 visibility: self.vis.clean(),
565 inner: TraitItem(Trait {
566 methods: self.methods.clean(),
567 generics: self.generics.clean(),
568 parents: self.parents.clean(),
574 impl Clean<Type> for ast::TraitRef {
575 fn clean(&self) -> Type {
576 resolve_type(self.path.clean(), None, self.ref_id)
580 #[deriving(Clone, Encodable, Decodable)]
581 pub enum TraitMethod {
587 pub fn is_req(&self) -> bool {
589 &Required(..) => true,
593 pub fn is_def(&self) -> bool {
595 &Provided(..) => true,
599 pub fn item<'a>(&'a self) -> &'a Item {
601 Required(ref item) => item,
602 Provided(ref item) => item,
607 impl Clean<TraitMethod> for ast::TraitMethod {
608 fn clean(&self) -> TraitMethod {
610 &ast::Required(ref t) => Required(t.clean()),
611 &ast::Provided(ref t) => Provided(t.clean()),
616 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
617 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
618 /// it does not preserve mutability or boxes.
619 #[deriving(Clone, Encodable, Decodable)]
621 /// structs/enums/traits (anything that'd be an ast::TyPath)
624 typarams: Option<Vec<TyParamBound> >,
627 /// Same as above, but only external variants
630 typarams: Option<Vec<TyParamBound> >,
633 krate: ast::CrateNum,
635 // I have no idea how to usefully use this.
636 TyParamBinder(ast::NodeId),
637 /// For parameterized types, so the consumer of the JSON don't go looking
638 /// for types which don't exist anywhere.
639 Generic(ast::NodeId),
640 /// For references to self
642 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
643 Primitive(ast::PrimTy),
644 Closure(~ClosureDecl),
646 BareFunction(~BareFunctionDecl),
649 FixedVector(~Type, ~str),
658 RawPointer(Mutability, ~Type),
659 BorrowedRef { lifetime: Option<Lifetime>, mutability: Mutability, type_: ~Type},
660 // region, raw, other boxes, mutable
663 #[deriving(Clone, Encodable, Decodable)]
671 impl Clean<Type> for ast::Ty {
672 fn clean(&self) -> Type {
674 debug!("cleaning type `{:?}`", self);
675 let codemap = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess().codemap();
676 debug!("span corresponds to `{}`", codemap.span_to_str(self.span));
679 TyPtr(ref m) => RawPointer(m.mutbl.clean(), ~m.ty.clean()),
680 TyRptr(ref l, ref m) =>
681 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
682 type_: ~m.ty.clean()},
683 TyBox(ty) => Managed(~ty.clean()),
684 TyUniq(ty) => Unique(~ty.clean()),
685 TyVec(ty) => Vector(~ty.clean()),
686 TyFixedLengthVec(ty, ref e) => FixedVector(~ty.clean(),
688 TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
689 TyPath(ref p, ref tpbs, id) => {
690 resolve_type(p.clean(),
691 tpbs.clean().map(|x| x.move_iter().collect()),
694 TyClosure(ref c) => Closure(~c.clean()),
695 TyBareFn(ref barefn) => BareFunction(~barefn.clean()),
697 ref x => fail!("Unimplemented type {:?}", x),
702 #[deriving(Clone, Encodable, Decodable)]
703 pub struct StructField {
707 impl Clean<Item> for ast::StructField {
708 fn clean(&self) -> Item {
709 let (name, vis) = match self.node.kind {
710 ast::NamedField(id, vis) => (Some(id), Some(vis)),
715 attrs: self.node.attrs.clean().move_iter().collect(),
716 source: self.span.clean(),
719 inner: StructFieldItem(StructField {
720 type_: self.node.ty.clean(),
726 pub type Visibility = ast::Visibility;
728 impl Clean<Option<Visibility>> for ast::Visibility {
729 fn clean(&self) -> Option<Visibility> {
734 #[deriving(Clone, Encodable, Decodable)]
736 struct_type: doctree::StructType,
739 fields_stripped: bool,
742 impl Clean<Item> for doctree::Struct {
743 fn clean(&self) -> Item {
745 name: Some(self.name.clean()),
746 attrs: self.attrs.clean(),
747 source: self.where.clean(),
749 visibility: self.vis.clean(),
750 inner: StructItem(Struct {
751 struct_type: self.struct_type,
752 generics: self.generics.clean(),
753 fields: self.fields.clean(),
754 fields_stripped: false,
760 /// This is a more limited form of the standard Struct, different in that
761 /// it lacks the things most items have (name, id, parameterization). Found
762 /// only as a variant in an enum.
763 #[deriving(Clone, Encodable, Decodable)]
764 pub struct VariantStruct {
765 struct_type: doctree::StructType,
767 fields_stripped: bool,
770 impl Clean<VariantStruct> for syntax::ast::StructDef {
771 fn clean(&self) -> VariantStruct {
773 struct_type: doctree::struct_type_from_def(self),
774 fields: self.fields.clean().move_iter().collect(),
775 fields_stripped: false,
780 #[deriving(Clone, Encodable, Decodable)]
782 variants: Vec<Item> ,
784 variants_stripped: bool,
787 impl Clean<Item> for doctree::Enum {
788 fn clean(&self) -> Item {
790 name: Some(self.name.clean()),
791 attrs: self.attrs.clean(),
792 source: self.where.clean(),
794 visibility: self.vis.clean(),
795 inner: EnumItem(Enum {
796 variants: self.variants.clean(),
797 generics: self.generics.clean(),
798 variants_stripped: false,
804 #[deriving(Clone, Encodable, Decodable)]
809 impl Clean<Item> for doctree::Variant {
810 fn clean(&self) -> Item {
812 name: Some(self.name.clean()),
813 attrs: self.attrs.clean(),
814 source: self.where.clean(),
815 visibility: self.vis.clean(),
817 inner: VariantItem(Variant {
818 kind: self.kind.clean(),
824 #[deriving(Clone, Encodable, Decodable)]
825 pub enum VariantKind {
827 TupleVariant(Vec<Type> ),
828 StructVariant(VariantStruct),
831 impl Clean<VariantKind> for ast::VariantKind {
832 fn clean(&self) -> VariantKind {
834 &ast::TupleVariantKind(ref args) => {
838 TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
841 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
846 #[deriving(Clone, Encodable, Decodable)]
855 impl Clean<Span> for syntax::codemap::Span {
856 fn clean(&self) -> Span {
857 let cm = local_data::get(super::ctxtkey, |x| *x.unwrap()).sess().codemap();
858 let filename = cm.span_to_filename(*self);
859 let lo = cm.lookup_char_pos(self.lo);
860 let hi = cm.lookup_char_pos(self.hi);
862 filename: filename.to_owned(),
864 locol: lo.col.to_uint(),
866 hicol: hi.col.to_uint(),
871 #[deriving(Clone, Encodable, Decodable)]
874 segments: Vec<PathSegment> ,
877 impl Clean<Path> for ast::Path {
878 fn clean(&self) -> Path {
881 segments: self.segments.clean().move_iter().collect(),
886 #[deriving(Clone, Encodable, Decodable)]
887 pub struct PathSegment {
889 lifetimes: Vec<Lifetime> ,
893 impl Clean<PathSegment> for ast::PathSegment {
894 fn clean(&self) -> PathSegment {
896 name: self.identifier.clean(),
897 lifetimes: self.lifetimes.clean().move_iter().collect(),
898 types: self.types.clean().move_iter().collect()
903 fn path_to_str(p: &ast::Path) -> ~str {
904 use syntax::parse::token;
907 let mut first = true;
908 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
909 if !first || p.global {
919 impl Clean<~str> for ast::Ident {
920 fn clean(&self) -> ~str {
921 token::get_ident(*self).get().to_owned()
925 #[deriving(Clone, Encodable, Decodable)]
931 impl Clean<Item> for doctree::Typedef {
932 fn clean(&self) -> Item {
934 name: Some(self.name.clean()),
935 attrs: self.attrs.clean(),
936 source: self.where.clean(),
938 visibility: self.vis.clean(),
939 inner: TypedefItem(Typedef {
940 type_: self.ty.clean(),
941 generics: self.gen.clean(),
947 #[deriving(Clone, Encodable, Decodable)]
948 pub struct BareFunctionDecl {
955 impl Clean<BareFunctionDecl> for ast::BareFnTy {
956 fn clean(&self) -> BareFunctionDecl {
960 lifetimes: self.lifetimes.clean().move_iter().collect(),
961 type_params: Vec::new(),
963 decl: self.decl.clean(),
964 abi: self.abis.to_str(),
969 #[deriving(Clone, Encodable, Decodable)]
972 mutability: Mutability,
973 /// It's useful to have the value of a static documented, but I have no
974 /// desire to represent expressions (that'd basically be all of the AST,
975 /// which is huge!). So, have a string.
979 impl Clean<Item> for doctree::Static {
980 fn clean(&self) -> Item {
981 debug!("claning static {}: {:?}", self.name.clean(), self);
983 name: Some(self.name.clean()),
984 attrs: self.attrs.clean(),
985 source: self.where.clean(),
987 visibility: self.vis.clean(),
988 inner: StaticItem(Static {
989 type_: self.type_.clean(),
990 mutability: self.mutability.clean(),
991 expr: self.expr.span.to_src(),
997 #[deriving(Show, Clone, Encodable, Decodable)]
998 pub enum Mutability {
1003 impl Clean<Mutability> for ast::Mutability {
1004 fn clean(&self) -> Mutability {
1006 &ast::MutMutable => Mutable,
1007 &ast::MutImmutable => Immutable,
1012 #[deriving(Clone, Encodable, Decodable)]
1015 trait_: Option<Type>,
1017 methods: Vec<Item> ,
1020 impl Clean<Item> for doctree::Impl {
1021 fn clean(&self) -> Item {
1024 attrs: self.attrs.clean(),
1025 source: self.where.clean(),
1027 visibility: self.vis.clean(),
1028 inner: ImplItem(Impl {
1029 generics: self.generics.clean(),
1030 trait_: self.trait_.clean(),
1031 for_: self.for_.clean(),
1032 methods: self.methods.clean(),
1038 #[deriving(Clone, Encodable, Decodable)]
1039 pub struct ViewItem {
1040 inner: ViewItemInner
1043 impl Clean<Item> for ast::ViewItem {
1044 fn clean(&self) -> Item {
1047 attrs: self.attrs.clean().move_iter().collect(),
1048 source: self.span.clean(),
1050 visibility: self.vis.clean(),
1051 inner: ViewItemItem(ViewItem {
1052 inner: self.node.clean()
1058 #[deriving(Clone, Encodable, Decodable)]
1059 pub enum ViewItemInner {
1060 ExternCrate(~str, Option<~str>, ast::NodeId),
1061 Import(Vec<ViewPath>)
1064 impl Clean<ViewItemInner> for ast::ViewItem_ {
1065 fn clean(&self) -> ViewItemInner {
1067 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1068 let string = match *p {
1070 Some((ref x, _)) => Some(x.get().to_owned()),
1072 ExternCrate(i.clean(), string, *id)
1074 &ast::ViewItemUse(ref vp) => {
1075 Import(vp.clean().move_iter().collect())
1081 #[deriving(Clone, Encodable, Decodable)]
1083 // use str = source;
1084 SimpleImport(~str, ImportSource),
1086 GlobImport(ImportSource),
1087 // use source::{a, b, c};
1088 ImportList(ImportSource, Vec<ViewListIdent> ),
1091 #[deriving(Clone, Encodable, Decodable)]
1092 pub struct ImportSource {
1094 did: Option<ast::DefId>,
1097 impl Clean<ViewPath> for ast::ViewPath {
1098 fn clean(&self) -> ViewPath {
1100 ast::ViewPathSimple(ref i, ref p, id) =>
1101 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1102 ast::ViewPathGlob(ref p, id) =>
1103 GlobImport(resolve_use_source(p.clean(), id)),
1104 ast::ViewPathList(ref p, ref pl, id) => {
1105 ImportList(resolve_use_source(p.clean(), id),
1106 pl.clean().move_iter().collect())
1112 #[deriving(Clone, Encodable, Decodable)]
1113 pub struct ViewListIdent {
1115 source: Option<ast::DefId>,
1118 impl Clean<ViewListIdent> for ast::PathListIdent {
1119 fn clean(&self) -> ViewListIdent {
1121 name: self.node.name.clean(),
1122 source: resolve_def(self.node.id),
1127 impl Clean<Vec<Item>> for ast::ForeignMod {
1128 fn clean(&self) -> Vec<Item> {
1133 impl Clean<Item> for ast::ForeignItem {
1134 fn clean(&self) -> Item {
1135 let inner = match self.node {
1136 ast::ForeignItemFn(ref decl, ref generics) => {
1137 ForeignFunctionItem(Function {
1139 generics: generics.clean(),
1140 purity: ast::ExternFn,
1143 ast::ForeignItemStatic(ref ty, mutbl) => {
1144 ForeignStaticItem(Static {
1146 mutability: if mutbl {Mutable} else {Immutable},
1152 name: Some(self.ident.clean()),
1153 attrs: self.attrs.clean().move_iter().collect(),
1154 source: self.span.clean(),
1156 visibility: self.vis.clean(),
1165 fn to_src(&self) -> ~str;
1168 impl ToSource for syntax::codemap::Span {
1169 fn to_src(&self) -> ~str {
1170 debug!("converting span {:?} to snippet", self.clean());
1171 let cm = local_data::get(super::ctxtkey, |x| x.unwrap().clone()).sess().codemap().clone();
1172 let sn = match cm.span_to_snippet(*self) {
1176 debug!("got snippet {}", sn);
1181 fn lit_to_str(lit: &ast::Lit) -> ~str {
1183 ast::LitStr(ref st, _) => st.get().to_owned(),
1184 ast::LitBinary(ref data) => format!("{:?}", data.deref().as_slice()),
1185 ast::LitChar(c) => ~"'" + std::char::from_u32(c).unwrap().to_str() + "'",
1186 ast::LitInt(i, _t) => i.to_str(),
1187 ast::LitUint(u, _t) => u.to_str(),
1188 ast::LitIntUnsuffixed(i) => i.to_str(),
1189 ast::LitFloat(ref f, _t) => f.get().to_str(),
1190 ast::LitFloatUnsuffixed(ref f) => f.get().to_str(),
1191 ast::LitBool(b) => b.to_str(),
1196 fn name_from_pat(p: &ast::Pat) -> ~str {
1198 debug!("Trying to get a name from pattern: {:?}", p);
1202 PatWildMulti => ~"..",
1203 PatIdent(_, ref p, _) => path_to_str(p),
1204 PatEnum(ref p, _) => path_to_str(p),
1205 PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1206 which is not allowed in function arguments"),
1207 PatTup(..) => ~"(tuple arg NYI)",
1208 PatUniq(p) => name_from_pat(p),
1209 PatRegion(p) => name_from_pat(p),
1211 warn!("tried to get argument name from PatLit, \
1212 which is silly in function arguments");
1215 PatRange(..) => fail!("tried to get argument name from PatRange, \
1216 which is not allowed in function arguments"),
1217 PatVec(..) => fail!("tried to get argument name from pat_vec, \
1218 which is not allowed in function arguments")
1222 /// Given a Type, resolve it using the def_map
1223 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound> >,
1224 id: ast::NodeId) -> Type {
1225 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1226 let tycx = match cx.maybe_typed {
1227 core::Typed(ref tycx) => tycx,
1228 // If we're extracting tests, this return value doesn't matter.
1229 core::NotTyped(_) => return Bool
1231 debug!("searching for {:?} in defmap", id);
1232 let d = match tycx.def_map.borrow().find(&id) {
1235 debug!("could not find {:?} in defmap (`{}`)", id, tycx.map.node_to_str(id));
1236 fail!("Unexpected failure: unresolved id not in defmap (this is a bug!)")
1240 let (def_id, kind) = match d {
1241 ast::DefFn(i, _) => (i, TypeFunction),
1242 ast::DefSelfTy(i) => return Self(i),
1243 ast::DefTy(i) => (i, TypeEnum),
1244 ast::DefTrait(i) => {
1245 debug!("saw DefTrait in def_to_id");
1248 ast::DefPrimTy(p) => match p {
1249 ast::TyStr => return String,
1250 ast::TyBool => return Bool,
1251 _ => return Primitive(p)
1253 ast::DefTyParam(i, _) => return Generic(i.node),
1254 ast::DefStruct(i) => (i, TypeStruct),
1255 ast::DefTyParamBinder(i) => {
1256 debug!("found a typaram_binder, what is it? {}", i);
1257 return TyParamBinder(i);
1259 x => fail!("resolved type maps to a weird def {:?}", x),
1261 if ast_util::is_local(def_id) {
1262 ResolvedPath{ path: path, typarams: tpbs, id: def_id.node }
1264 let fqn = csearch::get_item_path(tycx, def_id);
1265 let fqn = fqn.move_iter().map(|i| i.to_str()).collect();
1271 krate: def_id.krate,
1276 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
1279 did: resolve_def(id),
1283 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
1284 let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
1285 match cx.maybe_typed {
1286 core::Typed(ref tcx) => {
1287 tcx.def_map.borrow().find(&id).map(|&d| ast_util::def_id_of_def(d))
1289 core::NotTyped(_) => None
1293 #[deriving(Clone, Encodable, Decodable)]
1298 impl Clean<Item> for doctree::Macro {
1299 fn clean(&self) -> Item {
1301 name: Some(self.name.clean()),
1302 attrs: self.attrs.clean(),
1303 source: self.where.clean(),
1304 visibility: ast::Public.clean(),
1306 inner: MacroItem(Macro {
1307 source: self.where.to_src(),