]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/test_harness.rs
Rollup merge of #105359 - flba-eb:thread_local_key_sentinel_value, r=m-ou-se
[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(.., ast::ModSpans { inner_span: span, .. })) =
135             item.kind
136         {
137             let prev_tests = mem::take(&mut self.tests);
138             noop_visit_item_kind(&mut item.kind, self);
139             self.add_test_cases(item.id, span, prev_tests);
140         }
141         smallvec![P(item)]
142     }
143 }
144
145 // Beware, this is duplicated in librustc_passes/entry.rs (with
146 // `rustc_hir::Item`), so make sure to keep them in sync.
147 fn entry_point_type(sess: &Session, item: &ast::Item, depth: usize) -> EntryPointType {
148     match item.kind {
149         ast::ItemKind::Fn(..) => {
150             if sess.contains_name(&item.attrs, sym::start) {
151                 EntryPointType::Start
152             } else if sess.contains_name(&item.attrs, sym::rustc_main) {
153                 EntryPointType::RustcMainAttr
154             } else if item.ident.name == sym::main {
155                 if depth == 0 {
156                     // This is a top-level function so can be 'main'
157                     EntryPointType::MainNamed
158                 } else {
159                     EntryPointType::OtherMain
160                 }
161             } else {
162                 EntryPointType::None
163             }
164         }
165         _ => EntryPointType::None,
166     }
167 }
168 /// A folder used to remove any entry points (like fn main) because the harness
169 /// generator will provide its own
170 struct EntryPointCleaner<'a> {
171     // Current depth in the ast
172     sess: &'a Session,
173     depth: usize,
174     def_site: Span,
175 }
176
177 impl<'a> MutVisitor for EntryPointCleaner<'a> {
178     fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
179         self.depth += 1;
180         let item = noop_flat_map_item(i, self).expect_one("noop did something");
181         self.depth -= 1;
182
183         // Remove any #[rustc_main] or #[start] from the AST so it doesn't
184         // clash with the one we're going to add, but mark it as
185         // #[allow(dead_code)] to avoid printing warnings.
186         let item = match entry_point_type(self.sess, &item, self.depth) {
187             EntryPointType::MainNamed | EntryPointType::RustcMainAttr | EntryPointType::Start => {
188                 item.map(|ast::Item { id, ident, attrs, kind, vis, span, tokens }| {
189                     let allow_dead_code = attr::mk_attr_nested_word(
190                         &self.sess.parse_sess.attr_id_generator,
191                         ast::AttrStyle::Outer,
192                         sym::allow,
193                         sym::dead_code,
194                         self.def_site,
195                     );
196                     let attrs = attrs
197                         .into_iter()
198                         .filter(|attr| {
199                             !attr.has_name(sym::rustc_main) && !attr.has_name(sym::start)
200                         })
201                         .chain(iter::once(allow_dead_code))
202                         .collect();
203
204                     ast::Item { id, ident, attrs, kind, vis, span, tokens }
205                 })
206             }
207             EntryPointType::None | EntryPointType::OtherMain => item,
208         };
209
210         smallvec![item]
211     }
212 }
213
214 /// Crawl over the crate, inserting test reexports and the test main function
215 fn generate_test_harness(
216     sess: &Session,
217     resolver: &mut dyn ResolverExpand,
218     reexport_test_harness_main: Option<Symbol>,
219     krate: &mut ast::Crate,
220     features: &Features,
221     panic_strategy: PanicStrategy,
222     test_runner: Option<ast::Path>,
223 ) {
224     let mut econfig = ExpansionConfig::default("test".to_string());
225     econfig.features = Some(features);
226
227     let ext_cx = ExtCtxt::new(sess, econfig, resolver, None);
228
229     let expn_id = ext_cx.resolver.expansion_for_ast_pass(
230         DUMMY_SP,
231         AstPass::TestHarness,
232         &[sym::test, sym::rustc_attrs],
233         None,
234     );
235     let def_site = DUMMY_SP.with_def_site_ctxt(expn_id.to_expn_id());
236
237     // Remove the entry points
238     let mut cleaner = EntryPointCleaner { sess, depth: 0, def_site };
239     cleaner.visit_crate(krate);
240
241     let cx = TestCtxt {
242         ext_cx,
243         panic_strategy,
244         def_site,
245         test_cases: Vec::new(),
246         reexport_test_harness_main,
247         test_runner,
248     };
249
250     TestHarnessGenerator { cx, tests: Vec::new() }.visit_crate(krate);
251 }
252
253 /// Creates a function item for use as the main function of a test build.
254 /// This function will call the `test_runner` as specified by the crate attribute
255 ///
256 /// By default this expands to
257 ///
258 /// ```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?)
259 /// #[rustc_main]
260 /// pub fn main() {
261 ///     extern crate test;
262 ///     test::test_main_static(&[
263 ///         &test_const1,
264 ///         &test_const2,
265 ///         &test_const3,
266 ///     ]);
267 /// }
268 /// ```
269 ///
270 /// Most of the Ident have the usual def-site hygiene for the AST pass. The
271 /// exception is the `test_const`s. These have a syntax context that has two
272 /// opaque marks: one from the expansion of `test` or `test_case`, and one
273 /// generated  in `TestHarnessGenerator::flat_map_item`. When resolving this
274 /// identifier after failing to find a matching identifier in the root module
275 /// we remove the outer mark, and try resolving at its def-site, which will
276 /// then resolve to `test_const`.
277 ///
278 /// The expansion here can be controlled by two attributes:
279 ///
280 /// [`TestCtxt::reexport_test_harness_main`] provides a different name for the `main`
281 /// function and [`TestCtxt::test_runner`] provides a path that replaces
282 /// `test::test_main_static`.
283 fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
284     let sp = cx.def_site;
285     let ecx = &cx.ext_cx;
286     let test_id = Ident::new(sym::test, sp);
287
288     let runner_name = match cx.panic_strategy {
289         PanicStrategy::Unwind => "test_main_static",
290         PanicStrategy::Abort => "test_main_static_abort",
291     };
292
293     // test::test_main_static(...)
294     let mut test_runner = cx
295         .test_runner
296         .clone()
297         .unwrap_or_else(|| ecx.path(sp, vec![test_id, Ident::from_str_and_span(runner_name, sp)]));
298
299     test_runner.span = sp;
300
301     let test_main_path_expr = ecx.expr_path(test_runner);
302     let call_test_main = ecx.expr_call(sp, test_main_path_expr, vec![mk_tests_slice(cx, sp)]);
303     let call_test_main = ecx.stmt_expr(call_test_main);
304
305     // extern crate test
306     let test_extern_stmt = ecx.stmt_item(
307         sp,
308         ecx.item(sp, test_id, ast::AttrVec::new(), ast::ItemKind::ExternCrate(None)),
309     );
310
311     // #[rustc_main]
312     let main_attr = ecx.attr_word(sym::rustc_main, sp);
313
314     // pub fn main() { ... }
315     let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
316
317     // If no test runner is provided we need to import the test crate
318     let main_body = if cx.test_runner.is_none() {
319         ecx.block(sp, vec![test_extern_stmt, call_test_main])
320     } else {
321         ecx.block(sp, vec![call_test_main])
322     };
323
324     let decl = ecx.fn_decl(vec![], ast::FnRetTy::Ty(main_ret_ty));
325     let sig = ast::FnSig { decl, header: ast::FnHeader::default(), span: sp };
326     let defaultness = ast::Defaultness::Final;
327     let main = ast::ItemKind::Fn(Box::new(ast::Fn {
328         defaultness,
329         sig,
330         generics: ast::Generics::default(),
331         body: Some(main_body),
332     }));
333
334     // Honor the reexport_test_harness_main attribute
335     let main_id = match cx.reexport_test_harness_main {
336         Some(sym) => Ident::new(sym, sp.with_ctxt(SyntaxContext::root())),
337         None => Ident::new(sym::main, sp),
338     };
339
340     let main = P(ast::Item {
341         ident: main_id,
342         attrs: thin_vec![main_attr],
343         id: ast::DUMMY_NODE_ID,
344         kind: main,
345         vis: ast::Visibility { span: sp, kind: ast::VisibilityKind::Public, tokens: None },
346         span: sp,
347         tokens: None,
348     });
349
350     // Integrate the new item into existing module structures.
351     let main = AstFragment::Items(smallvec![main]);
352     cx.ext_cx.monotonic_expander().fully_expand_fragment(main).make_items().pop().unwrap()
353 }
354
355 /// Creates a slice containing every test like so:
356 /// &[&test1, &test2]
357 fn mk_tests_slice(cx: &TestCtxt<'_>, sp: Span) -> P<ast::Expr> {
358     debug!("building test vector from {} tests", cx.test_cases.len());
359     let ecx = &cx.ext_cx;
360
361     let mut tests = cx.test_cases.clone();
362     tests.sort_by(|a, b| a.name.as_str().cmp(&b.name.as_str()));
363
364     ecx.expr_array_ref(
365         sp,
366         tests
367             .iter()
368             .map(|test| {
369                 ecx.expr_addr_of(test.span, ecx.expr_path(ecx.path(test.span, vec![test.ident])))
370             })
371             .collect(),
372     )
373 }
374
375 fn get_test_name(sess: &Session, i: &ast::Item) -> Option<Symbol> {
376     sess.first_attr_value_str_by_name(&i.attrs, sym::rustc_test_marker)
377 }
378
379 fn get_test_runner(
380     sess: &Session,
381     sd: &rustc_errors::Handler,
382     krate: &ast::Crate,
383 ) -> Option<ast::Path> {
384     let test_attr = sess.find_by_name(&krate.attrs, sym::test_runner)?;
385     let meta_list = test_attr.meta_item_list()?;
386     let span = test_attr.span;
387     match &*meta_list {
388         [single] => match single.meta_item() {
389             Some(meta_item) if meta_item.is_word() => return Some(meta_item.path.clone()),
390             _ => {
391                 sd.struct_span_err(span, "`test_runner` argument must be a path").emit();
392             }
393         },
394         _ => {
395             sd.struct_span_err(span, "`#![test_runner(..)]` accepts exactly 1 argument").emit();
396         }
397     }
398     None
399 }