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