|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::source::snippet; |
| 3 | +use clippy_utils::ty::is_type_diagnostic_item; |
| 4 | +use clippy_utils::{is_res_lang_ctor, path_res, peel_blocks}; |
| 5 | +use rustc_errors::Applicability; |
| 6 | +use rustc_hir as hir; |
| 7 | +use rustc_hir::LangItem::{OptionNone, OptionSome}; |
| 8 | +use rustc_lint::LateContext; |
| 9 | +use rustc_span::symbol::sym; |
| 10 | + |
| 11 | +use super::RESULT_MAP_OR_INTO_OPTION; |
| 12 | + |
| 13 | +/// lint use of `_.map_or_else(|_| None, Some)` for `Result`s |
| 14 | +pub(super) fn check<'tcx>( |
| 15 | + cx: &LateContext<'tcx>, |
| 16 | + expr: &'tcx hir::Expr<'_>, |
| 17 | + recv: &'tcx hir::Expr<'_>, |
| 18 | + def_arg: &'tcx hir::Expr<'_>, |
| 19 | + map_arg: &'tcx hir::Expr<'_>, |
| 20 | +) { |
| 21 | + let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Result); |
| 22 | + |
| 23 | + if !is_result { |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + let f_arg_is_some = is_res_lang_ctor(cx, path_res(cx, map_arg), OptionSome); |
| 28 | + |
| 29 | + if f_arg_is_some |
| 30 | + && let hir::ExprKind::Closure(&hir::Closure { body, .. }) = def_arg.kind |
| 31 | + && let body = cx.tcx.hir().body(body) |
| 32 | + && is_res_lang_ctor(cx, path_res(cx, peel_blocks(body.value)), OptionNone) |
| 33 | + { |
| 34 | + let msg = "called `map_or_else(|_| None, Some)` on a `Result` value"; |
| 35 | + let self_snippet = snippet(cx, recv.span, ".."); |
| 36 | + span_lint_and_sugg( |
| 37 | + cx, |
| 38 | + RESULT_MAP_OR_INTO_OPTION, |
| 39 | + expr.span, |
| 40 | + msg, |
| 41 | + "try using `ok` instead", |
| 42 | + format!("{self_snippet}.ok()"), |
| 43 | + Applicability::MachineApplicable, |
| 44 | + ); |
| 45 | + } |
| 46 | +} |
0 commit comments