]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/option_if_let_else.rs
Auto merge of #6278 - ThibsG:DerefAddrOf, r=llogiq
[rust.git] / 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         if let Some(Expr {
113             kind:
114                 ExprKind::Match(
115                     _,
116                     arms,
117                     MatchSource::IfDesugar {
118                         contains_else_clause: true,
119                     }
120                     | MatchSource::IfLetDesugar {
121                         contains_else_clause: true,
122                     },
123                 ),
124             ..
125         }) = parent.expr
126         {
127             expr.hir_id == arms[1].body.hir_id
128         } else {
129             false
130         }
131     })
132 }
133
134 fn format_option_in_sugg(cx: &LateContext<'_>, cond_expr: &Expr<'_>, as_ref: bool, as_mut: bool) -> String {
135     format!(
136         "{}{}",
137         Sugg::hir(cx, cond_expr, "..").maybe_par(),
138         if as_mut {
139             ".as_mut()"
140         } else if as_ref {
141             ".as_ref()"
142         } else {
143             ""
144         }
145     )
146 }
147
148 /// If this expression is the option if let/else construct we're detecting, then
149 /// this function returns an `OptionIfLetElseOccurence` struct with details if
150 /// this construct is found, or None if this construct is not found.
151 fn detect_option_if_let_else<'tcx>(
152     cx: &'_ LateContext<'tcx>,
153     expr: &'_ Expr<'tcx>,
154 ) -> Option<OptionIfLetElseOccurence> {
155     if_chain! {
156         if !utils::in_macro(expr.span); // Don't lint macros, because it behaves weirdly
157         if let ExprKind::Match(cond_expr, arms, MatchSource::IfLetDesugar{contains_else_clause: true}) = &expr.kind;
158         if arms.len() == 2;
159         if !is_result_ok(cx, cond_expr); // Don't lint on Result::ok because a different lint does it already
160         if let PatKind::TupleStruct(struct_qpath, &[inner_pat], _) = &arms[0].pat.kind;
161         if utils::match_qpath(struct_qpath, &paths::OPTION_SOME);
162         if let PatKind::Binding(bind_annotation, _, id, _) = &inner_pat.kind;
163         if !utils::usage::contains_return_break_continue_macro(arms[0].body);
164         if !utils::usage::contains_return_break_continue_macro(arms[1].body);
165         then {
166             let capture_mut = if bind_annotation == &BindingAnnotation::Mutable { "mut " } else { "" };
167             let some_body = extract_body_from_arm(&arms[0])?;
168             let none_body = extract_body_from_arm(&arms[1])?;
169             let method_sugg = if eager_or_lazy::is_eagerness_candidate(cx, none_body) { "map_or" } else { "map_or_else" };
170             let capture_name = id.name.to_ident_string();
171             let wrap_braces = should_wrap_in_braces(cx, expr);
172             let (as_ref, as_mut) = match &cond_expr.kind {
173                 ExprKind::AddrOf(_, Mutability::Not, _) => (true, false),
174                 ExprKind::AddrOf(_, Mutability::Mut, _) => (false, true),
175                 _ => (bind_annotation == &BindingAnnotation::Ref, bind_annotation == &BindingAnnotation::RefMut),
176             };
177             let cond_expr = match &cond_expr.kind {
178                 // Pointer dereferencing happens automatically, so we can omit it in the suggestion
179                 ExprKind::Unary(UnOp::UnDeref, expr) | ExprKind::AddrOf(_, _, expr) => expr,
180                 _ => cond_expr,
181             };
182             Some(OptionIfLetElseOccurence {
183                 option: format_option_in_sugg(cx, cond_expr, as_ref, as_mut),
184                 method_sugg: method_sugg.to_string(),
185                 some_expr: format!("|{}{}| {}", capture_mut, capture_name, Sugg::hir(cx, some_body, "..")),
186                 none_expr: format!("{}{}", if method_sugg == "map_or" { "" } else { "|| " }, Sugg::hir(cx, none_body, "..")),
187                 wrap_braces,
188             })
189         } else {
190             None
191         }
192     }
193 }
194
195 impl<'tcx> LateLintPass<'tcx> for OptionIfLetElse {
196     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) {
197         if let Some(detection) = detect_option_if_let_else(cx, expr) {
198             span_lint_and_sugg(
199                 cx,
200                 OPTION_IF_LET_ELSE,
201                 expr.span,
202                 format!("use Option::{} instead of an if let/else", detection.method_sugg).as_str(),
203                 "try",
204                 format!(
205                     "{}{}.{}({}, {}){}",
206                     if detection.wrap_braces { "{ " } else { "" },
207                     detection.option,
208                     detection.method_sugg,
209                     detection.none_expr,
210                     detection.some_expr,
211                     if detection.wrap_braces { " }" } else { "" },
212                 ),
213                 Applicability::MaybeIncorrect,
214             );
215         }
216     }
217 }