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