1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::{indent_of, reindent_multiline, snippet_opt};
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use clippy_utils::{is_lang_ctor, path_to_local_id};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::LangItem::{ResultErr, ResultOk};
8 use rustc_hir::{Expr, ExprKind, PatKind};
9 use rustc_lint::LintContext;
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::lint::in_external_macro;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::symbol::sym;
15 declare_clippy_lint! {
18 /// Finds patterns that reimplement `Option::ok_or`.
20 /// ### Why is this bad?
22 /// Concise code helps focusing on behavior instead of boilerplate.
26 /// let foo: Option<i32> = None;
27 /// foo.map_or(Err("error"), |v| Ok(v));
32 /// let foo: Option<i32> = None;
33 /// foo.ok_or("error");
35 #[clippy::version = "1.49.0"]
38 "finds patterns that can be encoded more concisely with `Option::ok_or`"
41 declare_lint_pass!(ManualOkOr => [MANUAL_OK_OR]);
43 impl<'tcx> LateLintPass<'tcx> for ManualOkOr {
44 fn check_expr(&mut self, cx: &LateContext<'tcx>, scrutinee: &'tcx Expr<'tcx>) {
45 if in_external_macro(cx.sess(), scrutinee.span) {
50 if let ExprKind::MethodCall(method_segment, args, _) = scrutinee.kind;
51 if method_segment.ident.name == sym!(map_or);
53 let method_receiver = &args[0];
54 let ty = cx.typeck_results().expr_ty(method_receiver);
55 if is_type_diagnostic_item(cx, ty, sym::Option);
56 let or_expr = &args[1];
57 if is_ok_wrapping(cx, &args[2]);
58 if let ExprKind::Call(Expr { kind: ExprKind::Path(err_path), .. }, &[ref err_arg]) = or_expr.kind;
59 if is_lang_ctor(cx, err_path, ResultErr);
60 if let Some(method_receiver_snippet) = snippet_opt(cx, method_receiver.span);
61 if let Some(err_arg_snippet) = snippet_opt(cx, err_arg.span);
62 if let Some(indent) = indent_of(cx, scrutinee.span);
64 let reindented_err_arg_snippet =
65 reindent_multiline(err_arg_snippet.into(), true, Some(indent + 4));
70 "this pattern reimplements `Option::ok_or`",
74 method_receiver_snippet,
75 reindented_err_arg_snippet
77 Applicability::MachineApplicable,
84 fn is_ok_wrapping(cx: &LateContext<'_>, map_expr: &Expr<'_>) -> bool {
85 if let ExprKind::Path(ref qpath) = map_expr.kind {
86 if is_lang_ctor(cx, qpath, ResultOk) {
91 if let ExprKind::Closure(_, _, body_id, ..) = map_expr.kind;
92 let body = cx.tcx.hir().body(body_id);
93 if let PatKind::Binding(_, param_id, ..) = body.params[0].pat.kind;
94 if let ExprKind::Call(Expr { kind: ExprKind::Path(ok_path), .. }, &[ref ok_arg]) = body.value.kind;
95 if is_lang_ctor(cx, ok_path, ResultOk);
96 then { path_to_local_id(ok_arg, param_id) } else { false }