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