1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#![crate_type = "dylib"]
#![feature(plugin_registrar, rustc_private)]

extern crate syntax;
extern crate rustc_plugin;

use syntax::abi::Abi;
use syntax::ast::{self, Ident, Generics, Item, TraitItemKind, TraitRef, TraitItem, Path,
                  WhereClause, PathParameters, Ty, AngleBracketedParameterData,
                  PathSegment, ExprKind,Expr, ItemKind, StmtKind, Stmt, TyKind, MethodSig,
                  Unsafety, Constness, FunctionRetTy, FnDecl };
use syntax::codemap::{ self, Spanned};
use syntax::ext::base::{ExtCtxt, MultiModifier, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax::ptr::P;
use syntax::symbol::Symbol;
use syntax::tokenstream::{TokenStream};
use syntax::util::ThinVec;

use rustc_plugin::Registry;

#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(reg: &mut Registry) {
    reg.register_syntax_extension(Symbol::intern("trait_tests"),
                                  MultiModifier(Box::new(expand_meta_trait_test)));
}

fn expand_meta_trait_test(cx: &mut ExtCtxt,
                          span: codemap::Span,
                          _: &ast::MetaItem,
                          annot_item: Annotatable) -> Vec<Annotatable> {
    let item_kind;
    let item = annot_item.expect_item();
    {
        match item.node {
            ItemKind::Impl(_, _, _, _, Some(TraitRef { path: ref trait_ref, ref_id:_} ),
                            ref impl_type, _) => {
                // ![trait_tests] has been put on an implementation,
                // we need to generate a test that calls the test_all() function defined on the trait.
                //We look like: impl SetTestsisize for MySet<isize> {}

                let s : String = format!("{:?}",impl_type);
                let mut type_param = None;
                let type_impl_name : &str = if let Some(idx) = s.find('<') { // TODO dodgy
                    type_param = Some(&s[idx .. s.len() - 1]);
                    &s[5..idx]
                } else {
                    &s[5..s.len() - 1]
                };

                let trait_name = format!("{:?}", trait_ref); // TODO dodgy
                let trait_name_lower = trait_name[5..trait_name.len()-1].to_lowercase();

                let unangled = &(type_param.unwrap()[1 .. type_param.unwrap().len()-1]);//TODO dodgy

                let test_all_call = Stmt {
                    id: ast::DUMMY_NODE_ID,
                    node: StmtKind::Expr(P(Expr{
                        span,
                        attrs: ThinVec::new(),
                        id: ast::DUMMY_NODE_ID,
                        node: ExprKind::Call(P(Expr {
                            span,
                            attrs: ThinVec::new(),
                            id: ast::DUMMY_NODE_ID,
                            node:
                            ExprKind::Path(None, ::syntax::ast::Path {
                                span,
                                segments: vec![
                                    PathSegment { span, parameters: Some(P(PathParameters::AngleBracketed(AngleBracketedParameterData{
                                        span,
                                        lifetimes: vec![],
                                        bindings: vec![],
                                        types: vec![P(Ty{
                                            id: ast::DUMMY_NODE_ID,
                                            node : TyKind::Path(None,Path{segments: vec![ PathSegment{ span, parameters: None, identifier: Ident::from_str(unangled) } ], span}),//tODO!!
                                            span})]

                                    }))), identifier: Ident::from_str(type_impl_name) },//TODO dodgy
                                    PathSegment { span, parameters: None, identifier: Ident::from_str("test_all") },
                                ]
                            }
                            )
                        }), vec![])
                    })),
                    span,
                };

                let body = cx.block(span, vec![test_all_call]);

                let test = cx.item_fn(span, Ident::from_str(&(String::from("trait_test_")
                    + &type_impl_name.to_lowercase() +
                    "_" + &trait_name_lower )), vec![], cx.ty(span, TyKind::Tup(vec![])), body);

                // Copy attributes from original function
                let mut attrs = item.attrs.clone();

                // Add #[test] attribute
                attrs.push(cx.attribute(span, cx.meta_word(span, Symbol::intern("test"))));

                // Attach the attributes to the outer function
                let test_fn = Annotatable::Item(P(ast::Item {attrs, ..(*test).clone()}));

                return  vec![Annotatable::Item(P(Item{attrs: Vec::new(), ..(*item).clone() })), test_fn];
            },
            ItemKind::Trait(a, b, ref c, ref d, ref trait_items) => {
                // ![trait_tests] has been put on a trait, we need to generate a test_all() function.
                let mut test_names = vec![];

                for method in trait_items {
                    match method {
                        &TraitItem {
                            generics:Generics{ params: ref v, ..},
                            node:TraitItemKind::Method(
                                MethodSig{ decl: ref fn_decl, .. }, Some(_)),
                            ..
                        } if v.is_empty() => {
                            match **fn_decl {
                                FnDecl{inputs: ref args, ..} if args.is_empty() => {
                                    let fn_call = Stmt {
                                        id: ast::DUMMY_NODE_ID,
                                        node: StmtKind::Semi(P(Expr {
                                            id: ast::DUMMY_NODE_ID,
                                            node: ExprKind::Call(P(Expr {
                                                span,
                                                attrs: ThinVec::new(),
                                                id: ast::DUMMY_NODE_ID,
                                                node:
                                                ExprKind::Path(None, ::syntax::ast::Path {
                                                    span,
                                                    segments: vec![
                                                        PathSegment { span, parameters: None, identifier: Ident::from_str("Self") },
                                                        PathSegment { span, parameters: None, identifier: method.ident.clone() },
                                                    ]
                                                })
                                            }), vec![]),
                                            span,
                                            attrs: ThinVec::new()
                                        })),
                                        span,
                                    };
                                    test_names.push(fn_call);
                                },
                                _ => {}
                            }
                        },
                        _ => {}
                    }
                }

                let body = cx.block(span, test_names);

                let func = ::syntax::ast::TraitItemKind::Method(MethodSig {
                        abi: Abi::Rust,
                        constness: Spanned {
                            node: Constness::NotConst,
                            span
                        },
                        decl: P(FnDecl {
                            inputs: vec![],
                            output: FunctionRetTy::Default(
                                span
                            ),
                            variadic: false
                        }),

                        unsafety: Unsafety::Normal
                    }, Some(body) );

                let prop = ast::TraitItem {
                    attrs: Vec::new(),
                    ident: Ident::from_str("test_all"),
                    tokens: Some(TokenStream::empty()),
                    id:ast::DUMMY_NODE_ID,
                    span,
                    generics: Generics{span, where_clause:WhereClause{
                        id:ast::DUMMY_NODE_ID,
                        span,
                        predicates:vec![]}, params:vec![]},
                    node: func
                };

                let mut items = trait_items.clone();
                items.push(prop);
                item_kind = ItemKind::Trait(a, b, c.clone(), d.clone(), items);
                return vec![Annotatable::Item(P(Item{ node: item_kind, ..(*item).clone() }))]
            }
            _ => {
                cx.span_err(
                    span, "#[trait_tests] only supported on traits and associated impls");
            }
        }
    }
    vec![Annotatable::Item(P(Item{  ..(*item).clone() }))]
}