]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/option_if_let_else.rs
Auto merge of #9487 - kraktus:question_mark, r=Jarcho
[rust.git] / clippy_lints / src / option_if_let_else.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::sugg::Sugg;
3 use clippy_utils::{
4     can_move_expr_to_closure, eager_or_lazy, higher, in_constant, is_else_clause, is_lang_ctor, peel_blocks,
5     peel_hir_expr_while, CaptureKind,
6 };
7 use if_chain::if_chain;
8 use rustc_errors::Applicability;
9 use rustc_hir::LangItem::{OptionNone, OptionSome, ResultErr, ResultOk};
10 use rustc_hir::{
11     def::Res, Arm, BindingAnnotation, Expr, ExprKind, MatchSource, Mutability, Pat, PatKind, Path, QPath, UnOp,
12 };
13 use rustc_lint::{LateContext, LateLintPass};
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15
16 declare_clippy_lint! {
17     /// ### What it does
18     /// Lints usage of `if let Some(v) = ... { y } else { x }` and
19     /// `match .. { Some(v) => y, None/_ => x }` which are more
20     /// idiomatically done with `Option::map_or` (if the else bit is a pure
21     /// expression) or `Option::map_or_else` (if the else bit is an impure
22     /// expression).
23     ///
24     /// ### Why is this bad?
25     /// Using the dedicated functions of the `Option` type is clearer and
26     /// more concise than an `if let` expression.
27     ///
28     /// ### Known problems
29     /// This lint uses a deliberately conservative metric for checking
30     /// if the inside of either body contains breaks or continues which will
31     /// cause it to not suggest a fix if either block contains a loop with
32     /// continues or breaks contained within the loop.
33     ///
34     /// ### Example
35     /// ```rust
36     /// # let optional: Option<u32> = Some(0);
37     /// # fn do_complicated_function() -> u32 { 5 };
38     /// let _ = if let Some(foo) = optional {
39     ///     foo
40     /// } else {
41     ///     5
42     /// };
43     /// let _ = match optional {
44     ///     Some(val) => val + 1,
45     ///     None => 5
46     /// };
47     /// let _ = if let Some(foo) = optional {
48     ///     foo
49     /// } else {
50     ///     let y = do_complicated_function();
51     ///     y*y
52     /// };
53     /// ```
54     ///
55     /// should be
56     ///
57     /// ```rust
58     /// # let optional: Option<u32> = Some(0);
59     /// # fn do_complicated_function() -> u32 { 5 };
60     /// let _ = optional.map_or(5, |foo| foo);
61     /// let _ = optional.map_or(5, |val| val + 1);
62     /// let _ = optional.map_or_else(||{
63     ///     let y = do_complicated_function();
64     ///     y*y
65     /// }, |foo| foo);
66     /// ```
67     // FIXME: Before moving this lint out of nursery, the lint name needs to be updated. It now also
68     // covers matches and `Result`.
69     #[clippy::version = "1.47.0"]
70     pub OPTION_IF_LET_ELSE,
71     nursery,
72     "reimplementation of Option::map_or"
73 }
74
75 declare_lint_pass!(OptionIfLetElse => [OPTION_IF_LET_ELSE]);
76
77 /// A struct containing information about occurrences of construct that this lint detects
78 ///
79 /// Such as:
80 ///
81 /// ```ignore
82 /// if let Some(..) = {..} else {..}
83 /// ```
84 /// or
85 /// ```ignore
86 /// match x {
87 ///     Some(..) => {..},
88 ///     None/_ => {..}
89 /// }
90 /// ```
91 struct OptionOccurence {
92     option: String,
93     method_sugg: String,
94     some_expr: String,
95     none_expr: String,
96 }
97
98 fn format_option_in_sugg(cx: &LateContext<'_>, cond_expr: &Expr<'_>, as_ref: bool, as_mut: bool) -> String {
99     format!(
100         "{}{}",
101         Sugg::hir_with_macro_callsite(cx, cond_expr, "..").maybe_par(),
102         if as_mut {
103             ".as_mut()"
104         } else if as_ref {
105             ".as_ref()"
106         } else {
107             ""
108         }
109     )
110 }
111
112 fn try_get_option_occurence<'tcx>(
113     cx: &LateContext<'tcx>,
114     pat: &Pat<'tcx>,
115     expr: &Expr<'_>,
116     if_then: &'tcx Expr<'_>,
117     if_else: &'tcx Expr<'_>,
118 ) -> Option<OptionOccurence> {
119     let cond_expr = match expr.kind {
120         ExprKind::Unary(UnOp::Deref, inner_expr) | ExprKind::AddrOf(_, _, inner_expr) => inner_expr,
121         _ => expr,
122     };
123     let inner_pat = try_get_inner_pat(cx, pat)?;
124     if_chain! {
125         if let PatKind::Binding(bind_annotation, _, id, None) = inner_pat.kind;
126         if let Some(some_captures) = can_move_expr_to_closure(cx, if_then);
127         if let Some(none_captures) = can_move_expr_to_closure(cx, if_else);
128         if some_captures
129             .iter()
130             .filter_map(|(id, &c)| none_captures.get(id).map(|&c2| (c, c2)))
131             .all(|(x, y)| x.is_imm_ref() && y.is_imm_ref());
132         then {
133             let capture_mut = if bind_annotation == BindingAnnotation::MUT { "mut " } else { "" };
134             let some_body = peel_blocks(if_then);
135             let none_body = peel_blocks(if_else);
136             let method_sugg = if eager_or_lazy::switch_to_eager_eval(cx, none_body) { "map_or" } else { "map_or_else" };
137             let capture_name = id.name.to_ident_string();
138             let (as_ref, as_mut) = match &expr.kind {
139                 ExprKind::AddrOf(_, Mutability::Not, _) => (true, false),
140                 ExprKind::AddrOf(_, Mutability::Mut, _) => (false, true),
141                 _ => (bind_annotation == BindingAnnotation::REF, bind_annotation == BindingAnnotation::REF_MUT),
142             };
143
144             // Check if captures the closure will need conflict with borrows made in the scrutinee.
145             // TODO: check all the references made in the scrutinee expression. This will require interacting
146             // with the borrow checker. Currently only `<local>[.<field>]*` is checked for.
147             if as_ref || as_mut {
148                 let e = peel_hir_expr_while(cond_expr, |e| match e.kind {
149                     ExprKind::Field(e, _) | ExprKind::AddrOf(_, _, e) => Some(e),
150                     _ => None,
151                 });
152                 if let ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(local_id), .. })) = e.kind {
153                     match some_captures.get(local_id)
154                         .or_else(|| (method_sugg == "map_or_else").then_some(()).and_then(|_| none_captures.get(local_id)))
155                     {
156                         Some(CaptureKind::Value | CaptureKind::Ref(Mutability::Mut)) => return None,
157                         Some(CaptureKind::Ref(Mutability::Not)) if as_mut => return None,
158                         Some(CaptureKind::Ref(Mutability::Not)) | None => (),
159                     }
160                 }
161             }
162
163             return Some(OptionOccurence {
164                 option: format_option_in_sugg(cx, cond_expr, as_ref, as_mut),
165                 method_sugg: method_sugg.to_string(),
166                 some_expr: format!("|{capture_mut}{capture_name}| {}", Sugg::hir_with_macro_callsite(cx, some_body, "..")),
167                 none_expr: format!("{}{}", if method_sugg == "map_or" { "" } else { "|| " }, Sugg::hir_with_macro_callsite(cx, none_body, "..")),
168             });
169         }
170     }
171
172     None
173 }
174
175 fn try_get_inner_pat<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'tcx>) -> Option<&'tcx Pat<'tcx>> {
176     if let PatKind::TupleStruct(ref qpath, [inner_pat], ..) = pat.kind {
177         if is_lang_ctor(cx, qpath, OptionSome) || is_lang_ctor(cx, qpath, ResultOk) {
178             return Some(inner_pat);
179         }
180     }
181     None
182 }
183
184 /// If this expression is the option if let/else construct we're detecting, then
185 /// this function returns an `OptionOccurence` struct with details if
186 /// this construct is found, or None if this construct is not found.
187 fn detect_option_if_let_else<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) -> Option<OptionOccurence> {
188     if let Some(higher::IfLet {
189         let_pat,
190         let_expr,
191         if_then,
192         if_else: Some(if_else),
193     }) = higher::IfLet::hir(cx, expr)
194     {
195         if !is_else_clause(cx.tcx, expr) {
196             return try_get_option_occurence(cx, let_pat, let_expr, if_then, if_else);
197         }
198     }
199     None
200 }
201
202 fn detect_option_match<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) -> Option<OptionOccurence> {
203     if let ExprKind::Match(ex, arms, MatchSource::Normal) = expr.kind {
204         if let Some((let_pat, if_then, if_else)) = try_convert_match(cx, arms) {
205             return try_get_option_occurence(cx, let_pat, ex, if_then, if_else);
206         }
207     }
208     None
209 }
210
211 fn try_convert_match<'tcx>(
212     cx: &LateContext<'tcx>,
213     arms: &[Arm<'tcx>],
214 ) -> Option<(&'tcx Pat<'tcx>, &'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
215     if arms.len() == 2 {
216         return if is_none_or_err_arm(cx, &arms[1]) {
217             Some((arms[0].pat, arms[0].body, arms[1].body))
218         } else if is_none_or_err_arm(cx, &arms[0]) {
219             Some((arms[1].pat, arms[1].body, arms[0].body))
220         } else {
221             None
222         };
223     }
224     None
225 }
226
227 fn is_none_or_err_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
228     match arm.pat.kind {
229         PatKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
230         PatKind::TupleStruct(ref qpath, [first_pat], _) => {
231             is_lang_ctor(cx, qpath, ResultErr) && matches!(first_pat.kind, PatKind::Wild)
232         },
233         PatKind::Wild => true,
234         _ => false,
235     }
236 }
237
238 impl<'tcx> LateLintPass<'tcx> for OptionIfLetElse {
239     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) {
240         // Don't lint macros and constants
241         if expr.span.from_expansion() || in_constant(cx, expr.hir_id) {
242             return;
243         }
244
245         let detection = detect_option_if_let_else(cx, expr).or_else(|| detect_option_match(cx, expr));
246         if let Some(det) = detection {
247             span_lint_and_sugg(
248                 cx,
249                 OPTION_IF_LET_ELSE,
250                 expr.span,
251                 format!("use Option::{} instead of an if let/else", det.method_sugg).as_str(),
252                 "try",
253                 format!(
254                     "{}.{}({}, {})",
255                     det.option, det.method_sugg, det.none_expr, det.some_expr
256                 ),
257                 Applicability::MaybeIncorrect,
258             );
259         }
260     }
261 }