Skip to content

Commit b4c3f0f

Browse files
committed
fix
1 parent d901079 commit b4c3f0f

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-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: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2146,6 +2146,26 @@ 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+
&& items.len() == 1
2157+
&& items[0].has_name(sym::test)
2158+
{
2159+
true
2160+
} else {
2161+
false
2162+
}
2163+
}
2164+
tcx.hir()
2165+
.parent_iter(id)
2166+
.any(|(parent_id, _)| tcx.hir().attrs(parent_id).iter().any(is_cfg_test))
2167+
}
2168+
21492169
/// Checks whether item either has `test` attribute applied, or
21502170
/// is a module with `test` in its name.
21512171
///

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)