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