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