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