]> git.proxmox.com Git - rustc.git/blame - src/libsyntax/test.rs
New upstream version 1.30.0+dfsg1
[rustc.git] / src / libsyntax / test.rs
CommitLineData
1a4d82fc
JJ
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)]
3157f602 15
1a4d82fc
JJ
16use self::HasTestSignature::*;
17
e9174d1e 18use std::iter;
1a4d82fc
JJ
19use std::slice;
20use std::mem;
21use std::vec;
c30ab7b3 22use attr::{self, HasAttrs};
b7449926 23use syntax_pos::{self, DUMMY_SP, NO_EXPANSION, Span, SourceFile, BytePos};
3157f602 24
b7449926 25use source_map::{self, SourceMap, ExpnInfo, MacroAttribute, dummy_spanned, respan};
9cc50fc6 26use errors;
1a4d82fc 27use config;
e9174d1e 28use entry::{self, EntryPointType};
9e0c209e 29use ext::base::{ExtCtxt, Resolver};
1a4d82fc
JJ
30use ext::build::AstBuilder;
31use ext::expand::ExpansionConfig;
94b46f34 32use ext::hygiene::{self, Mark, SyntaxContext};
92a42be0 33use fold::Folder;
0531ce1d 34use feature_gate::Features;
92a42be0 35use util::move_map::MoveMap;
1a4d82fc 36use fold;
1a4d82fc
JJ
37use parse::{token, ParseSess};
38use print::pprust;
476ff2be 39use ast::{self, Ident};
1a4d82fc 40use ptr::P;
b7449926 41use OneVector;
476ff2be 42use symbol::{self, Symbol, keywords};
b7449926
XL
43use ThinVec;
44use rustc_data_structures::small_vec::ExpectOne;
1a4d82fc
JJ
45
46struct Test {
47 span: Span,
b7449926 48 path: Vec<Ident>,
1a4d82fc
JJ
49}
50
51struct TestCtxt<'a> {
9cc50fc6 52 span_diagnostic: &'a errors::Handler,
476ff2be 53 path: Vec<Ident>,
1a4d82fc 54 ext_cx: ExtCtxt<'a>,
b7449926 55 test_cases: Vec<Test>,
476ff2be 56 reexport_test_harness_main: Option<Symbol>,
3b2f2976 57 is_libtest: bool,
cc61c64b 58 ctxt: SyntaxContext,
0531ce1d 59 features: &'a Features,
b7449926 60 test_runner: Option<ast::Path>,
1a4d82fc
JJ
61
62 // top-level re-export submodule, filled out after folding is finished
476ff2be 63 toplevel_reexport: Option<Ident>,
1a4d82fc
JJ
64}
65
66// Traverse the crate, collecting all the test functions, eliding any
67// existing main functions, and synthesizing a main test harness
68pub fn modify_for_testing(sess: &ParseSess,
8faf50e0 69 resolver: &mut dyn Resolver,
3157f602 70 should_test: bool,
1a4d82fc 71 krate: ast::Crate,
0531ce1d
XL
72 span_diagnostic: &errors::Handler,
73 features: &Features) -> ast::Crate {
1a4d82fc 74 // Check for #[reexport_test_harness_main = "some_name"] which
0531ce1d 75 // creates a `use __test::main as some_name;`. This needs to be
1a4d82fc
JJ
76 // unconditional, so that the attribute is still marked as used in
77 // non-test builds.
78 let reexport_test_harness_main =
c34b1796 79 attr::first_attr_value_str_by_name(&krate.attrs,
1a4d82fc
JJ
80 "reexport_test_harness_main");
81
b7449926
XL
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);
85
1a4d82fc 86 if should_test {
0531ce1d 87 generate_test_harness(sess, resolver, reexport_test_harness_main,
b7449926 88 krate, span_diagnostic, features, test_runner)
1a4d82fc 89 } else {
3157f602 90 krate
1a4d82fc
JJ
91 }
92}
93
94struct TestHarnessGenerator<'a> {
95 cx: TestCtxt<'a>,
476ff2be 96 tests: Vec<Ident>,
1a4d82fc
JJ
97
98 // submodule name, gensym'd identifier for re-exports
476ff2be 99 tested_submods: Vec<(Ident, Ident)>,
1a4d82fc
JJ
100}
101
102impl<'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
b7449926
XL
106 // Create a main function to run our tests
107 let test_main = {
108 let unresolved = mk_main(&mut self.cx);
109 self.cx.ext_cx.monotonic_expander().fold_item(unresolved).pop().unwrap()
110 };
111
112 folded.module.items.push(test_main);
1a4d82fc
JJ
113 folded
114 }
115
b7449926 116 fn fold_item(&mut self, i: P<ast::Item>) -> OneVector<P<ast::Item>> {
1a4d82fc 117 let ident = i.ident;
a7813a04 118 if ident.name != keywords::Invalid.name() {
1a4d82fc
JJ
119 self.cx.path.push(ident);
120 }
54a0048b 121 debug!("current path: {}", path_name_i(&self.cx.path));
1a4d82fc 122
b7449926
XL
123 let mut item = i.into_inner();
124 if is_test_case(&item) {
125 debug!("this is a test item");
8faf50e0 126
8faf50e0 127 let test = Test {
b7449926 128 span: item.span,
8faf50e0 129 path: self.cx.path.clone(),
8faf50e0 130 };
b7449926
XL
131 self.cx.test_cases.push(test);
132 self.tests.push(item.ident);
c30ab7b3 133 }
1a4d82fc
JJ
134
135 // We don't want to recurse into anything other than mods, since
136 // mods or tests inside of functions will break things
c30ab7b3
SL
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);
143
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);
147
148 if !self.cx.path.is_empty() {
149 self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
150 } else {
151 debug!("pushing nothing, sym: {:?}", sym);
152 self.cx.toplevel_reexport = Some(sym);
153 }
154 }
155 item.node = ast::ItemKind::Mod(mod_folded);
156 }
a7813a04 157 if ident.name != keywords::Invalid.name() {
1a4d82fc
JJ
158 self.cx.path.pop();
159 }
b7449926 160 smallvec![P(item)]
1a4d82fc 161 }
5bcae85e
SL
162
163 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
1a4d82fc
JJ
164}
165
b7449926
XL
166/// A folder used to remove any entry points (like fn main) because the harness
167/// generator will provide its own
e9174d1e
SL
168struct EntryPointCleaner {
169 // Current depth in the ast
170 depth: usize,
171}
172
173impl fold::Folder for EntryPointCleaner {
b7449926 174 fn fold_item(&mut self, i: P<ast::Item>) -> OneVector<P<ast::Item>> {
e9174d1e
SL
175 self.depth += 1;
176 let folded = fold::noop_fold_item(i, self).expect_one("noop did something");
177 self.depth -= 1;
178
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.
7453a54e 182 let folded = match entry::entry_point_type(&folded, self.depth) {
e9174d1e
SL
183 EntryPointType::MainNamed |
184 EntryPointType::MainAttr |
185 EntryPointType::Start =>
3b2f2976 186 folded.map(|ast::Item {id, ident, attrs, node, vis, span, tokens}| {
83c7162d
XL
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,
190 vec![dc_nested]);
8bb4bdeb
XL
191 let allow_dead_code = attr::mk_attr_outer(DUMMY_SP,
192 attr::mk_attr_id(),
e9174d1e
SL
193 allow_dead_code_item);
194
195 ast::Item {
3b2f2976
XL
196 id,
197 ident,
e9174d1e
SL
198 attrs: attrs.into_iter()
199 .filter(|attr| {
200 !attr.check_name("main") && !attr.check_name("start")
201 })
202 .chain(iter::once(allow_dead_code))
203 .collect(),
3b2f2976
XL
204 node,
205 vis,
206 span,
207 tokens,
e9174d1e
SL
208 }
209 }),
210 EntryPointType::None |
211 EntryPointType::OtherMain => folded,
212 };
213
b7449926 214 smallvec![folded]
e9174d1e 215 }
5bcae85e
SL
216
217 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
e9174d1e
SL
218}
219
b7449926
XL
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`.
476ff2be
SL
224fn mk_reexport_mod(cx: &mut TestCtxt,
225 parent: ast::NodeId,
226 tests: Vec<Ident>,
227 tested_submods: Vec<(Ident, Ident)>)
228 -> (P<ast::Item>, Ident) {
229 let super_ = Ident::from_str("super");
1a4d82fc 230
85aaf69f 231 let items = tests.into_iter().map(|r| {
0531ce1d 232 cx.ext_cx.item_use_simple(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
1a4d82fc 233 cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
85aaf69f 234 }).chain(tested_submods.into_iter().map(|(r, sym)| {
1a4d82fc 235 let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
0531ce1d
XL
236 cx.ext_cx.item_use_simple_(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
237 Some(r), path)
9e0c209e 238 })).collect();
1a4d82fc
JJ
239
240 let reexport_mod = ast::Mod {
241 inner: DUMMY_SP,
3b2f2976 242 items,
1a4d82fc
JJ
243 };
244
476ff2be 245 let sym = Ident::with_empty_ctxt(Symbol::gensym("__test_reexports"));
c30ab7b3
SL
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);
9e0c209e 248 let it = cx.ext_cx.monotonic_expander().fold_item(P(ast::Item {
7cac9316 249 ident: sym,
1a4d82fc
JJ
250 attrs: Vec::new(),
251 id: ast::DUMMY_NODE_ID,
7453a54e 252 node: ast::ItemKind::Mod(reexport_mod),
0531ce1d 253 vis: dummy_spanned(ast::VisibilityKind::Public),
1a4d82fc 254 span: DUMMY_SP,
3b2f2976 255 tokens: None,
9e0c209e 256 })).pop().unwrap();
1a4d82fc
JJ
257
258 (it, sym)
259}
260
b7449926 261/// Crawl over the crate, inserting test reexports and the test main function
1a4d82fc 262fn generate_test_harness(sess: &ParseSess,
8faf50e0 263 resolver: &mut dyn Resolver,
476ff2be 264 reexport_test_harness_main: Option<Symbol>,
1a4d82fc 265 krate: ast::Crate,
0531ce1d 266 sd: &errors::Handler,
b7449926
XL
267 features: &Features,
268 test_runner: Option<ast::Path>) -> ast::Crate {
e9174d1e
SL
269 // Remove the entry points
270 let mut cleaner = EntryPointCleaner { depth: 0 };
271 let krate = cleaner.fold_crate(krate);
272
7cac9316 273 let mark = Mark::fresh(Mark::root());
3b2f2976 274
0531ce1d
XL
275 let mut econfig = ExpansionConfig::default("test".to_string());
276 econfig.features = Some(features);
277
ff7c6d11 278 let cx = TestCtxt {
1a4d82fc 279 span_diagnostic: sd,
0531ce1d 280 ext_cx: ExtCtxt::new(sess, econfig, resolver),
1a4d82fc 281 path: Vec::new(),
b7449926 282 test_cases: Vec::new(),
3b2f2976
XL
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),
1a4d82fc 286 toplevel_reexport: None,
cc61c64b 287 ctxt: SyntaxContext::empty().apply_mark(mark),
0531ce1d 288 features,
b7449926 289 test_runner
1a4d82fc
JJ
290 };
291
cc61c64b 292 mark.set_expn_info(ExpnInfo {
1a4d82fc 293 call_site: DUMMY_SP,
8faf50e0 294 def_site: None,
b7449926 295 format: MacroAttribute(Symbol::intern("test_case")),
8faf50e0
XL
296 allow_internal_unstable: true,
297 allow_internal_unsafe: false,
298 local_inner_macros: false,
299 edition: hygiene::default_edition(),
1a4d82fc
JJ
300 });
301
9e0c209e 302 TestHarnessGenerator {
3b2f2976 303 cx,
1a4d82fc
JJ
304 tests: Vec::new(),
305 tested_submods: Vec::new(),
9e0c209e 306 }.fold_crate(krate)
1a4d82fc
JJ
307}
308
85aaf69f 309/// Craft a span that will be ignored by the stability lint's
b7449926 310/// call to source_map's `is_internal` check.
85aaf69f
SL
311/// The expanded code calls some unstable functions in the test crate.
312fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
ea8adc8c 313 sp.with_ctxt(cx.ctxt)
85aaf69f
SL
314}
315
1a4d82fc
JJ
316enum HasTestSignature {
317 Yes,
83c7162d
XL
318 No(BadTestSignature),
319}
320
321#[derive(PartialEq)]
322enum BadTestSignature {
1a4d82fc 323 NotEvenAFunction,
83c7162d
XL
324 WrongTypeSignature,
325 NoArgumentsAllowed,
326 ShouldPanicOnlyWithNoArgs,
1a4d82fc
JJ
327}
328
b7449926
XL
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
85aaf69f
SL
331fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
332 // Writing this out by hand with 'ignored_span':
333 // pub fn main() {
334 // #![main]
b7449926 335 // test::test_main_static(::std::os::args().as_slice(), &[..tests]);
85aaf69f 336 // }
85aaf69f
SL
337 let sp = ignored_span(cx, DUMMY_SP);
338 let ecx = &cx.ext_cx;
b7449926 339 let test_id = ecx.ident_of("test").gensym();
476ff2be 340
85aaf69f 341 // test::test_main_static(...)
b7449926
XL
342 let mut test_runner = cx.test_runner.clone().unwrap_or(
343 ecx.path(sp, vec![
344 test_id, ecx.ident_of("test_main_static")
345 ]));
346
347 test_runner.span = sp;
348
349 let test_main_path_expr = ecx.expr_path(test_runner.clone());
85aaf69f 350 let call_test_main = ecx.expr_call(sp, test_main_path_expr,
b7449926 351 vec![mk_tests_slice(cx)]);
85aaf69f 352 let call_test_main = ecx.stmt_expr(call_test_main);
b7449926 353
85aaf69f 354 // #![main]
476ff2be 355 let main_meta = ecx.meta_word(sp, Symbol::intern("main"));
85aaf69f 356 let main_attr = ecx.attribute(sp, main_meta);
b7449926
XL
357
358 // extern crate test as test_gensym
359 let test_extern_stmt = ecx.stmt_item(sp, ecx.item(sp,
360 test_id,
361 vec![],
362 ast::ItemKind::ExternCrate(Some(Symbol::intern("test")))
363 ));
364
85aaf69f 365 // pub fn main() { ... }
7453a54e 366 let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
b7449926
XL
367
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])
371 } else {
372 ecx.block(sp, vec![call_test_main])
373 };
374
0531ce1d 375 let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], ast::FunctionRetTy::Ty(main_ret_ty)),
8faf50e0 376 ast::FnHeader::default(),
83c7162d
XL
377 ast::Generics::default(),
378 main_body);
b7449926
XL
379
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")),
383 sp);
384
7cac9316 385 P(ast::Item {
b7449926 386 ident: main_id,
85aaf69f
SL
387 attrs: vec![main_attr],
388 id: ast::DUMMY_NODE_ID,
389 node: main,
0531ce1d 390 vis: dummy_spanned(ast::VisibilityKind::Public),
3b2f2976
XL
391 span: sp,
392 tokens: None,
7cac9316 393 })
1a4d82fc 394
1a4d82fc
JJ
395}
396
476ff2be 397fn path_name_i(idents: &[Ident]) -> String {
0531ce1d
XL
398 let mut path_name = "".to_string();
399 let mut idents_iter = idents.iter().peekable();
400 while let Some(ident) = idents_iter.next() {
94b46f34 401 path_name.push_str(&ident.as_str());
b7449926 402 if idents_iter.peek().is_some() {
0531ce1d
XL
403 path_name.push_str("::")
404 }
405 }
406 path_name
54a0048b
SL
407}
408
b7449926
XL
409/// Creates a slice containing every test like so:
410/// &[path::to::test1, path::to::test2]
411fn 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;
414
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))))
419 }).collect())
1a4d82fc
JJ
420}
421
b7449926
XL
422/// Creates a path from the top-level __test module to the test via __test_reexports
423fn visible_path(cx: &TestCtxt, path: &[Ident]) -> Vec<Ident>{
0531ce1d 424 let mut visible_path = vec![];
0531ce1d
XL
425 match cx.toplevel_reexport {
426 Some(id) => visible_path.push(id),
1a4d82fc 427 None => {
b7449926 428 cx.span_diagnostic.bug("expected to find top-level re-export name, but found None");
0531ce1d 429 }
b7449926
XL
430 }
431 visible_path.extend_from_slice(path);
432 visible_path
433}
0531ce1d 434
b7449926
XL
435fn is_test_case(i: &ast::Item) -> bool {
436 attr::contains_name(&i.attrs, "rustc_test_marker")
437}
1a4d82fc 438
b7449926
XL
439fn 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()
445 }
446 Some(meta_list[0].word().as_ref().unwrap().ident.clone())
447 } else {
448 sd.span_fatal(test_attr.span(),
449 "test_runner must be of the form #[test_runner(..)]").raise()
450 }
1a4d82fc 451}