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