1 //! Checks for needless boolean results of if-else expressions
3 //! This lint is **warn** by default
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;
18 declare_clippy_lint! {
20 /// Checks for expressions of the form `if c { true } else {
21 /// false }` (or vice versa) and suggests using the condition directly.
23 /// ### Why is this bad?
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
49 #[clippy::version = "pre 1.29.0"]
52 "if-statements with plain booleans in the then- and else-clause, e.g., `if p { true } else { false }`"
55 declare_clippy_lint! {
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.
61 /// ### Why is this bad?
74 #[clippy::version = "pre 1.29.0"]
77 "comparing a variable to a boolean, e.g., `if x == true` or `if x != true`"
80 declare_lint_pass!(NeedlessBool => [NEEDLESS_BOOL]);
82 fn condition_needs_parentheses(e: &Expr<'_>) -> bool {
84 while let ExprKind::Binary(_, i, _)
85 | ExprKind::Call(i, _)
86 | ExprKind::Cast(i, _)
87 | ExprKind::Type(i, _)
88 | ExprKind::Index(i, _) = inner.kind
93 | ExprKind::ConstBlock(..)
105 fn is_parent_stmt(cx: &LateContext<'_>, id: HirId) -> bool {
107 get_parent_node(cx.tcx, id),
108 Some(Node::Stmt(..) | Node::Block(Block { stmts: &[], .. }))
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() {
118 if let Some(higher::If {
121 r#else: Some(r#else),
122 }) = higher::If::hir(e)
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 };
130 snip = snip.make_return();
133 if is_else_clause(cx.tcx, e) {
134 snip = snip.blockify();
137 if condition_needs_parentheses(cond) && is_parent_stmt(cx, e.hir_id) {
138 snip = snip.maybe_par();
145 "this if-then-else expression returns a bool literal",
146 "you can reduce it to",
151 if let Some((a, b)) = fetch_bool_block(then).and_then(|a| Some((a, fetch_bool_block(r#else)?))) {
153 (RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
158 "this if-then-else expression will always return true",
161 (RetBool(false), RetBool(false)) | (Bool(false), Bool(false)) => {
166 "this if-then-else expression will always return false",
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),
180 declare_lint_pass!(BoolComparison => [BOOL_COMPARISON]);
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() {
188 if let ExprKind::Binary(Spanned { node, .. }, ..) = e.kind {
189 let ignore_case = None::<(fn(_) -> _, &str)>;
190 let ignore_no_literal = None::<(fn(_, _) -> _, &str)>;
193 let true_case = Some((|h| h, "equality checks against true are unnecessary"));
194 let false_case = Some((
196 "equality checks against false can be replaced by a negation",
198 check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal);
201 let true_case = Some((
203 "inequality checks against true can be replaced by a negation",
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);
208 BinOpKind::Lt => check_comparison(
212 Some((|h| h, "greater than checks against false are unnecessary")),
215 "less than comparison against true can be replaced by a negation",
219 |l: Sugg<'tcx>, r: Sugg<'tcx>| (!l).bit_and(&r),
220 "order comparisons between booleans can be simplified",
223 BinOpKind::Gt => check_comparison(
228 "less than comparison against true can be replaced by a negation",
232 Some((|h| h, "greater than checks against false are unnecessary")),
234 |l: Sugg<'tcx>, r: Sugg<'tcx>| l.bit_and(&(!r)),
235 "order comparisons between booleans can be simplified",
244 struct ExpressionInfoWithSpan {
245 one_side_is_unary_not: bool,
250 fn is_unary_not(e: &Expr<'_>) -> (bool, Span) {
251 if let ExprKind::Unary(UnOp::Not, operand) = e.kind {
252 return (true, operand.span);
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);
261 ExpressionInfoWithSpan {
262 one_side_is_unary_not: left.0 != right.0,
268 fn check_comparison<'a, 'tcx>(
269 cx: &LateContext<'tcx>,
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)>,
277 if let ExprKind::Binary(op, left_side, right_side) = e.kind {
279 cx.typeck_results().expr_ty(left_side),
280 cx.typeck_results().expr_ty(right_side),
282 if is_expn_of(left_side.span, "cfg").is_some() || is_expn_of(right_side.span, "cfg").is_some() {
285 if l_ty.is_bool() && r_ty.is_bool() {
286 let mut applicability = Applicability::MachineApplicable;
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 {
295 "this comparison might be written more concisely",
296 "try simplifying it as shown",
299 snippet_with_applicability(cx, expression_info.left_span, "..", &mut applicability),
300 snippet_with_applicability(cx, expression_info.right_span, "..", &mut applicability)
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);
311 (None, Some(true)) => right_true.map_or((), |(h, m)| {
312 suggest_bool_comparison(cx, e, left_side, applicability, m, h);
314 (Some(false), None) => left_false.map_or((), |(h, m)| {
315 suggest_bool_comparison(cx, e, right_side, applicability, m, h);
317 (None, Some(false)) => right_false.map_or((), |(h, m)| {
318 suggest_bool_comparison(cx, e, left_side, applicability, m, h);
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);
328 "try simplifying it as shown",
329 h(left_side, right_side).to_string(),
339 fn suggest_bool_comparison<'a, 'tcx>(
340 cx: &LateContext<'tcx>,
343 mut applicability: Applicability,
345 conv_hint: impl FnOnce(Sugg<'a>) -> Sugg<'a>,
347 let hint = if expr.span.from_expansion() {
348 if applicability != Applicability::Unspecified {
349 applicability = Applicability::MaybeIncorrect;
351 Sugg::hir_with_macro_callsite(cx, expr, "..")
353 Sugg::hir_with_applicability(cx, expr, "..", &mut applicability)
360 "try simplifying it as shown",
361 conv_hint(hint).to_string(),
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)?)),
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 {