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