]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/option_if_let_else.rs
f092f1297c1bbf71ccd0c2a589b54eba4ec2018c
[rust.git] / clippy_lints / src / option_if_let_else.rs
1 use crate::utils::sugg::Sugg;
2 use crate::utils::{match_type, paths, span_lint_and_sugg};
3 use if_chain::if_chain;
4
5 use rustc_errors::Applicability;
6 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
7 use rustc_hir::*;
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::hir::map::Map;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11
12 use std::marker::PhantomData;
13
14 declare_clippy_lint! {
15     /// **What it does:**
16     /// Lints usage of  `if let Some(v) = ... { y } else { x }` which is more
17     /// idiomatically done with `Option::map_or` (if the else bit is a simple
18     /// expression) or `Option::map_or_else` (if the else bit is a longer
19     /// block).
20     ///
21     /// **Why is this bad?**
22     /// Using the dedicated functions of the Option type is clearer and
23     /// more concise than an if let expression.
24     ///
25     /// **Known problems:**
26     /// This lint uses whether the block is just an expression or if it has
27     /// more statements to decide whether to use `Option::map_or` or
28     /// `Option::map_or_else`. If you have a single expression which calls
29     /// an expensive function, then it would be more efficient to use
30     /// `Option::map_or_else`, but this lint would suggest `Option::map_or`.
31     ///
32     /// Also, this lint uses a deliberately conservative metric for checking
33     /// if the inside of either body contains breaks or continues which will
34     /// cause it to not suggest a fix if either block contains a loop with
35     /// continues or breaks contained within the loop.
36     ///
37     /// **Example:**
38     ///
39     /// ```rust
40     /// # let optional: Option<u32> = Some(0);
41     /// let _ = if let Some(foo) = optional {
42     ///     foo
43     /// } else {
44     ///     5
45     /// };
46     /// let _ = if let Some(foo) = optional {
47     ///     foo
48     /// } else {
49     ///     let y = do_complicated_function();
50     ///     y*y
51     /// };
52     /// ```
53     ///
54     /// should be
55     ///
56     /// ```rust
57     /// # let optional: Option<u32> = Some(0);
58     /// let _ = optional.map_or(5, |foo| foo);
59     /// let _ = optional.map_or_else(||{
60     ///     let y = do_complicated_function;
61     ///     y*y
62     /// }, |foo| foo);
63     /// ```
64     pub OPTION_IF_LET_ELSE,
65     style,
66     "reimplementation of Option::map_or"
67 }
68
69 declare_lint_pass!(OptionIfLetElse => [OPTION_IF_LET_ELSE]);
70
71 /// Returns true iff the given expression is the result of calling Result::ok
72 fn is_result_ok(cx: &LateContext<'_, '_>, expr: &'_ Expr<'_>) -> bool {
73     if_chain! {
74         if let ExprKind::MethodCall(ref path, _, &[ref receiver]) = &expr.kind;
75         if path.ident.name.to_ident_string() == "ok";
76         if match_type(cx, &cx.tables.expr_ty(&receiver), &paths::RESULT);
77         then {
78             true
79         } else {
80             false
81         }
82     }
83 }
84
85 /// A struct containing information about occurences of the
86 /// `if let Some(..) = .. else` construct that this lint detects.
87 struct OptionIfLetElseOccurence {
88     option: String,
89     method_sugg: String,
90     some_expr: String,
91     none_expr: String,
92 }
93
94 struct ReturnBreakContinueVisitor<'tcx> {
95     seen_return_break_continue: bool,
96     phantom_data: PhantomData<&'tcx bool>,
97 }
98 impl<'tcx> ReturnBreakContinueVisitor<'tcx> {
99     fn new() -> ReturnBreakContinueVisitor<'tcx> {
100         ReturnBreakContinueVisitor {
101             seen_return_break_continue: false,
102             phantom_data: PhantomData,
103         }
104     }
105 }
106 impl<'tcx> Visitor<'tcx> for ReturnBreakContinueVisitor<'tcx> {
107     type Map = Map<'tcx>;
108     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
109         NestedVisitorMap::None
110     }
111
112     fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
113         if self.seen_return_break_continue {
114             // No need to look farther if we've already seen one of them
115             return;
116         }
117         match &ex.kind {
118             ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => {
119                 self.seen_return_break_continue = true;
120             },
121             // Something special could be done here to handle while or for loop
122             // desugaring, as this will detect a break if there's a while loop
123             // or a for loop inside the expression.
124             _ => {
125                 rustc_hir::intravisit::walk_expr(self, ex);
126             },
127         }
128     }
129 }
130
131 fn contains_return_break_continue<'tcx>(expression: &'tcx Expr<'tcx>) -> bool {
132     let mut recursive_visitor: ReturnBreakContinueVisitor<'tcx> = ReturnBreakContinueVisitor::new();
133     recursive_visitor.visit_expr(expression);
134     recursive_visitor.seen_return_break_continue
135 }
136
137 /// If this expression is the option if let/else construct we're detecting, then
138 /// this function returns an OptionIfLetElseOccurence struct with details if
139 /// this construct is found, or None if this construct is not found.
140 fn detect_option_if_let_else<'a>(cx: &LateContext<'_, 'a>, expr: &'a Expr<'a>) -> Option<OptionIfLetElseOccurence> {
141     //(String, String, String, String)> {
142     if_chain! {
143         if let ExprKind::Match(let_body, arms, MatchSource::IfLetDesugar{contains_else_clause: true}) = &expr.kind;
144         if arms.len() == 2;
145         if match_type(cx, &cx.tables.expr_ty(let_body), &paths::OPTION);
146         if !is_result_ok(cx, let_body); // Don't lint on Result::ok because a different lint does it already
147         if let PatKind::TupleStruct(_, &[inner_pat], _) = &arms[0].pat.kind;
148         if let PatKind::Binding(_, _, id, _) = &inner_pat.kind;
149         if !contains_return_break_continue(arms[0].body);
150         if !contains_return_break_continue(arms[1].body);
151         then {
152             let some_body = if let ExprKind::Block(Block { stmts: statements, expr: Some(expr), .. }, _)
153                 = &arms[0].body.kind {
154                 if let &[] = &statements {
155                     expr
156                 } else {
157                     &arms[0].body
158                 }
159             } else {
160                 return None;
161             };
162             let (none_body, method_sugg) = if let ExprKind::Block(Block { stmts: statements, expr: Some(expr), .. }, _)
163                 = &arms[1].body.kind {
164                 if let &[] = &statements {
165                     (expr, "map_or")
166                 } else {
167                     (&arms[1].body, "map_or_else")
168                 }
169             } else {
170                 return None;
171             };
172             let capture_name = id.name.to_ident_string();
173             Some(OptionIfLetElseOccurence {
174                 option: format!("{}", Sugg::hir(cx, let_body, "..")),
175                 method_sugg: format!("{}", method_sugg),
176                 some_expr: format!("|{}| {}", capture_name, Sugg::hir(cx, some_body, "..")),
177                 none_expr: format!("{}{}", if method_sugg == "map_or" { "" } else { "|| " }, Sugg::hir(cx, none_body, ".."))
178             })
179         } else {
180             None
181         }
182     }
183 }
184
185 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OptionIfLetElse {
186     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
187         if let Some(detection) = detect_option_if_let_else(cx, expr) {
188             span_lint_and_sugg(
189                 cx,
190                 OPTION_IF_LET_ELSE,
191                 expr.span,
192                 format!("use Option::{} instead of an if let/else", detection.method_sugg).as_str(),
193                 "try",
194                 format!(
195                     "{}.{}({}, {})",
196                     detection.option, detection.method_sugg, detection.none_expr, detection.some_expr
197                 ),
198                 Applicability::MachineApplicable,
199             );
200         }
201     }
202 }