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