forked from rust-lang/rust-clippy
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create new lint
option_map_or_err_ok
- Loading branch information
1 parent
96eab06
commit b86903d
Showing
3 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
use clippy_utils::diagnostics::span_lint_and_sugg; | ||
use clippy_utils::source::snippet; | ||
use clippy_utils::ty::is_type_diagnostic_item; | ||
use clippy_utils::{is_res_lang_ctor, path_res}; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::LangItem::{ResultErr, ResultOk}; | ||
use rustc_hir::{Expr, ExprKind}; | ||
use rustc_lint::LateContext; | ||
use rustc_span::symbol::sym; | ||
|
||
use super::OPTION_MAP_OR_ERR_OK; | ||
|
||
pub(super) fn check<'tcx>( | ||
cx: &LateContext<'tcx>, | ||
expr: &'tcx Expr<'tcx>, | ||
recv: &'tcx Expr<'_>, | ||
or_expr: &'tcx Expr<'_>, | ||
map_expr: &'tcx Expr<'_>, | ||
) { | ||
let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Option); | ||
|
||
if !is_option { | ||
return; | ||
} | ||
|
||
let map_arg_is_ok = is_res_lang_ctor(cx, path_res(cx, map_expr), ResultOk); | ||
|
||
if map_arg_is_ok | ||
&& let ExprKind::Call(call, &[arg]) = or_expr.kind | ||
&& is_res_lang_ctor(cx, path_res(cx, call), ResultErr) | ||
{ | ||
let msg = "called `map_or(Err(_), Ok)` on an `Option` value"; | ||
let self_snippet = snippet(cx, recv.span, ".."); | ||
let err_snippet = snippet(cx, arg.span, ".."); | ||
span_lint_and_sugg( | ||
cx, | ||
OPTION_MAP_OR_ERR_OK, | ||
expr.span, | ||
msg, | ||
"try using `ok_or` instead", | ||
format!("{self_snippet}.ok_or({err_snippet})"), | ||
Applicability::MachineApplicable, | ||
); | ||
} | ||
} |