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::{in_macro, span_lint, span_lint_and_sugg};
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
9 use rustc::{declare_tool_lint, lint_array};
10 use rustc_errors::Applicability;
11 use syntax::ast::LitKind;
12 use syntax::source_map::Spanned;
14 /// **What it does:** Checks for expressions of the form `if c { true } else {
16 /// (or vice versa) and suggest using the condition directly.
18 /// **Why is this bad?** Redundant code.
20 /// **Known problems:** Maybe false positives: Sometimes, the two branches are
21 /// painstakingly documented (which we of course do not detect), so they *may*
22 /// have some value. Even then, the documentation can be rewritten to match the
33 declare_clippy_lint! {
36 "if-statements with plain booleans in the then- and else-clause, e.g. `if p { true } else { false }`"
39 /// **What it does:** Checks for expressions of the form `x == true`,
40 /// `x != true` and order comparisons such as `x < true` (or vice versa) and
41 /// suggest using the variable directly.
43 /// **Why is this bad?** Unnecessary code.
45 /// **Known problems:** None.
49 /// if x == true {} // could be `if x { }`
51 declare_clippy_lint! {
54 "comparing a variable to a boolean, e.g. `if x == true` or `if x != true`"
57 #[derive(Copy, Clone)]
58 pub struct NeedlessBool;
60 impl LintPass for NeedlessBool {
61 fn get_lints(&self) -> LintArray {
62 lint_array!(NEEDLESS_BOOL)
66 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
67 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
68 use self::Expression::*;
69 if let ExprKind::If(ref pred, ref then_block, Some(ref else_expr)) = e.node {
70 let reduce = |ret, not| {
71 let mut applicability = Applicability::MachineApplicable;
72 let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
73 let snip = if not { !snip } else { snip };
75 let mut hint = if ret {
76 format!("return {}", snip)
81 if parent_node_is_if_expr(&e, &cx) {
82 hint = format!("{{ {} }}", hint);
89 "this if-then-else expression returns a bool literal",
90 "you can reduce it to",
95 if let ExprKind::Block(ref then_block, _) = then_block.node {
96 match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
97 (RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
102 "this if-then-else expression will always return true",
105 (RetBool(false), RetBool(false)) | (Bool(false), Bool(false)) => {
110 "this if-then-else expression will always return false",
113 (RetBool(true), RetBool(false)) => reduce(true, false),
114 (Bool(true), Bool(false)) => reduce(false, false),
115 (RetBool(false), RetBool(true)) => reduce(true, true),
116 (Bool(false), Bool(true)) => reduce(false, true),
120 panic!("IfExpr 'then' node is not an ExprKind::Block");
126 fn parent_node_is_if_expr<'a, 'b>(expr: &Expr, cx: &LateContext<'a, 'b>) -> bool {
127 let parent_id = cx.tcx.hir().get_parent_node(expr.id);
128 let parent_node = cx.tcx.hir().get(parent_id);
130 if let rustc::hir::Node::Expr(e) = parent_node {
131 if let ExprKind::If(_, _, _) = e.node {
139 #[derive(Copy, Clone)]
140 pub struct BoolComparison;
142 impl LintPass for BoolComparison {
143 fn get_lints(&self) -> LintArray {
144 lint_array!(BOOL_COMPARISON)
148 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoolComparison {
149 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
150 if in_macro(e.span) {
154 if let ExprKind::Binary(Spanned { node, .. }, ..) = e.node {
155 let ignore_case = None::<(fn(_) -> _, &str)>;
156 let ignore_no_literal = None::<(fn(_, _) -> _, &str)>;
159 let true_case = Some((|h| h, "equality checks against true are unnecessary"));
160 let false_case = Some((
162 "equality checks against false can be replaced by a negation",
164 check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
167 let true_case = Some((
169 "inequality checks against true can be replaced by a negation",
171 let false_case = Some((|h| h, "inequality checks against false are unnecessary"));
172 check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
174 BinOpKind::Lt => check_comparison(
178 Some((|h| h, "greater than checks against false are unnecessary")),
181 "less than comparison against true can be replaced by a negation",
185 |l: Sugg<'_>, r: Sugg<'_>| (!l).bit_and(&r),
186 "order comparisons between booleans can be simplified",
189 BinOpKind::Gt => check_comparison(
194 "less than comparison against true can be replaced by a negation",
198 Some((|h| h, "greater than checks against false are unnecessary")),
200 |l: Sugg<'_>, r: Sugg<'_>| l.bit_and(&(!r)),
201 "order comparisons between booleans can be simplified",
210 fn check_comparison<'a, 'tcx>(
211 cx: &LateContext<'a, 'tcx>,
213 left_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
214 left_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
215 right_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
216 right_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
217 no_literal: Option<(impl FnOnce(Sugg<'a>, Sugg<'a>) -> Sugg<'a>, &str)>,
219 use self::Expression::*;
221 if let ExprKind::Binary(_, ref left_side, ref right_side) = e.node {
222 let mut applicability = Applicability::MachineApplicable;
223 match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
224 (Bool(true), Other) => left_true.map_or((), |(h, m)| {
225 suggest_bool_comparison(cx, e, right_side, applicability, m, h)
227 (Other, Bool(true)) => right_true.map_or((), |(h, m)| {
228 suggest_bool_comparison(cx, e, left_side, applicability, m, h)
230 (Bool(false), Other) => left_false.map_or((), |(h, m)| {
231 suggest_bool_comparison(cx, e, right_side, applicability, m, h)
233 (Other, Bool(false)) => right_false.map_or((), |(h, m)| {
234 suggest_bool_comparison(cx, e, left_side, applicability, m, h)
236 (Other, Other) => no_literal.map_or((), |(h, m)| {
237 let (l_ty, r_ty) = (cx.tables.expr_ty(left_side), cx.tables.expr_ty(right_side));
238 if l_ty.is_bool() && r_ty.is_bool() {
239 let left_side = Sugg::hir_with_applicability(cx, left_side, "..", &mut applicability);
240 let right_side = Sugg::hir_with_applicability(cx, right_side, "..", &mut applicability);
246 "try simplifying it as shown",
247 h(left_side, right_side).to_string(),
257 fn suggest_bool_comparison<'a, 'tcx>(
258 cx: &LateContext<'a, 'tcx>,
261 mut applicability: Applicability,
263 conv_hint: impl FnOnce(Sugg<'a>) -> Sugg<'a>,
265 let hint = Sugg::hir_with_applicability(cx, expr, "..", &mut applicability);
271 "try simplifying it as shown",
272 conv_hint(hint).to_string(),
283 fn fetch_bool_block(block: &Block) -> Expression {
284 match (&*block.stmts, block.expr.as_ref()) {
285 (&[], Some(e)) => fetch_bool_expr(&**e),
286 (&[ref e], None) => {
287 if let StmtKind::Semi(ref e) = e.node {
288 if let ExprKind::Ret(_) = e.node {
289 fetch_bool_expr(&**e)
297 _ => Expression::Other,
301 fn fetch_bool_expr(expr: &Expr) -> Expression {
303 ExprKind::Block(ref block, _) => fetch_bool_block(block),
304 ExprKind::Lit(ref lit_ptr) => {
305 if let LitKind::Bool(value) = lit_ptr.node {
306 Expression::Bool(value)
311 ExprKind::Ret(Some(ref expr)) => match fetch_bool_expr(expr) {
312 Expression::Bool(value) => Expression::RetBool(value),
313 _ => Expression::Other,
315 _ => Expression::Other,