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