1use std::assert_matches::assert_matches;
5use std::iter;
6
7use rustc_ast::ptr::P;
8use rustc_ast::{self as ast, GenericParamKind, attr, join_path_idents};
9use rustc_ast_pretty::pprust;
10use rustc_errors::{Applicability, Diag, Level};
11use rustc_expand::base::*;
12use rustc_span::{ErrorGuaranteed, FileNameDisplayPreference, Ident, Span, Symbol, sym};
13use thin_vec::{ThinVec, thin_vec};
14use tracing::debug;
15
16use crate::errors;
17use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute};
18
19pub(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 if !ecx.ecfg.should_test {
36 return vec![];
37 }
38
39 let sp = ecx.with_def_site_ctxt(attr_sp);
40 let (mut item, is_stmt) = match anno_item {
41 Annotatable::Item(item) => (item, false),
42 Annotatable::Stmt(stmt) if let ast::StmtKind::Item(_) = stmt.kind => {
43 if let ast::StmtKind::Item(i) = stmt.kind {
44 (i, true)
45 } else {
46 unreachable!()
47 }
48 }
49 _ => {
50 ecx.dcx().emit_err(errors::TestCaseNonItem { span: anno_item.span() });
51 return vec![];
52 }
53 };
54
55 match &mut item.kind {
58 ast::ItemKind::Fn(box ast::Fn { ident, .. })
59 | ast::ItemKind::Const(box ast::ConstItem { ident, .. })
60 | ast::ItemKind::Static(box ast::StaticItem { ident, .. }) => {
61 ident.span = ident.span.with_ctxt(sp.ctxt());
62 let test_path_symbol = Symbol::intern(&item_path(
63 &ecx.current_expansion.module.mod_path[1..],
65 ident,
66 ));
67 item.vis = ast::Visibility {
68 span: item.vis.span,
69 kind: ast::VisibilityKind::Public,
70 tokens: None,
71 };
72 item.attrs.push(ecx.attr_name_value_str(sym::rustc_test_marker, test_path_symbol, sp));
73 }
74 _ => {}
75 }
76
77 let ret = if is_stmt {
78 Annotatable::Stmt(P(ecx.stmt_item(item.span, item)))
79 } else {
80 Annotatable::Item(item)
81 };
82
83 vec![ret]
84}
85
86pub(crate) fn expand_test(
87 cx: &mut ExtCtxt<'_>,
88 attr_sp: Span,
89 meta_item: &ast::MetaItem,
90 item: Annotatable,
91) -> Vec<Annotatable> {
92 check_builtin_macro_attribute(cx, meta_item, sym::test);
93 warn_on_duplicate_attribute(cx, &item, sym::test);
94 expand_test_or_bench(cx, attr_sp, item, false)
95}
96
97pub(crate) fn expand_bench(
98 cx: &mut ExtCtxt<'_>,
99 attr_sp: Span,
100 meta_item: &ast::MetaItem,
101 item: Annotatable,
102) -> Vec<Annotatable> {
103 check_builtin_macro_attribute(cx, meta_item, sym::bench);
104 warn_on_duplicate_attribute(cx, &item, sym::bench);
105 expand_test_or_bench(cx, attr_sp, item, true)
106}
107
108pub(crate) fn expand_test_or_bench(
109 cx: &ExtCtxt<'_>,
110 attr_sp: Span,
111 item: Annotatable,
112 is_bench: bool,
113) -> Vec<Annotatable> {
114 if !cx.ecfg.should_test {
116 return vec![];
117 }
118
119 let (item, is_stmt) = match item {
120 Annotatable::Item(i) => (i, false),
121 Annotatable::Stmt(box ast::Stmt { kind: ast::StmtKind::Item(i), .. }) => (i, true),
122 other => {
123 not_testable_error(cx, attr_sp, None);
124 return vec![other];
125 }
126 };
127
128 let ast::ItemKind::Fn(fn_) = &item.kind else {
129 not_testable_error(cx, attr_sp, Some(&item));
130 return if is_stmt {
131 vec![Annotatable::Stmt(P(cx.stmt_item(item.span, item)))]
132 } else {
133 vec![Annotatable::Item(item)]
134 };
135 };
136
137 if let Some(attr) = attr::find_by_name(&item.attrs, sym::naked) {
138 cx.dcx().emit_err(errors::NakedFunctionTestingAttribute {
139 testing_span: attr_sp,
140 naked_span: attr.span,
141 });
142 return vec![Annotatable::Item(item)];
143 }
144
145 let check_result = if is_bench {
149 check_bench_signature(cx, &item, fn_)
150 } else {
151 check_test_signature(cx, &item, fn_)
152 };
153 if check_result.is_err() {
154 return if is_stmt {
155 vec![Annotatable::Stmt(P(cx.stmt_item(item.span, item)))]
156 } else {
157 vec![Annotatable::Item(item)]
158 };
159 }
160
161 let sp = cx.with_def_site_ctxt(item.span);
162 let ret_ty_sp = cx.with_def_site_ctxt(fn_.sig.decl.output.span());
163 let attr_sp = cx.with_def_site_ctxt(attr_sp);
164
165 let test_ident = Ident::new(sym::test, attr_sp);
166
167 let test_path = |name| cx.path(ret_ty_sp, vec![test_ident, Ident::from_str_and_span(name, sp)]);
169
170 let should_panic_path = |name| {
172 cx.path(
173 sp,
174 vec![
175 test_ident,
176 Ident::from_str_and_span("ShouldPanic", sp),
177 Ident::from_str_and_span(name, sp),
178 ],
179 )
180 };
181
182 let test_type_path = |name| {
184 cx.path(
185 sp,
186 vec![
187 test_ident,
188 Ident::from_str_and_span("TestType", sp),
189 Ident::from_str_and_span(name, sp),
190 ],
191 )
192 };
193
194 let field = |name, expr| cx.field_imm(sp, Ident::from_str_and_span(name, sp), expr);
196
197 let coverage_off = |mut expr: P<ast::Expr>| {
202 assert_matches!(expr.kind, ast::ExprKind::Closure(_));
203 expr.attrs.push(cx.attr_nested_word(sym::coverage, sym::off, sp));
204 expr
205 };
206
207 let test_fn = if is_bench {
208 let b = Ident::from_str_and_span("b", attr_sp);
210
211 cx.expr_call(
212 sp,
213 cx.expr_path(test_path("StaticBenchFn")),
214 thin_vec![
215 coverage_off(cx.lambda1(
218 sp,
219 cx.expr_call(
220 sp,
221 cx.expr_path(test_path("assert_test_result")),
222 thin_vec![
223 cx.expr_call(
225 ret_ty_sp,
226 cx.expr_path(cx.path(sp, vec![fn_.ident])),
227 thin_vec![cx.expr_ident(sp, b)],
228 ),
229 ],
230 ),
231 b,
232 )), ],
234 )
235 } else {
236 cx.expr_call(
237 sp,
238 cx.expr_path(test_path("StaticTestFn")),
239 thin_vec![
240 coverage_off(cx.lambda0(
243 sp,
244 cx.expr_call(
246 sp,
247 cx.expr_path(test_path("assert_test_result")),
248 thin_vec![
249 cx.expr_call(
251 ret_ty_sp,
252 cx.expr_path(cx.path(sp, vec![fn_.ident])),
253 ThinVec::new(),
254 ), ],
256 ), )), ],
259 )
260 };
261
262 let test_path_symbol = Symbol::intern(&item_path(
263 &cx.current_expansion.module.mod_path[1..],
265 &fn_.ident,
266 ));
267
268 let location_info = get_location_info(cx, &fn_);
269
270 let mut test_const =
271 cx.item(
272 sp,
273 thin_vec![
274 cx.attr_nested_word(sym::cfg, sym::test, attr_sp),
276 cx.attr_name_value_str(sym::rustc_test_marker, test_path_symbol, attr_sp),
278 cx.attr_nested_word(sym::doc, sym::hidden, attr_sp),
280 ],
281 ast::ItemKind::Const(
283 ast::ConstItem {
284 defaultness: ast::Defaultness::Final,
285 ident: Ident::new(fn_.ident.name, sp),
286 generics: ast::Generics::default(),
287 ty: cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))),
288 define_opaque: None,
289 expr: Some(
291 cx.expr_struct(
292 sp,
293 test_path("TestDescAndFn"),
294 thin_vec![
295 field(
297 "desc",
298 cx.expr_struct(sp, test_path("TestDesc"), thin_vec![
299 field(
301 "name",
302 cx.expr_call(
303 sp,
304 cx.expr_path(test_path("StaticTestName")),
305 thin_vec![cx.expr_str(sp, test_path_symbol)],
306 ),
307 ),
308 field("ignore", cx.expr_bool(sp, should_ignore(&item)),),
310 field(
312 "ignore_message",
313 if let Some(msg) = should_ignore_message(&item) {
314 cx.expr_some(sp, cx.expr_str(sp, msg))
315 } else {
316 cx.expr_none(sp)
317 },
318 ),
319 field("source_file", cx.expr_str(sp, location_info.0)),
321 field("start_line", cx.expr_usize(sp, location_info.1)),
323 field("start_col", cx.expr_usize(sp, location_info.2)),
325 field("end_line", cx.expr_usize(sp, location_info.3)),
327 field("end_col", cx.expr_usize(sp, location_info.4)),
329 field("compile_fail", cx.expr_bool(sp, false)),
331 field("no_run", cx.expr_bool(sp, false)),
333 field("should_panic", match should_panic(cx, &item) {
335 ShouldPanic::No => {
337 cx.expr_path(should_panic_path("No"))
338 }
339 ShouldPanic::Yes(None) => {
341 cx.expr_path(should_panic_path("Yes"))
342 }
343 ShouldPanic::Yes(Some(sym)) => cx.expr_call(
345 sp,
346 cx.expr_path(should_panic_path("YesWithMessage")),
347 thin_vec![cx.expr_str(sp, sym)],
348 ),
349 },),
350 field("test_type", match test_type(cx) {
352 TestType::UnitTest => {
354 cx.expr_path(test_type_path("UnitTest"))
355 }
356 TestType::IntegrationTest => {
358 cx.expr_path(test_type_path("IntegrationTest"))
359 }
360 TestType::Unknown => {
362 cx.expr_path(test_type_path("Unknown"))
363 }
364 },),
365 ],),
367 ),
368 field("testfn", test_fn), ],
371 ), ),
373 }
374 .into(),
375 ),
376 );
377 test_const.vis.kind = ast::VisibilityKind::Public;
378
379 let test_extern =
381 cx.item(sp, ast::AttrVec::new(), ast::ItemKind::ExternCrate(None, test_ident));
382
383 debug!("synthetic test item:\n{}\n", pprust::item_to_string(&test_const));
384
385 if is_stmt {
386 vec![
387 Annotatable::Stmt(P(cx.stmt_item(sp, test_extern))),
389 Annotatable::Stmt(P(cx.stmt_item(sp, test_const))),
391 Annotatable::Stmt(P(cx.stmt_item(sp, item))),
393 ]
394 } else {
395 vec![
396 Annotatable::Item(test_extern),
398 Annotatable::Item(test_const),
400 Annotatable::Item(item),
402 ]
403 }
404}
405
406fn not_testable_error(cx: &ExtCtxt<'_>, attr_sp: Span, item: Option<&ast::Item>) {
407 let dcx = cx.dcx();
408 let msg = "the `#[test]` attribute may only be used on a non-associated function";
409 let level = match item.map(|i| &i.kind) {
410 Some(ast::ItemKind::MacCall(_)) => Level::Warning,
413 _ => Level::Error,
414 };
415 let mut err = Diag::<()>::new(dcx, level, msg);
416 err.span(attr_sp);
417 if let Some(item) = item {
418 err.span_label(
419 item.span,
420 format!(
421 "expected a non-associated function, found {} {}",
422 item.kind.article(),
423 item.kind.descr()
424 ),
425 );
426 }
427 err.with_span_label(attr_sp, "the `#[test]` macro causes a function to be run as a test and has no effect on non-functions")
428 .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)
432 .emit();
433}
434
435fn get_location_info(cx: &ExtCtxt<'_>, fn_: &ast::Fn) -> (Symbol, usize, usize, usize, usize) {
436 let span = fn_.ident.span;
437 let (source_file, lo_line, lo_col, hi_line, hi_col) =
438 cx.sess.source_map().span_to_location_info(span);
439
440 let file_name = match source_file {
441 Some(sf) => sf.name.display(FileNameDisplayPreference::Remapped).to_string(),
442 None => "no-location".to_string(),
443 };
444
445 (Symbol::intern(&file_name), lo_line, lo_col, hi_line, hi_col)
446}
447
448fn item_path(mod_path: &[Ident], item_ident: &Ident) -> String {
449 join_path_idents(mod_path.iter().chain(iter::once(item_ident)))
450}
451
452enum ShouldPanic {
453 No,
454 Yes(Option<Symbol>),
455}
456
457fn should_ignore(i: &ast::Item) -> bool {
458 attr::contains_name(&i.attrs, sym::ignore)
459}
460
461fn should_ignore_message(i: &ast::Item) -> Option<Symbol> {
462 match attr::find_by_name(&i.attrs, sym::ignore) {
463 Some(attr) => {
464 match attr.meta_item_list() {
465 Some(_) => None,
467 None => attr.value_str(),
469 }
470 }
471 None => None,
472 }
473}
474
475fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
476 match attr::find_by_name(&i.attrs, sym::should_panic) {
477 Some(attr) => {
478 match attr.meta_item_list() {
479 Some(list) => {
481 let msg = list
482 .iter()
483 .find(|mi| mi.has_name(sym::expected))
484 .and_then(|mi| mi.meta_item())
485 .and_then(|mi| mi.value_str());
486 if list.len() != 1 || msg.is_none() {
487 cx.dcx()
488 .struct_span_warn(
489 attr.span,
490 "argument must be of the form: \
491 `expected = \"error message\"`",
492 )
493 .with_note(
494 "errors in this attribute were erroneously \
495 allowed and will become a hard error in a \
496 future release",
497 )
498 .emit();
499 ShouldPanic::Yes(None)
500 } else {
501 ShouldPanic::Yes(msg)
502 }
503 }
504 None => ShouldPanic::Yes(attr.value_str()),
506 }
507 }
508 None => ShouldPanic::No,
509 }
510}
511
512enum TestType {
513 UnitTest,
514 IntegrationTest,
515 Unknown,
516}
517
518fn test_type(cx: &ExtCtxt<'_>) -> TestType {
522 let crate_path = cx.root_path.as_path();
527
528 if crate_path.ends_with("src") {
529 TestType::UnitTest
531 } else if crate_path.ends_with("tests") {
532 TestType::IntegrationTest
534 } else {
535 TestType::Unknown
537 }
538}
539
540fn check_test_signature(
541 cx: &ExtCtxt<'_>,
542 i: &ast::Item,
543 f: &ast::Fn,
544) -> Result<(), ErrorGuaranteed> {
545 let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic);
546 let dcx = cx.dcx();
547
548 if let ast::Safety::Unsafe(span) = f.sig.header.safety {
549 return Err(dcx.emit_err(errors::TestBadFn { span: i.span, cause: span, kind: "unsafe" }));
550 }
551
552 if let Some(coroutine_kind) = f.sig.header.coroutine_kind {
553 match coroutine_kind {
554 ast::CoroutineKind::Async { span, .. } => {
555 return Err(dcx.emit_err(errors::TestBadFn {
556 span: i.span,
557 cause: span,
558 kind: "async",
559 }));
560 }
561 ast::CoroutineKind::Gen { span, .. } => {
562 return Err(dcx.emit_err(errors::TestBadFn {
563 span: i.span,
564 cause: span,
565 kind: "gen",
566 }));
567 }
568 ast::CoroutineKind::AsyncGen { span, .. } => {
569 return Err(dcx.emit_err(errors::TestBadFn {
570 span: i.span,
571 cause: span,
572 kind: "async gen",
573 }));
574 }
575 }
576 }
577
578 let has_output = match &f.sig.decl.output {
581 ast::FnRetTy::Default(..) => false,
582 ast::FnRetTy::Ty(t) if t.kind.is_unit() => false,
583 _ => true,
584 };
585
586 if !f.sig.decl.inputs.is_empty() {
587 return Err(dcx.span_err(i.span, "functions used as tests can not have any arguments"));
588 }
589
590 if has_should_panic_attr && has_output {
591 return Err(dcx.span_err(i.span, "functions using `#[should_panic]` must return `()`"));
592 }
593
594 if f.generics.params.iter().any(|param| !matches!(param.kind, GenericParamKind::Lifetime)) {
595 return Err(dcx.span_err(
596 i.span,
597 "functions used as tests can not have any non-lifetime generic parameters",
598 ));
599 }
600
601 Ok(())
602}
603
604fn check_bench_signature(
605 cx: &ExtCtxt<'_>,
606 i: &ast::Item,
607 f: &ast::Fn,
608) -> Result<(), ErrorGuaranteed> {
609 if f.sig.decl.inputs.len() != 1 {
612 return Err(cx.dcx().emit_err(errors::BenchSig { span: i.span }));
613 }
614 Ok(())
615}