Skip to main content

rustc_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
4use std::{assert_matches, iter};
5
6use rustc_ast::{self as ast, GeneratedAttr, GenericParamKind, Mutability, attr, join_path_idents};
7use rustc_ast_pretty::pprust;
8use rustc_attr_ir::{Attribute, AttributeKind};
9use rustc_attr_parsing::AttributeParser;
10use rustc_errors::{Applicability, Diag, Level};
11use rustc_expand::base::*;
12use rustc_span::{ErrorGuaranteed, Ident, RemapPathScopeComponents, Span, Symbol, sym};
13use thin_vec::{ThinVec, thin_vec};
14use tracing::debug;
15
16use crate::diagnostics;
17use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute};
18
19/// #[test_case] is used by custom test authors to mark tests
20/// When building for test, it needs to make the item public and gensym the name
21/// Otherwise, we'll omit the item. This behavior means that any item annotated
22/// with #[test_case] is never addressable.
23///
24/// We mark item with an inert attribute "rustc_test_marker" which the test generation
25/// logic will pick up on.
26pub(crate) fn expand_test_case(
27    ecx: &mut ExtCtxt<'_>,
28    attr_sp: Span,
29    meta_item: &ast::MetaItem,
30    anno_item: Annotatable,
31) -> Vec<Annotatable> {
32    check_builtin_macro_attribute(ecx, meta_item, sym::test_case);
33    warn_on_duplicate_attribute(ecx, &anno_item, sym::test_case);
34
35    let sp = ecx.with_def_site_ctxt(attr_sp);
36    let (mut item, is_stmt) = match anno_item {
37        Annotatable::Item(item) => (item, false),
38        Annotatable::Stmt(stmt) if let ast::StmtKind::Item(_) = stmt.kind => {
39            if let ast::StmtKind::Item(i) = stmt.kind {
40                (i, true)
41            } else {
42                ::core::panicking::unreachable_default_msg()unreachable!()
43            }
44        }
45        _ => {
46            ecx.dcx().emit_err(diagnostics::TestCaseNonItem { span: anno_item.span() });
47            return ::alloc::vec::Vec::new()vec![];
48        }
49    };
50
51    if !ecx.ecfg.should_test {
52        return ::alloc::vec::Vec::new()vec![];
53    }
54
55    // `#[test_case]` is valid on functions, consts, and statics. Only modify
56    // the item in those cases.
57    match &mut item.kind {
58        ast::ItemKind::Fn(ast::Fn { ident, .. })
59        | ast::ItemKind::Const(ast::ConstItem { ident, .. })
60        | ast::ItemKind::Static(ast::StaticItem { ident, .. }) => {
61            ident.span = ident.span.with_ctxt(sp.ctxt());
62            let test_path_symbol = Symbol::intern(&item_path(
63                // skip the name of the root module
64                &ecx.current_expansion.module.mod_path[1..],
65                ident,
66            ));
67            item.vis = ast::Visibility { span: item.vis.span, kind: ast::VisibilityKind::Public };
68            item.attrs.push(
69                ecx.generated_attr(attr_sp, GeneratedAttr::RustcTestMarker(test_path_symbol)),
70            );
71        }
72        _ => {}
73    }
74
75    let ret = if is_stmt {
76        Annotatable::Stmt(Box::new(ecx.stmt_item(item.span, item)))
77    } else {
78        Annotatable::Item(item)
79    };
80
81    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ret]))vec![ret]
82}
83
84pub(crate) fn expand_test(
85    cx: &mut ExtCtxt<'_>,
86    attr_sp: Span,
87    meta_item: &ast::MetaItem,
88    item: Annotatable,
89) -> Vec<Annotatable> {
90    check_builtin_macro_attribute(cx, meta_item, sym::test);
91    warn_on_duplicate_attribute(cx, &item, sym::test);
92    expand_test_or_bench(cx, attr_sp, item, false)
93}
94
95pub(crate) fn expand_bench(
96    cx: &mut ExtCtxt<'_>,
97    attr_path_sp: Span,
98    meta_item: &ast::MetaItem,
99    item: Annotatable,
100) -> Vec<Annotatable> {
101    check_builtin_macro_attribute(cx, meta_item, sym::bench);
102    warn_on_duplicate_attribute(cx, &item, sym::bench);
103    expand_test_or_bench(cx, attr_path_sp, item, true)
104}
105
106pub(crate) fn expand_test_or_bench(
107    cx: &ExtCtxt<'_>,
108    attr_sp: Span,
109    item: Annotatable,
110    is_bench: bool,
111) -> Vec<Annotatable> {
112    let (item, is_stmt) = match item {
113        Annotatable::Item(i) => (i, false),
114        Annotatable::Stmt(ast::Stmt { kind: ast::StmtKind::Item(i), .. }) => (i, true),
115        other => {
116            not_testable_error(cx, is_bench, attr_sp, None);
117            return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [other]))vec![other];
118        }
119    };
120
121    let ast::ItemKind::Fn(fn_) = &item.kind else {
122        not_testable_error(cx, is_bench, attr_sp, Some(&item));
123        return if is_stmt {
124            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Annotatable::Stmt(Box::new(cx.stmt_item(item.span, item)))]))vec![Annotatable::Stmt(Box::new(cx.stmt_item(item.span, item)))]
125        } else {
126            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Annotatable::Item(item)]))vec![Annotatable::Item(item)]
127        };
128    };
129
130    // If we're not in test configuration, remove the annotated item
131    if !cx.ecfg.should_test {
132        return ::alloc::vec::Vec::new()vec![];
133    }
134
135    if let Some(attr) = attr::find_by_name(&item.attrs, sym::naked) {
136        cx.dcx().emit_err(diagnostics::NakedFunctionTestingAttribute {
137            testing_span: attr_sp,
138            naked_span: attr.span,
139        });
140        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Annotatable::Item(item)]))vec![Annotatable::Item(item)];
141    }
142
143    // check_*_signature will report any errors in the type so compilation
144    // will fail. We shouldn't try to expand in this case because the errors
145    // would be spurious.
146    let check_result = if is_bench {
147        check_bench_signature(cx, &item, fn_)
148    } else {
149        check_test_signature(cx, &item, fn_)
150    };
151    if check_result.is_err() {
152        return if is_stmt {
153            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Annotatable::Stmt(Box::new(cx.stmt_item(item.span, item)))]))vec![Annotatable::Stmt(Box::new(cx.stmt_item(item.span, item)))]
154        } else {
155            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Annotatable::Item(item)]))vec![Annotatable::Item(item)]
156        };
157    }
158
159    let sp = cx.with_def_site_ctxt(item.span);
160    let ret_ty_sp = cx.with_def_site_ctxt(fn_.sig.decl.output.span());
161    let attr_sp = cx.with_def_site_ctxt(attr_sp);
162
163    let test_ident = Ident::new(sym::test, attr_sp);
164
165    // creates test::$name
166    let test_path = |name| cx.path(ret_ty_sp, &[test_ident, Ident::from_str_and_span(name, sp)]);
167
168    // creates test::ShouldPanic::$name
169    let should_panic_path = |name| {
170        cx.path(
171            sp,
172            &[test_ident, Ident::new(sym::ShouldPanic, sp), Ident::from_str_and_span(name, sp)],
173        )
174    };
175
176    // creates test::TestType::$name
177    let test_type_path = |name| {
178        cx.path(
179            sp,
180            &[test_ident, Ident::new(sym::TestType, sp), Ident::from_str_and_span(name, sp)],
181        )
182    };
183
184    // creates $name: $expr
185    let field = |name, expr| cx.field_imm(sp, Ident::from_str_and_span(name, sp), expr);
186
187    // Adds `#[coverage(off)]` to a closure, so it won't be instrumented in
188    // `-Cinstrument-coverage` builds.
189    // This requires `#[allow_internal_unstable(coverage_attribute)]` on the
190    // corresponding macro declaration in `core::macros`.
191    let coverage_off = |mut expr: Box<ast::Expr>| {
192        {
    match expr.kind {
        ast::ExprKind::Closure(_) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "ast::ExprKind::Closure(_)", ::core::option::Option::None);
        }
    }
};assert_matches!(expr.kind, ast::ExprKind::Closure(_));
193        expr.attrs.push(cx.generated_attr(sp, GeneratedAttr::CoverageOff));
194        expr
195    };
196
197    let test_fn = if is_bench {
198        // avoid name collisions by using the function name within the identifier, see bug #148275
199        let bencher_param = Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__bench_{0}", fn_.ident.name))
    })format!("__bench_{}", fn_.ident.name));
