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