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