200        cx.expr_call(
201            sp,
202            cx.expr_path(test_path("StaticBenchFn")),
203            {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(coverage_off(cx.closure(sp,
                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                        [bencher_param])),
                cx.expr_call(sp,
                    cx.expr_path(test_path("assert_test_result")),
                    {
                        let len = [()].len();
                        let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                        vec.push(cx.expr_call(ret_ty_sp,
                                cx.expr_path(cx.path_ident(sp, fn_.ident)),
                                {
                                    let len = [()].len();
                                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                                    vec.push(cx.expr_name(sp, bencher_param));
                                    vec
                                }));
                        vec
                    }))));
    vec
}thin_vec![
204                // #[coverage(off)]
205                // |__bench_fn_name| self::test::assert_test_result(
206                coverage_off(cx.closure(
207                    sp,
208                    vec![bencher_param],
209                    cx.expr_call(
210                        sp,
211                        cx.expr_path(test_path("assert_test_result")),
212                        thin_vec![
213                            // super::$test_fn(__bench_fn_name)
214                            cx.expr_call(
215                                ret_ty_sp,
216                                cx.expr_path(cx.path_ident(sp, fn_.ident)),
217                                thin_vec![cx.expr_name(sp, bencher_param)],
218                            ),
219                        ],
220                    ),
221                )), // )
222            ],
223        )
224    } else {
225        cx.expr_call(
226            sp,
227            cx.expr_path(test_path("StaticTestFn")),
228            {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(coverage_off(cx.closure(sp, ::alloc::vec::Vec::new(),
                cx.expr_call(sp,
                    cx.expr_path(test_path("assert_test_result")),
                    {
                        let len = [()].len();
                        let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                        vec.push(cx.expr_call(ret_ty_sp,
                                cx.expr_path(cx.path(sp, &[fn_.ident])), ThinVec::new()));
                        vec
                    }))));
    vec
}thin_vec![
229                // #[coverage(off)]
230                // || {
231                coverage_off(cx.closure(
232                    sp,
233                    vec![],
234                    // test::assert_test_result(
235                    cx.expr_call(
236                        sp,
237                        cx.expr_path(test_path("assert_test_result")),
238                        thin_vec![
239                            // $test_fn()
240                            cx.expr_call(
241                                ret_ty_sp,
242                                cx.expr_path(cx.path(sp, &[fn_.ident])),
243                                ThinVec::new(),
244                            ), // )
245                        ],
246                    ), // }
247                )), // )
248            ],
249        )
250    };
251
252    let test_path_symbol = Symbol::intern(&item_path(
253        // skip the name of the root module
254        &cx.current_expansion.module.mod_path[1..],
255        &fn_.ident,
256    ));
257
258    let location_info = get_location_info(cx, fn_);
259
260    // static $ident: test::TestDescAndFn =
261    // We use a static because these things only exist to have references taken
262    // to them for the test case array. No reason to introduce tons of promoteds for that.
263    // Promoteds have the advantage that they can be merged to save space, but every one
264    // of these points to a different function so that will not happen.
265    let mut test_const = cx.item_static(
266        sp,
267        {
    let len = [(), (), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(cx.attr_nested_word(sym::cfg, sym::test, attr_sp));
    vec.push(cx.generated_attr(attr_sp,
            GeneratedAttr::RustcTestMarker(test_path_symbol)));
    vec.push(cx.generated_attr(attr_sp, GeneratedAttr::DocHidden));
    vec
}thin_vec![
268            // #[cfg(test)]
269            cx.attr_nested_word(sym::cfg, sym::test, attr_sp),
270            // #[rustc_test_marker = "test_case_sort_key"]
271            cx.generated_attr(attr_sp, GeneratedAttr::RustcTestMarker(test_path_symbol)),
272            // #[doc(hidden)]
273            cx.generated_attr(attr_sp, GeneratedAttr::DocHidden),
274        ],
275        Ident::new(fn_.ident.name, sp),
276        cx.ty_path(test_path("TestDescAndFn")),
277        Mutability::Not,
278        // test::TestDescAndFn {
279        cx.expr_struct(
280            sp,
281            test_path("TestDescAndFn"),
282            {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(field("desc",
            cx.expr_struct(sp, test_path("TestDesc"),
                {
                    let len =
                        [(), (), (), (), (), (), (), (), (), (), (), ()].len();
                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                    vec.push(field("name",
                            cx.expr_call(sp, cx.expr_path(test_path("StaticTestName")),
                                {
                                    let len = [()].len();
                                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                                    vec.push(cx.expr_str(sp, test_path_symbol));
                                    vec
                                })));
                    vec.push(field("ignore",
                            cx.expr_bool(sp, should_ignore(&item))));
                    vec.push(field("ignore_message",
                            if let Some(msg) = should_ignore_message(&item) {
                                cx.expr_some(sp, cx.expr_str(sp, msg))
                            } else { cx.expr_none(sp) }));
                    vec.push(field("source_file",
                            cx.expr_str(sp, location_info.0)));
                    vec.push(field("start_line",
                            cx.expr_usize(sp, location_info.1)));
                    vec.push(field("start_col",
                            cx.expr_usize(sp, location_info.2)));
                    vec.push(field("end_line",
                            cx.expr_usize(sp, location_info.3)));
                    vec.push(field("end_col",
                            cx.expr_usize(sp, location_info.4)));
                    vec.push(field("compile_fail", cx.expr_bool(sp, false)));
                    vec.push(field("no_run", cx.expr_bool(sp, false)));
                    vec.push(field("should_panic",
                            match should_panic(cx, &item) {
                                ShouldPanic::No => { cx.expr_path(should_panic_path("No")) }
                                ShouldPanic::Yes(None) => {
                                    cx.expr_path(should_panic_path("Yes"))
                                }
                                ShouldPanic::Yes(Some(sym)) =>
                                    cx.expr_call(sp,
                                        cx.expr_path(should_panic_path("YesWithMessage")),
                                        {
                                            let len = [()].len();
                                            let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                                            vec.push(cx.expr_str(sp, sym));
                                            vec
                                        }),
                            }));
                    vec.push(field("test_type",
                            match test_type(cx) {
                                TestType::UnitTest => {
                                    cx.expr_path(test_type_path("UnitTest"))
                                }
                                TestType::IntegrationTest => {
                                    cx.expr_path(test_type_path("IntegrationTest"))
                                }
                                TestType::Unknown => {
                                    cx.expr_path(test_type_path("Unknown"))
                                }
                            }));
                    vec
                })));
    vec.push(field("testfn", test_fn));
    vec
}thin_vec![
283                // desc: test::TestDesc {
284                field(
285                    "desc",
286                    cx.expr_struct(
287                        sp,
288                        test_path("TestDesc"),
289                        thin_vec![
290                            // name: "path::to::test"
291                            field(
292                                "name",
293                                cx.expr_call(
294                                    sp,
295                                    cx.expr_path(test_path("StaticTestName")),
296                                    thin_vec![cx.expr_str(sp, test_path_symbol)],
297                                ),
298                            ),
299                            // ignore: true | false
300                            field("ignore", cx.expr_bool(sp, should_ignore(&item)),),
301                            // ignore_message: Some("...") | None
302                            field(
303                                "ignore_message",
304                                if let Some(msg) = should_ignore_message(&item) {
305                                    cx.expr_some(sp, cx.expr_str(sp, msg))
306                                } else {
307                                    cx.expr_none(sp)
308                                },
309                            ),
310                            // source_file: <relative_path_of_source_file>
311                            field("source_file", cx.expr_str(sp, location_info.0)),
312                            // start_line: start line of the test fn identifier.
313                            field("start_line", cx.expr_usize(sp, location_info.1)),
314                            // start_col: start column of the test fn identifier.
315                            field("start_col", cx.expr_usize(sp, location_info.2)),
316                            // end_line: end line of the test fn identifier.
317                            field("end_line", cx.expr_usize(sp, location_info.3)),
318                            // end_col: end column of the test fn identifier.
319                            field("end_col", cx.expr_usize(sp, location_info.4)),
320                            // compile_fail: true | false
321                            field("compile_fail", cx.expr_bool(sp, false)),
322                            // no_run: true | false
323                            field("no_run", cx.expr_bool(sp, false)),
324                            // should_panic: ...
325                            field(
326                                "should_panic",
327                                match should_panic(cx, &item) {
328                                    // test::ShouldPanic::No
329                                    ShouldPanic::No => {
330                                        cx.expr_path(should_panic_path("No"))
331                                    }
332                                    // test::ShouldPanic::Yes
333                                    ShouldPanic::Yes(None) => {
334                                        cx.expr_path(should_panic_path("Yes"))
335                                    }
336                                    // test::ShouldPanic::YesWithMessage("...")
337                                    ShouldPanic::Yes(Some(sym)) => cx.expr_call(
338                                        sp,
339                                        cx.expr_path(should_panic_path("YesWithMessage")),
340                                        thin_vec![cx.expr_str(sp, sym)],
341                                    ),
342                                },
343                            ),
344                            // test_type: ...
345                            field(
346                                "test_type",
347                                match test_type(cx) {
348                                    // test::TestType::UnitTest
349                                    TestType::UnitTest => {
350                                        cx.expr_path(test_type_path("UnitTest"))
351                                    }
352                                    // test::TestType::IntegrationTest
353                                    TestType::IntegrationTest => {
354                                        cx.expr_path(test_type_path("IntegrationTest"))
355                                    }
356                                    // test::TestPath::Unknown
357                                    TestType::Unknown => {
358                                        cx.expr_path(test_type_path("Unknown"))
359                                    }
360                                },
361                            ),
362                            // },
363                        ],
364                    ),
365                ),
366                // testfn: test::StaticTestFn(...) | test::StaticBenchFn(...)
367                field("testfn", test_fn), // }
368            ],
369            // }
370        ),
371    );
372    test_const.vis.kind = ast::VisibilityKind::Public;
373
374    // extern crate test
375    let test_extern =
376        cx.item(sp, ast::AttrVec::new(), ast::ItemKind::ExternCrate(None, test_ident));
377
378    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/2d20b42b883dcfc014f3c2c56081eeb6091c2179/compiler/rustc_builtin_macros/src/test.rs:378",
                        "rustc_builtin_macros::test", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/2d20b42b883dcfc014f3c2c56081eeb6091c2179/compiler/rustc_builtin_macros/src/test.rs"),
                        ::tracing_core::__macro_support::Option::Some(378u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_builtin_macros::test"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("synthetic test item:\n{0}\n",
                                                    pprust::item_to_string(&test_const)) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("synthetic test item:\n{}\n", pprust::item_to_string(&test_const));
379
380    if is_stmt {
381        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Annotatable::Stmt(Box::new(cx.stmt_item(sp, test_extern))),
                Annotatable::Stmt(Box::new(cx.stmt_item(sp, test_const))),
                Annotatable::Stmt(Box::new(cx.stmt_item(sp, item)))]))vec![
382            // Access to libtest under a hygienic name
383            Annotatable::Stmt(Box::new(cx.stmt_item(sp, test_extern))),
384            // The generated test case
385            Annotatable::Stmt(Box::new(cx.stmt_item(sp, test_const))),
386            // The original item
387            Annotatable::Stmt(Box::new(cx.stmt_item(sp, item))),
388        ]
389    } else {
390        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Annotatable::Item(test_extern), Annotatable::Item(test_const),
                Annotatable::Item(item)]))vec![
391            // Access to libtest under a hygienic name
392            Annotatable::Item(test_extern),
393            // The generated test case
394            Annotatable::Item(test_const),
395            // The original item
396            Annotatable::Item(item),
397        ]
398    }
399}
400
401fn not_testable_error(cx: &ExtCtxt<'_>, is_bench: bool, attr_sp: Span, item: Option<&ast::Item>) {
402    let dcx = cx.dcx();
403    let name = if is_bench { "bench" } else { "test" };
404    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the `{0}` attribute may only be used on a free function",
                name))
    })format!("the `{name}` attribute may only be used on a free function");
