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