]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/test.rs
libsyntax: fix for `has_test_signature`
[rust.git] / src / libsyntax / 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 use self::HasTestSignature::*;
16
17 use std::slice;
18 use std::mem;
19 use std::vec;
20 use ast_util::*;
21 use attr::AttrMetaMethods;
22 use attr;
23 use codemap::{DUMMY_SP, Span, ExpnInfo, NameAndSpan, MacroAttribute};
24 use codemap;
25 use diagnostic;
26 use config;
27 use ext::base::ExtCtxt;
28 use ext::build::AstBuilder;
29 use ext::expand::ExpansionConfig;
30 use fold::{Folder, MoveMap};
31 use fold;
32 use owned_slice::OwnedSlice;
33 use parse::token::InternedString;
34 use parse::{token, ParseSess};
35 use print::pprust;
36 use {ast, ast_util};
37 use ptr::P;
38 use util::small_vector::SmallVector;
39
40 enum ShouldFail {
41     No,
42     Yes(Option<InternedString>),
43 }
44
45 struct Test {
46     span: Span,
47     path: Vec<ast::Ident> ,
48     bench: bool,
49     ignore: bool,
50     should_fail: ShouldFail
51 }
52
53 struct TestCtxt<'a> {
54     sess: &'a ParseSess,
55     span_diagnostic: &'a diagnostic::SpanHandler,
56     path: Vec<ast::Ident>,
57     ext_cx: ExtCtxt<'a>,
58     testfns: Vec<Test>,
59     reexport_test_harness_main: Option<InternedString>,
60     is_test_crate: bool,
61     config: ast::CrateConfig,
62
63     // top-level re-export submodule, filled out after folding is finished
64     toplevel_reexport: Option<ast::Ident>,
65 }
66
67 // Traverse the crate, collecting all the test functions, eliding any
68 // existing main functions, and synthesizing a main test harness
69 pub fn modify_for_testing(sess: &ParseSess,
70                           cfg: &ast::CrateConfig,
71                           krate: ast::Crate,
72                           span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate {
73     // We generate the test harness when building in the 'test'
74     // configuration, either with the '--test' or '--cfg test'
75     // command line options.
76     let should_test = attr::contains_name(&krate.config[], "test");
77
78     // Check for #[reexport_test_harness_main = "some_name"] which
79     // creates a `use some_name = __test::main;`. This needs to be
80     // unconditional, so that the attribute is still marked as used in
81     // non-test builds.
82     let reexport_test_harness_main =
83         attr::first_attr_value_str_by_name(&krate.attrs[],
84                                            "reexport_test_harness_main");
85
86     if should_test {
87         generate_test_harness(sess, reexport_test_harness_main, krate, cfg, span_diagnostic)
88     } else {
89         strip_test_functions(krate)
90     }
91 }
92
93 struct TestHarnessGenerator<'a> {
94     cx: TestCtxt<'a>,
95     tests: Vec<ast::Ident>,
96
97     // submodule name, gensym'd identifier for re-exports
98     tested_submods: Vec<(ast::Ident, ast::Ident)>,
99 }
100
101 impl<'a> fold::Folder for TestHarnessGenerator<'a> {
102     fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
103         let mut folded = fold::noop_fold_crate(c, self);
104
105         // Add a special __test module to the crate that will contain code
106         // generated for the test harness
107         let (mod_, reexport) = mk_test_module(&mut self.cx);
108         match reexport {
109             Some(re) => folded.module.items.push(re),
110             None => {}
111         }
112         folded.module.items.push(mod_);
113         folded
114     }
115
116     fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
117         let ident = i.ident;
118         if ident.name != token::special_idents::invalid.name {
119             self.cx.path.push(ident);
120         }
121         debug!("current path: {}",
122                ast_util::path_name_i(&self.cx.path[]));
123
124         if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) {
125             match i.node {
126                 ast::ItemFn(_, ast::Unsafety::Unsafe, _, _, _) => {
127                     let diag = self.cx.span_diagnostic;
128                     diag.span_fatal(i.span,
129                                     "unsafe functions cannot be used for \
130                                      tests");
131                 }
132                 _ => {
133                     debug!("this is a test function");
134                     let test = Test {
135                         span: i.span,
136                         path: self.cx.path.clone(),
137                         bench: is_bench_fn(&self.cx, &*i),
138                         ignore: is_ignored(&*i),
139                         should_fail: should_fail(&*i)
140                     };
141                     self.cx.testfns.push(test);
142                     self.tests.push(i.ident);
143                     // debug!("have {} test/bench functions",
144                     //        cx.testfns.len());
145                 }
146             }
147         }
148
149         // We don't want to recurse into anything other than mods, since
150         // mods or tests inside of functions will break things
151         let res = match i.node {
152             ast::ItemMod(..) => fold::noop_fold_item(i, self),
153             _ => SmallVector::one(i),
154         };
155         if ident.name != token::special_idents::invalid.name {
156             self.cx.path.pop();
157         }
158         res
159     }
160
161     fn fold_mod(&mut self, m: ast::Mod) -> ast::Mod {
162         let tests = mem::replace(&mut self.tests, Vec::new());
163         let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
164         let mut mod_folded = fold::noop_fold_mod(m, self);
165         let tests = mem::replace(&mut self.tests, tests);
166         let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
167
168         // Remove any #[main] from the AST so it doesn't clash with
169         // the one we're going to add. Only if compiling an executable.
170
171         mod_folded.items = mem::replace(&mut mod_folded.items, vec![]).move_map(|item| {
172             item.map(|ast::Item {id, ident, attrs, node, vis, span}| {
173                 ast::Item {
174                     id: id,
175                     ident: ident,
176                     attrs: attrs.into_iter().filter_map(|attr| {
177                         if !attr.check_name("main") {
178                             Some(attr)
179                         } else {
180                             None
181                         }
182                     }).collect(),
183                     node: node,
184                     vis: vis,
185                     span: span
186                 }
187             })
188         });
189
190         if !tests.is_empty() || !tested_submods.is_empty() {
191             let (it, sym) = mk_reexport_mod(&mut self.cx, tests, tested_submods);
192             mod_folded.items.push(it);
193
194             if !self.cx.path.is_empty() {
195                 self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
196             } else {
197                 debug!("pushing nothing, sym: {:?}", sym);
198                 self.cx.toplevel_reexport = Some(sym);
199             }
200         }
201
202         mod_folded
203     }
204 }
205
206 fn mk_reexport_mod(cx: &mut TestCtxt, tests: Vec<ast::Ident>,
207                    tested_submods: Vec<(ast::Ident, ast::Ident)>) -> (P<ast::Item>, ast::Ident) {
208     let super_ = token::str_to_ident("super");
209
210     let items = tests.into_iter().map(|r| {
211         cx.ext_cx.item_use_simple(DUMMY_SP, ast::Public,
212                                   cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
213     }).chain(tested_submods.into_iter().map(|(r, sym)| {
214         let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
215         cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Public, r, path)
216     }));
217
218     let reexport_mod = ast::Mod {
219         inner: DUMMY_SP,
220         items: items.collect(),
221     };
222
223     let sym = token::gensym_ident("__test_reexports");
224     let it = P(ast::Item {
225         ident: sym.clone(),
226         attrs: Vec::new(),
227         id: ast::DUMMY_NODE_ID,
228         node: ast::ItemMod(reexport_mod),
229         vis: ast::Public,
230         span: DUMMY_SP,
231     });
232
233     (it, sym)
234 }
235
236 fn generate_test_harness(sess: &ParseSess,
237                          reexport_test_harness_main: Option<InternedString>,
238                          krate: ast::Crate,
239                          cfg: &ast::CrateConfig,
240                          sd: &diagnostic::SpanHandler) -> ast::Crate {
241     let mut cx: TestCtxt = TestCtxt {
242         sess: sess,
243         span_diagnostic: sd,
244         ext_cx: ExtCtxt::new(sess, cfg.clone(),
245                              ExpansionConfig::default("test".to_string())),
246         path: Vec::new(),
247         testfns: Vec::new(),
248         reexport_test_harness_main: reexport_test_harness_main,
249         is_test_crate: is_test_crate(&krate),
250         config: krate.config.clone(),
251         toplevel_reexport: None,
252     };
253
254     cx.ext_cx.bt_push(ExpnInfo {
255         call_site: DUMMY_SP,
256         callee: NameAndSpan {
257             name: "test".to_string(),
258             format: MacroAttribute,
259             span: None
260         }
261     });
262
263     let mut fold = TestHarnessGenerator {
264         cx: cx,
265         tests: Vec::new(),
266         tested_submods: Vec::new(),
267     };
268     let res = fold.fold_crate(krate);
269     fold.cx.ext_cx.bt_pop();
270     return res;
271 }
272
273 fn strip_test_functions(krate: ast::Crate) -> ast::Crate {
274     // When not compiling with --test we should not compile the
275     // #[test] functions
276     config::strip_items(krate, |attrs| {
277         !attr::contains_name(&attrs[], "test") &&
278         !attr::contains_name(&attrs[], "bench")
279     })
280 }
281
282 #[derive(PartialEq)]
283 enum HasTestSignature {
284     Yes,
285     No,
286     NotEvenAFunction,
287 }
288
289
290 fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
291     let has_test_attr = attr::contains_name(&i.attrs[], "test");
292
293     fn has_test_signature(i: &ast::Item) -> HasTestSignature {
294         match &i.node {
295           &ast::ItemFn(ref decl, _, _, ref generics, _) => {
296             let no_output = match decl.output {
297                 ast::DefaultReturn(..) => true,
298                 ast::Return(ref t) if t.node == ast::TyTup(vec![]) => true,
299                 _ => false
300             };
301             if decl.inputs.is_empty()
302                    && no_output
303                    && !generics.is_parameterized() {
304                 Yes
305             } else {
306                 No
307             }
308           }
309           _ => NotEvenAFunction,
310         }
311     }
312
313     if has_test_attr {
314         let diag = cx.span_diagnostic;
315         match has_test_signature(i) {
316             Yes => {},
317             No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"),
318             NotEvenAFunction => diag.span_err(i.span,
319                                               "only functions may be used as tests"),
320         }
321     }
322
323     return has_test_attr && has_test_signature(i) == Yes;
324 }
325
326 fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
327     let has_bench_attr = attr::contains_name(&i.attrs[], "bench");
328
329     fn has_test_signature(i: &ast::Item) -> bool {
330         match i.node {
331             ast::ItemFn(ref decl, _, _, ref generics, _) => {
332                 let input_cnt = decl.inputs.len();
333                 let no_output = match decl.output {
334                     ast::DefaultReturn(..) => true,
335                     ast::Return(ref t) if t.node == ast::TyTup(vec![]) => true,
336                     _ => false
337                 };
338                 let tparm_cnt = generics.ty_params.len();
339                 // NB: inadequate check, but we're running
340                 // well before resolve, can't get too deep.
341                 input_cnt == 1us
342                     && no_output && tparm_cnt == 0us
343             }
344           _ => false
345         }
346     }
347
348     if has_bench_attr && !has_test_signature(i) {
349         let diag = cx.span_diagnostic;
350         diag.span_err(i.span, "functions used as benches must have signature \
351                       `fn(&mut Bencher) -> ()`");
352     }
353
354     return has_bench_attr && has_test_signature(i);
355 }
356
357 fn is_ignored(i: &ast::Item) -> bool {
358     i.attrs.iter().any(|attr| attr.check_name("ignore"))
359 }
360
361 fn should_fail(i: &ast::Item) -> ShouldFail {
362     match i.attrs.iter().find(|attr| attr.check_name("should_fail")) {
363         Some(attr) => {
364             let msg = attr.meta_item_list()
365                 .and_then(|list| list.iter().find(|mi| mi.check_name("expected")))
366                 .and_then(|mi| mi.value_str());
367             ShouldFail::Yes(msg)
368         }
369         None => ShouldFail::No,
370     }
371 }
372
373 /*
374
375 We're going to be building a module that looks more or less like:
376
377 mod __test {
378   extern crate test (name = "test", vers = "...");
379   fn main() {
380     test::test_main_static(&::os::args()[], tests)
381   }
382
383   static tests : &'static [test::TestDescAndFn] = &[
384     ... the list of tests in the crate ...
385   ];
386 }
387
388 */
389
390 fn mk_std(cx: &TestCtxt) -> P<ast::Item> {
391     let id_test = token::str_to_ident("test");
392     let (vi, vis, ident) = if cx.is_test_crate {
393         (ast::ItemUse(
394             P(nospan(ast::ViewPathSimple(id_test,
395                                          path_node(vec!(id_test)))))),
396          ast::Public, token::special_idents::invalid)
397     } else {
398         (ast::ItemExternCrate(None), ast::Inherited, id_test)
399     };
400     P(ast::Item {
401         id: ast::DUMMY_NODE_ID,
402         ident: ident,
403         node: vi,
404         attrs: vec![],
405         vis: vis,
406         span: DUMMY_SP
407     })
408 }
409
410 fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) {
411     // Link to test crate
412     let import = mk_std(cx);
413
414     // A constant vector of test descriptors.
415     let tests = mk_tests(cx);
416
417     // The synthesized main function which will call the console test runner
418     // with our list of tests
419     let mainfn = (quote_item!(&mut cx.ext_cx,
420         pub fn main() {
421             #![main]
422             use std::slice::AsSlice;
423             test::test_main_static(::std::os::args().as_slice(), TESTS);
424         }
425     )).unwrap();
426
427     let testmod = ast::Mod {
428         inner: DUMMY_SP,
429         items: vec![import, mainfn, tests],
430     };
431     let item_ = ast::ItemMod(testmod);
432
433     let mod_ident = token::gensym_ident("__test");
434     let allow_unstable = {
435         let unstable = P(nospan(ast::MetaWord(InternedString::new("unstable"))));
436         let allow = P(nospan(ast::MetaList(InternedString::new("allow"),
437                                            vec![unstable])));
438         attr::mk_attr_inner(attr::mk_attr_id(), allow)
439     };
440     let item = P(ast::Item {
441         id: ast::DUMMY_NODE_ID,
442         ident: mod_ident,
443         attrs: vec![allow_unstable],
444         node: item_,
445         vis: ast::Public,
446         span: DUMMY_SP,
447     });
448     let reexport = cx.reexport_test_harness_main.as_ref().map(|s| {
449         // building `use <ident> = __test::main`
450         let reexport_ident = token::str_to_ident(s.get());
451
452         let use_path =
453             nospan(ast::ViewPathSimple(reexport_ident,
454                                        path_node(vec![mod_ident, token::str_to_ident("main")])));
455
456         P(ast::Item {
457             id: ast::DUMMY_NODE_ID,
458             ident: token::special_idents::invalid,
459             attrs: vec![],
460             node: ast::ItemUse(P(use_path)),
461             vis: ast::Inherited,
462             span: DUMMY_SP
463         })
464     });
465
466     debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&*item));
467
468     (item, reexport)
469 }
470
471 fn nospan<T>(t: T) -> codemap::Spanned<T> {
472     codemap::Spanned { node: t, span: DUMMY_SP }
473 }
474
475 fn path_node(ids: Vec<ast::Ident> ) -> ast::Path {
476     ast::Path {
477         span: DUMMY_SP,
478         global: false,
479         segments: ids.into_iter().map(|identifier| ast::PathSegment {
480             identifier: identifier,
481             parameters: ast::PathParameters::none(),
482         }).collect()
483     }
484 }
485
486 fn mk_tests(cx: &TestCtxt) -> P<ast::Item> {
487     // The vector of test_descs for this crate
488     let test_descs = mk_test_descs(cx);
489
490     // FIXME #15962: should be using quote_item, but that stringifies
491     // __test_reexports, causing it to be reinterned, losing the
492     // gensym information.
493     let sp = DUMMY_SP;
494     let ecx = &cx.ext_cx;
495     let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"),
496                                                     ecx.ident_of("test"),
497                                                     ecx.ident_of("TestDescAndFn")]));
498     let static_lt = ecx.lifetime(sp, token::special_idents::static_lifetime.name);
499     // &'static [self::test::TestDescAndFn]
500     let static_type = ecx.ty_rptr(sp,
501                                   ecx.ty(sp, ast::TyVec(struct_type)),
502                                   Some(static_lt),
503                                   ast::MutImmutable);
504     // static TESTS: $static_type = &[...];
505     ecx.item_const(sp,
506                    ecx.ident_of("TESTS"),
507                    static_type,
508                    test_descs)
509 }
510
511 fn is_test_crate(krate: &ast::Crate) -> bool {
512     match attr::find_crate_name(&krate.attrs[]) {
513         Some(ref s) if "test" == &s.get()[] => true,
514         _ => false
515     }
516 }
517
518 fn mk_test_descs(cx: &TestCtxt) -> P<ast::Expr> {
519     debug!("building test vector from {} tests", cx.testfns.len());
520
521     P(ast::Expr {
522         id: ast::DUMMY_NODE_ID,
523         node: ast::ExprAddrOf(ast::MutImmutable,
524             P(ast::Expr {
525                 id: ast::DUMMY_NODE_ID,
526                 node: ast::ExprVec(cx.testfns.iter().map(|test| {
527                     mk_test_desc_and_fn_rec(cx, test)
528                 }).collect()),
529                 span: DUMMY_SP,
530             })),
531         span: DUMMY_SP,
532     })
533 }
534
535 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P<ast::Expr> {
536     // FIXME #15962: should be using quote_expr, but that stringifies
537     // __test_reexports, causing it to be reinterned, losing the
538     // gensym information.
539
540     let span = test.span;
541     let path = test.path.clone();
542     let ecx = &cx.ext_cx;
543     let self_id = ecx.ident_of("self");
544     let test_id = ecx.ident_of("test");
545
546     // creates self::test::$name
547     let test_path = |&: name| {
548         ecx.path(span, vec![self_id, test_id, ecx.ident_of(name)])
549     };
550     // creates $name: $expr
551     let field = |&: name, expr| ecx.field_imm(span, ecx.ident_of(name), expr);
552
553     debug!("encoding {}", ast_util::path_name_i(&path[]));
554
555     // path to the #[test] function: "foo::bar::baz"
556     let path_string = ast_util::path_name_i(&path[]);
557     let name_expr = ecx.expr_str(span, token::intern_and_get_ident(&path_string[]));
558
559     // self::test::StaticTestName($name_expr)
560     let name_expr = ecx.expr_call(span,
561                                   ecx.expr_path(test_path("StaticTestName")),
562                                   vec![name_expr]);
563
564     let ignore_expr = ecx.expr_bool(span, test.ignore);
565     let should_fail_path = |&: name| {
566         ecx.path(span, vec![self_id, test_id, ecx.ident_of("ShouldFail"), ecx.ident_of(name)])
567     };
568     let fail_expr = match test.should_fail {
569         ShouldFail::No => ecx.expr_path(should_fail_path("No")),
570         ShouldFail::Yes(ref msg) => {
571             let path = should_fail_path("Yes");
572             let arg = match *msg {
573                 Some(ref msg) => ecx.expr_some(span, ecx.expr_str(span, msg.clone())),
574                 None => ecx.expr_none(span),
575             };
576             ecx.expr_call(span, ecx.expr_path(path), vec![arg])
577         }
578     };
579
580     // self::test::TestDesc { ... }
581     let desc_expr = ecx.expr_struct(
582         span,
583         test_path("TestDesc"),
584         vec![field("name", name_expr),
585              field("ignore", ignore_expr),
586              field("should_fail", fail_expr)]);
587
588
589     let mut visible_path = match cx.toplevel_reexport {
590         Some(id) => vec![id],
591         None => {
592             let diag = cx.span_diagnostic;
593             diag.handler.bug("expected to find top-level re-export name, but found None");
594         }
595     };
596     visible_path.extend(path.into_iter());
597
598     let fn_expr = ecx.expr_path(ecx.path_global(span, visible_path));
599
600     let variant_name = if test.bench { "StaticBenchFn" } else { "StaticTestFn" };
601     // self::test::$variant_name($fn_expr)
602     let testfn_expr = ecx.expr_call(span, ecx.expr_path(test_path(variant_name)), vec![fn_expr]);
603
604     // self::test::TestDescAndFn { ... }
605     ecx.expr_struct(span,
606                     test_path("TestDescAndFn"),
607                     vec![field("desc", desc_expr),
608                          field("testfn", testfn_expr)])
609 }