1use 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 test_runner: Option<ast::Path>,
43}
44
45pub 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 let reexport_test_harness_main =
62 attr::first_attr_value_str_by_name(&krate.attrs, sym::reexport_test_harness_main);
63
64 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 } 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 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 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 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 let test = Test { span: item.span, ident: item.kind.ident().unwrap(), name };
138 self.tests.push(test);
139 }
140
141 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 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
187struct EntryPointCleaner<'a> {
190 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 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
223fn 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 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
260fn add_main(cx: &mut TestCtxt<'_>, c: &mut ast::Crate) {
291 let sp = cx.def_site;
292 let ecx = &cx.ext_cx;
293 let test_ident = Ident::new(sym::test, sp);
295
296 let mut test_runner = cx.test_runner.clone().unwrap_or_else(|| {
298 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 let test_extern_stmt =
315 ecx.item(sp, ast::AttrVec::new(), ast::ItemKind::ExternCrate(None, test_ident));
316
317 let main_attr = ecx.attr_word(sym::rustc_main, sp);
319 let coverage_attr = ecx.attr_nested_word(sym::coverage, sym::off, sp);
321 let doc_hidden_attr = ecx.attr_nested_word(sym::doc, sym::hidden, sp);
323
324 let main_ret_ty = if cx.test_runner.is_none() {
326 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 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 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 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
376fn 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 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}