(index<- ) ./librustc/front/test.rs
git branch: * master 5200215 auto merge of #14035 : alexcrichton/rust/experimental, r=huonw
modified: Fri May 9 13:02:28 2014
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.borrow().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.borrow().clone(),
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(item: @ast::Item) -> @ast::Item {
129 @ast::Item {
130 attrs: item.attrs.iter().filter_map(|attr| {
131 if !attr.name().equiv(&("main")) {
132 Some(*attr)
133 } else {
134 None
135 }
136 }).collect(),
137 .. (*item).clone()
138 }
139 }
140
141 let mod_nomain = ast::Mod {
142 inner: m.inner,
143 view_items: m.view_items.clone(),
144 items: m.items.iter().map(|i| nomain(*i)).collect(),
145 };
146
147 fold::noop_fold_mod(&mod_nomain, self)
148 }
149 }
150
151 fn generate_test_harness(sess: &Session, krate: ast::Crate)
152 -> ast::Crate {
153 let loader = &mut Loader::new(sess);
154 let mut cx: TestCtxt = TestCtxt {
155 sess: sess,
156 ext_cx: ExtCtxt::new(&sess.parse_sess, sess.opts.cfg.clone(),
157 ExpansionConfig {
158 loader: loader,
159 deriving_hash_type_parameter: false,
160 crate_id: from_str("test").unwrap(),
161 }),
162 path: RefCell::new(Vec::new()),
163 testfns: RefCell::new(Vec::new()),
164 is_test_crate: is_test_crate(&krate),
165 config: krate.config.clone(),
166 };
167
168 cx.ext_cx.bt_push(ExpnInfo {
169 call_site: DUMMY_SP,
170 callee: NameAndSpan {
171 name: "test".to_strbuf(),
172 format: MacroAttribute,
173 span: None
174 }
175 });
176
177 let mut fold = TestHarnessGenerator {
178 cx: cx
179 };
180 let res = fold.fold_crate(krate);
181 fold.cx.ext_cx.bt_pop();
182 return res;
183 }
184
185 fn strip_test_functions(krate: ast::Crate) -> ast::Crate {
186 // When not compiling with --test we should not compile the
187 // #[test] functions
188 config::strip_items(krate, |attrs| {
189 !attr::contains_name(attrs.as_slice(), "test") &&
190 !attr::contains_name(attrs.as_slice(), "bench")
191 })
192 }
193
194 fn is_test_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
195 let has_test_attr = attr::contains_name(i.attrs.as_slice(), "test");
196
197 fn has_test_signature(i: @ast::Item) -> bool {
198 match &i.node {
199 &ast::ItemFn(ref decl, _, _, ref generics, _) => {
200 let no_output = match decl.output.node {
201 ast::TyNil => true,
202 _ => false
203 };
204 decl.inputs.is_empty()
205 && no_output
206 && !generics.is_parameterized()
207 }
208 _ => false
209 }
210 }
211
212 if has_test_attr && !has_test_signature(i) {
213 let sess = cx.sess;
214 sess.span_err(
215 i.span,
216 "functions used as tests must have signature fn() -> ()."
217 );
218 }
219
220 return has_test_attr && has_test_signature(i);
221 }
222
223 fn is_bench_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
224 let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "bench");
225
226 fn has_test_signature(i: @ast::Item) -> bool {
227 match i.node {
228 ast::ItemFn(ref decl, _, _, ref generics, _) => {
229 let input_cnt = decl.inputs.len();
230 let no_output = match decl.output.node {
231 ast::TyNil => true,
232 _ => false
233 };
234 let tparm_cnt = generics.ty_params.len();
235 // NB: inadequate check, but we're running
236 // well before resolve, can't get too deep.
237 input_cnt == 1u
238 && no_output && tparm_cnt == 0u
239 }
240 _ => false
241 }
242 }
243
244 if has_bench_attr && !has_test_signature(i) {
245 let sess = cx.sess;
246 sess.span_err(i.span, "functions used as benches must have signature \
247 `fn(&mut Bencher) -> ()`");
248 }
249
250 return has_bench_attr && has_test_signature(i);
251 }
252
253 fn is_ignored(cx: &TestCtxt, i: @ast::Item) -> bool {
254 i.attrs.iter().any(|attr| {
255 // check ignore(cfg(foo, bar))
256 attr.name().equiv(&("ignore")) && match attr.meta_item_list() {
257 Some(ref cfgs) => {
258 attr::test_cfg(cx.config.as_slice(), cfgs.iter().map(|x| *x))
259 }
260 None => true
261 }
262 })
263 }
264
265 fn should_fail(i: @ast::Item) -> bool {
266 attr::contains_name(i.attrs.as_slice(), "should_fail")
267 }
268
269 fn add_test_module(cx: &TestCtxt, m: &ast::Mod) -> ast::Mod {
270 let testmod = mk_test_module(cx);
271 ast::Mod {
272 items: m.items.clone().append_one(testmod),
273 ..(*m).clone()
274 }
275 }
276
277 /*
278
279 We're going to be building a module that looks more or less like:
280
281 mod __test {
282 #![!resolve_unexported]
283 extern crate test (name = "test", vers = "...");
284 fn main() {
285 test::test_main_static(::os::args().as_slice(), tests)
286 }
287
288 static tests : &'static [test::TestDescAndFn] = &[
289 ... the list of tests in the crate ...
290 ];
291 }
292
293 */
294
295 fn mk_std(cx: &TestCtxt) -> ast::ViewItem {
296 let id_test = token::str_to_ident("test");
297 let (vi, vis) = if cx.is_test_crate {
298 (ast::ViewItemUse(
299 @nospan(ast::ViewPathSimple(id_test,
300 path_node(vec!(id_test)),
301 ast::DUMMY_NODE_ID))),
302 ast::Public)
303 } else {
304 (ast::ViewItemExternCrate(id_test,
305 with_version("test"),
306 ast::DUMMY_NODE_ID),
307 ast::Inherited)
308 };
309 ast::ViewItem {
310 node: vi,
311 attrs: Vec::new(),
312 vis: vis,
313 span: DUMMY_SP
314 }
315 }
316
317 fn mk_test_module(cx: &TestCtxt) -> @ast::Item {
318 // Link to test crate
319 let view_items = vec!(mk_std(cx));
320
321 // A constant vector of test descriptors.
322 let tests = mk_tests(cx);
323
324 // The synthesized main function which will call the console test runner
325 // with our list of tests
326 let mainfn = (quote_item!(&cx.ext_cx,
327 pub fn main() {
328 #![main]
329 use std::slice::Vector;
330 test::test_main_static(::std::os::args().as_slice(), TESTS);
331 }
332 )).unwrap();
333
334 let testmod = ast::Mod {
335 inner: DUMMY_SP,
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.as_slice() => true,
402 _ => false
403 }
404 }
405
406 fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr {
407 debug!("building test vector from {} tests", cx.testfns.borrow().len());
408
409 @ast::Expr {
410 id: ast::DUMMY_NODE_ID,
411 node: ast::ExprVstore(@ast::Expr {
412 id: ast::DUMMY_NODE_ID,
413 node: ast::ExprVec(cx.testfns.borrow().iter().map(|test| {
414 mk_test_desc_and_fn_rec(cx, test)
415 }).collect()),
416 span: DUMMY_SP,
417 }, ast::ExprVstoreSlice),
418 span: DUMMY_SP,
419 }
420 }
421
422 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
423 let span = test.span;
424 let path = test.path.clone();
425
426 debug!("encoding {}", ast_util::path_name_i(path.as_slice()));
427
428 let name_lit: ast::Lit =
429 nospan(ast::LitStr(token::intern_and_get_ident(
430 ast_util::path_name_i(path.as_slice()).as_slice()),
431 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::test::StaticBenchFn($fn_expr) )
449 } else {
450 quote_expr!(&cx.ext_cx, self::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::test::TestDescAndFn {
467 desc: self::test::TestDesc {
468 name: self::test::StaticTestName($name_expr),
469 ignore: $ignore_expr,
470 should_fail: $fail_expr
471 },
472 testfn: $t_expr,
473 }
474 );
475 e
476 }
librustc/front/test.rs:359:1-359:1 -fn- definition:
fn nospan<T>(t: T) -> codemap::Spanned<T> {
codemap::Spanned { node: t, span: DUMMY_SP }
}
references:- 2428: let name_lit: ast::Lit =
429: nospan(ast::LitStr(token::intern_and_get_ident(
430: ast_util::path_name_i(path.as_slice()).as_slice()),
librustc/front/test.rs:48:1-48:1 -struct- definition:
struct TestCtxt<'a> {
sess: &'a Session,
path: RefCell<Vec<ast::Ident>>,
references:- 12153: let loader = &mut Loader::new(sess);
154: let mut cx: TestCtxt = TestCtxt {
155: sess: sess,
--
223: fn is_bench_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
224: let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "bench");
--
388: fn mk_tests(cx: &TestCtxt) -> @ast::Item {
389: // The vector of test_descs for this crate
--
422: fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
423: let span = test.span;
librustc/front/test.rs:226:4-226:4 -fn- definition:
fn has_test_signature(i: @ast::Item) -> bool {
match i.node {
ast::ItemFn(ref decl, _, _, ref generics, _) => {
references:- 2250: return has_bench_attr && has_test_signature(i);
251: }
librustc/front/test.rs:40:1-40:1 -struct- definition:
struct Test {
span: Span,
path: Vec<ast::Ident> ,
references:- 352: ext_cx: ExtCtxt<'a>,
53: testfns: RefCell<Vec<Test> >,
54: is_test_crate: bool,
--
422: fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
423: let span = test.span;
librustc/front/test.rs:73:1-73:1 -struct- definition:
struct TestHarnessGenerator<'a> {
cx: TestCtxt<'a>,
}
references:- 2177: let mut fold = TestHarnessGenerator {
178: cx: cx
librustc/front/test.rs:222:1-222:1 -fn- definition:
fn is_bench_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "bench");
fn has_test_signature(i: @ast::Item) -> bool {
references:- 2107: path: self.cx.path.borrow().clone(),
108: bench: is_bench_fn(&self.cx, i),
109: ignore: is_ignored(&self.cx, i),
librustc/front/test.rs:197:4-197:4 -fn- definition:
fn has_test_signature(i: @ast::Item) -> bool {
match &i.node {
&ast::ItemFn(ref decl, _, _, ref generics, _) => {
references:- 2212: if has_test_attr && !has_test_signature(i) {
213: let sess = cx.sess;
--
220: return has_test_attr && has_test_signature(i);
221: }