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