|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::sugg::Sugg; |
| 3 | +use clippy_utils::ty::option_arg_ty; |
| 4 | +use clippy_utils::{is_res_lang_ctor, path_res, peel_blocks, span_contains_comment}; |
| 5 | +use rustc_ast::BindingMode; |
| 6 | +use rustc_errors::Applicability; |
| 7 | +use rustc_hir::LangItem::{OptionNone, OptionSome, ResultErr}; |
| 8 | +use rustc_hir::def::{DefKind, Res}; |
| 9 | +use rustc_hir::{Arm, Expr, ExprKind, Pat, PatKind, Path, QPath}; |
| 10 | +use rustc_lint::{LateContext, LintContext}; |
| 11 | +use rustc_middle::ty::Ty; |
| 12 | +use rustc_span::symbol::Ident; |
| 13 | + |
| 14 | +use super::MANUAL_OK_ERR; |
| 15 | + |
| 16 | +pub(crate) fn check_if_let( |
| 17 | + cx: &LateContext<'_>, |
| 18 | + expr: &Expr<'_>, |
| 19 | + let_pat: &Pat<'_>, |
| 20 | + let_expr: &Expr<'_>, |
| 21 | + if_then: &Expr<'_>, |
| 22 | + else_expr: &Expr<'_>, |
| 23 | +) { |
| 24 | + if let Some(inner_expr_ty) = option_arg_ty(cx, cx.typeck_results().expr_ty(expr)) |
| 25 | + && let Some((is_ok, ident)) = is_ok_or_err(cx, let_pat) |
| 26 | + && is_some_ident(cx, if_then, ident, inner_expr_ty) |
| 27 | + && is_none(cx, else_expr) |
| 28 | + { |
| 29 | + apply_lint(cx, expr, let_expr, is_ok); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +pub(crate) fn check_match(cx: &LateContext<'_>, expr: &Expr<'_>, scrutinee: &Expr<'_>, arms: &[Arm<'_>]) { |
| 34 | + if let Some(inner_expr_ty) = option_arg_ty(cx, cx.typeck_results().expr_ty(expr)) |
| 35 | + && arms.len() == 2 |
| 36 | + && arms.iter().all(|arm| arm.guard.is_none()) |
| 37 | + && let Some((idx, is_ok)) = arms.iter().enumerate().find_map(|(arm_idx, arm)| { |
| 38 | + // Check if the arm is a `Ok(x) => x` or `Err(x) => x` alternative. |
| 39 | + // In this case, return its index and whether it uses `Ok` or `Err`. |
| 40 | + if let Some((is_ok, ident)) = is_ok_or_err(cx, arm.pat) |
| 41 | + && is_some_ident(cx, arm.body, ident, inner_expr_ty) |
| 42 | + { |
| 43 | + Some((arm_idx, is_ok)) |
| 44 | + } else { |
| 45 | + None |
| 46 | + } |
| 47 | + }) |
| 48 | + // Accept wildcard only as the second arm |
| 49 | + && is_variant_or_wildcard(cx, arms[1-idx].pat, idx == 0, is_ok) |
| 50 | + // Check that the body of the non `Ok`/`Err` arm is `None` |
| 51 | + && is_none(cx, arms[1 - idx].body) |
| 52 | + { |
| 53 | + apply_lint(cx, expr, scrutinee, is_ok); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +/// Check that `pat` applied to a `Result` only matches `Ok(_)`, `Err(_)`, not a subset or a |
| 58 | +/// superset of it. If `can_be_wild` is `true`, wildcards are also accepted. In the case of |
| 59 | +/// a non-wildcard, `must_match_err` indicates whether the `Err` or the `Ok` variant should be |
| 60 | +/// accepted. |
| 61 | +fn is_variant_or_wildcard(cx: &LateContext<'_>, pat: &Pat<'_>, can_be_wild: bool, must_match_err: bool) -> bool { |
| 62 | + match pat.kind { |
| 63 | + PatKind::Wild | PatKind::Path(..) | PatKind::Binding(_, _, _, None) if can_be_wild => true, |
| 64 | + PatKind::TupleStruct(qpath, ..) => { |
| 65 | + is_res_lang_ctor(cx, cx.qpath_res(&qpath, pat.hir_id), ResultErr) == must_match_err |
| 66 | + }, |
| 67 | + PatKind::Binding(_, _, _, Some(pat)) | PatKind::Ref(pat, _) => { |
| 68 | + is_variant_or_wildcard(cx, pat, can_be_wild, must_match_err) |
| 69 | + }, |
| 70 | + _ => false, |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +/// Return `Some((true, IDENT))` if `pat` contains `Ok(IDENT)`, `Some((false, IDENT))` if it |
| 75 | +/// contains `Err(IDENT)`, `None` otherwise. |
| 76 | +fn is_ok_or_err<'hir>(cx: &LateContext<'_>, pat: &Pat<'hir>) -> Option<(bool, &'hir Ident)> { |
| 77 | + if let PatKind::TupleStruct(qpath, [arg], _) = &pat.kind |
| 78 | + && let PatKind::Binding(BindingMode::NONE, _, ident, _) = &arg.kind |
| 79 | + && let res = cx.qpath_res(qpath, pat.hir_id) |
| 80 | + && let Res::Def(DefKind::Ctor(..), id) = res |
| 81 | + && let id @ Some(_) = cx.tcx.opt_parent(id) |
| 82 | + { |
| 83 | + let lang_items = cx.tcx.lang_items(); |
| 84 | + if id == lang_items.result_ok_variant() { |
| 85 | + return Some((true, ident)); |
| 86 | + } else if id == lang_items.result_err_variant() { |
| 87 | + return Some((false, ident)); |
| 88 | + } |
| 89 | + } |
| 90 | + None |
| 91 | +} |
| 92 | + |
| 93 | +/// Check if `expr` contains `Some(ident)`, possibly as a block |
| 94 | +fn is_some_ident<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, ident: &Ident, ty: Ty<'tcx>) -> bool { |
| 95 | + if let ExprKind::Call(body_callee, [body_arg]) = peel_blocks(expr).kind |
| 96 | + && is_res_lang_ctor(cx, path_res(cx, body_callee), OptionSome) |
| 97 | + && cx.typeck_results().expr_ty(body_arg) == ty |
| 98 | + && let ExprKind::Path(QPath::Resolved( |
| 99 | + _, |
| 100 | + Path { |
| 101 | + segments: [segment], .. |
| 102 | + }, |
| 103 | + )) = body_arg.kind |
| 104 | + { |
| 105 | + segment.ident.name == ident.name |
| 106 | + } else { |
| 107 | + false |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +/// Check if `expr` is `None`, possibly as a block |
| 112 | +fn is_none(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { |
| 113 | + is_res_lang_ctor(cx, path_res(cx, peel_blocks(expr)), OptionNone) |
| 114 | +} |
| 115 | + |
| 116 | +/// Suggest replacing `expr` by `scrutinee.METHOD()`, where `METHOD` is either `ok` or |
| 117 | +/// `err`, depending on `is_ok`. |
| 118 | +fn apply_lint(cx: &LateContext<'_>, expr: &Expr<'_>, scrutinee: &Expr<'_>, is_ok: bool) { |
| 119 | + let method = if is_ok { "ok" } else { "err" }; |
| 120 | + let mut app = if span_contains_comment(cx.sess().source_map(), expr.span) { |
| 121 | + Applicability::MaybeIncorrect |
| 122 | + } else { |
| 123 | + Applicability::MachineApplicable |
| 124 | + }; |
| 125 | + let scrut = Sugg::hir_with_applicability(cx, scrutinee, "..", &mut app).maybe_par(); |
| 126 | + span_lint_and_sugg( |
| 127 | + cx, |
| 128 | + MANUAL_OK_ERR, |
| 129 | + expr.span, |
| 130 | + format!("manual implementation of `{method}`"), |
| 131 | + "replace with", |
| 132 | + format!("{scrut}.{method}()"), |
| 133 | + app, |
| 134 | + ); |
| 135 | +} |
0 commit comments