]> git.proxmox.com Git - rustc.git/blob - src/libsyntax/test.rs
New upstream version 1.19.0+dfsg1
[rustc.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
16 use self::HasTestSignature::*;
17
18 use std::iter;
19 use std::slice;
20 use std::mem;
21 use std::vec;
22 use attr::{self, HasAttrs};
23 use syntax_pos::{self, DUMMY_SP, NO_EXPANSION, Span, FileMap, BytePos};
24 use std::rc::Rc;
25
26 use codemap::{self, CodeMap, ExpnInfo, NameAndSpan, MacroAttribute, dummy_spanned};
27 use errors;
28 use errors::snippet::{SnippetData};
29 use config;
30 use entry::{self, EntryPointType};
31 use ext::base::{ExtCtxt, Resolver};
32 use ext::build::AstBuilder;
33 use ext::expand::ExpansionConfig;
34 use ext::hygiene::{Mark, SyntaxContext};
35 use fold::Folder;
36 use util::move_map::MoveMap;
37 use fold;
38 use parse::{token, ParseSess};
39 use print::pprust;
40 use ast::{self, Ident};
41 use ptr::P;
42 use symbol::{self, Symbol, keywords};
43 use util::small_vector::SmallVector;
44
45 enum ShouldPanic {
46 No,
47 Yes(Option<Symbol>),
48 }
49
50 struct Test {
51 span: Span,
52 path: Vec<Ident> ,
53 bench: bool,
54 ignore: bool,
55 should_panic: ShouldPanic
56 }
57
58 struct TestCtxt<'a> {
59 sess: &'a ParseSess,
60 span_diagnostic: &'a errors::Handler,
61 path: Vec<Ident>,
62 ext_cx: ExtCtxt<'a>,
63 testfns: Vec<Test>,
64 reexport_test_harness_main: Option<Symbol>,
65 is_test_crate: bool,
66 ctxt: SyntaxContext,
67
68 // top-level re-export submodule, filled out after folding is finished
69 toplevel_reexport: Option<Ident>,
70 }
71
72 // Traverse the crate, collecting all the test functions, eliding any
73 // existing main functions, and synthesizing a main test harness
74 pub fn modify_for_testing(sess: &ParseSess,
75 resolver: &mut Resolver,
76 should_test: bool,
77 krate: ast::Crate,
78 span_diagnostic: &errors::Handler) -> ast::Crate {
79 // Check for #[reexport_test_harness_main = "some_name"] which
80 // creates a `use some_name = __test::main;`. This needs to be
81 // unconditional, so that the attribute is still marked as used in
82 // non-test builds.
83 let reexport_test_harness_main =
84 attr::first_attr_value_str_by_name(&krate.attrs,
85 "reexport_test_harness_main");
86
87 if should_test {
88 generate_test_harness(sess, resolver, reexport_test_harness_main, krate, span_diagnostic)
89 } else {
90 krate
91 }
92 }
93
94 struct TestHarnessGenerator<'a> {
95 cx: TestCtxt<'a>,
96 tests: Vec<Ident>,
97
98 // submodule name, gensym'd identifier for re-exports
99 tested_submods: Vec<(Ident, Ident)>,
100 }
101
102 impl<'a> fold::Folder for TestHarnessGenerator<'a> {
103 fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
104 let mut folded = fold::noop_fold_crate(c, self);
105
106 // Add a special __test module to the crate that will contain code
107 // generated for the test harness
108 let (mod_, reexport) = mk_test_module(&mut self.cx);
109 if let Some(re) = reexport {
110 folded.module.items.push(re)
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 != keywords::Invalid.name() {
119 self.cx.path.push(ident);
120 }
121 debug!("current path: {}", path_name_i(&self.cx.path));
122
123 if is_test_fn(&self.cx, &i) || is_bench_fn(&self.cx, &i) {
124 match i.node {
125 ast::ItemKind::Fn(_, ast::Unsafety::Unsafe, _, _, _, _) => {
126 let diag = self.cx.span_diagnostic;
127 panic!(diag.span_fatal(i.span, "unsafe functions cannot be used for tests"));
128 }
129 _ => {
130 debug!("this is a test function");
131 let test = Test {
132 span: i.span,
133 path: self.cx.path.clone(),
134 bench: is_bench_fn(&self.cx, &i),
135 ignore: is_ignored(&i),
136 should_panic: should_panic(&i, &self.cx)
137 };
138 self.cx.testfns.push(test);
139 self.tests.push(i.ident);
140 }
141 }
142 }
143
144 let mut item = i.unwrap();
145 // We don't want to recurse into anything other than mods, since
146 // mods or tests inside of functions will break things
147 if let ast::ItemKind::Mod(module) = item.node {
148 let tests = mem::replace(&mut self.tests, Vec::new());
149 let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
150 let mut mod_folded = fold::noop_fold_mod(module, self);
151 let tests = mem::replace(&mut self.tests, tests);
152 let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
153
154 if !tests.is_empty() || !tested_submods.is_empty() {
155 let (it, sym) = mk_reexport_mod(&mut self.cx, item.id, tests, tested_submods);
156 mod_folded.items.push(it);
157
158 if !self.cx.path.is_empty() {
159 self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
160 } else {
161 debug!("pushing nothing, sym: {:?}", sym);
162 self.cx.toplevel_reexport = Some(sym);
163 }
164 }
165 item.node = ast::ItemKind::Mod(mod_folded);
166 }
167 if ident.name != keywords::Invalid.name() {
168 self.cx.path.pop();
169 }
170 SmallVector::one(P(item))
171 }
172
173 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
174 }
175
176 struct EntryPointCleaner {
177 // Current depth in the ast
178 depth: usize,
179 }
180
181 impl fold::Folder for EntryPointCleaner {
182 fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
183 self.depth += 1;
184 let folded = fold::noop_fold_item(i, self).expect_one("noop did something");
185 self.depth -= 1;
186
187 // Remove any #[main] or #[start] from the AST so it doesn't
188 // clash with the one we're going to add, but mark it as
189 // #[allow(dead_code)] to avoid printing warnings.
190 let folded = match entry::entry_point_type(&folded, self.depth) {
191 EntryPointType::MainNamed |
192 EntryPointType::MainAttr |
193 EntryPointType::Start =>
194 folded.map(|ast::Item {id, ident, attrs, node, vis, span}| {
195 let allow_str = Symbol::intern("allow");
196 let dead_code_str = Symbol::intern("dead_code");
197 let word_vec = vec![attr::mk_list_word_item(dead_code_str)];
198 let allow_dead_code_item = attr::mk_list_item(allow_str, word_vec);
199 let allow_dead_code = attr::mk_attr_outer(DUMMY_SP,
200 attr::mk_attr_id(),
201 allow_dead_code_item);
202
203 ast::Item {
204 id: id,
205 ident: ident,
206 attrs: attrs.into_iter()
207 .filter(|attr| {
208 !attr.check_name("main") && !attr.check_name("start")
209 })
210 .chain(iter::once(allow_dead_code))
211 .collect(),
212 node: node,
213 vis: vis,
214 span: span
215 }
216 }),
217 EntryPointType::None |
218 EntryPointType::OtherMain => folded,
219 };
220
221 SmallVector::one(folded)
222 }
223
224 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
225 }
226
227 fn mk_reexport_mod(cx: &mut TestCtxt,
228 parent: ast::NodeId,
229 tests: Vec<Ident>,
230 tested_submods: Vec<(Ident, Ident)>)
231 -> (P<ast::Item>, Ident) {
232 let super_ = Ident::from_str("super");
233
234 let items = tests.into_iter().map(|r| {
235 cx.ext_cx.item_use_simple(DUMMY_SP, ast::Visibility::Public,
236 cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
237 }).chain(tested_submods.into_iter().map(|(r, sym)| {
238 let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
239 cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Visibility::Public, r, path)
240 })).collect();
241
242 let reexport_mod = ast::Mod {
243 inner: DUMMY_SP,
244 items: items,
245 };
246
247 let sym = Ident::with_empty_ctxt(Symbol::gensym("__test_reexports"));
248 let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent };
249 cx.ext_cx.current_expansion.mark = cx.ext_cx.resolver.get_module_scope(parent);
250 let it = cx.ext_cx.monotonic_expander().fold_item(P(ast::Item {
251 ident: sym,
252 attrs: Vec::new(),
253 id: ast::DUMMY_NODE_ID,
254 node: ast::ItemKind::Mod(reexport_mod),
255 vis: ast::Visibility::Public,
256 span: DUMMY_SP,
257 })).pop().unwrap();
258
259 (it, sym)
260 }
261
262 fn generate_test_harness(sess: &ParseSess,
263 resolver: &mut Resolver,
264 reexport_test_harness_main: Option<Symbol>,
265 krate: ast::Crate,
266 sd: &errors::Handler) -> ast::Crate {
267 // Remove the entry points
268 let mut cleaner = EntryPointCleaner { depth: 0 };
269 let krate = cleaner.fold_crate(krate);
270
271 let mark = Mark::fresh(Mark::root());
272 let mut cx: TestCtxt = TestCtxt {
273 sess: sess,
274 span_diagnostic: sd,
275 ext_cx: ExtCtxt::new(sess, ExpansionConfig::default("test".to_string()), resolver),
276 path: Vec::new(),
277 testfns: Vec::new(),
278 reexport_test_harness_main: reexport_test_harness_main,
279 is_test_crate: is_test_crate(&krate),
280 toplevel_reexport: None,
281 ctxt: SyntaxContext::empty().apply_mark(mark),
282 };
283 cx.ext_cx.crate_root = Some("std");
284
285 mark.set_expn_info(ExpnInfo {
286 call_site: DUMMY_SP,
287 callee: NameAndSpan {
288 format: MacroAttribute(Symbol::intern("test")),
289 span: None,
290 allow_internal_unstable: true,
291 }
292 });
293
294 TestHarnessGenerator {
295 cx: cx,
296 tests: Vec::new(),
297 tested_submods: Vec::new(),
298 }.fold_crate(krate)
299 }
300
301 /// Craft a span that will be ignored by the stability lint's
302 /// call to codemap's `is_internal` check.
303 /// The expanded code calls some unstable functions in the test crate.
304 fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
305 Span { ctxt: cx.ctxt, ..sp }
306 }
307
308 #[derive(PartialEq)]
309 enum HasTestSignature {
310 Yes,
311 No,
312 NotEvenAFunction,
313 }
314
315 fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
316 let has_test_attr = attr::contains_name(&i.attrs, "test");
317
318 fn has_test_signature(i: &ast::Item) -> HasTestSignature {
319 match i.node {
320 ast::ItemKind::Fn(ref decl, _, _, _, ref generics, _) => {
321 let no_output = match decl.output {
322 ast::FunctionRetTy::Default(..) => true,
323 ast::FunctionRetTy::Ty(ref t) if t.node == ast::TyKind::Tup(vec![]) => true,
324 _ => false
325 };
326 if decl.inputs.is_empty()
327 && no_output
328 && !generics.is_parameterized() {
329 Yes
330 } else {
331 No
332 }
333 }
334 _ => NotEvenAFunction,
335 }
336 }
337
338 if has_test_attr {
339 let diag = cx.span_diagnostic;
340 match has_test_signature(i) {
341 Yes => {},
342 No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"),
343 NotEvenAFunction => diag.span_err(i.span,
344 "only functions may be used as tests"),
345 }
346 }
347
348 has_test_attr && has_test_signature(i) == Yes
349 }
350
351 fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
352 let has_bench_attr = attr::contains_name(&i.attrs, "bench");
353
354 fn has_test_signature(i: &ast::Item) -> bool {
355 match i.node {
356 ast::ItemKind::Fn(ref decl, _, _, _, ref generics, _) => {
357 let input_cnt = decl.inputs.len();
358 let no_output = match decl.output {
359 ast::FunctionRetTy::Default(..) => true,
360 ast::FunctionRetTy::Ty(ref t) if t.node == ast::TyKind::Tup(vec![]) => true,
361 _ => false
362 };
363 let tparm_cnt = generics.ty_params.len();
364 // NB: inadequate check, but we're running
365 // well before resolve, can't get too deep.
366 input_cnt == 1
367 && no_output && tparm_cnt == 0
368 }
369 _ => false
370 }
371 }
372
373 if has_bench_attr && !has_test_signature(i) {
374 let diag = cx.span_diagnostic;
375 diag.span_err(i.span, "functions used as benches must have signature \
376 `fn(&mut Bencher) -> ()`");
377 }
378
379 has_bench_attr && has_test_signature(i)
380 }
381
382 fn is_ignored(i: &ast::Item) -> bool {
383 i.attrs.iter().any(|attr| attr.check_name("ignore"))
384 }
385
386 fn should_panic(i: &ast::Item, cx: &TestCtxt) -> ShouldPanic {
387 match i.attrs.iter().find(|attr| attr.check_name("should_panic")) {
388 Some(attr) => {
389 let sd = cx.span_diagnostic;
390 if attr.is_value_str() {
391 sd.struct_span_warn(
392 attr.span(),
393 "attribute must be of the form: \
394 `#[should_panic]` or \
395 `#[should_panic(expected = \"error message\")]`"
396 ).note("Errors in this attribute were erroneously allowed \
397 and will become a hard error in a future release.")
398 .emit();
399 return ShouldPanic::Yes(None);
400 }
401 match attr.meta_item_list() {
402 // Handle #[should_panic]
403 None => ShouldPanic::Yes(None),
404 // Handle #[should_panic(expected = "foo")]
405 Some(list) => {
406 let msg = list.iter()
407 .find(|mi| mi.check_name("expected"))
408 .and_then(|mi| mi.meta_item())
409 .and_then(|mi| mi.value_str());
410 if list.len() != 1 || msg.is_none() {
411 sd.struct_span_warn(
412 attr.span(),
413 "argument must be of the form: \
414 `expected = \"error message\"`"
415 ).note("Errors in this attribute were erroneously \
416 allowed and will become a hard error in a \
417 future release.").emit();
418 ShouldPanic::Yes(None)
419 } else {
420 ShouldPanic::Yes(msg)
421 }
422 },
423 }
424 }
425 None => ShouldPanic::No,
426 }
427 }
428
429 /*
430
431 We're going to be building a module that looks more or less like:
432
433 mod __test {
434 extern crate test (name = "test", vers = "...");
435 fn main() {
436 test::test_main_static(&::os::args()[], tests, test::Options::new())
437 }
438
439 static tests : &'static [test::TestDescAndFn] = &[
440 ... the list of tests in the crate ...
441 ];
442 }
443
444 */
445
446 fn mk_std(cx: &TestCtxt) -> P<ast::Item> {
447 let id_test = Ident::from_str("test");
448 let sp = ignored_span(cx, DUMMY_SP);
449 let (vi, vis, ident) = if cx.is_test_crate {
450 (ast::ItemKind::Use(
451 P(nospan(ast::ViewPathSimple(id_test,
452 path_node(vec![id_test]))))),
453 ast::Visibility::Public, keywords::Invalid.ident())
454 } else {
455 (ast::ItemKind::ExternCrate(None), ast::Visibility::Inherited, id_test)
456 };
457 P(ast::Item {
458 id: ast::DUMMY_NODE_ID,
459 ident: ident,
460 node: vi,
461 attrs: vec![],
462 vis: vis,
463 span: sp
464 })
465 }
466
467 fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
468 // Writing this out by hand with 'ignored_span':
469 // pub fn main() {
470 // #![main]
471 // use std::slice::AsSlice;
472 // test::test_main_static(::std::os::args().as_slice(), TESTS, test::Options::new());
473 // }
474
475 let sp = ignored_span(cx, DUMMY_SP);
476 let ecx = &cx.ext_cx;
477
478 // test::test_main_static
479 let test_main_path =
480 ecx.path(sp, vec![Ident::from_str("test"), Ident::from_str("test_main_static")]);
481
482 // test::test_main_static(...)
483 let test_main_path_expr = ecx.expr_path(test_main_path);
484 let tests_ident_expr = ecx.expr_ident(sp, Ident::from_str("TESTS"));
485 let call_test_main = ecx.expr_call(sp, test_main_path_expr,
486 vec![tests_ident_expr]);
487 let call_test_main = ecx.stmt_expr(call_test_main);
488 // #![main]
489 let main_meta = ecx.meta_word(sp, Symbol::intern("main"));
490 let main_attr = ecx.attribute(sp, main_meta);
491 // pub fn main() { ... }
492 let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
493 let main_body = ecx.block(sp, vec![call_test_main]);
494 let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], main_ret_ty),
495 ast::Unsafety::Normal,
496 dummy_spanned(ast::Constness::NotConst),
497 ::abi::Abi::Rust, ast::Generics::default(), main_body);
498 P(ast::Item {
499 ident: Ident::from_str("main"),
500 attrs: vec![main_attr],
501 id: ast::DUMMY_NODE_ID,
502 node: main,
503 vis: ast::Visibility::Public,
504 span: sp
505 })
506 }
507
508 fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) {
509 // Link to test crate
510 let import = mk_std(cx);
511
512 // A constant vector of test descriptors.
513 let tests = mk_tests(cx);
514
515 // The synthesized main function which will call the console test runner
516 // with our list of tests
517 let mainfn = mk_main(cx);
518
519 let testmod = ast::Mod {
520 inner: DUMMY_SP,
521 items: vec![import, mainfn, tests],
522 };
523 let item_ = ast::ItemKind::Mod(testmod);
524 let mod_ident = Ident::with_empty_ctxt(Symbol::gensym("__test"));
525
526 let mut expander = cx.ext_cx.monotonic_expander();
527 let item = expander.fold_item(P(ast::Item {
528 id: ast::DUMMY_NODE_ID,
529 ident: mod_ident,
530 attrs: vec![],
531 node: item_,
532 vis: ast::Visibility::Public,
533 span: DUMMY_SP,
534 })).pop().unwrap();
535 let reexport = cx.reexport_test_harness_main.map(|s| {
536 // building `use <ident> = __test::main`
537 let reexport_ident = Ident::with_empty_ctxt(s);
538
539 let use_path =
540 nospan(ast::ViewPathSimple(reexport_ident,
541 path_node(vec![mod_ident, Ident::from_str("main")])));
542
543 expander.fold_item(P(ast::Item {
544 id: ast::DUMMY_NODE_ID,
545 ident: keywords::Invalid.ident(),
546 attrs: vec![],
547 node: ast::ItemKind::Use(P(use_path)),
548 vis: ast::Visibility::Inherited,
549 span: DUMMY_SP
550 })).pop().unwrap()
551 });
552
553 debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&item));
554
555 (item, reexport)
556 }
557
558 fn nospan<T>(t: T) -> codemap::Spanned<T> {
559 codemap::Spanned { node: t, span: DUMMY_SP }
560 }
561
562 fn path_node(ids: Vec<Ident>) -> ast::Path {
563 ast::Path {
564 span: DUMMY_SP,
565 segments: ids.into_iter().map(|id| ast::PathSegment::from_ident(id, DUMMY_SP)).collect(),
566 }
567 }
568
569 fn path_name_i(idents: &[Ident]) -> String {
570 // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
571 idents.iter().map(|i| i.to_string()).collect::<Vec<String>>().join("::")
572 }
573
574 fn mk_tests(cx: &TestCtxt) -> P<ast::Item> {
575 // The vector of test_descs for this crate
576 let test_descs = mk_test_descs(cx);
577
578 // FIXME #15962: should be using quote_item, but that stringifies
579 // __test_reexports, causing it to be reinterned, losing the
580 // gensym information.
581 let sp = ignored_span(cx, DUMMY_SP);
582 let ecx = &cx.ext_cx;
583 let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"),
584 ecx.ident_of("test"),
585 ecx.ident_of("TestDescAndFn")]));
586 let static_lt = ecx.lifetime(sp, keywords::StaticLifetime.ident());
587 // &'static [self::test::TestDescAndFn]
588 let static_type = ecx.ty_rptr(sp,
589 ecx.ty(sp, ast::TyKind::Slice(struct_type)),
590 Some(static_lt),
591 ast::Mutability::Immutable);
592 // static TESTS: $static_type = &[...];
593 ecx.item_const(sp,
594 ecx.ident_of("TESTS"),
595 static_type,
596 test_descs)
597 }
598
599 fn is_test_crate(krate: &ast::Crate) -> bool {
600 match attr::find_crate_name(&krate.attrs) {
601 Some(s) if "test" == s.as_str() => true,
602 _ => false
603 }
604 }
605
606 fn mk_test_descs(cx: &TestCtxt) -> P<ast::Expr> {
607 debug!("building test vector from {} tests", cx.testfns.len());
608
609 P(ast::Expr {
610 id: ast::DUMMY_NODE_ID,
611 node: ast::ExprKind::AddrOf(ast::Mutability::Immutable,
612 P(ast::Expr {
613 id: ast::DUMMY_NODE_ID,
614 node: ast::ExprKind::Array(cx.testfns.iter().map(|test| {
615 mk_test_desc_and_fn_rec(cx, test)
616 }).collect()),
617 span: DUMMY_SP,
618 attrs: ast::ThinVec::new(),
619 })),
620 span: DUMMY_SP,
621 attrs: ast::ThinVec::new(),
622 })
623 }
624
625 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P<ast::Expr> {
626 // FIXME #15962: should be using quote_expr, but that stringifies
627 // __test_reexports, causing it to be reinterned, losing the
628 // gensym information.
629
630 let span = ignored_span(cx, test.span);
631 let path = test.path.clone();
632 let ecx = &cx.ext_cx;
633 let self_id = ecx.ident_of("self");
634 let test_id = ecx.ident_of("test");
635
636 // creates self::test::$name
637 let test_path = |name| {
638 ecx.path(span, vec![self_id, test_id, ecx.ident_of(name)])
639 };
640 // creates $name: $expr
641 let field = |name, expr| ecx.field_imm(span, ecx.ident_of(name), expr);
642
643 debug!("encoding {}", path_name_i(&path[..]));
644
645 // path to the #[test] function: "foo::bar::baz"
646 let path_string = path_name_i(&path[..]);
647 let name_expr = ecx.expr_str(span, Symbol::intern(&path_string));
648
649 // self::test::StaticTestName($name_expr)
650 let name_expr = ecx.expr_call(span,
651 ecx.expr_path(test_path("StaticTestName")),
652 vec![name_expr]);
653
654 let ignore_expr = ecx.expr_bool(span, test.ignore);
655 let should_panic_path = |name| {
656 ecx.path(span, vec![self_id, test_id, ecx.ident_of("ShouldPanic"), ecx.ident_of(name)])
657 };
658 let fail_expr = match test.should_panic {
659 ShouldPanic::No => ecx.expr_path(should_panic_path("No")),
660 ShouldPanic::Yes(msg) => {
661 match msg {
662 Some(msg) => {
663 let msg = ecx.expr_str(span, msg);
664 let path = should_panic_path("YesWithMessage");
665 ecx.expr_call(span, ecx.expr_path(path), vec![msg])
666 }
667 None => ecx.expr_path(should_panic_path("Yes")),
668 }
669 }
670 };
671
672 // self::test::TestDesc { ... }
673 let desc_expr = ecx.expr_struct(
674 span,
675 test_path("TestDesc"),
676 vec![field("name", name_expr),
677 field("ignore", ignore_expr),
678 field("should_panic", fail_expr)]);
679
680
681 let mut visible_path = match cx.toplevel_reexport {
682 Some(id) => vec![id],
683 None => {
684 let diag = cx.span_diagnostic;
685 diag.bug("expected to find top-level re-export name, but found None");
686 }
687 };
688 visible_path.extend(path);
689
690 let fn_expr = ecx.expr_path(ecx.path_global(span, visible_path));
691
692 let variant_name = if test.bench { "StaticBenchFn" } else { "StaticTestFn" };
693 // self::test::$variant_name($fn_expr)
694 let testfn_expr = ecx.expr_call(span, ecx.expr_path(test_path(variant_name)), vec![fn_expr]);
695
696 // self::test::TestDescAndFn { ... }
697 ecx.expr_struct(span,
698 test_path("TestDescAndFn"),
699 vec![field("desc", desc_expr),
700 field("testfn", testfn_expr)])
701 }