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