]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_bool.rs
Auto merge of #3681 - rmcteggart-r7:master, r=matthiaskrgr
[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::{in_macro, span_lint, span_lint_and_sugg};
7 use rustc::hir::*;
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
9 use rustc::{declare_tool_lint, lint_array};
10 use rustc_errors::Applicability;
11 use syntax::ast::LitKind;
12 use syntax::source_map::Spanned;
13
14 /// **What it does:** Checks for expressions of the form `if c { true } else {
15 /// false }`
16 /// (or vice versa) and suggest using the condition directly.
17 ///
18 /// **Why is this bad?** Redundant code.
19 ///
20 /// **Known problems:** Maybe false positives: Sometimes, the two branches are
21 /// painstakingly documented (which we of course do not detect), so they *may*
22 /// have some value. Even then, the documentation can be rewritten to match the
23 /// shorter code.
24 ///
25 /// **Example:**
26 /// ```rust
27 /// if x {
28 ///     false
29 /// } else {
30 ///     true
31 /// }
32 /// ```
33 declare_clippy_lint! {
34     pub NEEDLESS_BOOL,
35     complexity,
36     "if-statements with plain booleans in the then- and else-clause, e.g. `if p { true } else { false }`"
37 }
38
39 /// **What it does:** Checks for expressions of the form `x == true`,
40 /// `x != true` and order comparisons such as `x < true` (or vice versa) and
41 /// suggest using the variable directly.
42 ///
43 /// **Why is this bad?** Unnecessary code.
44 ///
45 /// **Known problems:** None.
46 ///
47 /// **Example:**
48 /// ```rust
49 /// if x == true {} // could be `if x { }`
50 /// ```
51 declare_clippy_lint! {
52     pub BOOL_COMPARISON,
53     complexity,
54     "comparing a variable to a boolean, e.g. `if x == true` or `if x != true`"
55 }
56
57 #[derive(Copy, Clone)]
58 pub struct NeedlessBool;
59
60 impl LintPass for NeedlessBool {
61     fn get_lints(&self) -> LintArray {
62         lint_array!(NEEDLESS_BOOL)
63     }
64 }
65
66 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
67     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
68         use self::Expression::*;
69         if let ExprKind::If(ref pred, ref then_block, Some(ref else_expr)) = e.node {
70             let reduce = |ret, not| {
71                 let mut applicability = Applicability::MachineApplicable;
72                 let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
73                 let snip = if not { !snip } else { snip };
74
75                 let hint = if ret {
76                     format!("return {}", snip)
77                 } else {
78                     snip.to_string()
79                 };
80
81                 span_lint_and_sugg(
82                     cx,
83                     NEEDLESS_BOOL,
84                     e.span,
85                     "this if-then-else expression returns a bool literal",
86                     "you can reduce it to",
87                     hint,
88                     applicability,
89                 );
90             };
91             if let ExprKind::Block(ref then_block, _) = then_block.node {
92                 match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
93                     (RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
94                         span_lint(
95                             cx,
96                             NEEDLESS_BOOL,
97                             e.span,
98                             "this if-then-else expression will always return true",
99                         );
100                     },
101                     (RetBool(false), RetBool(false)) | (Bool(false), Bool(false)) => {
102                         span_lint(
103                             cx,
104                             NEEDLESS_BOOL,
105                             e.span,
106                             "this if-then-else expression will always return false",
107                         );
108                     },
109                     (RetBool(true), RetBool(false)) => reduce(true, false),
110                     (Bool(true), Bool(false)) => reduce(false, false),
111                     (RetBool(false), RetBool(true)) => reduce(true, true),
112                     (Bool(false), Bool(true)) => reduce(false, true),
113                     _ => (),
114                 }
115             } else {
116                 panic!("IfExpr 'then' node is not an ExprKind::Block");
117             }
118         }
119     }
120 }
121
122 #[derive(Copy, Clone)]
123 pub struct BoolComparison;
124
125 impl LintPass for BoolComparison {
126     fn get_lints(&self) -> LintArray {
127         lint_array!(BOOL_COMPARISON)
128     }
129 }
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 in_macro(e.span) {
134             return;
135         }
136
137         if let ExprKind::Binary(Spanned { node, .. }, ..) = e.node {
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 fn check_comparison<'a, 'tcx>(
194     cx: &LateContext<'a, 'tcx>,
195     e: &'tcx Expr,
196     left_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
197     left_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
198     right_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
199     right_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
200     no_literal: Option<(impl FnOnce(Sugg<'a>, Sugg<'a>) -> Sugg<'a>, &str)>,
201 ) {
202     use self::Expression::*;
203
204     if let ExprKind::Binary(_, ref left_side, ref right_side) = e.node {
205         let mut applicability = Applicability::MachineApplicable;
206         match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
207             (Bool(true), Other) => left_true.map_or((), |(h, m)| {
208                 suggest_bool_comparison(cx, e, right_side, applicability, m, h)
209             }),
210             (Other, Bool(true)) => right_true.map_or((), |(h, m)| {
211                 suggest_bool_comparison(cx, e, left_side, applicability, m, h)
212             }),
213             (Bool(false), Other) => left_false.map_or((), |(h, m)| {
214                 suggest_bool_comparison(cx, e, right_side, applicability, m, h)
215             }),
216             (Other, Bool(false)) => right_false.map_or((), |(h, m)| {
217                 suggest_bool_comparison(cx, e, left_side, applicability, m, h)
218             }),
219             (Other, Other) => no_literal.map_or((), |(h, m)| {
220                 let (l_ty, r_ty) = (cx.tables.expr_ty(left_side), cx.tables.expr_ty(right_side));
221                 if l_ty.is_bool() && r_ty.is_bool() {
222                     let left_side = Sugg::hir_with_applicability(cx, left_side, "..", &mut applicability);
223                     let right_side = Sugg::hir_with_applicability(cx, right_side, "..", &mut applicability);
224                     span_lint_and_sugg(
225                         cx,
226                         BOOL_COMPARISON,
227                         e.span,
228                         m,
229                         "try simplifying it as shown",
230                         h(left_side, right_side).to_string(),
231                         applicability,
232                     )
233                 }
234             }),
235             _ => (),
236         }
237     }
238 }
239
240 fn suggest_bool_comparison<'a, 'tcx>(
241     cx: &LateContext<'a, 'tcx>,
242     e: &'tcx Expr,
243     expr: &Expr,
244     mut applicability: Applicability,
245     message: &str,
246     conv_hint: impl FnOnce(Sugg<'a>) -> Sugg<'a>,
247 ) {
248     let hint = Sugg::hir_with_applicability(cx, expr, "..", &mut applicability);
249     span_lint_and_sugg(
250         cx,
251         BOOL_COMPARISON,
252         e.span,
253         message,
254         "try simplifying it as shown",
255         conv_hint(hint).to_string(),
256         applicability,
257     );
258 }
259
260 enum Expression {
261     Bool(bool),
262     RetBool(bool),
263     Other,
264 }
265
266 fn fetch_bool_block(block: &Block) -> Expression {
267     match (&*block.stmts, block.expr.as_ref()) {
268         (&[], Some(e)) => fetch_bool_expr(&**e),
269         (&[ref e], None) => {
270             if let StmtKind::Semi(ref e) = e.node {
271                 if let ExprKind::Ret(_) = e.node {
272                     fetch_bool_expr(&**e)
273                 } else {
274                     Expression::Other
275                 }
276             } else {
277                 Expression::Other
278             }
279         },
280         _ => Expression::Other,
281     }
282 }
283
284 fn fetch_bool_expr(expr: &Expr) -> Expression {
285     match expr.node {
286         ExprKind::Block(ref block, _) => fetch_bool_block(block),
287         ExprKind::Lit(ref lit_ptr) => {
288             if let LitKind::Bool(value) = lit_ptr.node {
289                 Expression::Bool(value)
290             } else {
291                 Expression::Other
292             }
293         },
294         ExprKind::Ret(Some(ref expr)) => match fetch_bool_expr(expr) {
295             Expression::Bool(value) => Expression::RetBool(value),
296             _ => Expression::Other,
297         },
298         _ => Expression::Other,
299     }
300 }