]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/option_if_let_else.rs
Auto merge of #80290 - RalfJung:less-intrinsic-write, r=lcnr
[rust.git] / src / tools / clippy / clippy_lints / src / option_if_let_else.rs
1 use crate::utils;
2 use crate::utils::eager_or_lazy;
3 use crate::utils::sugg::Sugg;
4 use crate::utils::{is_type_diagnostic_item, paths, span_lint_and_sugg};
5 use if_chain::if_chain;
6
7 use rustc_errors::Applicability;
8 use rustc_hir::{Arm, BindingAnnotation, Block, Expr, ExprKind, MatchSource, Mutability, PatKind, UnOp};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::sym;
12
13 declare_clippy_lint! {
14     /// **What it does:**
15     /// Lints usage of `if let Some(v) = ... { y } else { x }` which is more
16     /// idiomatically done with `Option::map_or` (if the else bit is a pure
17     /// expression) or `Option::map_or_else` (if the else bit is an impure
18     /// expression).
19     ///
20     /// **Why is this bad?**
21     /// Using the dedicated functions of the Option type is clearer and
22     /// more concise than an `if let` expression.
23     ///
24     /// **Known problems:**
25     /// This lint uses a deliberately conservative metric for checking
26     /// if the inside of either body contains breaks or continues which will
27     /// cause it to not suggest a fix if either block contains a loop with
28     /// continues or breaks contained within the loop.
29     ///
30     /// **Example:**
31     ///
32     /// ```rust
33     /// # let optional: Option<u32> = Some(0);
34     /// # fn do_complicated_function() -> u32 { 5 };
35     /// let _ = if let Some(foo) = optional {
36     ///     foo
37     /// } else {
38     ///     5
39     /// };
40     /// let _ = if let Some(foo) = optional {
41     ///     foo
42     /// } else {
43     ///     let y = do_complicated_function();
44     ///     y*y
45     /// };
46     /// ```
47     ///
48     /// should be
49     ///
50     /// ```rust
51     /// # let optional: Option<u32> = Some(0);
52     /// # fn do_complicated_function() -> u32 { 5 };
53     /// let _ = optional.map_or(5, |foo| foo);
54     /// let _ = optional.map_or_else(||{
55     ///     let y = do_complicated_function();
56     ///     y*y
57     /// }, |foo| foo);
58     /// ```
59     pub OPTION_IF_LET_ELSE,
60     pedantic,
61     "reimplementation of Option::map_or"
62 }
63
64 declare_lint_pass!(OptionIfLetElse => [OPTION_IF_LET_ELSE]);
65
66 /// Returns true iff the given expression is the result of calling `Result::ok`
67 fn is_result_ok(cx: &LateContext<'_>, expr: &'_ Expr<'_>) -> bool {
68     if let ExprKind::MethodCall(ref path, _, &[ref receiver], _) = &expr.kind {
69         path.ident.name.to_ident_string() == "ok"
70             && is_type_diagnostic_item(cx, &cx.typeck_results().expr_ty(&receiver), sym::result_type)
71     } else {
72         false
73     }
74 }
75
76 /// A struct containing information about occurrences of the
77 /// `if let Some(..) = .. else` construct that this lint detects.
78 struct OptionIfLetElseOccurence {
79     option: String,
80     method_sugg: String,
81     some_expr: String,
82     none_expr: String,
83     wrap_braces: bool,
84 }
85
86 /// Extracts the body of a given arm. If the arm contains only an expression,
87 /// then it returns the expression. Otherwise, it returns the entire block
88 fn extract_body_from_arm<'a>(arm: &'a Arm<'a>) -> Option<&'a Expr<'a>> {
89     if let ExprKind::Block(
90         Block {
91             stmts: statements,
92             expr: Some(expr),
93             ..
94         },
95         _,
96     ) = &arm.body.kind
97     {
98         if let [] = statements {
99             Some(&expr)
100         } else {
101             Some(&arm.body)
102         }
103     } else {
104         None
105     }
106 }
107
108 /// If this is the else body of an if/else expression, then we need to wrap
109 /// it in curly braces. Otherwise, we don't.
110 fn should_wrap_in_braces(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
111     utils::get_enclosing_block(cx, expr.hir_id).map_or(false, |parent| {
112         let mut should_wrap = false;
113         
114         if let Some(Expr {
115             kind:
116                 ExprKind::Match(
117                     _,
118                     arms,
119                     MatchSource::IfLetDesugar {
120                         contains_else_clause: true,
121                     },
122                 ),
123             ..
124         }) = parent.expr
125         {
126             should_wrap = expr.hir_id == arms[1].body.hir_id;
127         } else if let Some(Expr { kind: ExprKind::If(_, _, Some(else_clause)), .. }) = parent.expr {
128             should_wrap = expr.hir_id == else_clause.hir_id;
129         }
130
131         should_wrap
132     })
133 }
134
135 fn format_option_in_sugg(cx: &LateContext<'_>, cond_expr: &Expr<'_>, as_ref: bool, as_mut: bool) -> String {
136     format!(
137         "{}{}",
138         Sugg::hir(cx, cond_expr, "..").maybe_par(),
139         if as_mut {
140             ".as_mut()"
141         } else if as_ref {
142             ".as_ref()"
143         } else {
144             ""
145         }
146     )
147 }
148
149 /// If this expression is the option if let/else construct we're detecting, then
150 /// this function returns an `OptionIfLetElseOccurence` struct with details if
151 /// this construct is found, or None if this construct is not found.
152 fn detect_option_if_let_else<'tcx>(
153     cx: &'_ LateContext<'tcx>,
154     expr: &'_ Expr<'tcx>,
155 ) -> Option<OptionIfLetElseOccurence> {
156     if_chain! {
157         if !utils::in_macro(expr.span); // Don't lint macros, because it behaves weirdly
158         if let ExprKind::Match(cond_expr, arms, MatchSource::IfLetDesugar{contains_else_clause: true}) = &expr.kind;
159         if arms.len() == 2;
160         if !is_result_ok(cx, cond_expr); // Don't lint on Result::ok because a different lint does it already
161         if let PatKind::TupleStruct(struct_qpath, &[inner_pat], _) = &arms[0].pat.kind;
162         if utils::match_qpath(struct_qpath, &paths::OPTION_SOME);
163         if let PatKind::Binding(bind_annotation, _, id, _) = &inner_pat.kind;
164         if !utils::usage::contains_return_break_continue_macro(arms[0].body);
165         if !utils::usage::contains_return_break_continue_macro(arms[1].body);
166         then {
167             let capture_mut = if bind_annotation == &BindingAnnotation::Mutable { "mut " } else { "" };
168             let some_body = extract_body_from_arm(&arms[0])?;
169             let none_body = extract_body_from_arm(&arms[1])?;
170             let method_sugg = if eager_or_lazy::is_eagerness_candidate(cx, none_body) { "map_or" } else { "map_or_else" };
171             let capture_name = id.name.to_ident_string();
172             let wrap_braces = should_wrap_in_braces(cx, expr);
173             let (as_ref, as_mut) = match &cond_expr.kind {
174                 ExprKind::AddrOf(_, Mutability::Not, _) => (true, false),
175                 ExprKind::AddrOf(_, Mutability::Mut, _) => (false, true),
176                 _ => (bind_annotation == &BindingAnnotation::Ref, bind_annotation == &BindingAnnotation::RefMut),
177             };
178             let cond_expr = match &cond_expr.kind {
179                 // Pointer dereferencing happens automatically, so we can omit it in the suggestion
180                 ExprKind::Unary(UnOp::UnDeref, expr) | ExprKind::AddrOf(_, _, expr) => expr,
181                 _ => cond_expr,
182             };
183             Some(OptionIfLetElseOccurence {
184                 option: format_option_in_sugg(cx, cond_expr, as_ref, as_mut),
185                 method_sugg: method_sugg.to_string(),
186                 some_expr: format!("|{}{}| {}", capture_mut, capture_name, Sugg::hir(cx, some_body, "..")),
187                 none_expr: format!("{}{}", if method_sugg == "map_or" { "" } else { "|| " }, Sugg::hir(cx, none_body, "..")),
188                 wrap_braces,
189             })
190         } else {
191             None
192         }
193     }
194 }
195
196 impl<'tcx> LateLintPass<'tcx> for OptionIfLetElse {
197     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) {
198         if let Some(detection) = detect_option_if_let_else(cx, expr) {
199             span_lint_and_sugg(
200                 cx,
201                 OPTION_IF_LET_ELSE,
202                 expr.span,
203                 format!("use Option::{} instead of an if let/else", detection.method_sugg).as_str(),
204                 "try",
205                 format!(
206                     "{}{}.{}({}, {}){}",
207                     if detection.wrap_braces { "{ " } else { "" },
208                     detection.option,
209                     detection.method_sugg,
210                     detection.none_expr,
211                     detection.some_expr,
212                     if detection.wrap_braces { " }" } else { "" },
213                 ),
214                 Applicability::MaybeIncorrect,
215             );
216         }
217     }
218 }