]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/needless_bool.rs
Use `summary_opts()` in another spot
[rust.git] / src / tools / clippy / 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::{
7     higher, is_expn_of, parent_node_is_if_expr, snippet_with_applicability, span_lint, span_lint_and_sugg,
8 };
9 use if_chain::if_chain;
10 use rustc_ast::ast::LitKind;
11 use rustc_errors::Applicability;
12 use rustc_hir::{BinOpKind, Block, Expr, ExprKind, StmtKind, UnOp};
13 use rustc_lint::{LateContext, LateLintPass};
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::source_map::Spanned;
16 use rustc_span::Span;
17
18 declare_clippy_lint! {
19     /// **What it does:** Checks for expressions of the form `if c { true } else {
20     /// false }` (or vice versa) and suggests using the condition directly.
21     ///
22     /// **Why is this bad?** Redundant code.
23     ///
24     /// **Known problems:** Maybe false positives: Sometimes, the two branches are
25     /// painstakingly documented (which we, of course, do not detect), so they *may*
26     /// have some value. Even then, the documentation can be rewritten to match the
27     /// shorter code.
28     ///
29     /// **Example:**
30     /// ```rust,ignore
31     /// if x {
32     ///     false
33     /// } else {
34     ///     true
35     /// }
36     /// ```
37     /// Could be written as
38     /// ```rust,ignore
39     /// !x
40     /// ```
41     pub NEEDLESS_BOOL,
42     complexity,
43     "if-statements with plain booleans in the then- and else-clause, e.g., `if p { true } else { false }`"
44 }
45
46 declare_clippy_lint! {
47     /// **What it does:** Checks for expressions of the form `x == true`,
48     /// `x != true` and order comparisons such as `x < true` (or vice versa) and
49     /// suggest using the variable directly.
50     ///
51     /// **Why is this bad?** Unnecessary code.
52     ///
53     /// **Known problems:** None.
54     ///
55     /// **Example:**
56     /// ```rust,ignore
57     /// if x == true {}
58     /// if y == false {}
59     /// ```
60     /// use `x` directly:
61     /// ```rust,ignore
62     /// if x {}
63     /// if !y {}
64     /// ```
65     pub BOOL_COMPARISON,
66     complexity,
67     "comparing a variable to a boolean, e.g., `if x == true` or `if x != true`"
68 }
69
70 declare_lint_pass!(NeedlessBool => [NEEDLESS_BOOL]);
71
72 impl<'tcx> LateLintPass<'tcx> for NeedlessBool {
73     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
74         use self::Expression::{Bool, RetBool};
75         if let Some((ref pred, ref then_block, Some(ref else_expr))) = higher::if_block(&e) {
76             let reduce = |ret, not| {
77                 let mut applicability = Applicability::MachineApplicable;
78                 let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
79                 let mut snip = if not { !snip } else { snip };
80
81                 if ret {
82                     snip = snip.make_return();
83                 }
84
85                 if parent_node_is_if_expr(&e, &cx) {
86                     snip = snip.blockify()
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                     snip.to_string(),
96                     applicability,
97                 );
98             };
99             if let ExprKind::Block(ref then_block, _) = then_block.kind {
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 declare_lint_pass!(BoolComparison => [BOOL_COMPARISON]);
131
132 impl<'tcx> LateLintPass<'tcx> for BoolComparison {
133     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
134         if e.span.from_expansion() {
135             return;
136         }
137
138         if let ExprKind::Binary(Spanned { node, .. }, ..) = e.kind {
139             let ignore_case = None::<(fn(_) -> _, &str)>;
140             let ignore_no_literal = None::<(fn(_, _) -> _, &str)>;
141             match node {
142                 BinOpKind::Eq => {
143                     let true_case = Some((|h| h, "equality checks against true are unnecessary"));
144                     let false_case = Some((
145                         |h: Sugg<'_>| !h,
146                         "equality checks against false can be replaced by a negation",
147                     ));
148                     check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
149                 },
150                 BinOpKind::Ne => {
151                     let true_case = Some((
152                         |h: Sugg<'_>| !h,
153                         "inequality checks against true can be replaced by a negation",
154                     ));
155                     let false_case = Some((|h| h, "inequality checks against false are unnecessary"));
156                     check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
157                 },
158                 BinOpKind::Lt => check_comparison(
159                     cx,
160                     e,
161                     ignore_case,
162                     Some((|h| h, "greater than checks against false are unnecessary")),
163                     Some((
164                         |h: Sugg<'_>| !h,
165                         "less than comparison against true can be replaced by a negation",
166                     )),
167                     ignore_case,
168                     Some((
169                         |l: Sugg<'_>, r: Sugg<'_>| (!l).bit_and(&r),
170                         "order comparisons between booleans can be simplified",
171                     )),
172                 ),
173                 BinOpKind::Gt => check_comparison(
174                     cx,
175                     e,
176                     Some((
177                         |h: Sugg<'_>| !h,
178                         "less than comparison against true can be replaced by a negation",
179                     )),
180                     ignore_case,
181                     ignore_case,
182                     Some((|h| h, "greater than checks against false are unnecessary")),
183                     Some((
184                         |l: Sugg<'_>, r: Sugg<'_>| l.bit_and(&(!r)),
185                         "order comparisons between booleans can be simplified",
186                     )),
187                 ),
188                 _ => (),
189             }
190         }
191     }
192 }
193
194 struct ExpressionInfoWithSpan {
195     one_side_is_unary_not: bool,
196     left_span: Span,
197     right_span: Span,
198 }
199
200 fn is_unary_not(e: &Expr<'_>) -> (bool, Span) {
201     if_chain! {
202         if let ExprKind::Unary(unop, operand) = e.kind;
203         if let UnOp::UnNot = unop;
204         then {
205             return (true, operand.span);
206         }
207     };
208     (false, e.span)
209 }
210
211 fn one_side_is_unary_not<'tcx>(left_side: &'tcx Expr<'_>, right_side: &'tcx Expr<'_>) -> ExpressionInfoWithSpan {
212     let left = is_unary_not(left_side);
213     let right = is_unary_not(right_side);
214
215     ExpressionInfoWithSpan {
216         one_side_is_unary_not: left.0 != right.0,
217         left_span: left.1,
218         right_span: right.1,
219     }
220 }
221
222 fn check_comparison<'a, 'tcx>(
223     cx: &LateContext<'tcx>,
224     e: &'tcx Expr<'_>,
225     left_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
226     left_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
227     right_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
228     right_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
229     no_literal: Option<(impl FnOnce(Sugg<'a>, Sugg<'a>) -> Sugg<'a>, &str)>,
230 ) {
231     use self::Expression::{Bool, Other};
232
233     if let ExprKind::Binary(op, ref left_side, ref right_side) = e.kind {
234         let (l_ty, r_ty) = (
235             cx.typeck_results().expr_ty(left_side),
236             cx.typeck_results().expr_ty(right_side),
237         );
238         if is_expn_of(left_side.span, "cfg").is_some() || is_expn_of(right_side.span, "cfg").is_some() {
239             return;
240         }
241         if l_ty.is_bool() && r_ty.is_bool() {
242             let mut applicability = Applicability::MachineApplicable;
243
244             if let BinOpKind::Eq = op.node {
245                 let expression_info = one_side_is_unary_not(&left_side, &right_side);
246                 if expression_info.one_side_is_unary_not {
247                     span_lint_and_sugg(
248                         cx,
249                         BOOL_COMPARISON,
250                         e.span,
251                         "this comparison might be written more concisely",
252                         "try simplifying it as shown",
253                         format!(
254                             "{} != {}",
255                             snippet_with_applicability(cx, expression_info.left_span, "..", &mut applicability),
256                             snippet_with_applicability(cx, expression_info.right_span, "..", &mut applicability)
257                         ),
258                         applicability,
259                     )
260                 }
261             }
262
263             match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
264                 (Bool(true), Other) => left_true.map_or((), |(h, m)| {
265                     suggest_bool_comparison(cx, e, right_side, applicability, m, h)
266                 }),
267                 (Other, Bool(true)) => right_true.map_or((), |(h, m)| {
268                     suggest_bool_comparison(cx, e, left_side, applicability, m, h)
269                 }),
270                 (Bool(false), Other) => left_false.map_or((), |(h, m)| {
271                     suggest_bool_comparison(cx, e, right_side, applicability, m, h)
272                 }),
273                 (Other, Bool(false)) => right_false.map_or((), |(h, m)| {
274                     suggest_bool_comparison(cx, e, left_side, applicability, m, h)
275                 }),
276                 (Other, Other) => no_literal.map_or((), |(h, m)| {
277                     let left_side = Sugg::hir_with_applicability(cx, left_side, "..", &mut applicability);
278                     let right_side = Sugg::hir_with_applicability(cx, right_side, "..", &mut applicability);
279                     span_lint_and_sugg(
280                         cx,
281                         BOOL_COMPARISON,
282                         e.span,
283                         m,
284                         "try simplifying it as shown",
285                         h(left_side, right_side).to_string(),
286                         applicability,
287                     )
288                 }),
289                 _ => (),
290             }
291         }
292     }
293 }
294
295 fn suggest_bool_comparison<'a, 'tcx>(
296     cx: &LateContext<'tcx>,
297     e: &'tcx Expr<'_>,
298     expr: &Expr<'_>,
299     mut applicability: Applicability,
300     message: &str,
301     conv_hint: impl FnOnce(Sugg<'a>) -> Sugg<'a>,
302 ) {
303     let hint = if expr.span.from_expansion() {
304         if applicability != Applicability::Unspecified {
305             applicability = Applicability::MaybeIncorrect;
306         }
307         Sugg::hir_with_macro_callsite(cx, expr, "..")
308     } else {
309         Sugg::hir_with_applicability(cx, expr, "..", &mut applicability)
310     };
311     span_lint_and_sugg(
312         cx,
313         BOOL_COMPARISON,
314         e.span,
315         message,
316         "try simplifying it as shown",
317         conv_hint(hint).to_string(),
318         applicability,
319     );
320 }
321
322 enum Expression {
323     Bool(bool),
324     RetBool(bool),
325     Other,
326 }
327
328 fn fetch_bool_block(block: &Block<'_>) -> Expression {
329     match (&*block.stmts, block.expr.as_ref()) {
330         (&[], Some(e)) => fetch_bool_expr(&**e),
331         (&[ref e], None) => {
332             if let StmtKind::Semi(ref e) = e.kind {
333                 if let ExprKind::Ret(_) = e.kind {
334                     fetch_bool_expr(&**e)
335                 } else {
336                     Expression::Other
337                 }
338             } else {
339                 Expression::Other
340             }
341         },
342         _ => Expression::Other,
343     }
344 }
345
346 fn fetch_bool_expr(expr: &Expr<'_>) -> Expression {
347     match expr.kind {
348         ExprKind::Block(ref block, _) => fetch_bool_block(block),
349         ExprKind::Lit(ref lit_ptr) => {
350             if let LitKind::Bool(value) = lit_ptr.node {
351                 Expression::Bool(value)
352             } else {
353                 Expression::Other
354             }
355         },
356         ExprKind::Ret(Some(ref expr)) => match fetch_bool_expr(expr) {
357             Expression::Bool(value) => Expression::RetBool(value),
358             _ => Expression::Other,
359         },
360         _ => Expression::Other,
361     }
362 }