Skip to content

Commit ea96091

Browse files
committed
Auto merge of #8838 - tamaroning:fix_dbg, r=Jarcho,xFrednet
[dbg_macro] tolerates use of `dbg!` in items which have `#[cfg(test)]` attribute fix: #8758 changelog: [dbg_macro] tolerates use of `dbg!` in items with `#[cfg(test)]` attribute
2 parents 6f8d18f + db41df1 commit ea96091

File tree

3 files changed

+35
-2
lines changed

3 files changed

+35
-2
lines changed

clippy_lints/src/dbg_macro.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use clippy_utils::diagnostics::span_lint_and_sugg;
2-
use clippy_utils::is_in_test_function;
32
use clippy_utils::macros::root_macro_call_first_node;
43
use clippy_utils::source::snippet_with_applicability;
4+
use clippy_utils::{is_in_cfg_test, is_in_test_function};
55
use rustc_errors::Applicability;
66
use rustc_hir::{Expr, ExprKind};
77
use rustc_lint::{LateContext, LateLintPass};
@@ -37,7 +37,7 @@ impl LateLintPass<'_> for DbgMacro {
3737
let Some(macro_call) = root_macro_call_first_node(cx, expr) else { return };
3838
if cx.tcx.is_diagnostic_item(sym::dbg_macro, macro_call.def_id) {
3939
// we make an exception for test code
40-
if is_in_test_function(cx.tcx, expr.hir_id) {
40+
if is_in_test_function(cx.tcx, expr.hir_id) || is_in_cfg_test(cx.tcx, expr.hir_id) {
4141
return;
4242
}
4343
let mut applicability = Applicability::MachineApplicable;

clippy_utils/src/lib.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2146,6 +2146,27 @@ pub fn is_in_test_function(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
21462146
})
21472147
}
21482148

2149+
/// Checks if the item containing the given `HirId` has `#[cfg(test)]` attribute applied
2150+
///
2151+
/// Note: Add `// compile-flags: --test` to UI tests with a `#[cfg(test)]` function
2152+
pub fn is_in_cfg_test(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
2153+
fn is_cfg_test(attr: &Attribute) -> bool {
2154+
if attr.has_name(sym::cfg)
2155+
&& let Some(items) = attr.meta_item_list()
2156+
&& let [item] = &*items
2157+
&& item.has_name(sym::test)
2158+
{
2159+
true
2160+
} else {
2161+
false
2162+
}
2163+
}
2164+
tcx.hir()
2165+
.parent_iter(id)
2166+
.flat_map(|(parent_id, _)| tcx.hir().attrs(parent_id))
2167+
.any(is_cfg_test)
2168+
}
2169+
21492170
/// Checks whether item either has `test` attribute applied, or
21502171
/// is a module with `test` in its name.
21512172
///

tests/ui/dbg_macro.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,15 @@ mod issue7274 {
4646
pub fn issue8481() {
4747
dbg!(1);
4848
}
49+
50+
#[cfg(test)]
51+
fn foo2() {
52+
dbg!(1);
53+
}
54+
55+
#[cfg(test)]
56+
mod mod1 {
57+
fn func() {
58+
dbg!(1);
59+
}
60+
}

0 commit comments

Comments
 (0)