]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/test.rs
Rollup merge of #94252 - lcnr:def_kind-encoding, r=cjgillot
[rust.git] / compiler / rustc_builtin_macros / src / test.rs
1 /// The expansion from a test function to the appropriate test struct for libtest
2 /// Ideally, this code would be in libtest but for efficiency and error messages it lives here.
3 use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute};
4
5 use rustc_ast as ast;
6 use rustc_ast::attr;
7 use rustc_ast::ptr::P;
8 use rustc_ast_pretty::pprust;
9 use rustc_errors::Applicability;
10 use rustc_expand::base::*;
11 use rustc_session::Session;
12 use rustc_span::symbol::{sym, Ident, Symbol};
13 use rustc_span::Span;
14
15 use std::iter;
16
17 // #[test_case] is used by custom test authors to mark tests
18 // When building for test, it needs to make the item public and gensym the name
19 // Otherwise, we'll omit the item. This behavior means that any item annotated
20 // with #[test_case] is never addressable.
21 //
22 // We mark item with an inert attribute "rustc_test_marker" which the test generation
23 // logic will pick up on.
24 pub fn expand_test_case(
25     ecx: &mut ExtCtxt<'_>,
26     attr_sp: Span,
27     meta_item: &ast::MetaItem,
28     anno_item: Annotatable,
29 ) -> Vec<Annotatable> {
30     check_builtin_macro_attribute(ecx, meta_item, sym::test_case);
31     warn_on_duplicate_attribute(&ecx, &anno_item, sym::test_case);
32
33     if !ecx.ecfg.should_test {
34         return vec![];
35     }
36
37     let sp = ecx.with_def_site_ctxt(attr_sp);
38     let mut item = anno_item.expect_item();
39     item = item.map(|mut item| {
40         item.vis = ast::Visibility {
41             span: item.vis.span,
42             kind: ast::VisibilityKind::Public,
43             tokens: None,
44         };
45         item.ident.span = item.ident.span.with_ctxt(sp.ctxt());
46         item.attrs.push(ecx.attribute(ecx.meta_word(sp, sym::rustc_test_marker)));
47         item
48     });
49
50     return vec![Annotatable::Item(item)];
51 }
52
53 pub fn expand_test(
54     cx: &mut ExtCtxt<'_>,
55     attr_sp: Span,
56     meta_item: &ast::MetaItem,
57     item: Annotatable,
58 ) -> Vec<Annotatable> {
59     check_builtin_macro_attribute(cx, meta_item, sym::test);
60     warn_on_duplicate_attribute(&cx, &item, sym::test);
61     expand_test_or_bench(cx, attr_sp, item, false)
62 }
63
64 pub fn expand_bench(
65     cx: &mut ExtCtxt<'_>,
66     attr_sp: Span,
67     meta_item: &ast::MetaItem,
68     item: Annotatable,
69 ) -> Vec<Annotatable> {
70     check_builtin_macro_attribute(cx, meta_item, sym::bench);
71     warn_on_duplicate_attribute(&cx, &item, sym::bench);
72     expand_test_or_bench(cx, attr_sp, item, true)
73 }
74
75 pub fn expand_test_or_bench(
76     cx: &mut ExtCtxt<'_>,
77     attr_sp: Span,
78     item: Annotatable,
79     is_bench: bool,
80 ) -> Vec<Annotatable> {
81     // If we're not in test configuration, remove the annotated item
82     if !cx.ecfg.should_test {
83         return vec![];
84     }
85
86     let (item, is_stmt) = match item {
87         Annotatable::Item(i) => (i, false),
88         Annotatable::Stmt(stmt) if matches!(stmt.kind, ast::StmtKind::Item(_)) => {
89             // FIXME: Use an 'if let' guard once they are implemented
90             if let ast::StmtKind::Item(i) = stmt.into_inner().kind {
91                 (i, true)
92             } else {
93                 unreachable!()
94             }
95         }
96         other => {
97             cx.struct_span_err(
98                 other.span(),
99                 "`#[test]` attribute is only allowed on non associated functions",
100             )
101             .emit();
102             return vec![other];
103         }
104     };
105
106     // Note: non-associated fn items are already handled by `expand_test_or_bench`
107     if !matches!(item.kind, ast::ItemKind::Fn(_)) {
108         cx.sess
109             .parse_sess
110             .span_diagnostic
111             .struct_span_err(
112                 attr_sp,
113                 "the `#[test]` attribute may only be used on a non-associated function",
114             )
115             .note("the `#[test]` macro causes a a function to be run on a test and has no effect on non-functions")
116             .span_label(item.span, format!("expected a non-associated function, found {} {}", item.kind.article(), item.kind.descr()))
117             .span_suggestion(attr_sp, "replace with conditional compilation to make the item only exist when tests are being run", String::from("#[cfg(test)]"), Applicability::MaybeIncorrect)
118             .emit();
119
120         return vec![Annotatable::Item(item)];
121     }
122
123     // has_*_signature will report any errors in the type so compilation
124     // will fail. We shouldn't try to expand in this case because the errors
125     // would be spurious.
126     if (!is_bench && !has_test_signature(cx, &item))
127         || (is_bench && !has_bench_signature(cx, &item))
128     {
129         return vec![Annotatable::Item(item)];
130     }
131
132     let (sp, attr_sp) = (cx.with_def_site_ctxt(item.span), cx.with_def_site_ctxt(attr_sp));
133
134     let test_id = Ident::new(sym::test, attr_sp);
135
136     // creates test::$name
137     let test_path = |name| cx.path(sp, vec![test_id, Ident::from_str_and_span(name, sp)]);
138
139     // creates test::ShouldPanic::$name
140     let should_panic_path = |name| {
141         cx.path(
142             sp,
143             vec![
144                 test_id,
145                 Ident::from_str_and_span("ShouldPanic", sp),
146                 Ident::from_str_and_span(name, sp),
147             ],
148         )
149     };
150
151     // creates test::TestType::$name
152     let test_type_path = |name| {
153         cx.path(
154             sp,
155             vec![
156                 test_id,
157                 Ident::from_str_and_span("TestType", sp),
158                 Ident::from_str_and_span(name, sp),
159             ],
160         )
161     };
162
163     // creates $name: $expr
164     let field = |name, expr| cx.field_imm(sp, Ident::from_str_and_span(name, sp), expr);
165
166     let test_fn = if is_bench {
167         // A simple ident for a lambda
168         let b = Ident::from_str_and_span("b", attr_sp);
169
170         cx.expr_call(
171             sp,
172             cx.expr_path(test_path("StaticBenchFn")),
173             vec![
174                 // |b| self::test::assert_test_result(
175                 cx.lambda1(
176                     sp,
177                     cx.expr_call(
178                         sp,
179                         cx.expr_path(test_path("assert_test_result")),
180                         vec![
181                             // super::$test_fn(b)
182                             cx.expr_call(
183                                 sp,
184                                 cx.expr_path(cx.path(sp, vec![item.ident])),
185                                 vec![cx.expr_ident(sp, b)],
186                             ),
187                         ],
188                     ),
189                     b,
190                 ), // )
191             ],
192         )
193     } else {
194         cx.expr_call(
195             sp,
196             cx.expr_path(test_path("StaticTestFn")),
197             vec![
198                 // || {
199                 cx.lambda0(
200                     sp,
201                     // test::assert_test_result(
202                     cx.expr_call(
203                         sp,
204                         cx.expr_path(test_path("assert_test_result")),
205                         vec![
206                             // $test_fn()
207                             cx.expr_call(sp, cx.expr_path(cx.path(sp, vec![item.ident])), vec![]), // )
208                         ],
209                     ), // }
210                 ), // )
211             ],
212         )
213     };
214
215     let mut test_const = cx.item(
216         sp,
217         Ident::new(item.ident.name, sp),
218         vec![
219             // #[cfg(test)]
220             cx.attribute(attr::mk_list_item(
221                 Ident::new(sym::cfg, attr_sp),
222                 vec![attr::mk_nested_word_item(Ident::new(sym::test, attr_sp))],
223             )),
224             // #[rustc_test_marker]
225             cx.attribute(cx.meta_word(attr_sp, sym::rustc_test_marker)),
226         ],
227         // const $ident: test::TestDescAndFn =
228         ast::ItemKind::Const(
229             ast::Defaultness::Final,
230             cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))),
231             // test::TestDescAndFn {
232             Some(
233                 cx.expr_struct(
234                     sp,
235                     test_path("TestDescAndFn"),
236                     vec![
237                         // desc: test::TestDesc {
238                         field(
239                             "desc",
240                             cx.expr_struct(
241                                 sp,
242                                 test_path("TestDesc"),
243                                 vec![
244                                     // name: "path::to::test"
245                                     field(
246                                         "name",
247                                         cx.expr_call(
248                                             sp,
249                                             cx.expr_path(test_path("StaticTestName")),
250                                             vec![cx.expr_str(
251                                                 sp,
252                                                 Symbol::intern(&item_path(
253                                                     // skip the name of the root module
254                                                     &cx.current_expansion.module.mod_path[1..],
255                                                     &item.ident,
256                                                 )),
257                                             )],
258                                         ),
259                                     ),
260                                     // ignore: true | false
261                                     field(
262                                         "ignore",
263                                         cx.expr_bool(sp, should_ignore(&cx.sess, &item)),
264                                     ),
265                                     // ignore_message: Some("...") | None
266                                     field(
267                                         "ignore_message",
268                                         if let Some(msg) = should_ignore_message(cx, &item) {
269                                             cx.expr_some(sp, cx.expr_str(sp, msg))
270                                         } else {
271                                             cx.expr_none(sp)
272                                         },
273                                     ),
274                                     // compile_fail: true | false
275                                     field("compile_fail", cx.expr_bool(sp, false)),
276                                     // no_run: true | false
277                                     field("no_run", cx.expr_bool(sp, false)),
278                                     // should_panic: ...
279                                     field(
280                                         "should_panic",
281                                         match should_panic(cx, &item) {
282                                             // test::ShouldPanic::No
283                                             ShouldPanic::No => {
284                                                 cx.expr_path(should_panic_path("No"))
285                                             }
286                                             // test::ShouldPanic::Yes
287                                             ShouldPanic::Yes(None) => {
288                                                 cx.expr_path(should_panic_path("Yes"))
289                                             }
290                                             // test::ShouldPanic::YesWithMessage("...")
291                                             ShouldPanic::Yes(Some(sym)) => cx.expr_call(
292                                                 sp,
293                                                 cx.expr_path(should_panic_path("YesWithMessage")),
294                                                 vec![cx.expr_str(sp, sym)],
295                                             ),
296                                         },
297                                     ),
298                                     // test_type: ...
299                                     field(
300                                         "test_type",
301                                         match test_type(cx) {
302                                             // test::TestType::UnitTest
303                                             TestType::UnitTest => {
304                                                 cx.expr_path(test_type_path("UnitTest"))
305                                             }
306                                             // test::TestType::IntegrationTest
307                                             TestType::IntegrationTest => {
308                                                 cx.expr_path(test_type_path("IntegrationTest"))
309                                             }
310                                             // test::TestPath::Unknown
311                                             TestType::Unknown => {
312                                                 cx.expr_path(test_type_path("Unknown"))
313                                             }
314                                         },
315                                     ),
316                                     // },
317                                 ],
318                             ),
319                         ),
320                         // testfn: test::StaticTestFn(...) | test::StaticBenchFn(...)
321                         field("testfn", test_fn), // }
322                     ],
323                 ), // }
324             ),
325         ),
326     );
327     test_const = test_const.map(|mut tc| {
328         tc.vis.kind = ast::VisibilityKind::Public;
329         tc
330     });
331
332     // extern crate test
333     let test_extern = cx.item(sp, test_id, vec![], ast::ItemKind::ExternCrate(None));
334
335     tracing::debug!("synthetic test item:\n{}\n", pprust::item_to_string(&test_const));
336
337     if is_stmt {
338         vec![
339             // Access to libtest under a hygienic name
340             Annotatable::Stmt(P(cx.stmt_item(sp, test_extern))),
341             // The generated test case
342             Annotatable::Stmt(P(cx.stmt_item(sp, test_const))),
343             // The original item
344             Annotatable::Stmt(P(cx.stmt_item(sp, item))),
345         ]
346     } else {
347         vec![
348             // Access to libtest under a hygienic name
349             Annotatable::Item(test_extern),
350             // The generated test case
351             Annotatable::Item(test_const),
352             // The original item
353             Annotatable::Item(item),
354         ]
355     }
356 }
357
358 fn item_path(mod_path: &[Ident], item_ident: &Ident) -> String {
359     mod_path
360         .iter()
361         .chain(iter::once(item_ident))
362         .map(|x| x.to_string())
363         .collect::<Vec<String>>()
364         .join("::")
365 }
366
367 enum ShouldPanic {
368     No,
369     Yes(Option<Symbol>),
370 }
371
372 fn should_ignore(sess: &Session, i: &ast::Item) -> bool {
373     sess.contains_name(&i.attrs, sym::ignore)
374 }
375
376 fn should_ignore_message(cx: &ExtCtxt<'_>, i: &ast::Item) -> Option<Symbol> {
377     match cx.sess.find_by_name(&i.attrs, sym::ignore) {
378         Some(attr) => {
379             match attr.meta_item_list() {
380                 // Handle #[ignore(bar = "foo")]
381                 Some(_) => None,
382                 // Handle #[ignore] and #[ignore = "message"]
383                 None => attr.value_str(),
384             }
385         }
386         None => None,
387     }
388 }
389
390 fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
391     match cx.sess.find_by_name(&i.attrs, sym::should_panic) {
392         Some(attr) => {
393             let sd = &cx.sess.parse_sess.span_diagnostic;
394
395             match attr.meta_item_list() {
396                 // Handle #[should_panic(expected = "foo")]
397                 Some(list) => {
398                     let msg = list
399                         .iter()
400                         .find(|mi| mi.has_name(sym::expected))
401                         .and_then(|mi| mi.meta_item())
402                         .and_then(|mi| mi.value_str());
403                     if list.len() != 1 || msg.is_none() {
404                         sd.struct_span_warn(
405                             attr.span,
406                             "argument must be of the form: \
407                              `expected = \"error message\"`",
408                         )
409                         .note(
410                             "errors in this attribute were erroneously \
411                                 allowed and will become a hard error in a \
412                                 future release",
413                         )
414                         .emit();
415                         ShouldPanic::Yes(None)
416                     } else {
417                         ShouldPanic::Yes(msg)
418                     }
419                 }
420                 // Handle #[should_panic] and #[should_panic = "expected"]
421                 None => ShouldPanic::Yes(attr.value_str()),
422             }
423         }
424         None => ShouldPanic::No,
425     }
426 }
427
428 enum TestType {
429     UnitTest,
430     IntegrationTest,
431     Unknown,
432 }
433
434 /// Attempts to determine the type of test.
435 /// Since doctests are created without macro expanding, only possible variants here
436 /// are `UnitTest`, `IntegrationTest` or `Unknown`.
437 fn test_type(cx: &ExtCtxt<'_>) -> TestType {
438     // Root path from context contains the topmost sources directory of the crate.
439     // I.e., for `project` with sources in `src` and tests in `tests` folders
440     // (no matter how many nested folders lie inside),
441     // there will be two different root paths: `/project/src` and `/project/tests`.
442     let crate_path = cx.root_path.as_path();
443
444     if crate_path.ends_with("src") {
445         // `/src` folder contains unit-tests.
446         TestType::UnitTest
447     } else if crate_path.ends_with("tests") {
448         // `/tests` folder contains integration tests.
449         TestType::IntegrationTest
450     } else {
451         // Crate layout doesn't match expected one, test type is unknown.
452         TestType::Unknown
453     }
454 }
455
456 fn has_test_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool {
457     let has_should_panic_attr = cx.sess.contains_name(&i.attrs, sym::should_panic);
458     let sd = &cx.sess.parse_sess.span_diagnostic;
459     if let ast::ItemKind::Fn(box ast::Fn { ref sig, ref generics, .. }) = i.kind {
460         if let ast::Unsafe::Yes(span) = sig.header.unsafety {
461             sd.struct_span_err(i.span, "unsafe functions cannot be used for tests")
462                 .span_label(span, "`unsafe` because of this")
463                 .emit();
464             return false;
465         }
466         if let ast::Async::Yes { span, .. } = sig.header.asyncness {
467             sd.struct_span_err(i.span, "async functions cannot be used for tests")
468                 .span_label(span, "`async` because of this")
469                 .emit();
470             return false;
471         }
472
473         // If the termination trait is active, the compiler will check that the output
474         // type implements the `Termination` trait as `libtest` enforces that.
475         let has_output = match sig.decl.output {
476             ast::FnRetTy::Default(..) => false,
477             ast::FnRetTy::Ty(ref t) if t.kind.is_unit() => false,
478             _ => true,
479         };
480
481         if !sig.decl.inputs.is_empty() {
482             sd.span_err(i.span, "functions used as tests can not have any arguments");
483             return false;
484         }
485
486         match (has_output, has_should_panic_attr) {
487             (true, true) => {
488                 sd.span_err(i.span, "functions using `#[should_panic]` must return `()`");
489                 false
490             }
491             (true, false) => {
492                 if !generics.params.is_empty() {
493                     sd.span_err(i.span, "functions used as tests must have signature fn() -> ()");
494                     false
495                 } else {
496                     true
497                 }
498             }
499             (false, _) => true,
500         }
501     } else {
502         // should be unreachable because `is_test_fn_item` should catch all non-fn items
503         false
504     }
505 }
506
507 fn has_bench_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool {
508     let has_sig = if let ast::ItemKind::Fn(box ast::Fn { ref sig, .. }) = i.kind {
509         // N.B., inadequate check, but we're running
510         // well before resolve, can't get too deep.
511         sig.decl.inputs.len() == 1
512     } else {
513         false
514     };
515
516     if !has_sig {
517         cx.sess.parse_sess.span_diagnostic.span_err(
518             i.span,
519             "functions used as benches must have \
520             signature `fn(&mut Bencher) -> impl Termination`",
521         );
522     }
523
524     has_sig
525 }