]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/test.rs
Rollup merge of #42227 - ollie27:into_to_from, r=aturon
[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::{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     allow_fail: bool,
57 }
58
59 struct TestCtxt<'a> {
60     sess: &'a ParseSess,
61     span_diagnostic: &'a errors::Handler,
62     path: Vec<Ident>,
63     ext_cx: ExtCtxt<'a>,
64     testfns: Vec<Test>,
65     reexport_test_harness_main: Option<Symbol>,
66     is_test_crate: bool,
67     ctxt: SyntaxContext,
68
69     // top-level re-export submodule, filled out after folding is finished
70     toplevel_reexport: Option<Ident>,
71 }
72
73 // Traverse the crate, collecting all the test functions, eliding any
74 // existing main functions, and synthesizing a main test harness
75 pub fn modify_for_testing(sess: &ParseSess,
76                           resolver: &mut Resolver,
77                           should_test: bool,
78                           krate: ast::Crate,
79                           span_diagnostic: &errors::Handler) -> ast::Crate {
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, resolver, reexport_test_harness_main, krate, span_diagnostic)
90     } else {
91         krate
92     }
93 }
94
95 struct TestHarnessGenerator<'a> {
96     cx: TestCtxt<'a>,
97     tests: Vec<Ident>,
98
99     // submodule name, gensym'd identifier for re-exports
100     tested_submods: Vec<(Ident, 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         if let Some(re) = reexport {
111             folded.module.items.push(re)
112         }
113         folded.module.items.push(mod_);
114         folded
115     }
116
117     fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
118         let ident = i.ident;
119         if ident.name != keywords::Invalid.name() {
120             self.cx.path.push(ident);
121         }
122         debug!("current path: {}", path_name_i(&self.cx.path));
123
124         if is_test_fn(&self.cx, &i) || is_bench_fn(&self.cx, &i) {
125             match i.node {
126                 ast::ItemKind::Fn(_, ast::Unsafety::Unsafe, _, _, _, _) => {
127                     let diag = self.cx.span_diagnostic;
128                     panic!(diag.span_fatal(i.span, "unsafe functions cannot be used for tests"));
129                 }
130                 _ => {
131                     debug!("this is a test function");
132                     let test = Test {
133                         span: i.span,
134                         path: self.cx.path.clone(),
135                         bench: is_bench_fn(&self.cx, &i),
136                         ignore: is_ignored(&i),
137                         should_panic: should_panic(&i, &self.cx),
138                         allow_fail: is_allowed_fail(&i),
139                     };
140                     self.cx.testfns.push(test);
141                     self.tests.push(i.ident);
142                 }
143             }
144         }
145
146         let mut item = i.unwrap();
147         // We don't want to recurse into anything other than mods, since
148         // mods or tests inside of functions will break things
149         if let ast::ItemKind::Mod(module) = item.node {
150             let tests = mem::replace(&mut self.tests, Vec::new());
151             let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
152             let mut mod_folded = fold::noop_fold_mod(module, self);
153             let tests = mem::replace(&mut self.tests, tests);
154             let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
155
156             if !tests.is_empty() || !tested_submods.is_empty() {
157                 let (it, sym) = mk_reexport_mod(&mut self.cx, item.id, tests, tested_submods);
158                 mod_folded.items.push(it);
159
160                 if !self.cx.path.is_empty() {
161                     self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
162                 } else {
163                     debug!("pushing nothing, sym: {:?}", sym);
164                     self.cx.toplevel_reexport = Some(sym);
165                 }
166             }
167             item.node = ast::ItemKind::Mod(mod_folded);
168         }
169         if ident.name != keywords::Invalid.name() {
170             self.cx.path.pop();
171         }
172         SmallVector::one(P(item))
173     }
174
175     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
176 }
177
178 struct EntryPointCleaner {
179     // Current depth in the ast
180     depth: usize,
181 }
182
183 impl fold::Folder for EntryPointCleaner {
184     fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
185         self.depth += 1;
186         let folded = fold::noop_fold_item(i, self).expect_one("noop did something");
187         self.depth -= 1;
188
189         // Remove any #[main] or #[start] from the AST so it doesn't
190         // clash with the one we're going to add, but mark it as
191         // #[allow(dead_code)] to avoid printing warnings.
192         let folded = match entry::entry_point_type(&folded, self.depth) {
193             EntryPointType::MainNamed |
194             EntryPointType::MainAttr |
195             EntryPointType::Start =>
196                 folded.map(|ast::Item {id, ident, attrs, node, vis, span}| {
197                     let allow_str = Symbol::intern("allow");
198                     let dead_code_str = Symbol::intern("dead_code");
199                     let word_vec = vec![attr::mk_list_word_item(dead_code_str)];
200                     let allow_dead_code_item = attr::mk_list_item(allow_str, word_vec);
201                     let allow_dead_code = attr::mk_attr_outer(DUMMY_SP,
202                                                               attr::mk_attr_id(),
203                                                               allow_dead_code_item);
204
205                     ast::Item {
206                         id: id,
207                         ident: ident,
208                         attrs: attrs.into_iter()
209                             .filter(|attr| {
210                                 !attr.check_name("main") && !attr.check_name("start")
211                             })
212                             .chain(iter::once(allow_dead_code))
213                             .collect(),
214                         node: node,
215                         vis: vis,
216                         span: span
217                     }
218                 }),
219             EntryPointType::None |
220             EntryPointType::OtherMain => folded,
221         };
222
223         SmallVector::one(folded)
224     }
225
226     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
227 }
228
229 fn mk_reexport_mod(cx: &mut TestCtxt,
230                    parent: ast::NodeId,
231                    tests: Vec<Ident>,
232                    tested_submods: Vec<(Ident, Ident)>)
233                    -> (P<ast::Item>, Ident) {
234     let super_ = Ident::from_str("super");
235
236     let items = tests.into_iter().map(|r| {
237         cx.ext_cx.item_use_simple(DUMMY_SP, ast::Visibility::Public,
238                                   cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
239     }).chain(tested_submods.into_iter().map(|(r, sym)| {
240         let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
241         cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Visibility::Public, r, path)
242     })).collect();
243
244     let reexport_mod = ast::Mod {
245         inner: DUMMY_SP,
246         items: items,
247     };
248
249     let sym = Ident::with_empty_ctxt(Symbol::gensym("__test_reexports"));
250     let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent };
251     cx.ext_cx.current_expansion.mark = cx.ext_cx.resolver.get_module_scope(parent);
252     let it = cx.ext_cx.monotonic_expander().fold_item(P(ast::Item {
253         ident: sym,
254         attrs: Vec::new(),
255         id: ast::DUMMY_NODE_ID,
256         node: ast::ItemKind::Mod(reexport_mod),
257         vis: ast::Visibility::Public,
258         span: DUMMY_SP,
259     })).pop().unwrap();
260
261     (it, sym)
262 }
263
264 fn generate_test_harness(sess: &ParseSess,
265                          resolver: &mut Resolver,
266                          reexport_test_harness_main: Option<Symbol>,
267                          krate: ast::Crate,
268                          sd: &errors::Handler) -> ast::Crate {
269     // Remove the entry points
270     let mut cleaner = EntryPointCleaner { depth: 0 };
271     let krate = cleaner.fold_crate(krate);
272
273     let mark = Mark::fresh(Mark::root());
274     let mut cx: TestCtxt = TestCtxt {
275         sess: sess,
276         span_diagnostic: sd,
277         ext_cx: ExtCtxt::new(sess, ExpansionConfig::default("test".to_string()), resolver),
278         path: Vec::new(),
279         testfns: Vec::new(),
280         reexport_test_harness_main: reexport_test_harness_main,
281         is_test_crate: is_test_crate(&krate),
282         toplevel_reexport: None,
283         ctxt: SyntaxContext::empty().apply_mark(mark),
284     };
285     cx.ext_cx.crate_root = Some("std");
286
287     mark.set_expn_info(ExpnInfo {
288         call_site: DUMMY_SP,
289         callee: NameAndSpan {
290             format: MacroAttribute(Symbol::intern("test")),
291             span: None,
292             allow_internal_unstable: true,
293         }
294     });
295
296     TestHarnessGenerator {
297         cx: cx,
298         tests: Vec::new(),
299         tested_submods: Vec::new(),
300     }.fold_crate(krate)
301 }
302
303 /// Craft a span that will be ignored by the stability lint's
304 /// call to codemap's `is_internal` check.
305 /// The expanded code calls some unstable functions in the test crate.
306 fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
307     Span { ctxt: cx.ctxt, ..sp }
308 }
309
310 #[derive(PartialEq)]
311 enum HasTestSignature {
312     Yes,
313     No,
314     NotEvenAFunction,
315 }
316
317 fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
318     let has_test_attr = attr::contains_name(&i.attrs, "test");
319
320     fn has_test_signature(i: &ast::Item) -> HasTestSignature {
321         match i.node {
322           ast::ItemKind::Fn(ref decl, _, _, _, ref generics, _) => {
323             let no_output = match decl.output {
324                 ast::FunctionRetTy::Default(..) => true,
325                 ast::FunctionRetTy::Ty(ref t) if t.node == ast::TyKind::Tup(vec![]) => true,
326                 _ => false
327             };
328             if decl.inputs.is_empty()
329                    && no_output
330                    && !generics.is_parameterized() {
331                 Yes
332             } else {
333                 No
334             }
335           }
336           _ => NotEvenAFunction,
337         }
338     }
339
340     if has_test_attr {
341         let diag = cx.span_diagnostic;
342         match has_test_signature(i) {
343             Yes => {},
344             No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"),
345             NotEvenAFunction => diag.span_err(i.span,
346                                               "only functions may be used as tests"),
347         }
348     }
349
350     has_test_attr && has_test_signature(i) == Yes
351 }
352
353 fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
354     let has_bench_attr = attr::contains_name(&i.attrs, "bench");
355
356     fn has_test_signature(i: &ast::Item) -> bool {
357         match i.node {
358             ast::ItemKind::Fn(ref decl, _, _, _, ref generics, _) => {
359                 let input_cnt = decl.inputs.len();
360                 let no_output = match decl.output {
361                     ast::FunctionRetTy::Default(..) => true,
362                     ast::FunctionRetTy::Ty(ref t) if t.node == ast::TyKind::Tup(vec![]) => true,
363                     _ => false
364                 };
365                 let tparm_cnt = generics.ty_params.len();
366                 // NB: inadequate check, but we're running
367                 // well before resolve, can't get too deep.
368                 input_cnt == 1
369                     && no_output && tparm_cnt == 0
370             }
371           _ => false
372         }
373     }
374
375     if has_bench_attr && !has_test_signature(i) {
376         let diag = cx.span_diagnostic;
377         diag.span_err(i.span, "functions used as benches must have signature \
378                       `fn(&mut Bencher) -> ()`");
379     }
380
381     has_bench_attr && has_test_signature(i)
382 }
383
384 fn is_ignored(i: &ast::Item) -> bool {
385     i.attrs.iter().any(|attr| attr.check_name("ignore"))
386 }
387
388 fn is_allowed_fail(i: &ast::Item) -> bool {
389     i.attrs.iter().any(|attr| attr.check_name("allow_fail"))
390 }
391
392 fn should_panic(i: &ast::Item, cx: &TestCtxt) -> ShouldPanic {
393     match i.attrs.iter().find(|attr| attr.check_name("should_panic")) {
394         Some(attr) => {
395             let sd = cx.span_diagnostic;
396             if attr.is_value_str() {
397                 sd.struct_span_warn(
398                     attr.span(),
399                     "attribute must be of the form: \
400                      `#[should_panic]` or \
401                      `#[should_panic(expected = \"error message\")]`"
402                 ).note("Errors in this attribute were erroneously allowed \
403                         and will become a hard error in a future release.")
404                 .emit();
405                 return ShouldPanic::Yes(None);
406             }
407             match attr.meta_item_list() {
408                 // Handle #[should_panic]
409                 None => ShouldPanic::Yes(None),
410                 // Handle #[should_panic(expected = "foo")]
411                 Some(list) => {
412                     let msg = list.iter()
413                         .find(|mi| mi.check_name("expected"))
414                         .and_then(|mi| mi.meta_item())
415                         .and_then(|mi| mi.value_str());
416                     if list.len() != 1 || msg.is_none() {
417                         sd.struct_span_warn(
418                             attr.span(),
419                             "argument must be of the form: \
420                              `expected = \"error message\"`"
421                         ).note("Errors in this attribute were erroneously \
422                                 allowed and will become a hard error in a \
423                                 future release.").emit();
424                         ShouldPanic::Yes(None)
425                     } else {
426                         ShouldPanic::Yes(msg)
427                     }
428                 },
429             }
430         }
431         None => ShouldPanic::No,
432     }
433 }
434
435 /*
436
437 We're going to be building a module that looks more or less like:
438
439 mod __test {
440   extern crate test (name = "test", vers = "...");
441   fn main() {
442     test::test_main_static(&::os::args()[], tests, test::Options::new())
443   }
444
445   static tests : &'static [test::TestDescAndFn] = &[
446     ... the list of tests in the crate ...
447   ];
448 }
449
450 */
451
452 fn mk_std(cx: &TestCtxt) -> P<ast::Item> {
453     let id_test = Ident::from_str("test");
454     let sp = ignored_span(cx, DUMMY_SP);
455     let (vi, vis, ident) = if cx.is_test_crate {
456         (ast::ItemKind::Use(
457             P(nospan(ast::ViewPathSimple(id_test,
458                                          path_node(vec![id_test]))))),
459          ast::Visibility::Public, keywords::Invalid.ident())
460     } else {
461         (ast::ItemKind::ExternCrate(None), ast::Visibility::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: 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, test::Options::new());
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 =
486         ecx.path(sp, vec![Ident::from_str("test"), Ident::from_str("test_main_static")]);
487
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, Ident::from_str("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, Symbol::intern("main"));
496     let main_attr = ecx.attribute(sp, main_meta);
497     // pub fn main() { ... }
498     let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
499     let main_body = ecx.block(sp, vec![call_test_main]);
500     let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], main_ret_ty),
501                            ast::Unsafety::Normal,
502                            dummy_spanned(ast::Constness::NotConst),
503                            ::abi::Abi::Rust, ast::Generics::default(), main_body);
504     P(ast::Item {
505         ident: Ident::from_str("main"),
506         attrs: vec![main_attr],
507         id: ast::DUMMY_NODE_ID,
508         node: main,
509         vis: ast::Visibility::Public,
510         span: sp
511     })
512 }
513
514 fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) {
515     // Link to test crate
516     let import = mk_std(cx);
517
518     // A constant vector of test descriptors.
519     let tests = mk_tests(cx);
520
521     // The synthesized main function which will call the console test runner
522     // with our list of tests
523     let mainfn = mk_main(cx);
524
525     let testmod = ast::Mod {
526         inner: DUMMY_SP,
527         items: vec![import, mainfn, tests],
528     };
529     let item_ = ast::ItemKind::Mod(testmod);
530     let mod_ident = Ident::with_empty_ctxt(Symbol::gensym("__test"));
531
532     let mut expander = cx.ext_cx.monotonic_expander();
533     let item = expander.fold_item(P(ast::Item {
534         id: ast::DUMMY_NODE_ID,
535         ident: mod_ident,
536         attrs: vec![],
537         node: item_,
538         vis: ast::Visibility::Public,
539         span: DUMMY_SP,
540     })).pop().unwrap();
541     let reexport = cx.reexport_test_harness_main.map(|s| {
542         // building `use <ident> = __test::main`
543         let reexport_ident = Ident::with_empty_ctxt(s);
544
545         let use_path =
546             nospan(ast::ViewPathSimple(reexport_ident,
547                                        path_node(vec![mod_ident, Ident::from_str("main")])));
548
549         expander.fold_item(P(ast::Item {
550             id: ast::DUMMY_NODE_ID,
551             ident: keywords::Invalid.ident(),
552             attrs: vec![],
553             node: ast::ItemKind::Use(P(use_path)),
554             vis: ast::Visibility::Inherited,
555             span: DUMMY_SP
556         })).pop().unwrap()
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<Ident>) -> ast::Path {
569     ast::Path {
570         span: DUMMY_SP,
571         segments: ids.into_iter().map(|id| ast::PathSegment::from_ident(id, DUMMY_SP)).collect(),
572     }
573 }
574
575 fn path_name_i(idents: &[Ident]) -> String {
576     // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
577     idents.iter().map(|i| i.to_string()).collect::<Vec<String>>().join("::")
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 = ignored_span(cx, 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, keywords::StaticLifetime.ident());
593     // &'static [self::test::TestDescAndFn]
594     let static_type = ecx.ty_rptr(sp,
595                                   ecx.ty(sp, ast::TyKind::Slice(struct_type)),
596                                   Some(static_lt),
597                                   ast::Mutability::Immutable);
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(s) if "test" == s.as_str() => 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::ExprKind::AddrOf(ast::Mutability::Immutable,
618             P(ast::Expr {
619                 id: ast::DUMMY_NODE_ID,
620                 node: ast::ExprKind::Array(cx.testfns.iter().map(|test| {
621                     mk_test_desc_and_fn_rec(cx, test)
622                 }).collect()),
623                 span: DUMMY_SP,
624                 attrs: ast::ThinVec::new(),
625             })),
626         span: DUMMY_SP,
627         attrs: ast::ThinVec::new(),
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 {}", path_name_i(&path[..]));
650
651     // path to the #[test] function: "foo::bar::baz"
652     let path_string = path_name_i(&path[..]);
653     let name_expr = ecx.expr_str(span, Symbol::intern(&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(msg) => {
667             match msg {
668                 Some(msg) => {
669                     let msg = ecx.expr_str(span, msg);
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     let allow_fail_expr = ecx.expr_bool(span, test.allow_fail);
678
679     // self::test::TestDesc { ... }
680     let desc_expr = ecx.expr_struct(
681         span,
682         test_path("TestDesc"),
683         vec![field("name", name_expr),
684              field("ignore", ignore_expr),
685              field("should_panic", fail_expr),
686              field("allow_fail", allow_fail_expr)]);
687
688
689     let mut visible_path = match cx.toplevel_reexport {
690         Some(id) => vec![id],
691         None => {
692             let diag = cx.span_diagnostic;
693             diag.bug("expected to find top-level re-export name, but found None");
694         }
695     };
696     visible_path.extend(path);
697
698     let fn_expr = ecx.expr_path(ecx.path_global(span, visible_path));
699
700     let variant_name = if test.bench { "StaticBenchFn" } else { "StaticTestFn" };
701     // self::test::$variant_name($fn_expr)
702     let testfn_expr = ecx.expr_call(span, ecx.expr_path(test_path(variant_name)), vec![fn_expr]);
703
704     // self::test::TestDescAndFn { ... }
705     ecx.expr_struct(span,
706                     test_path("TestDescAndFn"),
707                     vec![field("desc", desc_expr),
708                          field("testfn", testfn_expr)])
709 }