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