| 
 | 1 | +use clippy_utils::diagnostics::span_lint_and_then;  | 
 | 2 | +use clippy_utils::is_test_function;  | 
 | 3 | +use clippy_utils::visitors::for_each_expr;  | 
 | 4 | +use rustc_errors::Applicability;  | 
 | 5 | +use rustc_hir::intravisit::FnKind;  | 
 | 6 | +use rustc_hir::{self as hir, Body, ExprKind, FnDecl};  | 
 | 7 | +use rustc_lexer::is_ident;  | 
 | 8 | +use rustc_lint::{LateContext, LateLintPass};  | 
 | 9 | +use rustc_session::declare_lint_pass;  | 
 | 10 | +use rustc_span::def_id::LocalDefId;  | 
 | 11 | +use rustc_span::{Span, Symbol, edition};  | 
 | 12 | +use std::borrow::Cow;  | 
 | 13 | +use std::ops::ControlFlow;  | 
 | 14 | + | 
 | 15 | +declare_clippy_lint! {  | 
 | 16 | +    /// ### What it does  | 
 | 17 | +    /// Checks for test functions (functions annotated with `#[test]`) that are prefixed  | 
 | 18 | +    /// with `test_` which is redundant.  | 
 | 19 | +    ///  | 
 | 20 | +    /// ### Why is this bad?  | 
 | 21 | +    /// This is redundant because test functions are already annotated with `#[test]`.  | 
 | 22 | +    /// Moreover, it clutters the output of `cargo test` since test functions are expanded as  | 
 | 23 | +    /// `module::tests::test_use_case` in the output. Without the redundant prefix, the output  | 
 | 24 | +    /// becomes `module::tests::use_case`, which is more readable.  | 
 | 25 | +    ///  | 
 | 26 | +    /// ### Example  | 
 | 27 | +    /// ```no_run  | 
 | 28 | +    /// #[cfg(test)]  | 
 | 29 | +    /// mod tests {  | 
 | 30 | +    ///   use super::*;  | 
 | 31 | +    ///  | 
 | 32 | +    ///   #[test]  | 
 | 33 | +    ///   fn test_use_case() {  | 
 | 34 | +    ///       // test code  | 
 | 35 | +    ///   }  | 
 | 36 | +    /// }  | 
 | 37 | +    /// ```  | 
 | 38 | +    /// Use instead:  | 
 | 39 | +    /// ```no_run  | 
 | 40 | +    /// #[cfg(test)]  | 
 | 41 | +    /// mod tests {  | 
 | 42 | +    ///   use super::*;  | 
 | 43 | +    ///  | 
 | 44 | +    ///   #[test]  | 
 | 45 | +    ///   fn use_case() {  | 
 | 46 | +    ///       // test code  | 
 | 47 | +    ///   }  | 
 | 48 | +    /// }  | 
 | 49 | +    /// ```  | 
 | 50 | +    #[clippy::version = "1.88.0"]  | 
 | 51 | +    pub REDUNDANT_TEST_PREFIX,  | 
 | 52 | +    restriction,  | 
 | 53 | +    "redundant `test_` prefix in test function name"  | 
 | 54 | +}  | 
 | 55 | + | 
 | 56 | +declare_lint_pass!(RedundantTestPrefix => [REDUNDANT_TEST_PREFIX]);  | 
 | 57 | + | 
 | 58 | +impl<'tcx> LateLintPass<'tcx> for RedundantTestPrefix {  | 
 | 59 | +    fn check_fn(  | 
 | 60 | +        &mut self,  | 
 | 61 | +        cx: &LateContext<'tcx>,  | 
 | 62 | +        kind: FnKind<'_>,  | 
 | 63 | +        _decl: &FnDecl<'_>,  | 
 | 64 | +        body: &'tcx Body<'_>,  | 
 | 65 | +        _span: Span,  | 
 | 66 | +        fn_def_id: LocalDefId,  | 
 | 67 | +    ) {  | 
 | 68 | +        // Ignore methods and closures.  | 
 | 69 | +        let FnKind::ItemFn(ref ident, ..) = kind else {  | 
 | 70 | +            return;  | 
 | 71 | +        };  | 
 | 72 | + | 
 | 73 | +        // Skip the lint if the function is within a macro expansion.  | 
 | 74 | +        if ident.span.from_expansion() {  | 
 | 75 | +            return;  | 
 | 76 | +        }  | 
 | 77 | + | 
 | 78 | +        // Skip if the function name does not start with `test_`.  | 
 | 79 | +        if !ident.as_str().starts_with("test_") {  | 
 | 80 | +            return;  | 
 | 81 | +        }  | 
 | 82 | + | 
 | 83 | +        // If the function is not a test function, skip the lint.  | 
 | 84 | +        if !is_test_function(cx.tcx, fn_def_id) {  | 
 | 85 | +            return;  | 
 | 86 | +        }  | 
 | 87 | + | 
 | 88 | +        span_lint_and_then(  | 
 | 89 | +            cx,  | 
 | 90 | +            REDUNDANT_TEST_PREFIX,  | 
 | 91 | +            ident.span,  | 
 | 92 | +            "redundant `test_` prefix in test function name",  | 
 | 93 | +            |diag| {  | 
 | 94 | +                let non_prefixed = Symbol::intern(ident.as_str().trim_start_matches("test_"));  | 
 | 95 | +                if is_invalid_ident(non_prefixed) {  | 
 | 96 | +                    // If the prefix-trimmed name is not a valid function name, do not provide an  | 
 | 97 | +                    // automatic fix, just suggest renaming the function.  | 
 | 98 | +                    diag.help(  | 
 | 99 | +                        "consider function renaming (just removing `test_` prefix will produce invalid function name)",  | 
 | 100 | +                    );  | 
 | 101 | +                } else {  | 
 | 102 | +                    let (sugg, msg): (Cow<'_, str>, _) = if name_conflicts(cx, body, non_prefixed) {  | 
 | 103 | +                        // If `non_prefixed` conflicts with another function in the same module/scope,  | 
 | 104 | +                        // do not provide an automatic fix, but still emit a fix suggestion.  | 
 | 105 | +                        (  | 
 | 106 | +                            format!("{non_prefixed}_works").into(),  | 
 | 107 | +                            "consider function renaming (just removing `test_` prefix will cause a name conflict)",  | 
 | 108 | +                        )  | 
 | 109 | +                    } else {  | 
 | 110 | +                        // If `non_prefixed` is a valid identifier and does not conflict with another function,  | 
 | 111 | +                        // so we can suggest an auto-fix.  | 
 | 112 | +                        (non_prefixed.as_str().into(), "consider removing the `test_` prefix")  | 
 | 113 | +                    };  | 
 | 114 | +                    diag.span_suggestion(ident.span, msg, sugg, Applicability::MaybeIncorrect);  | 
 | 115 | +                }  | 
 | 116 | +            },  | 
 | 117 | +        );  | 
 | 118 | +    }  | 
 | 119 | +}  | 
 | 120 | + | 
 | 121 | +/// Checks whether removal of the `_test` prefix from the function name will cause a name conflict.  | 
 | 122 | +///  | 
 | 123 | +/// There should be no other function with the same name in the same module/scope. Also, there  | 
 | 124 | +/// should not be any function call with the same name within the body of the function, to avoid  | 
 | 125 | +/// recursion.  | 
 | 126 | +fn name_conflicts<'tcx>(cx: &LateContext<'tcx>, body: &'tcx Body<'_>, fn_name: Symbol) -> bool {  | 
 | 127 | +    let tcx = cx.tcx;  | 
 | 128 | +    let id = body.id().hir_id;  | 
 | 129 | + | 
 | 130 | +    // Iterate over items in the same module/scope  | 
 | 131 | +    let (module, _module_span, _module_hir) = tcx.hir_get_module(tcx.parent_module(id));  | 
 | 132 | +    if module  | 
 | 133 | +        .item_ids  | 
 | 134 | +        .iter()  | 
 | 135 | +        .any(|item| matches!(tcx.hir_item(*item).kind, hir::ItemKind::Fn { ident, .. } if ident.name == fn_name))  | 
 | 136 | +    {  | 
 | 137 | +        // Name conflict found  | 
 | 138 | +        return true;  | 
 | 139 | +    }  | 
 | 140 | + | 
 | 141 | +    // Also check that within the body of the function there is also no function call  | 
 | 142 | +    // with the same name (since it will result in recursion)  | 
 | 143 | +    for_each_expr(cx, body, |expr| {  | 
 | 144 | +        if let ExprKind::Path(qpath) = &expr.kind  | 
 | 145 | +            && let Some(def_id) = cx.qpath_res(qpath, expr.hir_id).opt_def_id()  | 
 | 146 | +            && let Some(name) = tcx.opt_item_name(def_id)  | 
 | 147 | +            && name == fn_name  | 
 | 148 | +        {  | 
 | 149 | +            // Function call with the same name found  | 
 | 150 | +            ControlFlow::Break(())  | 
 | 151 | +        } else {  | 
 | 152 | +            ControlFlow::Continue(())  | 
 | 153 | +        }  | 
 | 154 | +    })  | 
 | 155 | +    .is_some()  | 
 | 156 | +}  | 
 | 157 | + | 
 | 158 | +fn is_invalid_ident(ident: Symbol) -> bool {  | 
 | 159 | +    // The identifier is either a reserved keyword, or starts with an invalid sequence.  | 
 | 160 | +    ident.is_reserved(|| edition::LATEST_STABLE_EDITION) || !is_ident(ident.as_str())  | 
 | 161 | +}  | 
0 commit comments