Skip to main content

rustc_builtin_macros/
test_harness.rs

1// Code that generates a test runner to run all the tests in a crate
2
3use std::mem;
4use std::sync::atomic::Ordering;
5
6use rustc_ast as ast;
7use rustc_ast::attr::contains_name;
8use rustc_ast::entry::EntryPointType;
9use rustc_ast::mut_visit::*;
10use rustc_ast::visit::Visitor;
11use rustc_ast::{ModKind, attr};
12use rustc_attr_ir::AttributeKind;
13use rustc_attr_parsing::AttributeParser;
14use rustc_expand::base::{ExtCtxt, ResolverExpand};
15use rustc_expand::expand::{AstFragment, ExpansionConfig};
16use rustc_feature::Features;
17use rustc_lint_defs::builtin::UNNAMEABLE_TEST_ITEMS;
18use rustc_session::Session;
19use rustc_span::hygiene::{AstPass, SyntaxContext, Transparency};
20use rustc_span::{DUMMY_SP, Ident, Span, Symbol, sym};
21use rustc_target::spec::PanicStrategy;
22use smallvec::smallvec;
23use thin_vec::{ThinVec, thin_vec};
24use tracing::debug;
25
26use crate::diagnostics;
27
28#[derive(#[automatically_derived]
impl ::core::clone::Clone for Test {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            span: ::core::clone::Clone::clone(&self.span),
            ident: ::core::clone::Clone::clone(&self.ident),
            name: ::core::clone::Clone::clone(&self.name),
        }
    }
}Clone)]
29struct Test {
30    span: Span,
31    ident: Ident,
32    name: Symbol,
33}
34
35struct TestCtxt<'a> {
36    ext_cx: ExtCtxt<'a>,
37    panic_strategy: PanicStrategy,
38    def_site: Span,
39    test_cases: Vec<Test>,
40    reexport_test_harness_main: Option<Symbol>,
41    /// Value of a `#[test_runner]` attribute, if present.
42    test_runner: Option<ast::Path>,
43}
44
45/// Traverse the crate, collecting all the test functions, eliding any
46/// existing main functions, and synthesizing a main test harness
47pub fn inject(
48    krate: &mut ast::Crate,
49    sess: &Session,
50    features: &Features,
51    resolver: &mut dyn ResolverExpand,
52) {
53    let dcx = sess.dcx();
54    let panic_strategy = sess.panic_strategy();
55    let platform_panic_strategy = sess.target.panic_strategy;
56
57    // Check for #![reexport_test_harness_main = "some_name"] which gives the
58    // main test function the name `some_name` without hygiene. This needs to be
59    // unconditional, so that the attribute is still marked as used in
60    // non-test builds.
61    let reexport_test_harness_main =
62        attr::first_attr_value_str_by_name(&krate.attrs, sym::reexport_test_harness_main);
63
64    // Do this here so that the test_runner crate attribute gets marked as used
65    // even in non-test builds
66    let test_runner = get_test_runner(sess, krate);
67
68    if sess.is_test_crate() {
69        let panic_strategy = match (panic_strategy, sess.opts.unstable_opts.panic_abort_tests) {
70            (PanicStrategy::Abort | PanicStrategy::ImmediateAbort, true) => panic_strategy,
71            (PanicStrategy::Abort | PanicStrategy::ImmediateAbort, false) => {
72                if panic_strategy == platform_panic_strategy {
73                    // Silently allow compiling with panic=abort on these platforms,
74                    // but with old behavior (abort if a test fails).
75                } else {
76                    dcx.emit_err(diagnostics::TestsNotSupport {});
77                }
78                PanicStrategy::Unwind
79            }
80            (PanicStrategy::Unwind, _) => PanicStrategy::Unwind,
81        };
82        generate_test_harness(
83            sess,
84            resolver,
85            reexport_test_harness_main,
86            krate,
87            features,
88            panic_strategy,
89            test_runner,
90        )
91    }
92}
93
94struct TestHarnessGenerator<'a> {
95    cx: TestCtxt<'a>,
96    tests: Vec<Test>,
97}
98
99impl TestHarnessGenerator<'_> {
100    fn add_test_cases(&mut self, node_id: ast::NodeId, span: Span, prev_tests: Vec<Test>) {
101        let mut tests = mem::replace(&mut self.tests, prev_tests);
102
103        if !tests.is_empty() {
104            // Create an identifier that will hygienically resolve the test
105            // case name, even in another module.
106            let expn_id = self.cx.ext_cx.resolver.expansion_for_ast_pass(
107                span,
108                AstPass::TestHarness,
109                &[],
110                Some(node_id),
111            );
112            for test in &mut tests {
113                // See the comment on `add_main` for why we're using `apply_mark` directly.
114                test.ident.span =
115                    test.ident.span.apply_mark(expn_id.to_expn_id(), Transparency::Opaque);
116            }
117            self.cx.test_cases.extend(tests);
118        }
119    }
120}
121
122impl<'a> MutVisitor for TestHarnessGenerator<'a> {
123    fn visit_crate(&mut self, c: &mut ast::Crate) {
124        let prev_tests = mem::take(&mut self.tests);
125        walk_crate(self, c);
126        self.add_test_cases(ast::CRATE_NODE_ID, c.spans.inner_span, prev_tests);
127
128        // Create a main function to run our tests
129        add_main(&mut self.cx, c);
130    }
131
132    fn visit_item(&mut self, item: &mut ast::Item) {
133        if let Some(name) = get_test_name(item) {
134            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6bb1652a020e80cef79332741d89e996d71933c9/compiler/rustc_builtin_macros/src/test_harness.rs:134",
                        "rustc_builtin_macros::test_harness",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6bb1652a020e80cef79332741d89e996d71933c9/compiler/rustc_builtin_macros/src/test_harness.rs"),
                        ::tracing_core::__macro_support::Option::Some(134u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_builtin_macros::test_harness"),
                        ::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!("this is a test item")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("this is a test item");
135
136            // `unwrap` is ok because only functions, consts, and static should reach here.
137            let test = Test { span: item.span, ident: item.kind.ident().unwrap(), name };
138            self.tests.push(test);
139        }
140
141        // We don't want to recurse into anything other than mods, since
142        // mods or tests inside of functions will break things
143        if let ast::ItemKind::Mod(
144            _,
145            _,
146            ModKind::Loaded(.., ast::ModSpans { inner_span: span, .. }),
147        ) = item.kind
148        {
149            let prev_tests = mem::take(&mut self.tests);
150            ast::mut_visit::walk_item(self, item);
151            self.add_test_cases(item.id, span, prev_tests);
152        } else {
153            // But in those cases, we emit a lint to warn the user of these missing tests.
154            ast::visit::walk_item(&mut InnerItemLinter { sess: self.cx.ext_cx.sess }, item);
155        }
156    }
157}
158
159struct InnerItemLinter<'a> {
160    sess: &'a Session,
161}
162
163impl<'a> Visitor<'a> for InnerItemLinter<'_> {
164    fn visit_item(&mut self, i: &'a ast::Item) {
165        if let Some(attr) = attr::find_by_name(&i.attrs, sym::rustc_test_marker) {
166            self.sess.psess.buffer_lint(
167                UNNAMEABLE_TEST_ITEMS,
168                attr.span,
169                i.id,
170                diagnostics::UnnameableTestItems,
171            );
172        }
173    }
174}
175
176fn entry_point_type(item: &ast::Item, at_root: bool) -> EntryPointType {
177    match &item.kind {
178        ast::ItemKind::Fn(fn_) => rustc_ast::entry::entry_point_type(
179            contains_name(&item.attrs, sym::rustc_main),
180            at_root,
181            Some(fn_.ident.name),
182        ),
183        _ => EntryPointType::None,
184    }
185}
186
187/// A folder used to remove any entry points (like fn main) because the harness
188/// coroutine will provide its own
189struct EntryPointCleaner<'a> {
190    // Current depth in the ast
191    sess: &'a Session,
192    depth: usize,
193    def_site: Span,
194}
195
196impl<'a> MutVisitor for EntryPointCleaner<'a> {
197    fn visit_item(&mut self, item: &mut ast::Item) {
198        self.depth += 1;
199        ast::mut_visit::walk_item(self, item);
200        self.depth -= 1;
201
202        // Remove any #[rustc_main] from the AST so it doesn't
203        // clash with the one we're going to add, but mark it as
204        // #[allow(dead_code)] to avoid printing warnings.
205        match entry_point_type(item, self.depth == 0) {
206            EntryPointType::RustcMainAttr => {
207                let allow_dead_code = attr::mk_attr_nested_word(
208                    &self.sess.psess.attr_id_generator,
209                    ast::AttrStyle::Outer,
210                    sym::allow,
211                    sym::dead_code,
212                    self.def_site,
213                );
214                item.attrs.retain(|attr| !attr.has_name(sym::rustc_main));
215                item.attrs.push(allow_dead_code);
216                self.sess.removed_rustc_main_attr.store(true, Ordering::Relaxed);
217            }
218            EntryPointType::None | EntryPointType::MainNamed | EntryPointType::OtherMain => {}
219        };
220    }
221}
222
223/// Crawl over the crate, inserting test reexports and the test main function
224fn generate_test_harness(
225    sess: &Session,
226    resolver: &mut dyn ResolverExpand,
227    reexport_test_harness_main: Option<Symbol>,
228    krate: &mut ast::Crate,
229    features: &Features,
230    panic_strategy: PanicStrategy,
231    test_runner: Option<ast::Path>,
232) {
233    let econfig = ExpansionConfig::default(sym::test, features);
234    let ext_cx = ExtCtxt::new(sess, econfig, resolver, None);
235
236    let expn_id = ext_cx.resolver.expansion_for_ast_pass(
237        DUMMY_SP,
238        AstPass::TestHarness,
239        &[sym::test, sym::rustc_attrs, sym::coverage_attribute],
240        None,
241    );
242    let def_site = DUMMY_SP.with_def_site_ctxt(expn_id.to_expn_id());
243
244    // Remove the entry points
245    let mut cleaner = EntryPointCleaner { sess, depth: 0, def_site };
246    cleaner.visit_crate(krate);
247
248    let cx = TestCtxt {
249        ext_cx,
250        panic_strategy,
251        def_site,
252        test_cases: Vec::new(),
253        reexport_test_harness_main,
254        test_runner,
255    };
256
257    TestHarnessGenerator { cx, tests: Vec::new() }.visit_crate(krate);
258}
259
260/// Creates a function item for use as the main function of a test build.
261/// This function will call the `test_runner` as specified by the crate attribute
262///
263/// By default this expands to
264///
265/// ```ignore (messes with test internals)
266/// #[rustc_main]
267/// pub fn main() {
268///     extern crate test;
269///     test::test_main_env_args(&[
270///         &test_const1,
271///         &test_const2,
272///         &test_const3,
273///     ]);
274/// }
275/// ```
276///
277/// Most of the Ident have the usual def-site hygiene for the AST pass. The
278/// exception is the `test_const`s. These have a syntax context that has two
279/// opaque marks: one from the expansion of `test` or `test_case`, and one
280/// generated  in `TestHarnessGenerator::visit_item`. When resolving this
281/// identifier after failing to find a matching identifier in the root module
282/// we remove the outer mark, and try resolving at its def-site, which will
283/// then resolve to `test_const`.
284///
285/// The expansion here can be controlled by two attributes:
286///
287/// [`TestCtxt::reexport_test_harness_main`] provides a different name for the `main`
288/// function and [`TestCtxt::test_runner`] provides a path that replaces
289/// `test::test_main_env_args`.
290fn add_main(cx: &mut TestCtxt<'_>, c: &mut ast::Crate) {
291    let sp = cx.def_site;
292    let ecx = &cx.ext_cx;
293    // `sp` has def-site hygiene so should not clash with user-defined names.
294    let test_ident = Ident::new(sym::test, sp);
295
296    // test::test_main_env_args(...)
297    let mut test_runner = cx.test_runner.clone().unwrap_or_else(|| {
298        // Built-in runner name depends on panic strategy.
299        let runner_name = if cx.panic_strategy.unwinds() {
300            "test_main_env_args"
301        } else {
302            "test_main_env_args_abort"
303        };
304        ecx.path(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(runner_name, sp)]))vec![test_ident, Ident::from_str_and_span(runner_name, sp)])
305    });
306
307    test_runner.span = sp;
308
309    let test_main_path_expr = ecx.expr_path(test_runner);
310    let call_test_main = ecx.expr_call(sp, test_main_path_expr, {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(mk_tests_slice(cx, sp));
    vec
}thin_vec![mk_tests_slice(cx, sp)]);
311    let call_test_main = ecx.stmt_expr(call_test_main);
312
313    // extern crate test
314    let test_extern_stmt =
315        ecx.item(sp, ast::AttrVec::new(), ast::ItemKind::ExternCrate(None, test_ident));
316
317    // #[rustc_main]
318    let main_attr = ecx.attr_word(sym::rustc_main, sp);
319    // #[coverage(off)]
320    let coverage_attr = ecx.attr_nested_word(sym::coverage, sym::off, sp);
321    // #[doc(hidden)]
322    let doc_hidden_attr = ecx.attr_nested_word(sym::doc, sym::hidden, sp);
323
324    // pub fn main() -> ExitCode { ... }
325    let main_ret_ty = if cx.test_runner.is_none() {
326        // Built-in runner has return type `ExitCode`.
327        let exit_code_path = ::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("ExitCode", sp)]))vec![test_ident, Ident::from_str_and_span("ExitCode", sp)];
328        ecx.ty(sp, ast::TyKind::Path(None, ecx.path(sp, exit_code_path)))
329    } else {
330        // User-defined runners have return type `()`.
331        ecx.ty(sp, ast::TyKind::Tup(ThinVec::new()))
332    };
333
334    let main_body = ecx.block(sp, {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(call_test_main);
    vec
}thin_vec![call_test_main]);
335
336    let decl = ecx.fn_decl(ThinVec::new(), ast::FnRetTy::Ty(main_ret_ty));
337    let sig = ast::FnSig { decl, header: ast::FnHeader::default(), span: sp };
338    let defaultness = ast::Defaultness::Implicit;
339
340    // Honor the reexport_test_harness_main attribute
341    let main_ident = match cx.reexport_test_harness_main {
342        Some(sym) => Ident::new(sym, sp.with_ctxt(SyntaxContext::root())),
343        None => Ident::new(sym::main, sp),
344    };
345
346    let main = ast::ItemKind::Fn(Box::new(ast::Fn {
347        defaultness,
348        sig,
349        ident: main_ident,
350        generics: ast::Generics::default(),
351        contract: None,
352        body: Some(main_body),
353        define_opaque: None,
354        eii_impl: None,
355    }));
356
357    let main = Box::new(ast::Item {
358        attrs: {
    let len = [(), (), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(main_attr);
    vec.push(coverage_attr);
    vec.push(doc_hidden_attr);
    vec
}thin_vec![main_attr, coverage_attr, doc_hidden_attr],
359        id: ast::DUMMY_NODE_ID,
360        kind: main,
361        vis: ast::Visibility { span: sp, kind: ast::VisibilityKind::Public },
362        span: sp,
363        tokens: None,
364    });
365
366    // Integrate the new item into existing module structures.
367    // `extern crate test;` is only needed with the default runner.
368    let items = AstFragment::Items(if cx.test_runner.is_none() {
369        {
    let count = 0usize + 1usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(test_extern_stmt);
        vec.push(main);
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [test_extern_stmt, main])))
    }
}smallvec![test_extern_stmt, main]
370    } else {
371        {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(main);
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [main])))
    }
}smallvec![main]
372    });
373    c.items.extend(cx.ext_cx.monotonic_expander().fully_expand_fragment(items).make_items());
374}
375
376/// Creates a slice containing every test like so:
377/// &[&test1, &test2]
378fn mk_tests_slice(cx: &TestCtxt<'_>, sp: Span) -> Box<ast::Expr> {
379    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6bb1652a020e80cef79332741d89e996d71933c9/compiler/rustc_builtin_macros/src/test_harness.rs:379",
                        "rustc_builtin_macros::test_harness",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6bb1652a020e80cef79332741d89e996d71933c9/compiler/rustc_builtin_macros/src/test_harness.rs"),
                        ::tracing_core::__macro_support::Option::Some(379u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_builtin_macros::test_harness"),
                        ::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!("building test vector from {0} tests",
                                                    cx.test_cases.len()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("building test vector from {} tests", cx.test_cases.len());
380    let ecx = &cx.ext_cx;
381
382    let mut tests = cx.test_cases.clone();
383    // Note that this sort is load-bearing: the libtest harness uses binary search to find tests by
384    // name.
385    tests.sort_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
386
387    ecx.expr_array_ref(
388        sp,
389        tests
390            .iter()
391            .map(|test| {
392                ecx.expr_addr_of(test.span, ecx.expr_path(ecx.path(test.span, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [test.ident]))vec![test.ident])))
393            })
394            .collect(),
395    )
396}
397
398fn get_test_name(i: &ast::Item) -> Option<Symbol> {
399    attr::first_attr_value_str_by_name(&i.attrs, sym::rustc_test_marker)
400}
401
402fn get_test_runner(sess: &Session, krate: &ast::Crate) -> Option<ast::Path> {
403    match AttributeParser::parse_limited_sym(sess, &krate.attrs, &[sym::test_runner]) {
404        Some(rustc_attr_ir::Attribute::Parsed(AttributeKind::TestRunner(path))) => Some(path),
405        _ => None,
406    }
407}