]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_bool.rs
Merge pull request #3459 from flip1995/sugg_appl
[rust.git] / clippy_lints / src / needless_bool.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 //! Checks for needless boolean results of if-else expressions
12 //!
13 //! This lint is **warn** by default
14
15 use crate::rustc::hir::*;
16 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
17 use crate::rustc::{declare_tool_lint, lint_array};
18 use crate::rustc_errors::Applicability;
19 use crate::syntax::ast::LitKind;
20 use crate::syntax::source_map::Spanned;
21 use crate::utils::sugg::Sugg;
22 use crate::utils::{in_macro, snippet_with_applicability, span_lint, span_lint_and_sugg};
23
24 /// **What it does:** Checks for expressions of the form `if c { true } else {
25 /// false }`
26 /// (or vice versa) and suggest using the condition directly.
27 ///
28 /// **Why is this bad?** Redundant code.
29 ///
30 /// **Known problems:** Maybe false positives: Sometimes, the two branches are
31 /// painstakingly documented (which we of course do not detect), so they *may*
32 /// have some value. Even then, the documentation can be rewritten to match the
33 /// shorter code.
34 ///
35 /// **Example:**
36 /// ```rust
37 /// if x { false } else { true }
38 /// ```
39 declare_clippy_lint! {
40     pub NEEDLESS_BOOL,
41     complexity,
42     "if-statements with plain booleans in the then- and else-clause, e.g. \
43      `if p { true } else { false }`"
44 }
45
46 /// **What it does:** Checks for expressions of the form `x == true` (or vice
47 /// versa) and suggest using the variable directly.
48 ///
49 /// **Why is this bad?** Unnecessary code.
50 ///
51 /// **Known problems:** None.
52 ///
53 /// **Example:**
54 /// ```rust
55 /// if x == true { }  // could be `if x { }`
56 /// ```
57 declare_clippy_lint! {
58     pub BOOL_COMPARISON,
59     complexity,
60     "comparing a variable to a boolean, e.g. `if x == true`"
61 }
62
63 #[derive(Copy, Clone)]
64 pub struct NeedlessBool;
65
66 impl LintPass for NeedlessBool {
67     fn get_lints(&self) -> LintArray {
68         lint_array!(NEEDLESS_BOOL)
69     }
70 }
71
72 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
73     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
74         use self::Expression::*;
75         if let ExprKind::If(ref pred, ref then_block, Some(ref else_expr)) = e.node {
76             let reduce = |ret, not| {
77                 let mut applicability = Applicability::MachineApplicable;
78                 let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
79                 let snip = if not { !snip } else { snip };
80
81                 let hint = if ret {
82                     format!("return {}", snip)
83                 } else {
84                     snip.to_string()
85                 };
86
87                 span_lint_and_sugg(
88                     cx,
89                     NEEDLESS_BOOL,
90                     e.span,
91                     "this if-then-else expression returns a bool literal",
92                     "you can reduce it to",
93                     hint,
94                     applicability,
95                 );
96             };
97             if let ExprKind::Block(ref then_block, _) = then_block.node {
98                 match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
99                     (RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
100                         span_lint(
101                             cx,
102                             NEEDLESS_BOOL,
103                             e.span,
104                             "this if-then-else expression will always return true",
105                         );
106                     },
107                     (RetBool(false), RetBool(false)) | (Bool(false), Bool(false)) => {
108                         span_lint(
109                             cx,
110                             NEEDLESS_BOOL,
111                             e.span,
112                             "this if-then-else expression will always return false",
113                         );
114                     },
115                     (RetBool(true), RetBool(false)) => reduce(true, false),
116                     (Bool(true), Bool(false)) => reduce(false, false),
117                     (RetBool(false), RetBool(true)) => reduce(true, true),
118                     (Bool(false), Bool(true)) => reduce(false, true),
119                     _ => (),
120                 }
121             } else {
122                 panic!("IfExpr 'then' node is not an ExprKind::Block");
123             }
124         }
125     }
126 }
127
128 #[derive(Copy, Clone)]
129 pub struct BoolComparison;
130
131 impl LintPass for BoolComparison {
132     fn get_lints(&self) -> LintArray {
133         lint_array!(BOOL_COMPARISON)
134     }
135 }
136
137 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoolComparison {
138     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
139         use self::Expression::*;
140
141         if in_macro(e.span) {
142             return;
143         }
144
145         if let ExprKind::Binary(Spanned { node: BinOpKind::Eq, .. }, ref left_side, ref right_side) = e.node {
146             let mut applicability = Applicability::MachineApplicable;
147             match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
148                 (Bool(true), Other) => {
149                     let hint = snippet_with_applicability(cx, right_side.span, "..", &mut applicability);
150                     span_lint_and_sugg(
151                         cx,
152                         BOOL_COMPARISON,
153                         e.span,
154                         "equality checks against true are unnecessary",
155                         "try simplifying it as shown",
156                         hint.to_string(),
157                         applicability,
158                     );
159                 },
160                 (Other, Bool(true)) => {
161                     let hint = snippet_with_applicability(cx, left_side.span, "..", &mut applicability);
162                     span_lint_and_sugg(
163                         cx,
164                         BOOL_COMPARISON,
165                         e.span,
166                         "equality checks against true are unnecessary",
167                         "try simplifying it as shown",
168                         hint.to_string(),
169                         applicability,
170                     );
171                 },
172                 (Bool(false), Other) => {
173                     let hint = Sugg::hir_with_applicability(cx, right_side, "..", &mut applicability);
174                     span_lint_and_sugg(
175                         cx,
176                         BOOL_COMPARISON,
177                         e.span,
178                         "equality checks against false can be replaced by a negation",
179                         "try simplifying it as shown",
180                         (!hint).to_string(),
181                         applicability,
182                     );
183                 },
184                 (Other, Bool(false)) => {
185                     let hint = Sugg::hir_with_applicability(cx, left_side, "..", &mut applicability);
186                     span_lint_and_sugg(
187                         cx,
188                         BOOL_COMPARISON,
189                         e.span,
190                         "equality checks against false can be replaced by a negation",
191                         "try simplifying it as shown",
192                         (!hint).to_string(),
193                         applicability,
194                     );
195                 },
196                 _ => (),
197             }
198         }
199     }
200 }
201
202 enum Expression {
203     Bool(bool),
204     RetBool(bool),
205     Other,
206 }
207
208 fn fetch_bool_block(block: &Block) -> Expression {
209     match (&*block.stmts, block.expr.as_ref()) {
210         (&[], Some(e)) => fetch_bool_expr(&**e),
211         (&[ref e], None) => if let StmtKind::Semi(ref e, _) = e.node {
212             if let ExprKind::Ret(_) = e.node {
213                 fetch_bool_expr(&**e)
214             } else {
215                 Expression::Other
216             }
217         } else {
218             Expression::Other
219         },
220         _ => Expression::Other,
221     }
222 }
223
224 fn fetch_bool_expr(expr: &Expr) -> Expression {
225     match expr.node {
226         ExprKind::Block(ref block, _) => fetch_bool_block(block),
227         ExprKind::Lit(ref lit_ptr) => if let LitKind::Bool(value) = lit_ptr.node {
228             Expression::Bool(value)
229         } else {
230             Expression::Other
231         },
232         ExprKind::Ret(Some(ref expr)) => match fetch_bool_expr(expr) {
233             Expression::Bool(value) => Expression::RetBool(value),
234             _ => Expression::Other,
235         },
236         _ => Expression::Other,
237     }
238 }