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