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