]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/test_harness.rs
Rollup merge of #64898 - jakevossen5:master, r=jonas-schievink
[rust.git] / src / libsyntax_ext / test_harness.rs
1 // Code that generates a test runner to run all the tests in a crate
2
3 use log::debug;
4 use smallvec::{smallvec, SmallVec};
5 use rustc_target::spec::PanicStrategy;
6 use syntax::ast::{self, Ident};
7 use syntax::attr;
8 use syntax::entry::{self, EntryPointType};
9 use syntax::ext::base::{ExtCtxt, Resolver};
10 use syntax::ext::expand::{AstFragment, ExpansionConfig};
11 use syntax::feature_gate::Features;
12 use syntax::mut_visit::{*, ExpectOne};
13 use syntax::parse::ParseSess;
14 use syntax::ptr::P;
15 use syntax::source_map::respan;
16 use syntax::symbol::{sym, Symbol};
17 use syntax_pos::{Span, DUMMY_SP};
18 use syntax_pos::hygiene::{AstPass, SyntaxContext, Transparency};
19
20 use std::{iter, mem};
21
22 struct Test {
23     span: Span,
24     ident: Ident,
25 }
26
27 struct TestCtxt<'a> {
28     ext_cx: ExtCtxt<'a>,
29     panic_strategy: PanicStrategy,
30     def_site: Span,
31     test_cases: Vec<Test>,
32     reexport_test_harness_main: Option<Symbol>,
33     test_runner: Option<ast::Path>,
34 }
35
36 // Traverse the crate, collecting all the test functions, eliding any
37 // existing main functions, and synthesizing a main test harness
38 pub fn inject(
39     sess: &ParseSess,
40     resolver: &mut dyn Resolver,
41     should_test: bool,
42     krate: &mut ast::Crate,
43     span_diagnostic: &errors::Handler,
44     features: &Features,
45     panic_strategy: PanicStrategy,
46     platform_panic_strategy: PanicStrategy,
47     enable_panic_abort_tests: bool,
48 ) {
49     // Check for #![reexport_test_harness_main = "some_name"] which gives the
50     // main test function the name `some_name` without hygiene. This needs to be
51     // unconditional, so that the attribute is still marked as used in
52     // non-test builds.
53     let reexport_test_harness_main =
54         attr::first_attr_value_str_by_name(&krate.attrs, sym::reexport_test_harness_main);
55
56     // Do this here so that the test_runner crate attribute gets marked as used
57     // even in non-test builds
58     let test_runner = get_test_runner(span_diagnostic, &krate);
59
60     if should_test {
61         let panic_strategy = match (panic_strategy, enable_panic_abort_tests) {
62             (PanicStrategy::Abort, true) =>
63                 PanicStrategy::Abort,
64             (PanicStrategy::Abort, false) if panic_strategy == platform_panic_strategy => {
65                 // Silently allow compiling with panic=abort on these platforms,
66                 // but with old behavior (abort if a test fails).
67                 PanicStrategy::Unwind
68             }
69             (PanicStrategy::Abort, false) => {
70                 span_diagnostic.err("building tests with panic=abort is not yet supported");
71                 PanicStrategy::Unwind
72             }
73             (PanicStrategy::Unwind, _) => PanicStrategy::Unwind,
74         };
75         generate_test_harness(sess, resolver, reexport_test_harness_main,
76                               krate, features, panic_strategy, test_runner)
77     }
78 }
79
80 struct TestHarnessGenerator<'a> {
81     cx: TestCtxt<'a>,
82     tests: Vec<Test>,
83 }
84
85 impl<'a> MutVisitor for TestHarnessGenerator<'a> {
86     fn visit_crate(&mut self, c: &mut ast::Crate) {
87         noop_visit_crate(c, self);
88
89         // Create a main function to run our tests
90         c.module.items.push(mk_main(&mut self.cx));
91     }
92
93     fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
94         let mut item = i.into_inner();
95         if is_test_case(&item) {
96             debug!("this is a test item");
97
98             let test = Test {
99                 span: item.span,
100                 ident: item.ident,
101             };
102             self.tests.push(test);
103         }
104
105         // We don't want to recurse into anything other than mods, since
106         // mods or tests inside of functions will break things
107         if let ast::ItemKind::Mod(mut module) = item.kind {
108             let tests = mem::take(&mut self.tests);
109             noop_visit_mod(&mut module, self);
110             let mut tests = mem::replace(&mut self.tests, tests);
111
112             if !tests.is_empty() {
113                 let parent = if item.id == ast::DUMMY_NODE_ID {
114                     ast::CRATE_NODE_ID
115                 } else {
116                     item.id
117                 };
118                 // Create an identifier that will hygienically resolve the test
119                 // case name, even in another module.
120                 let expn_id = self.cx.ext_cx.resolver.expansion_for_ast_pass(
121                     module.inner,
122                     AstPass::TestHarness,
123                     &[],
124                     Some(parent),
125                 );
126                 for test in &mut tests {
127                     // See the comment on `mk_main` for why we're using
128                     // `apply_mark` directly.
129                     test.ident.span = test.ident.span.apply_mark(expn_id, Transparency::Opaque);
130                 }
131                 self.cx.test_cases.extend(tests);
132             }
133             item.kind = ast::ItemKind::Mod(module);
134         }
135         smallvec![P(item)]
136     }
137
138     fn visit_mac(&mut self, _mac: &mut ast::Mac) {
139         // Do nothing.
140     }
141 }
142
143 /// A folder used to remove any entry points (like fn main) because the harness
144 /// generator will provide its own
145 struct EntryPointCleaner {
146     // Current depth in the ast
147     depth: usize,
148     def_site: Span,
149 }
150
151 impl MutVisitor for EntryPointCleaner {
152     fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
153         self.depth += 1;
154         let item = noop_flat_map_item(i, self).expect_one("noop did something");
155         self.depth -= 1;
156
157         // Remove any #[main] or #[start] from the AST so it doesn't
158         // clash with the one we're going to add, but mark it as
159         // #[allow(dead_code)] to avoid printing warnings.
160         let item = match entry::entry_point_type(&item, self.depth) {
161             EntryPointType::MainNamed |
162             EntryPointType::MainAttr |
163             EntryPointType::Start =>
164                 item.map(|ast::Item {id, ident, attrs, kind, vis, span, tokens}| {
165                     let allow_ident = Ident::new(sym::allow, self.def_site);
166                     let dc_nested = attr::mk_nested_word_item(
167                         Ident::from_str_and_span("dead_code", self.def_site),
168                     );
169                     let allow_dead_code_item = attr::mk_list_item(allow_ident, vec![dc_nested]);
170                     let allow_dead_code = attr::mk_attr_outer(allow_dead_code_item);
171
172                     ast::Item {
173                         id,
174                         ident,
175                         attrs: attrs.into_iter()
176                             .filter(|attr| {
177                                 !attr.check_name(sym::main) && !attr.check_name(sym::start)
178                             })
179                             .chain(iter::once(allow_dead_code))
180                             .collect(),
181                         kind,
182                         vis,
183                         span,
184                         tokens,
185                     }
186                 }),
187             EntryPointType::None |
188             EntryPointType::OtherMain => item,
189         };
190
191         smallvec![item]
192     }
193
194     fn visit_mac(&mut self, _mac: &mut ast::Mac) {
195         // Do nothing.
196     }
197 }
198
199 /// Crawl over the crate, inserting test reexports and the test main function
200 fn generate_test_harness(sess: &ParseSess,
201                          resolver: &mut dyn Resolver,
202                          reexport_test_harness_main: Option<Symbol>,
203                          krate: &mut ast::Crate,
204                          features: &Features,
205                          panic_strategy: PanicStrategy,
206                          test_runner: Option<ast::Path>) {
207     let mut econfig = ExpansionConfig::default("test".to_string());
208     econfig.features = Some(features);
209
210     let ext_cx = ExtCtxt::new(sess, econfig, resolver);
211
212     let expn_id = ext_cx.resolver.expansion_for_ast_pass(
213         DUMMY_SP,
214         AstPass::TestHarness,
215         &[sym::main, sym::test, sym::rustc_attrs],
216         None,
217     );
218     let def_site = DUMMY_SP.with_def_site_ctxt(expn_id);
219
220     // Remove the entry points
221     let mut cleaner = EntryPointCleaner { depth: 0, def_site };
222     cleaner.visit_crate(krate);
223
224     let cx = TestCtxt {
225         ext_cx,
226         panic_strategy,
227         def_site,
228         test_cases: Vec::new(),
229         reexport_test_harness_main,
230         test_runner
231     };
232
233     TestHarnessGenerator {
234         cx,
235         tests: Vec::new(),
236     }.visit_crate(krate);
237 }
238
239 /// Creates a function item for use as the main function of a test build.
240 /// This function will call the `test_runner` as specified by the crate attribute
241 ///
242 /// By default this expands to
243 ///
244 /// #[main]
245 /// pub fn main() {
246 ///     extern crate test;
247 ///     test::test_main_static(&[
248 ///         &test_const1,
249 ///         &test_const2,
250 ///         &test_const3,
251 ///     ]);
252 /// }
253 ///
254 /// Most of the Ident have the usual def-site hygiene for the AST pass. The
255 /// exception is the `test_const`s. These have a syntax context that has two
256 /// opaque marks: one from the expansion of `test` or `test_case`, and one
257 /// generated  in `TestHarnessGenerator::flat_map_item`. When resolving this
258 /// identifier after failing to find a matching identifier in the root module
259 /// we remove the outer mark, and try resolving at its def-site, which will
260 /// then resolve to `test_const`.
261 ///
262 /// The expansion here can be controlled by two attributes:
263 ///
264 /// `reexport_test_harness_main` provides a different name for the `main`
265 /// function and `test_runner` provides a path that replaces
266 /// `test::test_main_static`.
267 fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
268     let sp = cx.def_site;
269     let ecx = &cx.ext_cx;
270     let test_id = Ident::new(sym::test, sp);
271
272     let runner_name = match cx.panic_strategy {
273         PanicStrategy::Unwind => "test_main_static",
274         PanicStrategy::Abort => "test_main_static_abort",
275     };
276
277     // test::test_main_static(...)
278     let mut test_runner = cx.test_runner.clone().unwrap_or(
279         ecx.path(sp, vec![test_id, ecx.ident_of(runner_name, sp)]));
280
281     test_runner.span = sp;
282
283     let test_main_path_expr = ecx.expr_path(test_runner);
284     let call_test_main = ecx.expr_call(sp, test_main_path_expr,
285                                        vec![mk_tests_slice(cx, sp)]);
286     let call_test_main = ecx.stmt_expr(call_test_main);
287
288     // extern crate test
289     let test_extern_stmt = ecx.stmt_item(sp, ecx.item(sp,
290         test_id,
291         vec![],
292         ast::ItemKind::ExternCrate(None)
293     ));
294
295     // #[main]
296     let main_meta = ecx.meta_word(sp, sym::main);
297     let main_attr = ecx.attribute(main_meta);
298
299     // pub fn main() { ... }
300     let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
301
302     // If no test runner is provided we need to import the test crate
303     let main_body = if cx.test_runner.is_none() {
304         ecx.block(sp, vec![test_extern_stmt, call_test_main])
305     } else {
306         ecx.block(sp, vec![call_test_main])
307     };
308
309     let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], ast::FunctionRetTy::Ty(main_ret_ty)),
310                            ast::FnHeader::default(),
311                            ast::Generics::default(),
312                            main_body);
313
314     // Honor the reexport_test_harness_main attribute
315     let main_id = match cx.reexport_test_harness_main {
316         Some(sym) => Ident::new(sym, sp.with_ctxt(SyntaxContext::root())),
317         None => Ident::new(sym::main, sp),
318     };
319
320     let main = P(ast::Item {
321         ident: main_id,
322         attrs: vec![main_attr],
323         id: ast::DUMMY_NODE_ID,
324         kind: main,
325         vis: respan(sp, ast::VisibilityKind::Public),
326         span: sp,
327         tokens: None,
328     });
329
330     // Integrate the new item into existing module structures.
331     let main = AstFragment::Items(smallvec![main]);
332     cx.ext_cx.monotonic_expander().fully_expand_fragment(main).make_items().pop().unwrap()
333 }
334
335 /// Creates a slice containing every test like so:
336 /// &[&test1, &test2]
337 fn mk_tests_slice(cx: &TestCtxt<'_>, sp: Span) -> P<ast::Expr> {
338     debug!("building test vector from {} tests", cx.test_cases.len());
339     let ref ecx = cx.ext_cx;
340
341
342     ecx.expr_vec_slice(sp,
343         cx.test_cases.iter().map(|test| {
344             ecx.expr_addr_of(test.span,
345                 ecx.expr_path(ecx.path(test.span, vec![test.ident])))
346         }).collect())
347 }
348
349 fn is_test_case(i: &ast::Item) -> bool {
350     attr::contains_name(&i.attrs, sym::rustc_test_marker)
351 }
352
353 fn get_test_runner(sd: &errors::Handler, krate: &ast::Crate) -> Option<ast::Path> {
354     let test_attr = attr::find_by_name(&krate.attrs, sym::test_runner)?;
355     test_attr.meta_item_list().map(|meta_list| {
356         if meta_list.len() != 1 {
357             sd.span_fatal(test_attr.span,
358                 "`#![test_runner(..)]` accepts exactly 1 argument").raise()
359         }
360         match meta_list[0].meta_item() {
361             Some(meta_item) if meta_item.is_word() => meta_item.path.clone(),
362             _ => sd.span_fatal(test_attr.span, "`test_runner` argument must be a path").raise()
363         }
364     })
365 }