]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_bool.rs
formatting fix
[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
71             let reduce = |ret, not| {
72                 let mut applicability = Applicability::MachineApplicable;
73                 let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
74                 let snip = if not { !snip } else { snip };
75
76                 let mut hint = if ret {
77                     format!("return {}", snip)
78                 } else {
79                     snip.to_string()
80                 };
81
82                 if parent_node_is_if_expr(&e, &cx) {
83                     hint = format!("{{ {} }}", hint);
84                 }
85
86                 span_lint_and_sugg(
87                     cx,
88                     NEEDLESS_BOOL,
89                     e.span,
90                     "this if-then-else expression returns a bool literal",
91                     "you can reduce it to",
92                     hint,
93                     applicability,
94                 );
95             };
96             if let ExprKind::Block(ref then_block, _) = then_block.node {
97                 match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
98                     (RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
99                         span_lint(
100                             cx,
101                             NEEDLESS_BOOL,
102                             e.span,
103                             "this if-then-else expression will always return true",
104                         );
105                     },
106                     (RetBool(false), RetBool(false)) | (Bool(false), Bool(false)) => {
107                         span_lint(
108                             cx,
109                             NEEDLESS_BOOL,
110                             e.span,
111                             "this if-then-else expression will always return false",
112                         );
113                     },
114                     (RetBool(true), RetBool(false)) => reduce(true, false),
115                     (Bool(true), Bool(false)) => reduce(false, false),
116                     (RetBool(false), RetBool(true)) => reduce(true, true),
117                     (Bool(false), Bool(true)) => reduce(false, true),
118                     _ => (),
119                 }
120             } else {
121                 panic!("IfExpr 'then' node is not an ExprKind::Block");
122             }
123         }
124     }
125 }
126
127 fn parent_node_is_if_expr<'a, 'b>(expr: &Expr, cx: &LateContext<'a, 'b>) -> bool {
128     let parent_id = cx.tcx.hir().get_parent_node(expr.id);
129     let parent_node = cx.tcx.hir().get(parent_id);
130
131     if let rustc::hir::Node::Expr(e) = parent_node {
132         if let ExprKind::If(_,_,_) = e.node {
133             return true;
134         }
135     }
136
137     false
138 }
139
140 #[derive(Copy, Clone)]
141 pub struct BoolComparison;
142
143 impl LintPass for BoolComparison {
144     fn get_lints(&self) -> LintArray {
145         lint_array!(BOOL_COMPARISON)
146     }
147 }
148
149 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoolComparison {
150     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
151         if in_macro(e.span) {
152             return;
153         }
154
155         if let ExprKind::Binary(Spanned { node, .. }, ..) = e.node {
156             let ignore_case = None::<(fn(_) -> _, &str)>;
157             let ignore_no_literal = None::<(fn(_, _) -> _, &str)>;
158             match node {
159                 BinOpKind::Eq => {
160                     let true_case = Some((|h| h, "equality checks against true are unnecessary"));
161                     let false_case = Some((
162                         |h: Sugg<'_>| !h,
163                         "equality checks against false can be replaced by a negation",
164                     ));
165                     check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
166                 },
167                 BinOpKind::Ne => {
168                     let true_case = Some((
169                         |h: Sugg<'_>| !h,
170                         "inequality checks against true can be replaced by a negation",
171                     ));
172                     let false_case = Some((|h| h, "inequality checks against false are unnecessary"));
173                     check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
174                 },
175                 BinOpKind::Lt => check_comparison(
176                     cx,
177                     e,
178                     ignore_case,
179                     Some((|h| h, "greater than checks against false are unnecessary")),
180                     Some((
181                         |h: Sugg<'_>| !h,
182                         "less than comparison against true can be replaced by a negation",
183                     )),
184                     ignore_case,
185                     Some((
186                         |l: Sugg<'_>, r: Sugg<'_>| (!l).bit_and(&r),
187                         "order comparisons between booleans can be simplified",
188                     )),
189                 ),
190                 BinOpKind::Gt => check_comparison(
191                     cx,
192                     e,
193                     Some((
194                         |h: Sugg<'_>| !h,
195                         "less than comparison against true can be replaced by a negation",
196                     )),
197                     ignore_case,
198                     ignore_case,
199                     Some((|h| h, "greater than checks against false are unnecessary")),
200                     Some((
201                         |l: Sugg<'_>, r: Sugg<'_>| l.bit_and(&(!r)),
202                         "order comparisons between booleans can be simplified",
203                     )),
204                 ),
205                 _ => (),
206             }
207         }
208     }
209 }
210
211 fn check_comparison<'a, 'tcx>(
212     cx: &LateContext<'a, 'tcx>,
213     e: &'tcx Expr,
214     left_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
215     left_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
216     right_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
217     right_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
218     no_literal: Option<(impl FnOnce(Sugg<'a>, Sugg<'a>) -> Sugg<'a>, &str)>,
219 ) {
220     use self::Expression::*;
221
222     if let ExprKind::Binary(_, ref left_side, ref right_side) = e.node {
223         let mut applicability = Applicability::MachineApplicable;
224         match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
225             (Bool(true), Other) => left_true.map_or((), |(h, m)| {
226                 suggest_bool_comparison(cx, e, right_side, applicability, m, h)
227             }),
228             (Other, Bool(true)) => right_true.map_or((), |(h, m)| {
229                 suggest_bool_comparison(cx, e, left_side, applicability, m, h)
230             }),
231             (Bool(false), Other) => left_false.map_or((), |(h, m)| {
232                 suggest_bool_comparison(cx, e, right_side, applicability, m, h)
233             }),
234             (Other, Bool(false)) => right_false.map_or((), |(h, m)| {
235                 suggest_bool_comparison(cx, e, left_side, applicability, m, h)
236             }),
237             (Other, Other) => no_literal.map_or((), |(h, m)| {
238                 let (l_ty, r_ty) = (cx.tables.expr_ty(left_side), cx.tables.expr_ty(right_side));
239                 if l_ty.is_bool() && r_ty.is_bool() {
240                     let left_side = Sugg::hir_with_applicability(cx, left_side, "..", &mut applicability);
241                     let right_side = Sugg::hir_with_applicability(cx, right_side, "..", &mut applicability);
242                     span_lint_and_sugg(
243                         cx,
244                         BOOL_COMPARISON,
245                         e.span,
246                         m,
247                         "try simplifying it as shown",
248                         h(left_side, right_side).to_string(),
249                         applicability,
250                     )
251                 }
252             }),
253             _ => (),
254         }
255     }
256 }
257
258 fn suggest_bool_comparison<'a, 'tcx>(
259     cx: &LateContext<'a, 'tcx>,
260     e: &'tcx Expr,
261     expr: &Expr,
262     mut applicability: Applicability,
263     message: &str,
264     conv_hint: impl FnOnce(Sugg<'a>) -> Sugg<'a>,
265 ) {
266     let hint = Sugg::hir_with_applicability(cx, expr, "..", &mut applicability);
267     span_lint_and_sugg(
268         cx,
269         BOOL_COMPARISON,
270         e.span,
271         message,
272         "try simplifying it as shown",
273         conv_hint(hint).to_string(),
274         applicability,
275     );
276 }
277
278 enum Expression {
279     Bool(bool),
280     RetBool(bool),
281     Other,
282 }
283
284 fn fetch_bool_block(block: &Block) -> Expression {
285     match (&*block.stmts, block.expr.as_ref()) {
286         (&[], Some(e)) => fetch_bool_expr(&**e),
287         (&[ref e], None) => {
288             if let StmtKind::Semi(ref e, _) = e.node {
289                 if let ExprKind::Ret(_) = e.node {
290                     fetch_bool_expr(&**e)
291                 } else {
292                     Expression::Other
293                 }
294             } else {
295                 Expression::Other
296             }
297         },
298         _ => Expression::Other,
299     }
300 }
301
302 fn fetch_bool_expr(expr: &Expr) -> Expression {
303     match expr.node {
304         ExprKind::Block(ref block, _) => fetch_bool_block(block),
305         ExprKind::Lit(ref lit_ptr) => {
306             if let LitKind::Bool(value) = lit_ptr.node {
307                 Expression::Bool(value)
308             } else {
309                 Expression::Other
310             }
311         },
312         ExprKind::Ret(Some(ref expr)) => match fetch_bool_expr(expr) {
313             Expression::Bool(value) => Expression::RetBool(value),
314             _ => Expression::Other,
315         },
316         _ => Expression::Other,
317     }
318 }