This commit is contained in:
tamaron 2022-05-18 00:37:12 +09:00
parent d901079ca1
commit b4c3f0f79b
3 changed files with 34 additions and 2 deletions

View File

@ -1,7 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_in_test_function;
use clippy_utils::macros::root_macro_call_first_node;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::{is_in_cfg_test, is_in_test_function};
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
@ -37,7 +37,7 @@ impl LateLintPass<'_> for DbgMacro {
let Some(macro_call) = root_macro_call_first_node(cx, expr) else { return };
if cx.tcx.is_diagnostic_item(sym::dbg_macro, macro_call.def_id) {
// we make an exception for test code
if is_in_test_function(cx.tcx, expr.hir_id) {
if is_in_test_function(cx.tcx, expr.hir_id) || is_in_cfg_test(cx.tcx, expr.hir_id) {
return;
}
let mut applicability = Applicability::MachineApplicable;

View File

@ -2146,6 +2146,26 @@ pub fn is_in_test_function(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
})
}
/// Checks if the item containing the given `HirId` has `#[cfg(test)]` attribute applied
///
/// Note: Add `// compile-flags: --test` to UI tests with a `#[cfg(test)]` function
pub fn is_in_cfg_test(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
fn is_cfg_test(attr: &Attribute) -> bool {
if attr.has_name(sym::cfg)
&& let Some(items) = attr.meta_item_list()
&& items.len() == 1
&& items[0].has_name(sym::test)
{
true
} else {
false
}
}
tcx.hir()
.parent_iter(id)
.any(|(parent_id, _)| tcx.hir().attrs(parent_id).iter().any(is_cfg_test))
}
/// Checks whether item either has `test` attribute applied, or
/// is a module with `test` in its name.
///

View File

@ -46,3 +46,15 @@ mod issue7274 {
pub fn issue8481() {
dbg!(1);
}
#[cfg(test)]
fn foo2() {
dbg!(1);
}
#[cfg(test)]
mod mod1 {
fn func() {
dbg!(1);
}
}