405    let level = match item.map(|i| &i.kind) {
406        // These were a warning before #92959 and need to continue being that to avoid breaking
407        // stable user code (#94508).
408        Some(ast::ItemKind::MacCall(_)) => Level::Warning(None),
409        _ => Level::Error,
410    };
411    let mut err = Diag::new(dcx, level, msg);
412    err.span(attr_sp);
413    if let Some(item) = item {
414        err.span_label(
415            item.span,
416            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected a non-associated function, found {0} {1}",
                item.kind.article(), item.kind.descr()))
    })format!(
417                "expected a non-associated function, found {} {}",
418                item.kind.article(),
419                item.kind.descr()
420            ),
421        );
422    }
423    err.span_label(attr_sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the `{0}` attribute causes a function to be run as a test and has no effect on non-functions",
                name))
    })format!("the `{name}` attribute causes a function to be run as a test and has no effect on non-functions"));
424
425    if !is_bench {
426        err.with_span_suggestion(attr_sp,
427            "replace with conditional compilation to make the item only exist when tests are being run",
428            "#[cfg(test)]",
429            Applicability::MaybeIncorrect).emit();
430    } else {
431        err.emit();
432    }
433}
434
435fn get_location_info(cx: &ExtCtxt<'_>, fn_: &ast::Fn) -> (Symbol, usize, usize, usize, usize) {
436    let span = fn_.ident.span;
437    let (source_file, lo_line, lo_col, hi_line, hi_col) =
438        cx.sess.source_map().span_to_location_info(span);
439
440    let file_name = match source_file {
441        Some(sf) => sf.name.display(RemapPathScopeComponents::MACRO).to_string(),
442        None => "no-location".to_string(),
443    };
444
445    (Symbol::intern(&file_name), lo_line, lo_col, hi_line, hi_col)
446}
447
448fn item_path(mod_path: &[Ident], item_ident: &Ident) -> String {
449    join_path_idents(mod_path.iter().chain(iter::once(item_ident)))
450}
451
452enum ShouldPanic {
453    No,
454    Yes(Option<Symbol>),
455}
456
457fn should_ignore(i: &ast::Item) -> bool {
458    attr::contains_name(&i.attrs, sym::ignore)
459}
460
461fn should_ignore_message(i: &ast::Item) -> Option<Symbol> {
462    match attr::find_by_name(&i.attrs, sym::ignore) {
463        Some(attr) => {
464            match attr.meta_item_list() {
465                // Handle #[ignore(bar = "foo")]
466                Some(_) => None,
467                // Handle #[ignore] and #[ignore = "message"]
468                None => attr.value_str(),
469            }
470        }
471        None => None,
472    }
473}
474
475fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
476    if let Some(Attribute::Parsed(AttributeKind::ShouldPanic { reason, .. })) =
477        AttributeParser::parse_limited_sym(cx.sess, &i.attrs, &[sym::should_panic])
478    {
479        ShouldPanic::Yes(reason)
480    } else {
481        ShouldPanic::No
482    }
483}
484
485enum TestType {
486    UnitTest,
487    IntegrationTest,
488    Unknown,
489}
490
491/// Attempts to determine the type of test.
492/// Since doctests are created without macro expanding, only possible variants here
493/// are `UnitTest`, `IntegrationTest` or `Unknown`.
494fn test_type(cx: &ExtCtxt<'_>) -> TestType {
495    // Root path from context contains the topmost sources directory of the crate.
496    // I.e., for `project` with sources in `src` and tests in `tests` folders
497    // (no matter how many nested folders lie inside),
498    // there will be two different root paths: `/project/src` and `/project/tests`.
499    let crate_path = cx.root_path.as_path();
500
501    if crate_path.ends_with("src") {
502        // `/src` folder contains unit-tests.
503        TestType::UnitTest
504    } else if crate_path.ends_with("tests") {
505        // `/tests` folder contains integration tests.
506        TestType::IntegrationTest
507    } else {
508        // Crate layout doesn't match expected one, test type is unknown.
509        TestType::Unknown
510    }
511}
512
513fn check_test_signature(
514    cx: &ExtCtxt<'_>,
515    i: &ast::Item,
516    f: &ast::Fn,
517) -> Result<(), ErrorGuaranteed> {
518    let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic);
519    let dcx = cx.dcx();
520
521    if let ast::Safety::Unsafe(span) = f.sig.header.safety {
522        return Err(dcx.emit_err(diagnostics::TestBadFn {
523            span: i.span,
524            cause: span,
525            kind: "unsafe",
526        }));
527    }
528
529    if let Some(coroutine_marker) = f.sig.header.coroutine_marker {
530        return Err(dcx.emit_err(diagnostics::TestBadFn {
531            span: i.span,
532            cause: coroutine_marker.span,
533            kind: coroutine_marker.kind.as_str(),
534        }));
535    }
536
537    // If the termination trait is active, the compiler will check that the output
538    // type implements the `Termination` trait as `libtest` enforces that.
539    let has_output = match &f.sig.decl.output {
540        ast::FnRetTy::Default(..) => false,
541        ast::FnRetTy::Ty(t) if t.kind.is_unit() => false,
542        _ => true,
543    };
544
545    if !f.sig.decl.inputs.is_empty() {
546        return Err(dcx.span_err(i.span, "functions used as tests can not have any arguments"));
547    }
548
549    if has_should_panic_attr && has_output {
550        return Err(dcx.span_err(i.span, "functions using `#[should_panic]` must return `()`"));
551    }
552
553    if f.generics.params.iter().any(|param| !#[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamKind::Lifetime => true,
    _ => false,
}matches!(param.kind, GenericParamKind::Lifetime)) {
554        return Err(dcx.span_err(
555            i.span,
556            "functions used as tests can not have any non-lifetime generic parameters",
557        ));
558    }
559
560    Ok(())
561}
562
563fn check_bench_signature(
564    cx: &ExtCtxt<'_>,
565    i: &ast::Item,
566    f: &ast::Fn,
567) -> Result<(), ErrorGuaranteed> {
568    // N.B., inadequate check, but we're running
569    // well before resolve, can't get too deep.
570    if f.sig.decl.inputs.len() != 1 {
571        return Err(cx.dcx().emit_err(diagnostics::BenchSig { span: i.span }));
572    }
573    Ok(())
574}