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) -> Test {
        Test {
            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 `mk_main` for why we're using
114                // `apply_mark` directly.
115                test.ident.span =
116                    test.ident.span.apply_mark(expn_id.to_expn_id(), Transparency::Opaque);
117            }
118            self.cx.test_cases.extend(tests);
119        }
120    }
121}
122
123impl<'a> MutVisitor for TestHarnessGenerator<'a> {
124    fn visit_crate(&mut self, c: &mut ast::Crate) {
125        let prev_tests = mem::take(&mut self.tests);
126        walk_crate(self, c);
127        self.add_test_cases(ast::CRATE_NODE_ID, c.spans.inner_span, prev_tests);
128
129        // Create a main function to run our tests
130        c.items.push(mk_main(&mut self.cx));
131    }
132
133    fn visit_item(&mut self, item: &mut ast::Item) {
134        if let Some(name) = get_test_name(item) {
135            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_builtin_macros/src/test_harness.rs:135",
                        "rustc_builtin_macros::test_harness",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_builtin_macros/src/test_harness.rs"),
                        ::tracing_core::__macro_support::Option::Some(135u32),
                        ::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");
136
137            // `unwrap` is ok because only functions, consts, and static should reach here.
138            let test = Test { span: item.span, ident: item.kind.ident().unwrap(), name };
139            self.tests.push(test);
140        }
141
142        // We don't want to recurse into anything other than mods, since
143        // mods or tests inside of functions will break things
144        if let ast::ItemKind::Mod(
145            _,
146            _,
147            ModKind::Loaded(.., ast::ModSpans { inner_span: span, .. }),
148        ) = item.kind
149        {
150            let prev_tests = mem::take(&mut self.tests);
151            ast::mut_visit::walk_item(self, item);
152            self.add_test_cases(item.id, span, prev_tests);
153        } else {
154            // But in those cases, we emit a lint to warn the user of these missing tests.
155            ast::visit::walk_item(&mut InnerItemLinter { sess: self.cx.ext_cx.sess }, item);
156        }
157    }
158}
159
160struct InnerItemLinter<'a> {
161    sess: &'a Session,
162}
163
164impl<'a> Visitor<'a> for InnerItemLinter<'_> {
165    fn visit_item(&mut self, i: &'a ast::Item) {
166        if let Some(attr) = attr::find_by_name(&i.attrs, sym::rustc_test_marker) {
167            self.sess.psess.buffer_lint(
168                UNNAMEABLE_TEST_ITEMS,
169                attr.span,
170                i.id,
171                diagnostics::UnnameableTestItems,
172            );
173        }
174    }
175}
176
177fn entry_point_type(item: &ast::Item, at_root: bool) -> EntryPointType {
178    match &item.kind {
179        ast::ItemKind::Fn(fn_) => rustc_ast::entry::entry_point_type(
180            contains_name(&item.attrs, sym::rustc_main),
181            at_root,
182            Some(fn_.ident.name),
183        ),
184        _ => EntryPointType::None,
185    }
186}
187
188/// A folder used to remove any entry points (like fn main) because the harness
189/// coroutine will provide its own
190struct EntryPointCleaner<'a> {
191    // Current depth in the ast
192    sess: &'a Session,
193    depth: usize,
194    def_site: Span,
195}
196
197impl<'a> MutVisitor for EntryPointCleaner<'a> {
198    fn visit_item(&mut self, item: &mut ast::Item) {
199        self.depth += 1;
200        ast::mut_visit::walk_item(self, item);
201        self.depth -= 1;
202
203        // Remove any #[rustc_main] from the AST so it doesn't
204        // clash with the one we're going to add, but mark it as
205        // #[allow(dead_code)] to avoid printing warnings.
206        match entry_point_type(item, self.depth == 0) {
207            EntryPointType::RustcMainAttr => {
208                let allow_dead_code = attr::mk_attr_nested_word(
209                    &self.sess.psess.attr_id_generator,
210                    ast::AttrStyle::Outer,
211                    sym::allow,
212                    sym::dead_code,
213                    self.def_site,
214                );
215                item.attrs.retain(|attr| !attr.has_name(sym::rustc_main));
216                item.attrs.push(allow_dead_code);
217                self.sess.removed_rustc_main_attr.store(true, Ordering::Relaxed);
218            }
219            EntryPointType::None | EntryPointType::MainNamed | EntryPointType::OtherMain => {}
220        };
221    }
222}
223
224/// Crawl over the crate, inserting test reexports and the test main function
225fn generate_test_harness(
226    sess: &Session,
227    resolver: &mut dyn ResolverExpand,
228    reexport_test_harness_main: Option<Symbol>,
229    krate: &mut ast::Crate,
230    features: &Features,
231    panic_strategy: PanicStrategy,
232    test_runner: Option<ast::Path>,
233) {
234    let econfig = ExpansionConfig::default(sym::test, features);
235    let ext_cx = ExtCtxt::new(sess, econfig, resolver, None);
236
237    let expn_id = ext_cx.resolver.expansion_for_ast_pass(
238        DUMMY_SP,
239        AstPass::TestHarness,
240        &[sym::test, sym::rustc_attrs, sym::coverage_attribute],
241        None,
242    );
243    let def_site = DUMMY_SP.with_def_site_ctxt(expn_id.to_expn_id());
244
245    // Remove the entry points
246    let mut cleaner = EntryPointCleaner { sess, depth: 0, def_site };
247    cleaner.visit_crate(krate);
248
249    let cx = TestCtxt {
250        ext_cx,
251        panic_strategy,
252        def_site,
253        test_cases: Vec::new(),
254        reexport_test_harness_main,
255        test_runner,
256    };
257
258    TestHarnessGenerator { cx, tests: Vec::new() }.visit_crate(krate);
259}
260
261/// Creates a function item for use as the main function of a test build.
262/// This function will call the `test_runner` as specified by the crate attribute
263///
264/// By default this expands to
265///
266/// ```ignore (messes with test internals)
267/// #[rustc_main]
268/// pub fn main() {
269///     extern crate test;
270///     test::test_main_env_args(&[
271///         &test_const1,
272///         &test_const2,
273///         &test_const3,
274///     ]);
275/// }
276/// ```
277///
278/// Most of the Ident have the usual def-site hygiene for the AST pass. The
279/// exception is the `test_const`s. These have a syntax context that has two
280/// opaque marks: one from the expansion of `test` or `test_case`, and one
281/// generated  in `TestHarnessGenerator::visit_item`. When resolving this
282/// identifier after failing to find a matching identifier in the root module
283/// we remove the outer mark, and try resolving at its def-site, which will
284/// then resolve to `test_const`.
285///
286/// The expansion here can be controlled by two attributes:
287///
288/// [`TestCtxt::reexport_test_harness_main`] provides a different name for the `main`
289/// function and [`TestCtxt::test_runner`] provides a path that replaces
290/// `test::test_main_env_args`.
291fn mk_main(cx: &mut TestCtxt<'_>) -> Box<ast::Item> {
292    let sp = cx.def_site;
293    let ecx = &cx.ext_cx;
294    let test_ident = Ident::new(sym::test, sp);
295
296    let runner_name =
297        if cx.panic_strategy.unwinds() { "test_main_env_args" } else { "test_main_env_args_abort" };
298
299    // test::test_main_env_args(...)
300    let mut test_runner = cx.test_runner.clone().unwrap_or_else(|| {
301        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)])
302    });
303
304    test_runner.span = sp;
305
306    let test_main_path_expr = ecx.expr_path(test_runner);
307    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)]);
308    let call_test_main = ecx.stmt_expr(call_test_main);
309
310    // extern crate test
311    let test_extern_stmt = ecx.stmt_item(
312        sp,
313        ecx.item(sp, ast::AttrVec::new(), ast::ItemKind::ExternCrate(None, test_ident)),
314    );
315
316    // #[rustc_main]
317    let main_attr = ecx.attr_word(sym::rustc_main, sp);
318    // #[coverage(off)]
319    let coverage_attr = ecx.attr_nested_word(sym::coverage, sym::off, sp);
320    // #[doc(hidden)]
321    let doc_hidden_attr = ecx.attr_nested_word(sym::doc, sym::hidden, sp);
322
323    // pub fn main() { ... }
324    // FIXME: it would be nice if we could use `std::process::ExitCode` as return type here, and
325    // remove all early-exit from libtest itself. Or rather, it should be `test::ExitCode` so we
326    // don't depend on whatever `std` may be. This needs the `extern crate test` to be *outside*
327    // `main`. But naively moving it out causes ICEs that give no hint as to what is wrong.
328    let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(ThinVec::new()));
329
330    // If no test runner is provided we need to import the test crate
331    let main_body = if cx.test_runner.is_none() {
332        ecx.block(sp, {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(test_extern_stmt);
    vec.push(call_test_main);
    vec
}thin_vec![test_extern_stmt, call_test_main])
333    } else {
334        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
337    let decl = ecx.fn_decl(ThinVec::new(), ast::FnRetTy::Ty(main_ret_ty));
338    let sig = ast::FnSig { decl, header: ast::FnHeader::default(), span: sp };
339    let defaultness = ast::Defaultness::Implicit;
340
341    // Honor the reexport_test_harness_main attribute
342    let main_ident = match cx.reexport_test_harness_main {
343        Some(sym) => Ident::new(sym, sp.with_ctxt(SyntaxContext::root())),
344        None => Ident::new(sym::main, sp),
345    };
346
347    let main = ast::ItemKind::Fn(Box::new(ast::Fn {
348        defaultness,
349        sig,
350        ident: main_ident,
351        generics: ast::Generics::default(),
352        contract: None,
353        body: Some(main_body),
354        define_opaque: None,
355        eii_impl: None,
356    }));
357
358    let main = Box::new(ast::Item {
359        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],
360        id: ast::DUMMY_NODE_ID,
361        kind: main,
362        vis: ast::Visibility { span: sp, kind: ast::VisibilityKind::Public },
363        span: sp,
364        tokens: None,
365    });
366
367    // Integrate the new item into existing module structures.
368    let main = AstFragment::Items({
    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]);
