]> git.lizzy.rs Git - rust.git/blob - src/librustc_builtin_macros/test.rs
Auto merge of #69084 - yaahc:delayed-doc-lint, r=petrochenkov
[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_pretty::pprust;
6 use rustc_expand::base::*;
7 use rustc_span::source_map::respan;
8 use rustc_span::symbol::{sym, Symbol};
9 use rustc_span::Span;
10 use syntax::ast;
11 use syntax::attr;
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             cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))),
188             // test::TestDescAndFn {
189             Some(
190                 cx.expr_struct(
191                     sp,
192                     test_path("TestDescAndFn"),
193                     vec![
194                         // desc: test::TestDesc {
195                         field(
196                             "desc",
197                             cx.expr_struct(
198                                 sp,
199                                 test_path("TestDesc"),
200                                 vec![
201                                     // name: "path::to::test"
202                                     field(
203                                         "name",
204                                         cx.expr_call(
205                                             sp,
206                                             cx.expr_path(test_path("StaticTestName")),
207                                             vec![cx.expr_str(
208                                                 sp,
209                                                 Symbol::intern(&item_path(
210                                                     // skip the name of the root module
211                                                     &cx.current_expansion.module.mod_path[1..],
212                                                     &item.ident,
213                                                 )),
214                                             )],
215                                         ),
216                                     ),
217                                     // ignore: true | false
218                                     field("ignore", cx.expr_bool(sp, should_ignore(&item))),
219                                     // allow_fail: true | false
220                                     field("allow_fail", cx.expr_bool(sp, should_fail(&item))),
221                                     // should_panic: ...
222                                     field(
223                                         "should_panic",
224                                         match should_panic(cx, &item) {
225                                             // test::ShouldPanic::No
226                                             ShouldPanic::No => {
227                                                 cx.expr_path(should_panic_path("No"))
228                                             }
229                                             // test::ShouldPanic::Yes
230                                             ShouldPanic::Yes(None) => {
231                                                 cx.expr_path(should_panic_path("Yes"))
232                                             }
233                                             // test::ShouldPanic::YesWithMessage("...")
234                                             ShouldPanic::Yes(Some(sym)) => cx.expr_call(
235                                                 sp,
236                                                 cx.expr_path(should_panic_path("YesWithMessage")),
237                                                 vec![cx.expr_str(sp, sym)],
238                                             ),
239                                         },
240                                     ),
241                                     // test_type: ...
242                                     field(
243                                         "test_type",
244                                         match test_type(cx) {
245                                             // test::TestType::UnitTest
246                                             TestType::UnitTest => {
247                                                 cx.expr_path(test_type_path("UnitTest"))
248                                             }
249                                             // test::TestType::IntegrationTest
250                                             TestType::IntegrationTest => {
251                                                 cx.expr_path(test_type_path("IntegrationTest"))
252                                             }
253                                             // test::TestPath::Unknown
254                                             TestType::Unknown => {
255                                                 cx.expr_path(test_type_path("Unknown"))
256                                             }
257                                         },
258                                     ),
259                                     // },
260                                 ],
261                             ),
262                         ),
263                         // testfn: test::StaticTestFn(...) | test::StaticBenchFn(...)
264                         field("testfn", test_fn), // }
265                     ],
266                 ), // }
267             ),
268         ),
269     );
270     test_const = test_const.map(|mut tc| {
271         tc.vis.node = ast::VisibilityKind::Public;
272         tc
273     });
274
275     // extern crate test
276     let test_extern = cx.item(sp, test_id, vec![], ast::ItemKind::ExternCrate(None));
277
278     log::debug!("synthetic test item:\n{}\n", pprust::item_to_string(&test_const));
279
280     vec![
281         // Access to libtest under a hygienic name
282         Annotatable::Item(test_extern),
283         // The generated test case
284         Annotatable::Item(test_const),
285         // The original item
286         Annotatable::Item(item),
287     ]
288 }
289
290 fn item_path(mod_path: &[ast::Ident], item_ident: &ast::Ident) -> String {
291     mod_path
292         .iter()
293         .chain(iter::once(item_ident))
294         .map(|x| x.to_string())
295         .collect::<Vec<String>>()
296         .join("::")
297 }
298
299 enum ShouldPanic {
300     No,
301     Yes(Option<Symbol>),
302 }
303
304 fn should_ignore(i: &ast::Item) -> bool {
305     attr::contains_name(&i.attrs, sym::ignore)
306 }
307
308 fn should_fail(i: &ast::Item) -> bool {
309     attr::contains_name(&i.attrs, sym::allow_fail)
310 }
311
312 fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
313     match attr::find_by_name(&i.attrs, sym::should_panic) {
314         Some(attr) => {
315             let ref sd = cx.parse_sess.span_diagnostic;
316
317             match attr.meta_item_list() {
318                 // Handle #[should_panic(expected = "foo")]
319                 Some(list) => {
320                     let msg = list
321                         .iter()
322                         .find(|mi| mi.check_name(sym::expected))
323                         .and_then(|mi| mi.meta_item())
324                         .and_then(|mi| mi.value_str());
325                     if list.len() != 1 || msg.is_none() {
326                         sd.struct_span_warn(
327                             attr.span,
328                             "argument must be of the form: \
329                              `expected = \"error message\"`",
330                         )
331                         .note(
332                             "errors in this attribute were erroneously \
333                                 allowed and will become a hard error in a \
334                                 future release.",
335                         )
336                         .emit();
337                         ShouldPanic::Yes(None)
338                     } else {
339                         ShouldPanic::Yes(msg)
340                     }
341                 }
342                 // Handle #[should_panic] and #[should_panic = "expected"]
343                 None => ShouldPanic::Yes(attr.value_str()),
344             }
345         }
346         None => ShouldPanic::No,
347     }
348 }
349
350 enum TestType {
351     UnitTest,
352     IntegrationTest,
353     Unknown,
354 }
355
356 /// Attempts to determine the type of test.
357 /// Since doctests are created without macro expanding, only possible variants here
358 /// are `UnitTest`, `IntegrationTest` or `Unknown`.
359 fn test_type(cx: &ExtCtxt<'_>) -> TestType {
360     // Root path from context contains the topmost sources directory of the crate.
361     // I.e., for `project` with sources in `src` and tests in `tests` folders
362     // (no matter how many nested folders lie inside),
363     // there will be two different root paths: `/project/src` and `/project/tests`.
364     let crate_path = cx.root_path.as_path();
365
366     if crate_path.ends_with("src") {
367         // `/src` folder contains unit-tests.
368         TestType::UnitTest
369     } else if crate_path.ends_with("tests") {
370         // `/tests` folder contains integration tests.
371         TestType::IntegrationTest
372     } else {
373         // Crate layout doesn't match expected one, test type is unknown.
374         TestType::Unknown
375     }
376 }
377
378 fn has_test_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool {
379     let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic);
380     let ref sd = cx.parse_sess.span_diagnostic;
381     if let ast::ItemKind::Fn(ref sig, ref generics, _) = i.kind {
382         if let ast::Unsafe::Yes(span) = sig.header.unsafety {
383             sd.struct_span_err(i.span, "unsafe functions cannot be used for tests")
384                 .span_label(span, "`unsafe` because of this")
385                 .emit();
386             return false;
387         }
388         if let ast::Async::Yes { span, .. } = sig.header.asyncness {
389             sd.struct_span_err(i.span, "async functions cannot be used for tests")
390                 .span_label(span, "`async` because of this")
391                 .emit();
392             return false;
393         }
394
395         // If the termination trait is active, the compiler will check that the output
396         // type implements the `Termination` trait as `libtest` enforces that.
397         let has_output = match sig.decl.output {
398             ast::FnRetTy::Default(..) => false,
399             ast::FnRetTy::Ty(ref t) if t.kind.is_unit() => false,
400             _ => true,
401         };
402
403         if !sig.decl.inputs.is_empty() {
404             sd.span_err(i.span, "functions used as tests can not have any arguments");
405             return false;
406         }
407
408         match (has_output, has_should_panic_attr) {
409             (true, true) => {
410                 sd.span_err(i.span, "functions using `#[should_panic]` must return `()`");
411                 false
412             }
413             (true, false) => {
414                 if !generics.params.is_empty() {
415                     sd.span_err(i.span, "functions used as tests must have signature fn() -> ()");
416                     false
417                 } else {
418                     true
419                 }
420             }
421             (false, _) => true,
422         }
423     } else {
424         sd.span_err(i.span, "only functions may be used as tests");
425         false
426     }
427 }
428
429 fn has_bench_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool {
430     let has_sig = if let ast::ItemKind::Fn(ref sig, _, _) = i.kind {
431         // N.B., inadequate check, but we're running
432         // well before resolve, can't get too deep.
433         sig.decl.inputs.len() == 1
434     } else {
435         false
436     };
437
438     if !has_sig {
439         cx.parse_sess.span_diagnostic.span_err(
440             i.span,
441             "functions used as benches must have \
442             signature `fn(&mut Bencher) -> impl Termination`",
443         );
444     }
445
446     has_sig
447 }