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.
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.
11 // Code that generates a test runner to run all the tests in a crate
14 #![allow(unused_imports)]
16 use self::HasTestSignature::*;
22 use attr::{self, HasAttrs};
23 use syntax_pos::{self, DUMMY_SP, NO_EXPANSION, Span, SourceFile, BytePos};
25 use source_map::{self, SourceMap, ExpnInfo, MacroAttribute, dummy_spanned, respan};
28 use entry::{self, EntryPointType};
29 use ext::base::{ExtCtxt, Resolver};
30 use ext::build::AstBuilder;
31 use ext::expand::ExpansionConfig;
32 use ext::hygiene::{self, Mark, SyntaxContext};
34 use feature_gate::Features;
35 use util::move_map::MoveMap;
37 use parse::{token, ParseSess};
39 use ast::{self, Ident};
42 use symbol::{self, Symbol, keywords};
44 use rustc_data_structures::small_vec::ExpectOne;
52 span_diagnostic: &'a errors::Handler,
55 test_cases: Vec<Test>,
56 reexport_test_harness_main: Option<Symbol>,
59 features: &'a Features,
60 test_runner: Option<ast::Path>,
62 // top-level re-export submodule, filled out after folding is finished
63 toplevel_reexport: Option<Ident>,
66 // Traverse the crate, collecting all the test functions, eliding any
67 // existing main functions, and synthesizing a main test harness
68 pub fn modify_for_testing(sess: &ParseSess,
69 resolver: &mut dyn Resolver,
72 span_diagnostic: &errors::Handler,
73 features: &Features) -> ast::Crate {
74 // Check for #[reexport_test_harness_main = "some_name"] which
75 // creates a `use __test::main as some_name;`. This needs to be
76 // unconditional, so that the attribute is still marked as used in
78 let reexport_test_harness_main =
79 attr::first_attr_value_str_by_name(&krate.attrs,
80 "reexport_test_harness_main");
82 // Do this here so that the test_runner crate attribute gets marked as used
83 // even in non-test builds
84 let test_runner = get_test_runner(span_diagnostic, &krate);
87 generate_test_harness(sess, resolver, reexport_test_harness_main,
88 krate, span_diagnostic, features, test_runner)
94 struct TestHarnessGenerator<'a> {
98 // submodule name, gensym'd identifier for re-exports
99 tested_submods: Vec<(Ident, Ident)>,
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);
106 // Create a main function to run our tests
108 let unresolved = mk_main(&mut self.cx);
109 self.cx.ext_cx.monotonic_expander().fold_item(unresolved).pop().unwrap()
112 folded.module.items.push(test_main);
116 fn fold_item(&mut self, i: P<ast::Item>) -> OneVector<P<ast::Item>> {
118 if ident.name != keywords::Invalid.name() {
119 self.cx.path.push(ident);
121 debug!("current path: {}", path_name_i(&self.cx.path));
123 let mut item = i.into_inner();
124 if is_test_case(&item) {
125 debug!("this is a test item");
129 path: self.cx.path.clone(),
131 self.cx.test_cases.push(test);
132 self.tests.push(item.ident);
135 // We don't want to recurse into anything other than mods, since
136 // mods or tests inside of functions will break things
137 if let ast::ItemKind::Mod(module) = item.node {
138 let tests = mem::replace(&mut self.tests, Vec::new());
139 let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
140 let mut mod_folded = fold::noop_fold_mod(module, self);
141 let tests = mem::replace(&mut self.tests, tests);
142 let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
144 if !tests.is_empty() || !tested_submods.is_empty() {
145 let (it, sym) = mk_reexport_mod(&mut self.cx, item.id, tests, tested_submods);
146 mod_folded.items.push(it);
148 if !self.cx.path.is_empty() {
149 self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
151 debug!("pushing nothing, sym: {:?}", sym);
152 self.cx.toplevel_reexport = Some(sym);
155 item.node = ast::ItemKind::Mod(mod_folded);
157 if ident.name != keywords::Invalid.name() {
163 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
166 /// A folder used to remove any entry points (like fn main) because the harness
167 /// generator will provide its own
168 struct EntryPointCleaner {
169 // Current depth in the ast
173 impl fold::Folder for EntryPointCleaner {
174 fn fold_item(&mut self, i: P<ast::Item>) -> OneVector<P<ast::Item>> {
176 let folded = fold::noop_fold_item(i, self).expect_one("noop did something");
179 // Remove any #[main] or #[start] from the AST so it doesn't
180 // clash with the one we're going to add, but mark it as
181 // #[allow(dead_code)] to avoid printing warnings.
182 let folded = match entry::entry_point_type(&folded, self.depth) {
183 EntryPointType::MainNamed |
184 EntryPointType::MainAttr |
185 EntryPointType::Start =>
186 folded.map(|ast::Item {id, ident, attrs, node, vis, span, tokens}| {
187 let allow_ident = Ident::from_str("allow");
188 let dc_nested = attr::mk_nested_word_item(Ident::from_str("dead_code"));
189 let allow_dead_code_item = attr::mk_list_item(DUMMY_SP, allow_ident,
191 let allow_dead_code = attr::mk_attr_outer(DUMMY_SP,
193 allow_dead_code_item);
198 attrs: attrs.into_iter()
200 !attr.check_name("main") && !attr.check_name("start")
202 .chain(iter::once(allow_dead_code))
210 EntryPointType::None |
211 EntryPointType::OtherMain => folded,
217 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
220 /// Creates an item (specifically a module) that "pub use"s the tests passed in.
221 /// Each tested submodule will contain a similar reexport module that we will export
222 /// under the name of the original module. That is, `submod::__test_reexports` is
223 /// reexported like so `pub use submod::__test_reexports as submod`.
224 fn mk_reexport_mod(cx: &mut TestCtxt,
227 tested_submods: Vec<(Ident, Ident)>)
228 -> (P<ast::Item>, Ident) {
229 let super_ = Ident::from_str("super");
231 let items = tests.into_iter().map(|r| {
232 cx.ext_cx.item_use_simple(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
233 cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
234 }).chain(tested_submods.into_iter().map(|(r, sym)| {
235 let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
236 cx.ext_cx.item_use_simple_(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
240 let reexport_mod = ast::Mod {
245 let sym = Ident::with_empty_ctxt(Symbol::gensym("__test_reexports"));
246 let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent };
247 cx.ext_cx.current_expansion.mark = cx.ext_cx.resolver.get_module_scope(parent);
248 let it = cx.ext_cx.monotonic_expander().fold_item(P(ast::Item {
251 id: ast::DUMMY_NODE_ID,
252 node: ast::ItemKind::Mod(reexport_mod),
253 vis: dummy_spanned(ast::VisibilityKind::Public),
261 /// Crawl over the crate, inserting test reexports and the test main function
262 fn generate_test_harness(sess: &ParseSess,
263 resolver: &mut dyn Resolver,
264 reexport_test_harness_main: Option<Symbol>,
266 sd: &errors::Handler,
268 test_runner: Option<ast::Path>) -> ast::Crate {
269 // Remove the entry points
270 let mut cleaner = EntryPointCleaner { depth: 0 };
271 let krate = cleaner.fold_crate(krate);
273 let mark = Mark::fresh(Mark::root());
275 let mut econfig = ExpansionConfig::default("test".to_string());
276 econfig.features = Some(features);
280 ext_cx: ExtCtxt::new(sess, econfig, resolver),
282 test_cases: Vec::new(),
283 reexport_test_harness_main,
284 // NB: doesn't consider the value of `--crate-name` passed on the command line.
285 is_libtest: attr::find_crate_name(&krate.attrs).map(|s| s == "test").unwrap_or(false),
286 toplevel_reexport: None,
287 ctxt: SyntaxContext::empty().apply_mark(mark),
292 mark.set_expn_info(ExpnInfo {
295 format: MacroAttribute(Symbol::intern("test_case")),
296 allow_internal_unstable: true,
297 allow_internal_unsafe: false,
298 local_inner_macros: false,
299 edition: hygiene::default_edition(),
302 TestHarnessGenerator {
305 tested_submods: Vec::new(),
309 /// Craft a span that will be ignored by the stability lint's
310 /// call to source_map'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 sp.with_ctxt(cx.ctxt)
316 enum HasTestSignature {
318 No(BadTestSignature),
322 enum BadTestSignature {
326 ShouldPanicOnlyWithNoArgs,
329 /// Creates a function item for use as the main function of a test build.
330 /// This function will call the `test_runner` as specified by the crate attribute
331 fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
332 // Writing this out by hand with 'ignored_span':
335 // test::test_main_static(::std::os::args().as_slice(), &[..tests]);
337 let sp = ignored_span(cx, DUMMY_SP);
338 let ecx = &cx.ext_cx;
339 let test_id = ecx.ident_of("test").gensym();
341 // test::test_main_static(...)
342 let mut test_runner = cx.test_runner.clone().unwrap_or(
344 test_id, ecx.ident_of("test_main_static")
347 test_runner.span = sp;
349 let test_main_path_expr = ecx.expr_path(test_runner.clone());
350 let call_test_main = ecx.expr_call(sp, test_main_path_expr,
351 vec![mk_tests_slice(cx)]);
352 let call_test_main = ecx.stmt_expr(call_test_main);
355 let main_meta = ecx.meta_word(sp, Symbol::intern("main"));
356 let main_attr = ecx.attribute(sp, main_meta);
358 // extern crate test as test_gensym
359 let test_extern_stmt = ecx.stmt_item(sp, ecx.item(sp,
362 ast::ItemKind::ExternCrate(Some(Symbol::intern("test")))
365 // pub fn main() { ... }
366 let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
368 // If no test runner is provided we need to import the test crate
369 let main_body = if cx.test_runner.is_none() {
370 ecx.block(sp, vec![test_extern_stmt, call_test_main])
372 ecx.block(sp, vec![call_test_main])
375 let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], ast::FunctionRetTy::Ty(main_ret_ty)),
376 ast::FnHeader::default(),
377 ast::Generics::default(),
380 // Honor the reexport_test_harness_main attribute
381 let main_id = Ident::new(
382 cx.reexport_test_harness_main.unwrap_or(Symbol::gensym("main")),
387 attrs: vec![main_attr],
388 id: ast::DUMMY_NODE_ID,
390 vis: dummy_spanned(ast::VisibilityKind::Public),
397 fn path_name_i(idents: &[Ident]) -> String {
398 let mut path_name = "".to_string();
399 let mut idents_iter = idents.iter().peekable();
400 while let Some(ident) = idents_iter.next() {
401 path_name.push_str(&ident.as_str());
402 if idents_iter.peek().is_some() {
403 path_name.push_str("::")
409 /// Creates a slice containing every test like so:
410 /// &[path::to::test1, path::to::test2]
411 fn mk_tests_slice(cx: &TestCtxt) -> P<ast::Expr> {
412 debug!("building test vector from {} tests", cx.test_cases.len());
413 let ref ecx = cx.ext_cx;
415 ecx.expr_vec_slice(DUMMY_SP,
416 cx.test_cases.iter().map(|test| {
417 ecx.expr_addr_of(test.span,
418 ecx.expr_path(ecx.path(test.span, visible_path(cx, &test.path))))
422 /// Creates a path from the top-level __test module to the test via __test_reexports
423 fn visible_path(cx: &TestCtxt, path: &[Ident]) -> Vec<Ident>{
424 let mut visible_path = vec![];
425 match cx.toplevel_reexport {
426 Some(id) => visible_path.push(id),
428 cx.span_diagnostic.bug("expected to find top-level re-export name, but found None");
431 visible_path.extend_from_slice(path);
435 fn is_test_case(i: &ast::Item) -> bool {
436 attr::contains_name(&i.attrs, "rustc_test_marker")
439 fn get_test_runner(sd: &errors::Handler, krate: &ast::Crate) -> Option<ast::Path> {
440 let test_attr = attr::find_by_name(&krate.attrs, "test_runner")?;
441 if let Some(meta_list) = test_attr.meta_item_list() {
442 if meta_list.len() != 1 {
443 sd.span_fatal(test_attr.span(),
444 "#![test_runner(..)] accepts exactly 1 argument").raise()
446 Some(meta_list[0].word().as_ref().unwrap().ident.clone())
448 sd.span_fatal(test_attr.span(),
449 "test_runner must be of the form #[test_runner(..)]").raise()