369    cx.ext_cx.monotonic_expander().fully_expand_fragment(main).make_items().pop().unwrap()
370}
371
372/// Creates a slice containing every test like so:
373/// &[&test1, &test2]
374fn mk_tests_slice(cx: &TestCtxt<'_>, sp: Span) -> Box<ast::Expr> {
375    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_builtin_macros/src/test_harness.rs:375",
                        "rustc_builtin_macros::test_harness",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_builtin_macros/src/test_harness.rs"),
                        ::tracing_core::__macro_support::Option::Some(375u32),
                        ::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());
376    let ecx = &cx.ext_cx;
377
378    let mut tests = cx.test_cases.clone();
379    // Note that this sort is load-bearing: the libtest harness uses binary search to find tests by
380    // name.
381    tests.sort_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
382
383    ecx.expr_array_ref(
384        sp,
385        tests
386            .iter()
387            .map(|test| {
388                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])))
389            })
390            .collect(),
391    )
392}
393
394fn get_test_name(i: &ast::Item) -> Option<Symbol> {
395    attr::first_attr_value_str_by_name(&i.attrs, sym::rustc_test_marker)
396}
397
398fn get_test_runner(sess: &Session, krate: &ast::Crate) -> Option<ast::Path> {
399    match AttributeParser::parse_limited_sym(sess, &krate.attrs, &[sym::test_runner]) {
400        Some(rustc_attr_ir::Attribute::Parsed(AttributeKind::TestRunner(path))) => Some(path),
401        _ => None,
402    }
403}