]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/test_harness.rs
Rollup merge of #101057 - cjgillot:one-fn-sig, r=compiler-errors
[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::entry::EntryPointType;
5 use rustc_ast::mut_visit::{ExpectOne, *};
6 use rustc_ast::ptr::P;
7 use rustc_ast::{attr, ModKind};
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.unstable_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 TestHarnessGenerator<'_> {
88     fn add_test_cases(&mut self, node_id: ast::NodeId, span: Span, prev_tests: Vec<Test>) {
89         let mut tests = mem::replace(&mut self.tests, prev_tests);
90
91         if !tests.is_empty() {
92             // Create an identifier that will hygienically resolve the test
93             // case name, even in another module.
94             let expn_id = self.cx.ext_cx.resolver.expansion_for_ast_pass(
95                 span,
96                 AstPass::TestHarness,
97                 &[],
98                 Some(node_id),
99             );
100             for test in &mut tests {
101                 // See the comment on `mk_main` for why we're using
102                 // `apply_mark` directly.
103                 test.ident.span =
104                     test.ident.span.apply_mark(expn_id.to_expn_id(), Transparency::Opaque);
105             }
106             self.cx.test_cases.extend(tests);
107         }
108     }
109 }
110
111 impl<'a> MutVisitor for TestHarnessGenerator<'a> {
112     fn visit_crate(&mut self, c: &mut ast::Crate) {
113         let prev_tests = mem::take(&mut self.tests);
114         noop_visit_crate(c, self);
115         self.add_test_cases(ast::CRATE_NODE_ID, c.spans.inner_span, prev_tests);
116
117         // Create a main function to run our tests
118         c.items.push(mk_main(&mut self.cx));
119     }
120
121     fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
122         let mut item = i.into_inner();
123         if is_test_case(&self.cx.ext_cx.sess, &item) {
124             debug!("this is a test item");
125
126             let test = Test { span: item.span, ident: item.ident };
127             self.tests.push(test);
128         }
129
130         // We don't want to recurse into anything other than mods, since
131         // mods or tests inside of functions will break things
132         if let ast::ItemKind::Mod(_, ModKind::Loaded(.., ref spans)) = item.kind {
133             let ast::ModSpans { inner_span: span, inject_use_span: _ } = *spans;
134             let prev_tests = mem::take(&mut self.tests);
135             noop_visit_item_kind(&mut item.kind, self);
136             self.add_test_cases(item.id, span, prev_tests);
137         }
138         smallvec![P(item)]
139     }
140 }
141
142 // Beware, this is duplicated in librustc_passes/entry.rs (with
143 // `rustc_hir::Item`), so make sure to keep them in sync.
144 fn entry_point_type(sess: &Session, item: &ast::Item, depth: usize) -> EntryPointType {
145     match item.kind {
146         ast::ItemKind::Fn(..) => {
147             if sess.contains_name(&item.attrs, sym::start) {
148                 EntryPointType::Start
149             } else if sess.contains_name(&item.attrs, sym::rustc_main) {
150                 EntryPointType::RustcMainAttr
151             } else if item.ident.name == sym::main {
152                 if depth == 0 {
153                     // This is a top-level function so can be 'main'
154                     EntryPointType::MainNamed
155                 } else {
156                     EntryPointType::OtherMain
157                 }
158             } else {
159                 EntryPointType::None
160             }
161         }
162         _ => EntryPointType::None,
163     }
164 }
165 /// A folder used to remove any entry points (like fn main) because the harness
166 /// generator will provide its own
167 struct EntryPointCleaner<'a> {
168     // Current depth in the ast
169     sess: &'a Session,
170     depth: usize,
171     def_site: Span,
172 }
173
174 impl<'a> MutVisitor for EntryPointCleaner<'a> {
175     fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
176         self.depth += 1;
177         let item = noop_flat_map_item(i, self).expect_one("noop did something");
178         self.depth -= 1;
179
180         // Remove any #[rustc_main] or #[start] from the AST so it doesn't
181         // clash with the one we're going to add, but mark it as
182         // #[allow(dead_code)] to avoid printing warnings.
183         let item = match entry_point_type(self.sess, &item, self.depth) {
184             EntryPointType::MainNamed | EntryPointType::RustcMainAttr | EntryPointType::Start => {
185                 item.map(|ast::Item { id, ident, attrs, kind, vis, span, tokens }| {
186                     let allow_ident = Ident::new(sym::allow, self.def_site);
187                     let dc_nested =
188                         attr::mk_nested_word_item(Ident::new(sym::dead_code, self.def_site));
189                     let allow_dead_code_item = attr::mk_list_item(allow_ident, vec![dc_nested]);
190                     let allow_dead_code = attr::mk_attr_outer(allow_dead_code_item);
191                     let attrs = attrs
192                         .into_iter()
193                         .filter(|attr| {
194                             !attr.has_name(sym::rustc_main) && !attr.has_name(sym::start)
195                         })
196                         .chain(iter::once(allow_dead_code))
197                         .collect();
198
199                     ast::Item { id, ident, attrs, kind, vis, span, tokens }
200                 })
201             }
202             EntryPointType::None | EntryPointType::OtherMain => item,
203         };
204
205         smallvec![item]
206     }
207 }
208
209 /// Crawl over the crate, inserting test reexports and the test main function
210 fn generate_test_harness(
211     sess: &Session,
212     resolver: &mut dyn ResolverExpand,
213     reexport_test_harness_main: Option<Symbol>,
214     krate: &mut ast::Crate,
215     features: &Features,
216     panic_strategy: PanicStrategy,
217     test_runner: Option<ast::Path>,
218 ) {
219     let mut econfig = ExpansionConfig::default("test".to_string());
220     econfig.features = Some(features);
221
222     let ext_cx = ExtCtxt::new(sess, econfig, resolver, None);
223
224     let expn_id = ext_cx.resolver.expansion_for_ast_pass(
225         DUMMY_SP,
226         AstPass::TestHarness,
227         &[sym::test, sym::rustc_attrs],
228         None,
229     );
230     let def_site = DUMMY_SP.with_def_site_ctxt(expn_id.to_expn_id());
231
232     // Remove the entry points
233     let mut cleaner = EntryPointCleaner { sess, depth: 0, def_site };
234     cleaner.visit_crate(krate);
235
236     let cx = TestCtxt {
237         ext_cx,
238         panic_strategy,
239         def_site,
240         test_cases: Vec::new(),
241         reexport_test_harness_main,
242         test_runner,
243     };
244
245     TestHarnessGenerator { cx, tests: Vec::new() }.visit_crate(krate);
246 }
247
248 /// Creates a function item for use as the main function of a test build.
249 /// This function will call the `test_runner` as specified by the crate attribute
250 ///
251 /// By default this expands to
252 ///
253 /// ```ignore UNSOLVED (I think I still need guidance for this one. Is it correct? Do we try to make it run? How do we nicely fill it out?)
254 /// #[rustc_main]
255 /// pub fn main() {
256 ///     extern crate test;
257 ///     test::test_main_static(&[
258 ///         &test_const1,
259 ///         &test_const2,
260 ///         &test_const3,
261 ///     ]);
262 /// }
263 /// ```
264 ///
265 /// Most of the Ident have the usual def-site hygiene for the AST pass. The
266 /// exception is the `test_const`s. These have a syntax context that has two
267 /// opaque marks: one from the expansion of `test` or `test_case`, and one
268 /// generated  in `TestHarnessGenerator::flat_map_item`. When resolving this
269 /// identifier after failing to find a matching identifier in the root module
270 /// we remove the outer mark, and try resolving at its def-site, which will
271 /// then resolve to `test_const`.
272 ///
273 /// The expansion here can be controlled by two attributes:
274 ///
275 /// [`TestCtxt::reexport_test_harness_main`] provides a different name for the `main`
276 /// function and [`TestCtxt::test_runner`] provides a path that replaces
277 /// `test::test_main_static`.
278 fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
279     let sp = cx.def_site;
280     let ecx = &cx.ext_cx;
281     let test_id = Ident::new(sym::test, sp);
282
283     let runner_name = match cx.panic_strategy {
284         PanicStrategy::Unwind => "test_main_static",
285         PanicStrategy::Abort => "test_main_static_abort",
286     };
287
288     // test::test_main_static(...)
289     let mut test_runner = cx
290         .test_runner
291         .clone()
292         .unwrap_or_else(|| ecx.path(sp, vec![test_id, Ident::from_str_and_span(runner_name, sp)]));
293
294     test_runner.span = sp;
295
296     let test_main_path_expr = ecx.expr_path(test_runner);
297     let call_test_main = ecx.expr_call(sp, test_main_path_expr, vec![mk_tests_slice(cx, sp)]);
298     let call_test_main = ecx.stmt_expr(call_test_main);
299
300     // extern crate test
301     let test_extern_stmt = ecx.stmt_item(
302         sp,
303         ecx.item(sp, test_id, ast::AttrVec::new(), ast::ItemKind::ExternCrate(None)),
304     );
305
306     // #[rustc_main]
307     let main_meta = ecx.meta_word(sp, sym::rustc_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(), span: sp };
322     let defaultness = ast::Defaultness::Final;
323     let main = ast::ItemKind::Fn(Box::new(ast::Fn {
324         defaultness,
325         sig,
326         generics: ast::Generics::default(),
327         body: Some(main_body),
328     }));
329
330     // Honor the reexport_test_harness_main attribute
331     let main_id = match cx.reexport_test_harness_main {
332         Some(sym) => Ident::new(sym, sp.with_ctxt(SyntaxContext::root())),
333         None => Ident::new(sym::main, sp),
334     };
335
336     let main = P(ast::Item {
337         ident: main_id,
338         attrs: vec![main_attr].into(),
339         id: ast::DUMMY_NODE_ID,
340         kind: main,
341         vis: ast::Visibility { span: sp, kind: ast::VisibilityKind::Public, tokens: None },
342         span: sp,
343         tokens: None,
344     });
345
346     // Integrate the new item into existing module structures.
347     let main = AstFragment::Items(smallvec![main]);
348     cx.ext_cx.monotonic_expander().fully_expand_fragment(main).make_items().pop().unwrap()
349 }
350
351 /// Creates a slice containing every test like so:
352 /// &[&test1, &test2]
353 fn mk_tests_slice(cx: &TestCtxt<'_>, sp: Span) -> P<ast::Expr> {
354     debug!("building test vector from {} tests", cx.test_cases.len());
355     let ecx = &cx.ext_cx;
356
357     ecx.expr_array_ref(
358         sp,
359         cx.test_cases
360             .iter()
361             .map(|test| {
362                 ecx.expr_addr_of(test.span, ecx.expr_path(ecx.path(test.span, vec![test.ident])))
363             })
364             .collect(),
365     )
366 }
367
368 fn is_test_case(sess: &Session, i: &ast::Item) -> bool {
369     sess.contains_name(&i.attrs, sym::rustc_test_marker)
370 }
371
372 fn get_test_runner(
373     sess: &Session,
374     sd: &rustc_errors::Handler,
375     krate: &ast::Crate,
376 ) -> Option<ast::Path> {
377     let test_attr = sess.find_by_name(&krate.attrs, sym::test_runner)?;
378     let meta_list = test_attr.meta_item_list()?;
379     let span = test_attr.span;
380     match &*meta_list {
381         [single] => match single.meta_item() {
382             Some(meta_item) if meta_item.is_word() => return Some(meta_item.path.clone()),
383             _ => {
384                 sd.struct_span_err(span, "`test_runner` argument must be a path").emit();
385             }
386         },
387         _ => {
388             sd.struct_span_err(span, "`#![test_runner(..)]` accepts exactly 1 argument").emit();
389         }
390     }
391     None
392 }