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