1 //! Checks for needless boolean results of if-else expressions
3 //! This lint is **warn** by default
5 use crate::utils::sugg::Sugg;
6 use crate::utils::{higher, parent_node_is_if_expr, span_lint, span_lint_and_sugg};
7 use rustc_ast::ast::LitKind;
8 use rustc_errors::Applicability;
9 use rustc_hir::{BinOpKind, Block, Expr, ExprKind, StmtKind};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Spanned;
14 declare_clippy_lint! {
15 /// **What it does:** Checks for expressions of the form `if c { true } else {
17 /// (or vice versa) and suggest using the condition directly.
19 /// **Why is this bad?** Redundant code.
21 /// **Known problems:** Maybe false positives: Sometimes, the two branches are
22 /// painstakingly documented (which we, of course, do not detect), so they *may*
23 /// have some value. Even then, the documentation can be rewritten to match the
34 /// Could be written as
40 "if-statements with plain booleans in the then- and else-clause, e.g., `if p { true } else { false }`"
43 declare_clippy_lint! {
44 /// **What it does:** Checks for expressions of the form `x == true`,
45 /// `x != true` and order comparisons such as `x < true` (or vice versa) and
46 /// suggest using the variable directly.
48 /// **Why is this bad?** Unnecessary code.
50 /// **Known problems:** None.
64 "comparing a variable to a boolean, e.g., `if x == true` or `if x != true`"
67 declare_lint_pass!(NeedlessBool => [NEEDLESS_BOOL]);
69 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
70 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
71 use self::Expression::{Bool, RetBool};
72 if let Some((ref pred, ref then_block, Some(ref else_expr))) = higher::if_block(&e) {
73 let reduce = |ret, not| {
74 let mut applicability = Applicability::MachineApplicable;
75 let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
76 let mut snip = if not { !snip } else { snip };
79 snip = snip.make_return();
82 if parent_node_is_if_expr(&e, &cx) {
83 snip = snip.blockify()
90 "this if-then-else expression returns a bool literal",
91 "you can reduce it to",
96 if let ExprKind::Block(ref then_block, _) = then_block.kind {
97 match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
98 (RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
103 "this if-then-else expression will always return true",
106 (RetBool(false), RetBool(false)) | (Bool(false), Bool(false)) => {
111 "this if-then-else expression will always return false",
114 (RetBool(true), RetBool(false)) => reduce(true, false),
115 (Bool(true), Bool(false)) => reduce(false, false),
116 (RetBool(false), RetBool(true)) => reduce(true, true),
117 (Bool(false), Bool(true)) => reduce(false, true),
121 panic!("IfExpr `then` node is not an `ExprKind::Block`");
127 declare_lint_pass!(BoolComparison => [BOOL_COMPARISON]);
129 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoolComparison {
130 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
131 if e.span.from_expansion() {
135 if let ExprKind::Binary(Spanned { node, .. }, ..) = e.kind {
136 let ignore_case = None::<(fn(_) -> _, &str)>;
137 let ignore_no_literal = None::<(fn(_, _) -> _, &str)>;
140 let true_case = Some((|h| h, "equality checks against true are unnecessary"));
141 let false_case = Some((
143 "equality checks against false can be replaced by a negation",
145 check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
148 let true_case = Some((
150 "inequality checks against true can be replaced by a negation",
152 let false_case = Some((|h| h, "inequality checks against false are unnecessary"));
153 check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
155 BinOpKind::Lt => check_comparison(
159 Some((|h| h, "greater than checks against false are unnecessary")),
162 "less than comparison against true can be replaced by a negation",
166 |l: Sugg<'_>, r: Sugg<'_>| (!l).bit_and(&r),
167 "order comparisons between booleans can be simplified",
170 BinOpKind::Gt => check_comparison(
175 "less than comparison against true can be replaced by a negation",
179 Some((|h| h, "greater than checks against false are unnecessary")),
181 |l: Sugg<'_>, r: Sugg<'_>| l.bit_and(&(!r)),
182 "order comparisons between booleans can be simplified",
191 fn check_comparison<'a, 'tcx>(
192 cx: &LateContext<'a, 'tcx>,
194 left_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
195 left_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
196 right_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
197 right_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
198 no_literal: Option<(impl FnOnce(Sugg<'a>, Sugg<'a>) -> Sugg<'a>, &str)>,
200 use self::Expression::{Bool, Other};
202 if let ExprKind::Binary(_, ref left_side, ref right_side) = e.kind {
203 let (l_ty, r_ty) = (cx.tables.expr_ty(left_side), cx.tables.expr_ty(right_side));
204 if l_ty.is_bool() && r_ty.is_bool() {
205 let mut applicability = Applicability::MachineApplicable;
206 match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
207 (Bool(true), Other) => left_true.map_or((), |(h, m)| {
208 suggest_bool_comparison(cx, e, right_side, applicability, m, h)
210 (Other, Bool(true)) => right_true.map_or((), |(h, m)| {
211 suggest_bool_comparison(cx, e, left_side, applicability, m, h)
213 (Bool(false), Other) => left_false.map_or((), |(h, m)| {
214 suggest_bool_comparison(cx, e, right_side, applicability, m, h)
216 (Other, Bool(false)) => right_false.map_or((), |(h, m)| {
217 suggest_bool_comparison(cx, e, left_side, applicability, m, h)
219 (Other, Other) => no_literal.map_or((), |(h, m)| {
220 let left_side = Sugg::hir_with_applicability(cx, left_side, "..", &mut applicability);
221 let right_side = Sugg::hir_with_applicability(cx, right_side, "..", &mut applicability);
227 "try simplifying it as shown",
228 h(left_side, right_side).to_string(),
238 fn suggest_bool_comparison<'a, 'tcx>(
239 cx: &LateContext<'a, 'tcx>,
242 mut applicability: Applicability,
244 conv_hint: impl FnOnce(Sugg<'a>) -> Sugg<'a>,
246 let hint = Sugg::hir_with_applicability(cx, expr, "..", &mut applicability);
252 "try simplifying it as shown",
253 conv_hint(hint).to_string(),
264 fn fetch_bool_block(block: &Block<'_>) -> Expression {
265 match (&*block.stmts, block.expr.as_ref()) {
266 (&[], Some(e)) => fetch_bool_expr(&**e),
267 (&[ref e], None) => {
268 if let StmtKind::Semi(ref e) = e.kind {
269 if let ExprKind::Ret(_) = e.kind {
270 fetch_bool_expr(&**e)
278 _ => Expression::Other,
282 fn fetch_bool_expr(expr: &Expr<'_>) -> Expression {
284 ExprKind::Block(ref block, _) => fetch_bool_block(block),
285 ExprKind::Lit(ref lit_ptr) => {
286 if let LitKind::Bool(value) = lit_ptr.node {
287 Expression::Bool(value)
292 ExprKind::Ret(Some(ref expr)) => match fetch_bool_expr(expr) {
293 Expression::Bool(value) => Expression::RetBool(value),
294 _ => Expression::Other,
296 _ => Expression::Other,