]> git.lizzy.rs Git - rust.git/blob - src/librustc/front/test.rs
librustc: De-`@str` `NameAndSpan`
[rust.git] / src / librustc / front / test.rs
1 // Copyright 2012 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_extra: 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                           crate: 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(crate.config, "test");
61
62     if should_test {
63         generate_test_harness(sess, crate)
64     } else {
65         strip_test_functions(crate)
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, crate: 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_extra: is_extra(&crate),
168         config: crate.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(crate);
184     fold.cx.ext_cx.bt_pop();
185     return res;
186 }
187
188 fn strip_test_functions(crate: ast::Crate) -> ast::Crate {
189     // When not compiling with --test we should not compile the
190     // #[test] functions
191     config::strip_items(crate, |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 mod extra (name = "extra", vers = "...");
279   fn main() {
280     #[main];
281     extra::test::test_main_static(::os::args(), tests)
282   }
283
284   static tests : &'static [extra::test::TestDescAndFn] = &[
285     ... the list of tests in the crate ...
286   ];
287 }
288
289 */
290
291 fn mk_std(cx: &TestCtxt) -> ast::ViewItem {
292     let id_extra = cx.sess.ident_of("extra");
293     let vi = if cx.is_extra {
294         ast::ViewItemUse(
295             ~[@nospan(ast::ViewPathSimple(id_extra,
296                                           path_node(~[id_extra]),
297                                           ast::DUMMY_NODE_ID))])
298     } else {
299         ast::ViewItemExternMod(id_extra,
300                                with_version("extra"),
301                                ast::DUMMY_NODE_ID)
302     };
303     ast::ViewItem {
304         node: vi,
305         attrs: ~[],
306         vis: ast::Inherited,
307         span: DUMMY_SP
308     }
309 }
310
311 fn mk_test_module(cx: &TestCtxt) -> @ast::Item {
312
313     // Link to extra
314     let view_items = ~[mk_std(cx)];
315
316     // A constant vector of test descriptors.
317     let tests = mk_tests(cx);
318
319     // The synthesized main function which will call the console test runner
320     // with our list of tests
321     let mainfn = (quote_item!(&cx.ext_cx,
322         pub fn main() {
323             #[main];
324             extra::test::test_main_static(::std::os::args(), TESTS);
325         }
326     )).unwrap();
327
328     let testmod = ast::Mod {
329         view_items: view_items,
330         items: ~[mainfn, tests],
331     };
332     let item_ = ast::ItemMod(testmod);
333
334     // This attribute tells resolve to let us call unexported functions
335     let resolve_unexported_str = InternedString::new("!resolve_unexported");
336     let resolve_unexported_attr =
337         attr::mk_attr(attr::mk_word_item(resolve_unexported_str));
338
339     let item = ast::Item {
340         ident: cx.sess.ident_of("__test"),
341         attrs: ~[resolve_unexported_attr],
342         id: ast::DUMMY_NODE_ID,
343         node: item_,
344         vis: ast::Public,
345         span: DUMMY_SP,
346      };
347
348     debug!("Synthetic test module:\n{}\n",
349            pprust::item_to_str(&item, cx.sess.intr()));
350
351     return @item;
352 }
353
354 fn nospan<T>(t: T) -> codemap::Spanned<T> {
355     codemap::Spanned { node: t, span: DUMMY_SP }
356 }
357
358 fn path_node(ids: ~[ast::Ident]) -> ast::Path {
359     ast::Path {
360         span: DUMMY_SP,
361         global: false,
362         segments: ids.move_iter().map(|identifier| ast::PathSegment {
363             identifier: identifier,
364             lifetimes: opt_vec::Empty,
365             types: opt_vec::Empty,
366         }).collect()
367     }
368 }
369
370 fn path_node_global(ids: ~[ast::Ident]) -> ast::Path {
371     ast::Path {
372         span: DUMMY_SP,
373         global: true,
374         segments: ids.move_iter().map(|identifier| ast::PathSegment {
375             identifier: identifier,
376             lifetimes: opt_vec::Empty,
377             types: opt_vec::Empty,
378         }).collect()
379     }
380 }
381
382 fn mk_tests(cx: &TestCtxt) -> @ast::Item {
383     // The vector of test_descs for this crate
384     let test_descs = mk_test_descs(cx);
385
386     (quote_item!(&cx.ext_cx,
387         pub static TESTS : &'static [self::extra::test::TestDescAndFn] =
388             $test_descs
389         ;
390     )).unwrap()
391 }
392
393 fn is_extra(crate: &ast::Crate) -> bool {
394     match attr::find_crateid(crate.attrs) {
395         Some(ref s) if "extra" == s.name => true,
396         _ => false
397     }
398 }
399
400 fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr {
401     let mut descs = ~[];
402     {
403         let testfns = cx.testfns.borrow();
404         debug!("building test vector from {} tests", testfns.get().len());
405         for test in testfns.get().iter() {
406             descs.push(mk_test_desc_and_fn_rec(cx, test));
407         }
408     }
409
410     let inner_expr = @ast::Expr {
411         id: ast::DUMMY_NODE_ID,
412         node: ast::ExprVec(descs, ast::MutImmutable),
413         span: DUMMY_SP,
414     };
415
416     @ast::Expr {
417         id: ast::DUMMY_NODE_ID,
418         node: ast::ExprVstore(inner_expr, ast::ExprVstoreSlice),
419         span: DUMMY_SP,
420     }
421 }
422
423 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
424     let span = test.span;
425     let path = test.path.clone();
426
427     debug!("encoding {}", ast_util::path_name_i(path));
428
429     let name_lit: ast::Lit =
430         nospan(ast::LitStr(token::intern_and_get_ident(
431                     ast_util::path_name_i(path)), ast::CookedStr));
432
433     let name_expr = @ast::Expr {
434           id: ast::DUMMY_NODE_ID,
435           node: ast::ExprLit(@name_lit),
436           span: span
437     };
438
439     let fn_path = path_node_global(path);
440
441     let fn_expr = @ast::Expr {
442         id: ast::DUMMY_NODE_ID,
443         node: ast::ExprPath(fn_path),
444         span: span,
445     };
446
447     let t_expr = if test.bench {
448         quote_expr!(&cx.ext_cx, self::extra::test::StaticBenchFn($fn_expr) )
449     } else {
450         quote_expr!(&cx.ext_cx, self::extra::test::StaticTestFn($fn_expr) )
451     };
452
453     let ignore_expr = if test.ignore {
454         quote_expr!(&cx.ext_cx, true )
455     } else {
456         quote_expr!(&cx.ext_cx, false )
457     };
458
459     let fail_expr = if test.should_fail {
460         quote_expr!(&cx.ext_cx, true )
461     } else {
462         quote_expr!(&cx.ext_cx, false )
463     };
464
465     let e = quote_expr!(&cx.ext_cx,
466         self::extra::test::TestDescAndFn {
467             desc: self::extra::test::TestDesc {
468                 name: self::extra::test::StaticTestName($name_expr),
469                 ignore: $ignore_expr,
470                 should_fail: $fail_expr
471             },
472             testfn: $t_expr,
473         }
474     );
475     e
476 }