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