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.
5 use syntax::attr::{self, check_builtin_macro_attribute};
6 use syntax::ext::base::*;
7 use syntax::ext::hygiene::SyntaxContext;
8 use syntax::print::pprust;
9 use syntax::source_map::respan;
10 use syntax::symbol::{Symbol, sym};
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.
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<'_>,
25 meta_item: &ast::MetaItem,
26 anno_item: Annotatable
27 ) -> Vec<Annotatable> {
28 check_builtin_macro_attribute(ecx, meta_item, sym::test_case);
30 if !ecx.ecfg.should_test { return vec![]; }
32 let sp = attr_sp.with_ctxt(SyntaxContext::empty().apply_mark(ecx.current_expansion.id));
33 let mut item = anno_item.expect_item();
34 item = item.map(|mut item| {
35 item.vis = respan(item.vis.span, ast::VisibilityKind::Public);
36 item.ident = item.ident.gensym();
38 ecx.attribute(ecx.meta_word(sp, sym::rustc_test_marker))
43 return vec![Annotatable::Item(item)]
49 meta_item: &ast::MetaItem,
51 ) -> Vec<Annotatable> {
52 check_builtin_macro_attribute(cx, meta_item, sym::test);
53 expand_test_or_bench(cx, attr_sp, item, false)
59 meta_item: &ast::MetaItem,
61 ) -> Vec<Annotatable> {
62 check_builtin_macro_attribute(cx, meta_item, sym::bench);
63 expand_test_or_bench(cx, attr_sp, item, true)
66 pub fn expand_test_or_bench(
71 ) -> Vec<Annotatable> {
72 // If we're not in test configuration, remove the annotated item
73 if !cx.ecfg.should_test { return vec![]; }
76 if let Annotatable::Item(i) = item { i }
78 cx.parse_sess.span_diagnostic.span_fatal(item.span(),
79 "`#[test]` attribute is only allowed on non associated functions").raise();
82 if let ast::ItemKind::Mac(_) = item.node {
83 cx.parse_sess.span_diagnostic.span_warn(item.span,
84 "`#[test]` attribute should not be used on macros. Use `#[cfg(test)]` instead.");
85 return vec![Annotatable::Item(item)];
88 // has_*_signature will report any errors in the type so compilation
89 // will fail. We shouldn't try to expand in this case because the errors
91 if (!is_bench && !has_test_signature(cx, &item)) ||
92 (is_bench && !has_bench_signature(cx, &item)) {
93 return vec![Annotatable::Item(item)];
96 let ctxt = SyntaxContext::empty().apply_mark(cx.current_expansion.id);
97 let (sp, attr_sp) = (item.span.with_ctxt(ctxt), attr_sp.with_ctxt(ctxt));
99 // Gensym "test" so we can extern crate without conflicting with any local names
100 let test_id = cx.ident_of("test").gensym();
102 // creates test::$name
103 let test_path = |name| {
104 cx.path(sp, vec![test_id, cx.ident_of(name)])
107 // creates test::ShouldPanic::$name
108 let should_panic_path = |name| {
109 cx.path(sp, vec![test_id, cx.ident_of("ShouldPanic"), cx.ident_of(name)])
112 // creates $name: $expr
113 let field = |name, expr| cx.field_imm(sp, cx.ident_of(name), expr);
115 let test_fn = if is_bench {
116 // A simple ident for a lambda
117 let b = cx.ident_of("b");
119 cx.expr_call(sp, cx.expr_path(test_path("StaticBenchFn")), vec![
120 // |b| self::test::assert_test_result(
122 cx.expr_call(sp, cx.expr_path(test_path("assert_test_result")), vec![
123 // super::$test_fn(b)
125 cx.expr_path(cx.path(sp, vec![item.ident])),
126 vec![cx.expr_ident(sp, b)])
133 cx.expr_call(sp, cx.expr_path(test_path("StaticTestFn")), vec![
136 // test::assert_test_result(
137 cx.expr_call(sp, cx.expr_path(test_path("assert_test_result")), vec![
139 cx.expr_call(sp, cx.expr_path(cx.path(sp, vec![item.ident])), vec![])
148 let mut test_const = cx.item(sp, ast::Ident::new(item.ident.name, sp).gensym(),
151 cx.attribute(cx.meta_list(attr_sp, sym::cfg, vec![
152 cx.meta_list_item_word(attr_sp, sym::test)
154 // #[rustc_test_marker]
155 cx.attribute(cx.meta_word(attr_sp, sym::rustc_test_marker)),
157 // const $ident: test::TestDescAndFn =
158 ast::ItemKind::Const(cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))),
159 // test::TestDescAndFn {
160 cx.expr_struct(sp, test_path("TestDescAndFn"), vec![
161 // desc: test::TestDesc {
162 field("desc", cx.expr_struct(sp, test_path("TestDesc"), vec![
163 // name: "path::to::test"
164 field("name", cx.expr_call(sp, cx.expr_path(test_path("StaticTestName")),
166 cx.expr_str(sp, Symbol::intern(&item_path(
167 // skip the name of the root module
168 &cx.current_expansion.module.mod_path[1..],
172 // ignore: true | false
173 field("ignore", cx.expr_bool(sp, should_ignore(&item))),
174 // allow_fail: true | false
175 field("allow_fail", cx.expr_bool(sp, should_fail(&item))),
177 field("should_panic", match should_panic(cx, &item) {
178 // test::ShouldPanic::No
179 ShouldPanic::No => cx.expr_path(should_panic_path("No")),
180 // test::ShouldPanic::Yes
181 ShouldPanic::Yes(None) => cx.expr_path(should_panic_path("Yes")),
182 // test::ShouldPanic::YesWithMessage("...")
183 ShouldPanic::Yes(Some(sym)) => cx.expr_call(sp,
184 cx.expr_path(should_panic_path("YesWithMessage")),
185 vec![cx.expr_str(sp, sym)]),
189 // testfn: test::StaticTestFn(...) | test::StaticBenchFn(...)
190 field("testfn", test_fn)
195 test_const = test_const.map(|mut tc| { tc.vis.node = ast::VisibilityKind::Public; tc});
197 // extern crate test as test_gensym
198 let test_extern = cx.item(sp,
201 ast::ItemKind::ExternCrate(Some(sym::test))
204 log::debug!("synthetic test item:\n{}\n", pprust::item_to_string(&test_const));
207 // Access to libtest under a gensymed name
208 Annotatable::Item(test_extern),
209 // The generated test case
210 Annotatable::Item(test_const),
212 Annotatable::Item(item)
216 fn item_path(mod_path: &[ast::Ident], item_ident: &ast::Ident) -> String {
217 mod_path.iter().chain(iter::once(item_ident))
218 .map(|x| x.to_string()).collect::<Vec<String>>().join("::")
226 fn should_ignore(i: &ast::Item) -> bool {
227 attr::contains_name(&i.attrs, sym::ignore)
230 fn should_fail(i: &ast::Item) -> bool {
231 attr::contains_name(&i.attrs, sym::allow_fail)
234 fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
235 match attr::find_by_name(&i.attrs, sym::should_panic) {
237 let ref sd = cx.parse_sess.span_diagnostic;
239 match attr.meta_item_list() {
240 // Handle #[should_panic(expected = "foo")]
242 let msg = list.iter()
243 .find(|mi| mi.check_name(sym::expected))
244 .and_then(|mi| mi.meta_item())
245 .and_then(|mi| mi.value_str());
246 if list.len() != 1 || msg.is_none() {
249 "argument must be of the form: \
250 `expected = \"error message\"`"
251 ).note("Errors in this attribute were erroneously \
252 allowed and will become a hard error in a \
253 future release.").emit();
254 ShouldPanic::Yes(None)
256 ShouldPanic::Yes(msg)
259 // Handle #[should_panic] and #[should_panic = "expected"]
260 None => ShouldPanic::Yes(attr.value_str())
263 None => ShouldPanic::No,
267 fn has_test_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool {
268 let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic);
269 let ref sd = cx.parse_sess.span_diagnostic;
270 if let ast::ItemKind::Fn(ref decl, ref header, ref generics, _) = i.node {
271 if header.unsafety == ast::Unsafety::Unsafe {
274 "unsafe functions cannot be used for tests"
278 if header.asyncness.node.is_async() {
281 "async functions cannot be used for tests"
287 // If the termination trait is active, the compiler will check that the output
288 // type implements the `Termination` trait as `libtest` enforces that.
289 let has_output = match decl.output {
290 ast::FunctionRetTy::Default(..) => false,
291 ast::FunctionRetTy::Ty(ref t) if t.node.is_unit() => false,
295 if !decl.inputs.is_empty() {
296 sd.span_err(i.span, "functions used as tests can not have any arguments");
300 match (has_output, has_should_panic_attr) {
302 sd.span_err(i.span, "functions using `#[should_panic]` must return `()`");
305 (true, false) => if !generics.params.is_empty() {
307 "functions used as tests must have signature fn() -> ()");
315 sd.span_err(i.span, "only functions may be used as tests");
320 fn has_bench_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool {
321 let has_sig = if let ast::ItemKind::Fn(ref decl, _, _, _) = i.node {
322 // N.B., inadequate check, but we're running
323 // well before resolve, can't get too deep.
324 decl.inputs.len() == 1
330 cx.parse_sess.span_diagnostic.span_err(i.span, "functions used as benches must have \
331 signature `fn(&mut Bencher) -> impl Termination`");