]> git.lizzy.rs Git - rust.git/blob - src/librustc/front/test.rs
Get "make check" to work with unused-attribute
[rust.git] / src / librustc / front / test.rs
1 // Copyright 2012-2014 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.
4 //
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.
10
11 // Code that generates a test runner to run all the tests in a crate
12
13 #![allow(dead_code)]
14 #![allow(unused_imports)]
15
16 use driver::session::Session;
17 use front::config;
18 use front::std_inject::with_version;
19 use metadata::creader::Loader;
20
21 use std::cell::RefCell;
22 use std::slice;
23 use std::vec::Vec;
24 use std::vec;
25 use syntax::ast_util::*;
26 use syntax::attr::AttrMetaMethods;
27 use syntax::attr;
28 use syntax::codemap::{DUMMY_SP, Span, ExpnInfo, NameAndSpan, MacroAttribute};
29 use syntax::codemap;
30 use syntax::ext::base::ExtCtxt;
31 use syntax::ext::expand::ExpansionConfig;
32 use syntax::fold::Folder;
33 use syntax::fold;
34 use syntax::owned_slice::OwnedSlice;
35 use syntax::parse::token::InternedString;
36 use syntax::parse::token;
37 use syntax::print::pprust;
38 use syntax::{ast, ast_util};
39 use syntax::util::small_vector::SmallVector;
40
41 struct Test {
42     span: Span,
43     path: Vec<ast::Ident> ,
44     bench: bool,
45     ignore: bool,
46     should_fail: bool
47 }
48
49 struct TestCtxt<'a> {
50     sess: &'a Session,
51     path: RefCell<Vec<ast::Ident>>,
52     ext_cx: ExtCtxt<'a>,
53     testfns: RefCell<Vec<Test> >,
54     is_test_crate: bool,
55     config: ast::CrateConfig,
56 }
57
58 // Traverse the crate, collecting all the test functions, eliding any
59 // existing main functions, and synthesizing a main test harness
60 pub fn modify_for_testing(sess: &Session,
61                           krate: ast::Crate) -> ast::Crate {
62     // We generate the test harness when building in the 'test'
63     // configuration, either with the '--test' or '--cfg test'
64     // command line options.
65     let should_test = attr::contains_name(krate.config.as_slice(), "test");
66
67     if should_test {
68         generate_test_harness(sess, krate)
69     } else {
70         strip_test_functions(krate)
71     }
72 }
73
74 struct TestHarnessGenerator<'a> {
75     cx: TestCtxt<'a>,
76 }
77
78 impl<'a> fold::Folder for TestHarnessGenerator<'a> {
79     fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
80         let folded = fold::noop_fold_crate(c, self);
81
82         // Add a special __test module to the crate that will contain code
83         // generated for the test harness
84         ast::Crate {
85             module: add_test_module(&self.cx, &folded.module),
86             .. folded
87         }
88     }
89
90     fn fold_item(&mut self, i: @ast::Item) -> SmallVector<@ast::Item> {
91         self.cx.path.borrow_mut().push(i.ident);
92         debug!("current path: {}",
93                ast_util::path_name_i(self.cx.path.borrow().as_slice()));
94
95         if is_test_fn(&self.cx, i) || is_bench_fn(&self.cx, i) {
96             match i.node {
97                 ast::ItemFn(_, ast::UnsafeFn, _, _, _) => {
98                     let sess = self.cx.sess;
99                     sess.span_fatal(i.span,
100                                     "unsafe functions cannot be used for \
101                                      tests");
102                 }
103                 _ => {
104                     debug!("this is a test function");
105                     let test = Test {
106                         span: i.span,
107                         path: self.cx.path.borrow().clone(),
108                         bench: is_bench_fn(&self.cx, i),
109                         ignore: is_ignored(&self.cx, i),
110                         should_fail: should_fail(i)
111                     };
112                     self.cx.testfns.borrow_mut().push(test);
113                     // debug!("have {} test/bench functions",
114                     //        cx.testfns.len());
115                 }
116             }
117         }
118
119         let res = fold::noop_fold_item(i, self);
120         self.cx.path.borrow_mut().pop();
121         res
122     }
123
124     fn fold_mod(&mut self, m: &ast::Mod) -> ast::Mod {
125         // Remove any #[main] from the AST so it doesn't clash with
126         // the one we're going to add. Only if compiling an executable.
127
128         fn nomain(item: @ast::Item) -> @ast::Item {
129             @ast::Item {
130                 attrs: item.attrs.iter().filter_map(|attr| {
131                     if !attr.name().equiv(&("main")) {
132                         Some(*attr)
133                     } else {
134                         None
135                     }
136                 }).collect(),
137                 .. (*item).clone()
138             }
139         }
140
141         let mod_nomain = ast::Mod {
142             inner: m.inner,
143             view_items: m.view_items.clone(),
144             items: m.items.iter().map(|i| nomain(*i)).collect(),
145         };
146
147         fold::noop_fold_mod(&mod_nomain, self)
148     }
149 }
150
151 fn generate_test_harness(sess: &Session, krate: ast::Crate)
152                          -> ast::Crate {
153     let loader = &mut Loader::new(sess);
154     let mut cx: TestCtxt = TestCtxt {
155         sess: sess,
156         ext_cx: ExtCtxt::new(&sess.parse_sess, sess.opts.cfg.clone(),
157                              ExpansionConfig {
158                                  loader: loader,
159                                  deriving_hash_type_parameter: false,
160                                  crate_id: from_str("test").unwrap(),
161                              }),
162         path: RefCell::new(Vec::new()),
163         testfns: RefCell::new(Vec::new()),
164         is_test_crate: is_test_crate(&krate),
165         config: krate.config.clone(),
166     };
167
168     cx.ext_cx.bt_push(ExpnInfo {
169         call_site: DUMMY_SP,
170         callee: NameAndSpan {
171             name: "test".to_strbuf(),
172             format: MacroAttribute,
173             span: None
174         }
175     });
176
177     let mut fold = TestHarnessGenerator {
178         cx: cx
179     };
180     let res = fold.fold_crate(krate);
181     fold.cx.ext_cx.bt_pop();
182     return res;
183 }
184
185 fn strip_test_functions(krate: ast::Crate) -> ast::Crate {
186     // When not compiling with --test we should not compile the
187     // #[test] functions
188     config::strip_items(krate, |attrs| {
189         !attr::contains_name(attrs.as_slice(), "test") &&
190         !attr::contains_name(attrs.as_slice(), "bench")
191     })
192 }
193
194 fn is_test_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
195     let has_test_attr = attr::contains_name(i.attrs.as_slice(), "test");
196
197     fn has_test_signature(i: @ast::Item) -> bool {
198         match &i.node {
199           &ast::ItemFn(ref decl, _, _, ref generics, _) => {
200             let no_output = match decl.output.node {
201                 ast::TyNil => true,
202                 _ => false
203             };
204             decl.inputs.is_empty()
205                 && no_output
206                 && !generics.is_parameterized()
207           }
208           _ => false
209         }
210     }
211
212     if has_test_attr && !has_test_signature(i) {
213         let sess = cx.sess;
214         sess.span_err(
215             i.span,
216             "functions used as tests must have signature fn() -> ()."
217         );
218     }
219
220     return has_test_attr && has_test_signature(i);
221 }
222
223 fn is_bench_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
224     let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "bench");
225
226     fn has_test_signature(i: @ast::Item) -> bool {
227         match i.node {
228             ast::ItemFn(ref decl, _, _, ref generics, _) => {
229                 let input_cnt = decl.inputs.len();
230                 let no_output = match decl.output.node {
231                     ast::TyNil => true,
232                     _ => false
233                 };
234                 let tparm_cnt = generics.ty_params.len();
235                 // NB: inadequate check, but we're running
236                 // well before resolve, can't get too deep.
237                 input_cnt == 1u
238                     && no_output && tparm_cnt == 0u
239             }
240           _ => false
241         }
242     }
243
244     if has_bench_attr && !has_test_signature(i) {
245         let sess = cx.sess;
246         sess.span_err(i.span, "functions used as benches must have signature \
247                       `fn(&mut Bencher) -> ()`");
248     }
249
250     return has_bench_attr && has_test_signature(i);
251 }
252
253 fn is_ignored(cx: &TestCtxt, i: @ast::Item) -> bool {
254     i.attrs.iter().any(|attr| {
255         // check ignore(cfg(foo, bar))
256         attr.check_name("ignore") && match attr.meta_item_list() {
257             Some(ref cfgs) => {
258                 attr::test_cfg(cx.config.as_slice(), cfgs.iter().map(|x| *x))
259             }
260             None => true
261         }
262     })
263 }
264
265 fn should_fail(i: @ast::Item) -> bool {
266     attr::contains_name(i.attrs.as_slice(), "should_fail")
267 }
268
269 fn add_test_module(cx: &TestCtxt, m: &ast::Mod) -> ast::Mod {
270     let testmod = mk_test_module(cx);
271     ast::Mod {
272         items: m.items.clone().append_one(testmod),
273         ..(*m).clone()
274     }
275 }
276
277 /*
278
279 We're going to be building a module that looks more or less like:
280
281 mod __test {
282   #![!resolve_unexported]
283   extern crate test (name = "test", vers = "...");
284   fn main() {
285     test::test_main_static(::os::args().as_slice(), tests)
286   }
287
288   static tests : &'static [test::TestDescAndFn] = &[
289     ... the list of tests in the crate ...
290   ];
291 }
292
293 */
294
295 fn mk_std(cx: &TestCtxt) -> ast::ViewItem {
296     let id_test = token::str_to_ident("test");
297     let (vi, vis) = if cx.is_test_crate {
298         (ast::ViewItemUse(
299             @nospan(ast::ViewPathSimple(id_test,
300                                         path_node(vec!(id_test)),
301                                         ast::DUMMY_NODE_ID))),
302          ast::Public)
303     } else {
304         (ast::ViewItemExternCrate(id_test,
305                                with_version("test"),
306                                ast::DUMMY_NODE_ID),
307          ast::Inherited)
308     };
309     ast::ViewItem {
310         node: vi,
311         attrs: Vec::new(),
312         vis: vis,
313         span: DUMMY_SP
314     }
315 }
316
317 fn mk_test_module(cx: &TestCtxt) -> @ast::Item {
318     // Link to test crate
319     let view_items = vec!(mk_std(cx));
320
321     // A constant vector of test descriptors.
322     let tests = mk_tests(cx);
323
324     // The synthesized main function which will call the console test runner
325     // with our list of tests
326     let mainfn = (quote_item!(&cx.ext_cx,
327         pub fn main() {
328             #![main]
329             use std::slice::Vector;
330             test::test_main_static(::std::os::args().as_slice(), TESTS);
331         }
332     )).unwrap();
333
334     let testmod = ast::Mod {
335         inner: DUMMY_SP,
336         view_items: view_items,
337         items: vec!(mainfn, tests),
338     };
339     let item_ = ast::ItemMod(testmod);
340
341     // This attribute tells resolve to let us call unexported functions
342     let resolve_unexported_str = InternedString::new("!resolve_unexported");
343     let resolve_unexported_attr =
344         attr::mk_attr_inner(attr::mk_attr_id(),
345                             attr::mk_word_item(resolve_unexported_str));
346
347     let item = ast::Item {
348         ident: token::str_to_ident("__test"),
349         attrs: vec!(resolve_unexported_attr),
350         id: ast::DUMMY_NODE_ID,
351         node: item_,
352         vis: ast::Public,
353         span: DUMMY_SP,
354      };
355
356     debug!("Synthetic test module:\n{}\n", pprust::item_to_str(&item));
357
358     return @item;
359 }
360
361 fn nospan<T>(t: T) -> codemap::Spanned<T> {
362     codemap::Spanned { node: t, span: DUMMY_SP }
363 }
364
365 fn path_node(ids: Vec<ast::Ident> ) -> ast::Path {
366     ast::Path {
367         span: DUMMY_SP,
368         global: false,
369         segments: ids.move_iter().map(|identifier| ast::PathSegment {
370             identifier: identifier,
371             lifetimes: Vec::new(),
372             types: OwnedSlice::empty(),
373         }).collect()
374     }
375 }
376
377 fn path_node_global(ids: Vec<ast::Ident> ) -> ast::Path {
378     ast::Path {
379         span: DUMMY_SP,
380         global: true,
381         segments: ids.move_iter().map(|identifier| ast::PathSegment {
382             identifier: identifier,
383             lifetimes: Vec::new(),
384             types: OwnedSlice::empty(),
385         }).collect()
386     }
387 }
388
389 fn mk_tests(cx: &TestCtxt) -> @ast::Item {
390     // The vector of test_descs for this crate
391     let test_descs = mk_test_descs(cx);
392
393     (quote_item!(&cx.ext_cx,
394         pub static TESTS : &'static [self::test::TestDescAndFn] =
395             $test_descs
396         ;
397     )).unwrap()
398 }
399
400 fn is_test_crate(krate: &ast::Crate) -> bool {
401     match attr::find_crateid(krate.attrs.as_slice()) {
402         Some(ref s) if "test" == s.name.as_slice() => true,
403         _ => false
404     }
405 }
406
407 fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr {
408     debug!("building test vector from {} tests", cx.testfns.borrow().len());
409
410     @ast::Expr {
411         id: ast::DUMMY_NODE_ID,
412         node: ast::ExprVstore(@ast::Expr {
413             id: ast::DUMMY_NODE_ID,
414             node: ast::ExprVec(cx.testfns.borrow().iter().map(|test| {
415                 mk_test_desc_and_fn_rec(cx, test)
416             }).collect()),
417             span: DUMMY_SP,
418         }, ast::ExprVstoreSlice),
419         span: DUMMY_SP,
420     }
421 }
422
423 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
424     let span = test.span;
425     let path = test.path.clone();
426
427     debug!("encoding {}", ast_util::path_name_i(path.as_slice()));
428
429     let name_lit: ast::Lit =
430         nospan(ast::LitStr(token::intern_and_get_ident(
431                     ast_util::path_name_i(path.as_slice()).as_slice()),
432                     ast::CookedStr));
433
434     let name_expr = @ast::Expr {
435           id: ast::DUMMY_NODE_ID,
436           node: ast::ExprLit(@name_lit),
437           span: span
438     };
439
440     let fn_path = path_node_global(path);
441
442     let fn_expr = @ast::Expr {
443         id: ast::DUMMY_NODE_ID,
444         node: ast::ExprPath(fn_path),
445         span: span,
446     };
447
448     let t_expr = if test.bench {
449         quote_expr!(&cx.ext_cx, self::test::StaticBenchFn($fn_expr) )
450     } else {
451         quote_expr!(&cx.ext_cx, self::test::StaticTestFn($fn_expr) )
452     };
453
454     let ignore_expr = if test.ignore {
455         quote_expr!(&cx.ext_cx, true )
456     } else {
457         quote_expr!(&cx.ext_cx, false )
458     };
459
460     let fail_expr = if test.should_fail {
461         quote_expr!(&cx.ext_cx, true )
462     } else {
463         quote_expr!(&cx.ext_cx, false )
464     };
465
466     let e = quote_expr!(&cx.ext_cx,
467         self::test::TestDescAndFn {
468             desc: self::test::TestDesc {
469                 name: self::test::StaticTestName($name_expr),
470                 ignore: $ignore_expr,
471                 should_fail: $fail_expr
472             },
473             testfn: $t_expr,
474         }
475     );
476     e
477 }