]> git.lizzy.rs Git - rust.git/blob - src/librustc/front/test.rs
auto merge of #13049 : alexcrichton/rust/io-fill, r=huonw
[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.get().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.get(),
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(cx: &TestCtxt, item: @ast::Item) -> @ast::Item {
129             if !cx.sess.building_library.get() {
130                 @ast::Item {
131                     attrs: item.attrs.iter().filter_map(|attr| {
132                         if !attr.name().equiv(&("main")) {
133                             Some(*attr)
134                         } else {
135                             None
136                         }
137                     }).collect(),
138                     .. (*item).clone()
139                 }
140             } else {
141                 item
142             }
143         }
144
145         let mod_nomain = ast::Mod {
146             view_items: m.view_items.clone(),
147             items: m.items.iter().map(|i| nomain(&self.cx, *i)).collect(),
148         };
149
150         fold::noop_fold_mod(&mod_nomain, self)
151     }
152 }
153
154 fn generate_test_harness(sess: &Session, krate: ast::Crate)
155                          -> ast::Crate {
156     let loader = &mut Loader::new(sess);
157     let mut cx: TestCtxt = TestCtxt {
158         sess: sess,
159         ext_cx: ExtCtxt::new(&sess.parse_sess, sess.opts.cfg.clone(),
160                              ExpansionConfig {
161                                  loader: loader,
162                                  deriving_hash_type_parameter: false,
163                                  crate_id: from_str("test").unwrap(),
164                              }),
165         path: RefCell::new(Vec::new()),
166         testfns: RefCell::new(Vec::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.as_slice(), "test") &&
193         !attr::contains_name(attrs.as_slice(), "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.as_slice(), "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(cx: &TestCtxt, i: @ast::Item) -> bool {
227     let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "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     if has_bench_attr && !has_test_signature(i) {
248         let sess = cx.sess;
249         sess.span_err(i.span, "functions used as benches must have signature \
250                       `fn(&mut BenchHarness) -> ()`");
251     }
252
253     return has_bench_attr && has_test_signature(i);
254 }
255
256 fn is_ignored(cx: &TestCtxt, i: @ast::Item) -> bool {
257     i.attrs.iter().any(|attr| {
258         // check ignore(cfg(foo, bar))
259         attr.name().equiv(&("ignore")) && match attr.meta_item_list() {
260             Some(ref cfgs) => {
261                 attr::test_cfg(cx.config.as_slice(), cfgs.iter().map(|x| *x))
262             }
263             None => true
264         }
265     })
266 }
267
268 fn should_fail(i: @ast::Item) -> bool {
269     attr::contains_name(i.attrs.as_slice(), "should_fail")
270 }
271
272 fn add_test_module(cx: &TestCtxt, m: &ast::Mod) -> ast::Mod {
273     let testmod = mk_test_module(cx);
274     ast::Mod {
275         items: vec::append_one(m.items.clone(), testmod),
276         ..(*m).clone()
277     }
278 }
279
280 /*
281
282 We're going to be building a module that looks more or less like:
283
284 mod __test {
285   #[!resolve_unexported]
286   extern crate test (name = "test", vers = "...");
287   fn main() {
288     test::test_main_static(::os::args(), tests)
289   }
290
291   static tests : &'static [test::TestDescAndFn] = &[
292     ... the list of tests in the crate ...
293   ];
294 }
295
296 */
297
298 fn mk_std(cx: &TestCtxt) -> ast::ViewItem {
299     let id_test = token::str_to_ident("test");
300     let vi = if cx.is_test_crate {
301         ast::ViewItemUse(
302             vec!(@nospan(ast::ViewPathSimple(id_test,
303                                              path_node(vec!(id_test)),
304                                              ast::DUMMY_NODE_ID))))
305     } else {
306         ast::ViewItemExternCrate(id_test,
307                                with_version("test"),
308                                ast::DUMMY_NODE_ID)
309     };
310     ast::ViewItem {
311         node: vi,
312         attrs: Vec::new(),
313         vis: ast::Inherited,
314         span: DUMMY_SP
315     }
316 }
317
318 fn mk_test_module(cx: &TestCtxt) -> @ast::Item {
319     // Link to test crate
320     let view_items = vec!(mk_std(cx));
321
322     // A constant vector of test descriptors.
323     let tests = mk_tests(cx);
324
325     // The synthesized main function which will call the console test runner
326     // with our list of tests
327     let mainfn = (quote_item!(&cx.ext_cx,
328         pub fn main() {
329             #[allow(deprecated_owned_vector)];
330             #[main];
331             test::test_main_static(::std::os::args(), TESTS);
332         }
333     )).unwrap();
334
335     let testmod = ast::Mod {
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(attr::mk_word_item(resolve_unexported_str));
345
346     let item = ast::Item {
347         ident: token::str_to_ident("__test"),
348         attrs: vec!(resolve_unexported_attr),
349         id: ast::DUMMY_NODE_ID,
350         node: item_,
351         vis: ast::Public,
352         span: DUMMY_SP,
353      };
354
355     debug!("Synthetic test module:\n{}\n", pprust::item_to_str(&item));
356
357     return @item;
358 }
359
360 fn nospan<T>(t: T) -> codemap::Spanned<T> {
361     codemap::Spanned { node: t, span: DUMMY_SP }
362 }
363
364 fn path_node(ids: Vec<ast::Ident> ) -> ast::Path {
365     ast::Path {
366         span: DUMMY_SP,
367         global: false,
368         segments: ids.move_iter().map(|identifier| ast::PathSegment {
369             identifier: identifier,
370             lifetimes: Vec::new(),
371             types: OwnedSlice::empty(),
372         }).collect()
373     }
374 }
375
376 fn path_node_global(ids: Vec<ast::Ident> ) -> ast::Path {
377     ast::Path {
378         span: DUMMY_SP,
379         global: true,
380         segments: ids.move_iter().map(|identifier| ast::PathSegment {
381             identifier: identifier,
382             lifetimes: Vec::new(),
383             types: OwnedSlice::empty(),
384         }).collect()
385     }
386 }
387
388 fn mk_tests(cx: &TestCtxt) -> @ast::Item {
389     // The vector of test_descs for this crate
390     let test_descs = mk_test_descs(cx);
391
392     (quote_item!(&cx.ext_cx,
393         pub static TESTS : &'static [self::test::TestDescAndFn] =
394             $test_descs
395         ;
396     )).unwrap()
397 }
398
399 fn is_test_crate(krate: &ast::Crate) -> bool {
400     match attr::find_crateid(krate.attrs.as_slice()) {
401         Some(ref s) if "test" == s.name => true,
402         _ => false
403     }
404 }
405
406 fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr {
407     let mut descs = Vec::new();
408     debug!("building test vector from {} tests", cx.testfns.borrow().len());
409     for test in cx.testfns.borrow().iter() {
410         descs.push(mk_test_desc_and_fn_rec(cx, test));
411     }
412
413     let inner_expr = @ast::Expr {
414         id: ast::DUMMY_NODE_ID,
415         node: ast::ExprVec(descs, ast::MutImmutable),
416         span: DUMMY_SP,
417     };
418
419     @ast::Expr {
420         id: ast::DUMMY_NODE_ID,
421         node: ast::ExprVstore(inner_expr, ast::ExprVstoreSlice),
422         span: DUMMY_SP,
423     }
424 }
425
426 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
427     let span = test.span;
428     let path = test.path.clone();
429
430     debug!("encoding {}", ast_util::path_name_i(path.as_slice()));
431
432     let name_lit: ast::Lit =
433         nospan(ast::LitStr(token::intern_and_get_ident(
434                     ast_util::path_name_i(path.as_slice())),
435                     ast::CookedStr));
436
437     let name_expr = @ast::Expr {
438           id: ast::DUMMY_NODE_ID,
439           node: ast::ExprLit(@name_lit),
440           span: span
441     };
442
443     let fn_path = path_node_global(path);
444
445     let fn_expr = @ast::Expr {
446         id: ast::DUMMY_NODE_ID,
447         node: ast::ExprPath(fn_path),
448         span: span,
449     };
450
451     let t_expr = if test.bench {
452         quote_expr!(&cx.ext_cx, self::test::StaticBenchFn($fn_expr) )
453     } else {
454         quote_expr!(&cx.ext_cx, self::test::StaticTestFn($fn_expr) )
455     };
456
457     let ignore_expr = if test.ignore {
458         quote_expr!(&cx.ext_cx, true )
459     } else {
460         quote_expr!(&cx.ext_cx, false )
461     };
462
463     let fail_expr = if test.should_fail {
464         quote_expr!(&cx.ext_cx, true )
465     } else {
466         quote_expr!(&cx.ext_cx, false )
467     };
468
469     let e = quote_expr!(&cx.ext_cx,
470         self::test::TestDescAndFn {
471             desc: self::test::TestDesc {
472                 name: self::test::StaticTestName($name_expr),
473                 ignore: $ignore_expr,
474                 should_fail: $fail_expr
475             },
476             testfn: $t_expr,
477         }
478     );
479     e
480 }