2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::{def, Arm, Expr, ExprKind, PatKind, QPath};
5 use rustc_lint::LintContext;
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::lint::in_external_macro;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 declare_clippy_lint! {
12 /// Finds patterns that reimplement `Option::unwrap_or`.
14 /// **Why is this bad?**
15 /// Concise code helps focusing on behavior instead of boilerplate.
17 /// **Known problems:** None.
21 /// match int_option {
29 /// int_option.unwrap_or(1)
33 "finds patterns that can be encoded more concisely with `Option::unwrap_or(_else)`"
36 declare_lint_pass!(ManualUnwrapOr => [MANUAL_UNWRAP_OR]);
38 impl LateLintPass<'_> for ManualUnwrapOr {
39 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
40 if in_external_macro(cx.sess(), expr.span) {
43 lint_option_unwrap_or_case(cx, expr);
47 fn lint_option_unwrap_or_case<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
48 fn applicable_none_arm<'a>(arms: &'a [Arm<'a>]) -> Option<&'a Arm<'a>> {
51 if arms.iter().all(|arm| arm.guard.is_none());
52 if let Some((idx, none_arm)) = arms.iter().enumerate().find(|(_, arm)|
53 if let PatKind::Path(ref qpath) = arm.pat.kind {
54 utils::match_qpath(qpath, &utils::paths::OPTION_NONE)
59 let some_arm = &arms[1 - idx];
60 if let PatKind::TupleStruct(ref some_qpath, &[some_binding], _) = some_arm.pat.kind;
61 if utils::match_qpath(some_qpath, &utils::paths::OPTION_SOME);
62 if let PatKind::Binding(_, binding_hir_id, ..) = some_binding.kind;
63 if let ExprKind::Path(QPath::Resolved(_, body_path)) = some_arm.body.kind;
64 if let def::Res::Local(body_path_hir_id) = body_path.res;
65 if body_path_hir_id == binding_hir_id;
66 if !utils::usage::contains_return_break_continue_macro(none_arm.body);
77 if let ExprKind::Match(scrutinee, match_arms, _) = expr.kind;
78 let ty = cx.typeck_results().expr_ty(scrutinee);
79 if utils::is_type_diagnostic_item(cx, ty, sym!(option_type));
80 if let Some(none_arm) = applicable_none_arm(match_arms);
81 if let Some(scrutinee_snippet) = utils::snippet_opt(cx, scrutinee.span);
82 if let Some(none_body_snippet) = utils::snippet_opt(cx, none_arm.body.span);
83 if let Some(indent) = utils::indent_of(cx, expr.span);
85 let reindented_none_body =
86 utils::reindent_multiline(none_body_snippet.into(), true, Some(indent));
87 let eager_eval = utils::eager_or_lazy::is_eagerness_candidate(cx, none_arm.body);
88 let method = if eager_eval {
93 utils::span_lint_and_sugg(
95 MANUAL_UNWRAP_OR, expr.span,
96 &format!("this pattern reimplements `Option::{}`", &method),
102 if eager_eval { ""} else { "|| " },
105 Applicability::MachineApplicable,