src/tools/clippy/clippy_lints/src/matches/manual_utils.rs RUST 269 lines View on github.com → Search inside
1use crate::map_unit_fn::OPTION_MAP_UNIT_FN;2use crate::matches::MATCH_AS_REF;3use clippy_utils::res::{MaybeDef, MaybeResPath};4use clippy_utils::source::{snippet_with_applicability, snippet_with_context};5use clippy_utils::sugg::Sugg;6use clippy_utils::ty::{is_copy, is_unsafe_fn, peel_and_count_ty_refs};7use clippy_utils::{8    CaptureKind, as_some_pattern, can_move_expr_to_closure, expr_requires_coercion, is_else_clause, is_lint_allowed,9    is_none_expr, is_none_pattern, peel_blocks, peel_hir_expr_refs, peel_hir_expr_while,10};11use rustc_ast::util::parser::ExprPrecedence;12use rustc_errors::Applicability;13use rustc_hir::def::Res;14use rustc_hir::{BindingMode, Expr, ExprKind, HirId, Mutability, Pat, PatKind, Path, QPath};15use rustc_lint::LateContext;16use rustc_span::{SyntaxContext, sym};1718#[expect(clippy::too_many_arguments)]19#[expect(clippy::too_many_lines)]20pub(super) fn check_with<'tcx, F>(21    cx: &LateContext<'tcx>,22    expr: &'tcx Expr<'_>,23    scrutinee: &'tcx Expr<'_>,24    then_pat: &'tcx Pat<'_>,25    then_body: &'tcx Expr<'_>,26    else_pat: Option<&'tcx Pat<'_>>,27    else_body: &'tcx Expr<'_>,28    get_some_expr_fn: F,29) -> Option<SuggInfo<'tcx>>30where31    F: Fn(&LateContext<'tcx>, &'tcx Pat<'_>, &'tcx Expr<'_>, SyntaxContext) -> Option<SomeExpr<'tcx>>,32{33    let (scrutinee_ty, ty_ref_count, ty_mutability) = peel_and_count_ty_refs(cx.typeck_results().expr_ty(scrutinee));34    let ty_mutability = ty_mutability.unwrap_or(Mutability::Mut);3536    if !(scrutinee_ty.is_diag_item(cx, sym::Option) && cx.typeck_results().expr_ty(expr).is_diag_item(cx, sym::Option))37    {38        return None;39    }4041    let expr_ctxt = expr.span.ctxt();42    let (some_expr, some_pat, pat_ref_count, is_wild_none) = match (43        try_parse_pattern(cx, then_pat, expr_ctxt),44        else_pat.map_or(Some(OptionPat::Wild), |p| try_parse_pattern(cx, p, expr_ctxt)),45    ) {46        (Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count })) if is_none_arm_body(cx, then_body) => {47            (else_body, pattern, ref_count, true)48        },49        (Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count })) if is_none_arm_body(cx, then_body) => {50            (else_body, pattern, ref_count, false)51        },52        (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild)) if is_none_arm_body(cx, else_body) => {53            (then_body, pattern, ref_count, true)54        },55        (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None)) if is_none_arm_body(cx, else_body) => {56            (then_body, pattern, ref_count, false)57        },58        _ => return None,59    };6061    // Top level or patterns aren't allowed in closures.62    if matches!(some_pat.kind, PatKind::Or(_)) {63        return None;64    }6566    let some_expr = get_some_expr_fn(cx, some_pat, some_expr, expr_ctxt)?;6768    // These two lints will go back and forth with each other.69    if cx.typeck_results().expr_ty(some_expr.expr) == cx.tcx.types.unit70        && !is_lint_allowed(cx, OPTION_MAP_UNIT_FN, expr.hir_id)71    {72        return None;73    }7475    // `map` won't perform any adjustments.76    if expr_requires_coercion(cx, expr) {77        return None;78    }7980    // Determine which binding mode to use.81    let explicit_ref = some_pat.contains_explicit_ref_binding();82    let binding_ref = explicit_ref.or_else(|| (ty_ref_count != pat_ref_count).then_some(ty_mutability));8384    let as_ref_str = match binding_ref {85        Some(Mutability::Mut) => ".as_mut()",86        Some(Mutability::Not) => ".as_ref()",87        None => "",88    };8990    let captures = can_move_expr_to_closure(cx, some_expr.expr)?;91    // Check if captures the closure will need conflict with borrows made in the scrutinee.92    // TODO: check all the references made in the scrutinee expression. This will require interacting93    // with the borrow checker. Currently only `<local>[.<field>]*` is checked for.94    if let Some(binding_ref_mutability) = binding_ref {95        let e = peel_hir_expr_while(scrutinee, |e| match e.kind {96            ExprKind::Field(e, _) | ExprKind::AddrOf(_, _, e) => Some(e),97            _ => None,98        });99        if let ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(l), .. })) = e.kind {100            match captures.get(l) {101                Some(CaptureKind::Value | CaptureKind::Use | CaptureKind::Ref(Mutability::Mut)) => return None,102                Some(CaptureKind::Ref(Mutability::Not)) if binding_ref_mutability == Mutability::Mut => {103                    return None;104                },105                Some(CaptureKind::Ref(Mutability::Not)) | None => (),106            }107        }108    }109110    let mut app = Applicability::MachineApplicable;111112    // Remove address-of expressions from the scrutinee. Either `as_ref` will be called, or113    // it's being passed by value.114    let scrutinee = peel_hir_expr_refs(scrutinee).0;115    let (scrutinee_str, _) = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app);116    let scrutinee_str = if scrutinee.span.eq_ctxt(expr.span) && cx.precedence(scrutinee) < ExprPrecedence::Unambiguous {117        format!("({scrutinee_str})")118    } else {119        scrutinee_str.into()120    };121122    let closure_expr_snip = some_expr.to_snippet_with_context(cx, expr_ctxt, &mut app);123    let closure_body = if some_expr.needs_unsafe_block {124        format!("unsafe {}", closure_expr_snip.blockify())125    } else {126        closure_expr_snip.to_string()127    };128129    let body_str = if let PatKind::Binding(annotation, id, some_binding, None) = some_pat.kind {130        if !some_expr.needs_unsafe_block131            && let Some(func) = can_pass_as_func(cx, id, some_expr.expr)132            && func.span.eq_ctxt(some_expr.expr.span)133        {134            snippet_with_applicability(cx, func.span, "..", &mut app).into_owned()135        } else {136            if some_expr.expr.res_local_id() == Some(id)137                && !is_lint_allowed(cx, MATCH_AS_REF, expr.hir_id)138                && binding_ref.is_some()139            {140                return None;141            }142143            // `ref` and `ref mut` annotations were handled earlier.144            let annotation = if matches!(annotation, BindingMode::MUT) {145                "mut "146            } else {147                ""148            };149150            format!("|{annotation}{some_binding}| {closure_body}")151        }152    } else if !is_wild_none && explicit_ref.is_none() {153        // TODO: handle explicit reference annotations.154        let pat_snip = snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0;155        format!("|{pat_snip}| {closure_body}")156    } else {157        // Refutable bindings and mixed reference annotations can't be handled by `map`.158        return None;159    };160161    // relies on the fact that Option<T>: Copy where T: copy162    let scrutinee_impl_copy = is_copy(cx, scrutinee_ty);163164    Some(SuggInfo {165        needs_brackets: else_pat.is_none() && is_else_clause(cx.tcx, expr),166        scrutinee_impl_copy,167        scrutinee_str,168        as_ref_str,169        body_str,170        app,171    })172}173174pub struct SuggInfo<'a> {175    pub needs_brackets: bool,176    pub scrutinee_impl_copy: bool,177    pub scrutinee_str: String,178    pub as_ref_str: &'a str,179    pub body_str: String,180    pub app: Applicability,181}182183// Checks whether the expression could be passed as a function, or whether a closure is needed.184// Returns the function to be passed to `map` if it exists.185fn can_pass_as_func<'tcx>(cx: &LateContext<'tcx>, binding: HirId, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {186    match expr.kind {187        ExprKind::Call(func, [arg])188            if arg.res_local_id() == Some(binding)189                && cx.typeck_results().expr_adjustments(arg).is_empty()190                && !is_unsafe_fn(cx, cx.typeck_results().expr_ty(func).peel_refs()) =>191        {192            Some(func)193        },194        _ => None,195    }196}197198#[derive(Debug)]199pub(super) enum OptionPat<'a> {200    Wild,201    None,202    Some {203        // The pattern contained in the `Some` tuple.204        pattern: &'a Pat<'a>,205        // The number of references before the `Some` tuple.206        // e.g. `&&Some(_)` has a ref count of 2.207        ref_count: usize,208    },209}210211pub(super) struct SomeExpr<'tcx> {212    pub expr: &'tcx Expr<'tcx>,213    pub needs_unsafe_block: bool,214    pub needs_negated: bool, // for `manual_filter` lint215}216217impl<'tcx> SomeExpr<'tcx> {218    pub fn new_no_negated(expr: &'tcx Expr<'tcx>, needs_unsafe_block: bool) -> Self {219        Self {220            expr,221            needs_unsafe_block,222            needs_negated: false,223        }224    }225226    pub fn to_snippet_with_context(227        &self,228        cx: &LateContext<'tcx>,229        ctxt: SyntaxContext,230        app: &mut Applicability,231    ) -> Sugg<'tcx> {232        let sugg = Sugg::hir_with_context(cx, self.expr, ctxt, "..", app);233        if self.needs_negated { !sugg } else { sugg }234    }235}236237// Try to parse into a recognized `Option` pattern.238// i.e. `_`, `None`, `Some(..)`, or a reference to any of those.239pub(super) fn try_parse_pattern<'tcx>(240    cx: &LateContext<'tcx>,241    pat: &'tcx Pat<'_>,242    ctxt: SyntaxContext,243) -> Option<OptionPat<'tcx>> {244    fn f<'tcx>(245        cx: &LateContext<'tcx>,246        pat: &'tcx Pat<'_>,247        ref_count: usize,248        ctxt: SyntaxContext,249    ) -> Option<OptionPat<'tcx>> {250        match pat.kind {251            PatKind::Wild => Some(OptionPat::Wild),252            PatKind::Ref(pat, _, _) => f(cx, pat, ref_count + 1, ctxt),253            _ if is_none_pattern(cx, pat) => Some(OptionPat::None),254            _ if let Some([pattern]) = as_some_pattern(cx, pat)255                && pat.span.ctxt() == ctxt =>256            {257                Some(OptionPat::Some { pattern, ref_count })258            },259            _ => None,260        }261    }262    f(cx, pat, 0, ctxt)263}264265/// Checks for the `None` value, possibly in a block.266fn is_none_arm_body(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {267    is_none_expr(cx, peel_blocks(expr))268}

Code quality findings 5

Critical: Use of 'unsafe' keyword bypasses Rust's safety guarantees. Requires careful auditing, clear justification (FFI, specific optimizations), and minimal scope.
error safety unsafe-block
format!("unsafe {}", closure_expr_snip.blockify())
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
let e = peel_hir_expr_while(scrutinee, |e| match e.kind {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match captures.get(l) {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match expr.kind {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match pat.kind {

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.