]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_bool.rs
Auto merge of #4335 - phansch:fix_needless_bool_suggestion, 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, in_macro_or_desugar, span_lint, span_lint_and_sugg};
7 use rustc::hir::*;
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
9 use rustc::{declare_lint_pass, declare_tool_lint};
10 use rustc_errors::Applicability;
11 use syntax::ast::LitKind;
12 use syntax::source_map::Spanned;
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for expressions of the form `if c { true } else {
16     /// false }`
17     /// (or vice versa) and suggest using the condition directly.
18     ///
19     /// **Why is this bad?** Redundant code.
20     ///
21     /// **Known problems:** Maybe false positives: Sometimes, the two branches are
22     /// painstakingly documented (which we, of course, do not detect), so they *may*
23     /// have some value. Even then, the documentation can be rewritten to match the
24     /// shorter code.
25     ///
26     /// **Example:**
27     /// ```rust,ignore
28     /// if x {
29     ///     false
30     /// } else {
31     ///     true
32     /// }
33     /// ```
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 declare_clippy_lint! {
40     /// **What it does:** Checks for expressions of the form `x == true`,
41     /// `x != true` and order comparisons such as `x < true` (or vice versa) and
42     /// suggest using the variable directly.
43     ///
44     /// **Why is this bad?** Unnecessary code.
45     ///
46     /// **Known problems:** None.
47     ///
48     /// **Example:**
49     /// ```rust,ignore
50     /// if x == true {} // could be `if x { }`
51     /// ```
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 declare_lint_pass!(NeedlessBool => [NEEDLESS_BOOL]);
58
59 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
60     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
61         use self::Expression::*;
62         if let Some((ref pred, ref then_block, Some(ref else_expr))) = higher::if_block(&e) {
63             let reduce = |ret, not| {
64                 let mut applicability = Applicability::MachineApplicable;
65                 let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
66                 let mut snip = if not { !snip } else { snip };
67
68                 if ret {
69                     snip = snip.make_return();
70                 }
71
72                 if parent_node_is_if_expr(&e, &cx) {
73                     snip = snip.blockify()
74                 }
75
76                 span_lint_and_sugg(
77                     cx,
78                     NEEDLESS_BOOL,
79                     e.span,
80                     "this if-then-else expression returns a bool literal",
81                     "you can reduce it to",
82                     snip.to_string(),
83                     applicability,
84                 );
85             };
86             if let ExprKind::Block(ref then_block, _) = then_block.node {
87                 match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
88                     (RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
89                         span_lint(
90                             cx,
91                             NEEDLESS_BOOL,
92                             e.span,
93                             "this if-then-else expression will always return true",
94                         );
95                     },
96                     (RetBool(false), RetBool(false)) | (Bool(false), Bool(false)) => {
97                         span_lint(
98                             cx,
99                             NEEDLESS_BOOL,
100                             e.span,
101                             "this if-then-else expression will always return false",
102                         );
103                     },
104                     (RetBool(true), RetBool(false)) => reduce(true, false),
105                     (Bool(true), Bool(false)) => reduce(false, false),
106                     (RetBool(false), RetBool(true)) => reduce(true, true),
107                     (Bool(false), Bool(true)) => reduce(false, true),
108                     _ => (),
109                 }
110             } else {
111                 panic!("IfExpr 'then' node is not an ExprKind::Block");
112             }
113         }
114     }
115 }
116
117 fn parent_node_is_if_expr<'a, 'b>(expr: &Expr, cx: &LateContext<'a, 'b>) -> bool {
118     let parent_id = cx.tcx.hir().get_parent_node(expr.hir_id);
119     let parent_node = cx.tcx.hir().get(parent_id);
120
121     match parent_node {
122         rustc::hir::Node::Expr(e) => higher::if_block(&e).is_some(),
123         rustc::hir::Node::Arm(e) => higher::if_block(&e.body).is_some(),
124         _ => false,
125     }
126 }
127
128 declare_lint_pass!(BoolComparison => [BOOL_COMPARISON]);
129
130 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoolComparison {
131     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
132         if in_macro_or_desugar(e.span) {
133             return;
134         }
135
136         if let ExprKind::Binary(Spanned { node, .. }, ..) = e.node {
137             let ignore_case = None::<(fn(_) -> _, &str)>;
138             let ignore_no_literal = None::<(fn(_, _) -> _, &str)>;
139             match node {
140                 BinOpKind::Eq => {
141                     let true_case = Some((|h| h, "equality checks against true are unnecessary"));
142                     let false_case = Some((
143                         |h: Sugg<'_>| !h,
144                         "equality checks against false can be replaced by a negation",
145                     ));
146                     check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
147                 },
148                 BinOpKind::Ne => {
149                     let true_case = Some((
150                         |h: Sugg<'_>| !h,
151                         "inequality checks against true can be replaced by a negation",
152                     ));
153                     let false_case = Some((|h| h, "inequality checks against false are unnecessary"));
154                     check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
155                 },
156                 BinOpKind::Lt => check_comparison(
157                     cx,
158                     e,
159                     ignore_case,
160                     Some((|h| h, "greater than checks against false are unnecessary")),
161                     Some((
162                         |h: Sugg<'_>| !h,
163                         "less than comparison against true can be replaced by a negation",
164                     )),
165                     ignore_case,
166                     Some((
167                         |l: Sugg<'_>, r: Sugg<'_>| (!l).bit_and(&r),
168                         "order comparisons between booleans can be simplified",
169                     )),
170                 ),
171                 BinOpKind::Gt => check_comparison(
172                     cx,
173                     e,
174                     Some((
175                         |h: Sugg<'_>| !h,
176                         "less than comparison against true can be replaced by a negation",
177                     )),
178                     ignore_case,
179                     ignore_case,
180                     Some((|h| h, "greater than checks against false are unnecessary")),
181                     Some((
182                         |l: Sugg<'_>, r: Sugg<'_>| l.bit_and(&(!r)),
183                         "order comparisons between booleans can be simplified",
184                     )),
185                 ),
186                 _ => (),
187             }
188         }
189     }
190 }
191
192 fn check_comparison<'a, 'tcx>(
193     cx: &LateContext<'a, 'tcx>,
194     e: &'tcx Expr,
195     left_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
196     left_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
197     right_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
198     right_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
199     no_literal: Option<(impl FnOnce(Sugg<'a>, Sugg<'a>) -> Sugg<'a>, &str)>,
200 ) {
201     use self::Expression::*;
202
203     if let ExprKind::Binary(_, ref left_side, ref right_side) = e.node {
204         let (l_ty, r_ty) = (cx.tables.expr_ty(left_side), cx.tables.expr_ty(right_side));
205         if l_ty.is_bool() && r_ty.is_bool() {
206             let mut applicability = Applicability::MachineApplicable;
207             match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
208                 (Bool(true), Other) => left_true.map_or((), |(h, m)| {
209                     suggest_bool_comparison(cx, e, right_side, applicability, m, h)
210                 }),
211                 (Other, Bool(true)) => right_true.map_or((), |(h, m)| {
212                     suggest_bool_comparison(cx, e, left_side, applicability, m, h)
213                 }),
214                 (Bool(false), Other) => left_false.map_or((), |(h, m)| {
215                     suggest_bool_comparison(cx, e, right_side, applicability, m, h)
216                 }),
217                 (Other, Bool(false)) => right_false.map_or((), |(h, m)| {
218                     suggest_bool_comparison(cx, e, left_side, applicability, m, h)
219                 }),
220                 (Other, Other) => no_literal.map_or((), |(h, m)| {
221                     let left_side = Sugg::hir_with_applicability(cx, left_side, "..", &mut applicability);
222                     let right_side = Sugg::hir_with_applicability(cx, right_side, "..", &mut applicability);
223                     span_lint_and_sugg(
224                         cx,
225                         BOOL_COMPARISON,
226                         e.span,
227                         m,
228                         "try simplifying it as shown",
229                         h(left_side, right_side).to_string(),
230                         applicability,
231                     )
232                 }),
233                 _ => (),
234             }
235         }
236     }
237 }
238
239 fn suggest_bool_comparison<'a, 'tcx>(
240     cx: &LateContext<'a, 'tcx>,
241     e: &'tcx Expr,
242     expr: &Expr,
243     mut applicability: Applicability,
244     message: &str,
245     conv_hint: impl FnOnce(Sugg<'a>) -> Sugg<'a>,
246 ) {
247     let hint = Sugg::hir_with_applicability(cx, expr, "..", &mut applicability);
248     span_lint_and_sugg(
249         cx,
250         BOOL_COMPARISON,
251         e.span,
252         message,
253         "try simplifying it as shown",
254         conv_hint(hint).to_string(),
255         applicability,
256     );
257 }
258
259 enum Expression {
260     Bool(bool),
261     RetBool(bool),
262     Other,
263 }
264
265 fn fetch_bool_block(block: &Block) -> Expression {
266     match (&*block.stmts, block.expr.as_ref()) {
267         (&[], Some(e)) => fetch_bool_expr(&**e),
268         (&[ref e], None) => {
269             if let StmtKind::Semi(ref e) = e.node {
270                 if let ExprKind::Ret(_) = e.node {
271                     fetch_bool_expr(&**e)
272                 } else {
273                     Expression::Other
274                 }
275             } else {
276                 Expression::Other
277             }
278         },
279         _ => Expression::Other,
280     }
281 }
282
283 fn fetch_bool_expr(expr: &Expr) -> Expression {
284     match expr.node {
285         ExprKind::Block(ref block, _) => fetch_bool_block(block),
286         ExprKind::Lit(ref lit_ptr) => {
287             if let LitKind::Bool(value) = lit_ptr.node {
288                 Expression::Bool(value)
289             } else {
290                 Expression::Other
291             }
292         },
293         ExprKind::Ret(Some(ref expr)) => match fetch_bool_expr(expr) {
294             Expression::Bool(value) => Expression::RetBool(value),
295             _ => Expression::Other,
296         },
297         _ => Expression::Other,
298     }
299 }