]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_bool.rs
Rollup merge of #5420 - dtolnay:newret, r=flip1995
[rust.git] / clippy_lints / src / needless_bool.rs
1 //! Checks for needless boolean results of if-else expressions
2 //!
3 //! This lint is **warn** by default
4
5 use crate::utils::sugg::Sugg;
6 use crate::utils::{higher, parent_node_is_if_expr, snippet_with_applicability, span_lint, span_lint_and_sugg};
7 use if_chain::if_chain;
8 use rustc_ast::ast::LitKind;
9 use rustc_errors::Applicability;
10 use rustc_hir::{BinOpKind, Block, Expr, ExprKind, StmtKind, UnOp};
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::source_map::Spanned;
14 use rustc_span::Span;
15
16 declare_clippy_lint! {
17     /// **What it does:** Checks for expressions of the form `if c { true } else {
18     /// false }`
19     /// (or vice versa) and suggest using the condition directly.
20     ///
21     /// **Why is this bad?** Redundant code.
22     ///
23     /// **Known problems:** Maybe false positives: Sometimes, the two branches are
24     /// painstakingly documented (which we, of course, do not detect), so they *may*
25     /// have some value. Even then, the documentation can be rewritten to match the
26     /// shorter code.
27     ///
28     /// **Example:**
29     /// ```rust,ignore
30     /// if x {
31     ///     false
32     /// } else {
33     ///     true
34     /// }
35     /// ```
36     /// Could be written as
37     /// ```rust,ignore
38     /// !x
39     /// ```
40     pub NEEDLESS_BOOL,
41     complexity,
42     "if-statements with plain booleans in the then- and else-clause, e.g., `if p { true } else { false }`"
43 }
44
45 declare_clippy_lint! {
46     /// **What it does:** Checks for expressions of the form `x == true`,
47     /// `x != true` and order comparisons such as `x < true` (or vice versa) and
48     /// suggest using the variable directly.
49     ///
50     /// **Why is this bad?** Unnecessary code.
51     ///
52     /// **Known problems:** None.
53     ///
54     /// **Example:**
55     /// ```rust,ignore
56     /// if x == true {}
57     /// if y == false {}
58     /// ```
59     /// use `x` directly:
60     /// ```rust,ignore
61     /// if x {}
62     /// if !y {}
63     /// ```
64     pub BOOL_COMPARISON,
65     complexity,
66     "comparing a variable to a boolean, e.g., `if x == true` or `if x != true`"
67 }
68
69 declare_lint_pass!(NeedlessBool => [NEEDLESS_BOOL]);
70
71 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
72     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
73         use self::Expression::{Bool, RetBool};
74         if let Some((ref pred, ref then_block, Some(ref else_expr))) = higher::if_block(&e) {
75             let reduce = |ret, not| {
76                 let mut applicability = Applicability::MachineApplicable;
77                 let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
78                 let mut snip = if not { !snip } else { snip };
79
80                 if ret {
81                     snip = snip.make_return();
82                 }
83
84                 if parent_node_is_if_expr(&e, &cx) {
85                     snip = snip.blockify()
86                 }
87
88                 span_lint_and_sugg(
89                     cx,
90                     NEEDLESS_BOOL,
91                     e.span,
92                     "this if-then-else expression returns a bool literal",
93                     "you can reduce it to",
94                     snip.to_string(),
95                     applicability,
96                 );
97             };
98             if let ExprKind::Block(ref then_block, _) = then_block.kind {
99                 match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
100                     (RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
101                         span_lint(
102                             cx,
103                             NEEDLESS_BOOL,
104                             e.span,
105                             "this if-then-else expression will always return true",
106                         );
107                     },
108                     (RetBool(false), RetBool(false)) | (Bool(false), Bool(false)) => {
109                         span_lint(
110                             cx,
111                             NEEDLESS_BOOL,
112                             e.span,
113                             "this if-then-else expression will always return false",
114                         );
115                     },
116                     (RetBool(true), RetBool(false)) => reduce(true, false),
117                     (Bool(true), Bool(false)) => reduce(false, false),
118                     (RetBool(false), RetBool(true)) => reduce(true, true),
119                     (Bool(false), Bool(true)) => reduce(false, true),
120                     _ => (),
121                 }
122             } else {
123                 panic!("IfExpr `then` node is not an `ExprKind::Block`");
124             }
125         }
126     }
127 }
128
129 declare_lint_pass!(BoolComparison => [BOOL_COMPARISON]);
130
131 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoolComparison {
132     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
133         if e.span.from_expansion() {
134             return;
135         }
136
137         if let ExprKind::Binary(Spanned { node, .. }, ..) = e.kind {
138             let ignore_case = None::<(fn(_) -> _, &str)>;
139             let ignore_no_literal = None::<(fn(_, _) -> _, &str)>;
140             match node {
141                 BinOpKind::Eq => {
142                     let true_case = Some((|h| h, "equality checks against true are unnecessary"));
143                     let false_case = Some((
144                         |h: Sugg<'_>| !h,
145                         "equality checks against false can be replaced by a negation",
146                     ));
147                     check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
148                 },
149                 BinOpKind::Ne => {
150                     let true_case = Some((
151                         |h: Sugg<'_>| !h,
152                         "inequality checks against true can be replaced by a negation",
153                     ));
154                     let false_case = Some((|h| h, "inequality checks against false are unnecessary"));
155                     check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
156                 },
157                 BinOpKind::Lt => check_comparison(
158                     cx,
159                     e,
160                     ignore_case,
161                     Some((|h| h, "greater than checks against false are unnecessary")),
162                     Some((
163                         |h: Sugg<'_>| !h,
164                         "less than comparison against true can be replaced by a negation",
165                     )),
166                     ignore_case,
167                     Some((
168                         |l: Sugg<'_>, r: Sugg<'_>| (!l).bit_and(&r),
169                         "order comparisons between booleans can be simplified",
170                     )),
171                 ),
172                 BinOpKind::Gt => check_comparison(
173                     cx,
174                     e,
175                     Some((
176                         |h: Sugg<'_>| !h,
177                         "less than comparison against true can be replaced by a negation",
178                     )),
179                     ignore_case,
180                     ignore_case,
181                     Some((|h| h, "greater than checks against false are unnecessary")),
182                     Some((
183                         |l: Sugg<'_>, r: Sugg<'_>| l.bit_and(&(!r)),
184                         "order comparisons between booleans can be simplified",
185                     )),
186                 ),
187                 _ => (),
188             }
189         }
190     }
191 }
192
193 struct ExpressionInfoWithSpan {
194     one_side_is_unary_not: bool,
195     left_span: Span,
196     right_span: Span,
197 }
198
199 fn is_unary_not(e: &Expr<'_>) -> (bool, Span) {
200     if_chain! {
201         if let ExprKind::Unary(unop, operand) = e.kind;
202         if let UnOp::UnNot = unop;
203         then {
204             return (true, operand.span);
205         }
206     };
207     (false, e.span)
208 }
209
210 fn one_side_is_unary_not<'tcx>(left_side: &'tcx Expr<'_>, right_side: &'tcx Expr<'_>) -> ExpressionInfoWithSpan {
211     let left = is_unary_not(left_side);
212     let right = is_unary_not(right_side);
213
214     ExpressionInfoWithSpan {
215         one_side_is_unary_not: left.0 != right.0,
216         left_span: left.1,
217         right_span: right.1,
218     }
219 }
220
221 fn check_comparison<'a, 'tcx>(
222     cx: &LateContext<'a, 'tcx>,
223     e: &'tcx Expr<'_>,
224     left_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
225     left_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
226     right_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
227     right_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
228     no_literal: Option<(impl FnOnce(Sugg<'a>, Sugg<'a>) -> Sugg<'a>, &str)>,
229 ) {
230     use self::Expression::{Bool, Other};
231
232     if let ExprKind::Binary(op, ref left_side, ref right_side) = e.kind {
233         let (l_ty, r_ty) = (cx.tables.expr_ty(left_side), cx.tables.expr_ty(right_side));
234         if l_ty.is_bool() && r_ty.is_bool() {
235             let mut applicability = Applicability::MachineApplicable;
236
237             if let BinOpKind::Eq = op.node {
238                 let expression_info = one_side_is_unary_not(&left_side, &right_side);
239                 if expression_info.one_side_is_unary_not {
240                     span_lint_and_sugg(
241                         cx,
242                         BOOL_COMPARISON,
243                         e.span,
244                         "This comparison might be written more concisely",
245                         "try simplifying it as shown",
246                         format!(
247                             "{} != {}",
248                             snippet_with_applicability(cx, expression_info.left_span, "..", &mut applicability),
249                             snippet_with_applicability(cx, expression_info.right_span, "..", &mut applicability)
250                         ),
251                         applicability,
252                     )
253                 }
254             }
255
256             match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
257                 (Bool(true), Other) => left_true.map_or((), |(h, m)| {
258                     suggest_bool_comparison(cx, e, right_side, applicability, m, h)
259                 }),
260                 (Other, Bool(true)) => right_true.map_or((), |(h, m)| {
261                     suggest_bool_comparison(cx, e, left_side, applicability, m, h)
262                 }),
263                 (Bool(false), Other) => left_false.map_or((), |(h, m)| {
264                     suggest_bool_comparison(cx, e, right_side, applicability, m, h)
265                 }),
266                 (Other, Bool(false)) => right_false.map_or((), |(h, m)| {
267                     suggest_bool_comparison(cx, e, left_side, applicability, m, h)
268                 }),
269                 (Other, Other) => no_literal.map_or((), |(h, m)| {
270                     let left_side = Sugg::hir_with_applicability(cx, left_side, "..", &mut applicability);
271                     let right_side = Sugg::hir_with_applicability(cx, right_side, "..", &mut applicability);
272                     span_lint_and_sugg(
273                         cx,
274                         BOOL_COMPARISON,
275                         e.span,
276                         m,
277                         "try simplifying it as shown",
278                         h(left_side, right_side).to_string(),
279                         applicability,
280                     )
281                 }),
282                 _ => (),
283             }
284         }
285     }
286 }
287
288 fn suggest_bool_comparison<'a, 'tcx>(
289     cx: &LateContext<'a, 'tcx>,
290     e: &'tcx Expr<'_>,
291     expr: &Expr<'_>,
292     mut applicability: Applicability,
293     message: &str,
294     conv_hint: impl FnOnce(Sugg<'a>) -> Sugg<'a>,
295 ) {
296     let hint = Sugg::hir_with_applicability(cx, expr, "..", &mut applicability);
297     span_lint_and_sugg(
298         cx,
299         BOOL_COMPARISON,
300         e.span,
301         message,
302         "try simplifying it as shown",
303         conv_hint(hint).to_string(),
304         applicability,
305     );
306 }
307
308 enum Expression {
309     Bool(bool),
310     RetBool(bool),
311     Other,
312 }
313
314 fn fetch_bool_block(block: &Block<'_>) -> Expression {
315     match (&*block.stmts, block.expr.as_ref()) {
316         (&[], Some(e)) => fetch_bool_expr(&**e),
317         (&[ref e], None) => {
318             if let StmtKind::Semi(ref e) = e.kind {
319                 if let ExprKind::Ret(_) = e.kind {
320                     fetch_bool_expr(&**e)
321                 } else {
322                     Expression::Other
323                 }
324             } else {
325                 Expression::Other
326             }
327         },
328         _ => Expression::Other,
329     }
330 }
331
332 fn fetch_bool_expr(expr: &Expr<'_>) -> Expression {
333     match expr.kind {
334         ExprKind::Block(ref block, _) => fetch_bool_block(block),
335         ExprKind::Lit(ref lit_ptr) => {
336             if let LitKind::Bool(value) = lit_ptr.node {
337                 Expression::Bool(value)
338             } else {
339                 Expression::Other
340             }
341         },
342         ExprKind::Ret(Some(ref expr)) => match fetch_bool_expr(expr) {
343             Expression::Bool(value) => Expression::RetBool(value),
344             _ => Expression::Other,
345         },
346         _ => Expression::Other,
347     }
348 }