|
1 | 1 | use clippy_utils::diagnostics::{span_lint, span_lint_and_then}; |
2 | 2 | use clippy_utils::macros::{root_macro_call_first_node, FormatArgsExpn, MacroCall}; |
3 | 3 | use clippy_utils::source::{expand_past_previous_comma, snippet_opt}; |
| 4 | +use clippy_utils::{is_in_cfg_test, is_in_test_function}; |
4 | 5 | use rustc_ast::LitKind; |
5 | 6 | use rustc_errors::Applicability; |
6 | 7 | use rustc_hir::{Expr, ExprKind, HirIdMap, Impl, Item, ItemKind}; |
@@ -232,6 +233,16 @@ declare_clippy_lint! { |
232 | 233 | #[derive(Default)] |
233 | 234 | pub struct Write { |
234 | 235 | in_debug_impl: bool, |
| 236 | + allow_print_in_tests: bool, |
| 237 | +} |
| 238 | + |
| 239 | +impl Write { |
| 240 | + pub fn new(allow_print_in_tests: bool) -> Self { |
| 241 | + Self { |
| 242 | + allow_print_in_tests, |
| 243 | + ..Default::default() |
| 244 | + } |
| 245 | + } |
235 | 246 | } |
236 | 247 |
|
237 | 248 | impl_lint_pass!(Write => [ |
@@ -271,13 +282,15 @@ impl<'tcx> LateLintPass<'tcx> for Write { |
271 | 282 | .as_ref() |
272 | 283 | .map_or(false, |crate_name| crate_name == "build_script_build"); |
273 | 284 |
|
| 285 | + let allowed_in_tests = self.allow_print_in_tests |
| 286 | + && (is_in_test_function(cx.tcx, expr.hir_id) || is_in_cfg_test(cx.tcx, expr.hir_id)); |
274 | 287 | match diag_name { |
275 | | - sym::print_macro | sym::println_macro => { |
| 288 | + sym::print_macro | sym::println_macro if !allowed_in_tests => { |
276 | 289 | if !is_build_script { |
277 | 290 | span_lint(cx, PRINT_STDOUT, macro_call.span, &format!("use of `{name}!`")); |
278 | 291 | } |
279 | 292 | }, |
280 | | - sym::eprint_macro | sym::eprintln_macro => { |
| 293 | + sym::eprint_macro | sym::eprintln_macro if !allowed_in_tests => { |
281 | 294 | span_lint(cx, PRINT_STDERR, macro_call.span, &format!("use of `{name}!`")); |
282 | 295 | }, |
283 | 296 | sym::write_macro | sym::writeln_macro => {}, |
|
0 commit comments