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
40 /// Could be written as
44 #[clippy::version = "pre 1.29.0"]
47 "if-statements with plain booleans in the then- and else-clause, e.g., `if p { true } else { false }`"
50 declare_clippy_lint! {
52 /// Checks for expressions of the form `x == true`,
53 /// `x != true` and order comparisons such as `x < true` (or vice versa) and
54 /// suggest using the variable directly.
56 /// ### Why is this bad?
69 #[clippy::version = "pre 1.29.0"]
72 "comparing a variable to a boolean, e.g., `if x == true` or `if x != true`"
75 declare_lint_pass!(NeedlessBool => [NEEDLESS_BOOL]);
77 fn condition_needs_parentheses(e: &Expr<'_>) -> bool {
79 while let ExprKind::Binary(_, i, _)
80 | ExprKind::Call(i, _)
81 | ExprKind::Cast(i, _)
82 | ExprKind::Type(i, _)
83 | ExprKind::Index(i, _) = inner.kind
88 | ExprKind::ConstBlock(..)
100 fn is_parent_stmt(cx: &LateContext<'_>, id: HirId) -> bool {
102 get_parent_node(cx.tcx, id),
103 Some(Node::Stmt(..) | Node::Block(Block { stmts: &[], .. }))
107 impl<'tcx> LateLintPass<'tcx> for NeedlessBool {
108 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
109 use self::Expression::{Bool, RetBool};
110 if e.span.from_expansion() {
113 if let Some(higher::If {
116 r#else: Some(r#else),
117 }) = higher::If::hir(e)
119 let reduce = |ret, not| {
120 let mut applicability = Applicability::MachineApplicable;
121 let snip = Sugg::hir_with_applicability(cx, cond, "<predicate>", &mut applicability);
122 let mut snip = if not { !snip } else { snip };
125 snip = snip.make_return();
128 if is_else_clause(cx.tcx, e) {
129 snip = snip.blockify();
132 if condition_needs_parentheses(cond) && is_parent_stmt(cx, e.hir_id) {
133 snip = snip.maybe_par();
140 "this if-then-else expression returns a bool literal",
141 "you can reduce it to",
146 if let Some((a, b)) = fetch_bool_block(then).and_then(|a| Some((a, fetch_bool_block(r#else)?))) {
148 (RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
153 "this if-then-else expression will always return true",
156 (RetBool(false), RetBool(false)) | (Bool(false), Bool(false)) => {
161 "this if-then-else expression will always return false",
164 (RetBool(true), RetBool(false)) => reduce(true, false),
165 (Bool(true), Bool(false)) => reduce(false, false),
166 (RetBool(false), RetBool(true)) => reduce(true, true),
167 (Bool(false), Bool(true)) => reduce(false, true),
175 declare_lint_pass!(BoolComparison => [BOOL_COMPARISON]);
177 impl<'tcx> LateLintPass<'tcx> for BoolComparison {
178 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
179 if e.span.from_expansion() {
183 if let ExprKind::Binary(Spanned { node, .. }, ..) = e.kind {
184 let ignore_case = None::<(fn(_) -> _, &str)>;
185 let ignore_no_literal = None::<(fn(_, _) -> _, &str)>;
188 let true_case = Some((|h| h, "equality checks against true are unnecessary"));
189 let false_case = Some((
191 "equality checks against false can be replaced by a negation",
193 check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal);
196 let true_case = Some((
198 "inequality checks against true can be replaced by a negation",
200 let false_case = Some((|h| h, "inequality checks against false are unnecessary"));
201 check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal);
203 BinOpKind::Lt => check_comparison(
207 Some((|h| h, "greater than checks against false are unnecessary")),
210 "less than comparison against true can be replaced by a negation",
214 |l: Sugg<'tcx>, r: Sugg<'tcx>| (!l).bit_and(&r),
215 "order comparisons between booleans can be simplified",
218 BinOpKind::Gt => check_comparison(
223 "less than comparison against true can be replaced by a negation",
227 Some((|h| h, "greater than checks against false are unnecessary")),
229 |l: Sugg<'tcx>, r: Sugg<'tcx>| l.bit_and(&(!r)),
230 "order comparisons between booleans can be simplified",
239 struct ExpressionInfoWithSpan {
240 one_side_is_unary_not: bool,
245 fn is_unary_not(e: &Expr<'_>) -> (bool, Span) {
246 if let ExprKind::Unary(UnOp::Not, operand) = e.kind {
247 return (true, operand.span);
252 fn one_side_is_unary_not<'tcx>(left_side: &'tcx Expr<'_>, right_side: &'tcx Expr<'_>) -> ExpressionInfoWithSpan {
253 let left = is_unary_not(left_side);
254 let right = is_unary_not(right_side);
256 ExpressionInfoWithSpan {
257 one_side_is_unary_not: left.0 != right.0,
263 fn check_comparison<'a, 'tcx>(
264 cx: &LateContext<'tcx>,
266 left_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
267 left_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
268 right_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
269 right_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
270 no_literal: Option<(impl FnOnce(Sugg<'a>, Sugg<'a>) -> Sugg<'a>, &str)>,
272 if let ExprKind::Binary(op, left_side, right_side) = e.kind {
274 cx.typeck_results().expr_ty(left_side),
275 cx.typeck_results().expr_ty(right_side),
277 if is_expn_of(left_side.span, "cfg").is_some() || is_expn_of(right_side.span, "cfg").is_some() {
280 if l_ty.is_bool() && r_ty.is_bool() {
281 let mut applicability = Applicability::MachineApplicable;
283 if op.node == BinOpKind::Eq {
284 let expression_info = one_side_is_unary_not(left_side, right_side);
285 if expression_info.one_side_is_unary_not {
290 "this comparison might be written more concisely",
291 "try simplifying it as shown",
294 snippet_with_applicability(cx, expression_info.left_span, "..", &mut applicability),
295 snippet_with_applicability(cx, expression_info.right_span, "..", &mut applicability)
302 match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
303 (Some(true), None) => left_true.map_or((), |(h, m)| {
304 suggest_bool_comparison(cx, e, right_side, applicability, m, h);
306 (None, Some(true)) => right_true.map_or((), |(h, m)| {
307 suggest_bool_comparison(cx, e, left_side, applicability, m, h);
309 (Some(false), None) => left_false.map_or((), |(h, m)| {
310 suggest_bool_comparison(cx, e, right_side, applicability, m, h);
312 (None, Some(false)) => right_false.map_or((), |(h, m)| {
313 suggest_bool_comparison(cx, e, left_side, applicability, m, h);
315 (None, None) => no_literal.map_or((), |(h, m)| {
316 let left_side = Sugg::hir_with_applicability(cx, left_side, "..", &mut applicability);
317 let right_side = Sugg::hir_with_applicability(cx, right_side, "..", &mut applicability);
323 "try simplifying it as shown",
324 h(left_side, right_side).to_string(),
334 fn suggest_bool_comparison<'a, 'tcx>(
335 cx: &LateContext<'tcx>,
338 mut applicability: Applicability,
340 conv_hint: impl FnOnce(Sugg<'a>) -> Sugg<'a>,
342 let hint = if expr.span.from_expansion() {
343 if applicability != Applicability::Unspecified {
344 applicability = Applicability::MaybeIncorrect;
346 Sugg::hir_with_macro_callsite(cx, expr, "..")
348 Sugg::hir_with_applicability(cx, expr, "..", &mut applicability)
355 "try simplifying it as shown",
356 conv_hint(hint).to_string(),
366 fn fetch_bool_block(expr: &Expr<'_>) -> Option<Expression> {
367 match peel_blocks_with_stmt(expr).kind {
368 ExprKind::Ret(Some(ret)) => Some(Expression::RetBool(fetch_bool_expr(ret)?)),
369 _ => Some(Expression::Bool(fetch_bool_expr(expr)?)),
373 fn fetch_bool_expr(expr: &Expr<'_>) -> Option<bool> {
374 if let ExprKind::Lit(ref lit_ptr) = peel_blocks(expr).kind {
375 if let LitKind::Bool(value) = lit_ptr.node {