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