1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
2 use clippy_utils::source::snippet_opt;
3 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
4 use clippy_utils::{eq_expr_value, get_trait_def_id, paths};
5 use if_chain::if_chain;
6 use rustc_ast::ast::LitKind;
7 use rustc_errors::Applicability;
8 use rustc_hir::intravisit::{walk_expr, FnKind, Visitor};
9 use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, UnOp};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Span;
15 declare_clippy_lint! {
17 /// Checks for boolean expressions that can be written more
20 /// ### Why is this bad?
21 /// Readability of boolean expressions suffers from
22 /// unnecessary duplication.
24 /// ### Known problems
25 /// Ignores short circuiting behavior of `||` and
26 /// `&&`. Ignores `|`, `&` and `^`.
39 #[clippy::version = "pre 1.29.0"]
42 "boolean expressions that can be written more concisely"
45 declare_clippy_lint! {
47 /// Checks for boolean expressions that contain terminals that
48 /// can be eliminated.
50 /// ### Why is this bad?
51 /// This is most likely a logic bug.
53 /// ### Known problems
54 /// Ignores short circuiting behavior.
58 /// // The `b` is unnecessary, the expression is equivalent to `if a`.
59 /// if a && b || a { ... }
66 #[clippy::version = "pre 1.29.0"]
69 "boolean expressions that contain terminals which can be eliminated"
72 // For each pairs, both orders are considered.
73 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
75 declare_lint_pass!(NonminimalBool => [NONMINIMAL_BOOL, LOGIC_BUG]);
77 impl<'tcx> LateLintPass<'tcx> for NonminimalBool {
80 cx: &LateContext<'tcx>,
87 NonminimalBoolVisitor { cx }.visit_body(body);
91 struct NonminimalBoolVisitor<'a, 'tcx> {
92 cx: &'a LateContext<'tcx>,
95 use quine_mc_cluskey::Bool;
96 struct Hir2Qmm<'a, 'tcx, 'v> {
97 terminals: Vec<&'v Expr<'v>>,
98 cx: &'a LateContext<'tcx>,
101 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
102 fn extract(&mut self, op: BinOpKind, a: &[&'v Expr<'_>], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
104 if let ExprKind::Binary(binop, lhs, rhs) = &a.kind {
105 if binop.node == op {
106 v = self.extract(op, &[lhs, rhs], v)?;
110 v.push(self.run(a)?);
115 fn run(&mut self, e: &'v Expr<'_>) -> Result<Bool, String> {
116 fn negate(bin_op_kind: BinOpKind) -> Option<BinOpKind> {
118 BinOpKind::Eq => Some(BinOpKind::Ne),
119 BinOpKind::Ne => Some(BinOpKind::Eq),
120 BinOpKind::Gt => Some(BinOpKind::Le),
121 BinOpKind::Ge => Some(BinOpKind::Lt),
122 BinOpKind::Lt => Some(BinOpKind::Ge),
123 BinOpKind::Le => Some(BinOpKind::Gt),
128 // prevent folding of `cfg!` macros and the like
129 if !e.span.from_expansion() {
131 ExprKind::Unary(UnOp::Not, inner) => return Ok(Bool::Not(Box::new(self.run(inner)?))),
132 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
134 return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?));
137 return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?));
141 ExprKind::Lit(lit) => match lit.node {
142 LitKind::Bool(true) => return Ok(Bool::True),
143 LitKind::Bool(false) => return Ok(Bool::False),
149 for (n, expr) in self.terminals.iter().enumerate() {
150 if eq_expr_value(self.cx, e, expr) {
151 #[expect(clippy::cast_possible_truncation)]
152 return Ok(Bool::Term(n as u8));
156 if let ExprKind::Binary(e_binop, e_lhs, e_rhs) = &e.kind;
157 if implements_ord(self.cx, e_lhs);
158 if let ExprKind::Binary(expr_binop, expr_lhs, expr_rhs) = &expr.kind;
159 if negate(e_binop.node) == Some(expr_binop.node);
160 if eq_expr_value(self.cx, e_lhs, expr_lhs);
161 if eq_expr_value(self.cx, e_rhs, expr_rhs);
163 #[expect(clippy::cast_possible_truncation)]
164 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
168 let n = self.terminals.len();
169 self.terminals.push(e);
171 #[expect(clippy::cast_possible_truncation)]
172 Ok(Bool::Term(n as u8))
174 Err("too many literals".to_owned())
179 struct SuggestContext<'a, 'tcx, 'v> {
180 terminals: &'v [&'v Expr<'v>],
181 cx: &'a LateContext<'tcx>,
185 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
186 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
187 use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
190 self.output.push_str("true");
193 self.output.push_str("false");
195 Not(inner) => match **inner {
197 self.output.push('!');
198 self.output.push('(');
200 self.output.push(')');
203 let terminal = self.terminals[n as usize];
204 if let Some(str) = simplify_not(self.cx, terminal) {
205 self.output.push_str(&str);
207 self.output.push('!');
208 let snip = snippet_opt(self.cx, terminal.span)?;
209 self.output.push_str(&snip);
212 True | False | Not(_) => {
213 self.output.push('!');
214 self.recurse(inner)?;
218 for (index, inner) in v.iter().enumerate() {
220 self.output.push_str(" && ");
222 if let Or(_) = *inner {
223 self.output.push('(');
225 self.output.push(')');
232 for (index, inner) in v.iter().rev().enumerate() {
234 self.output.push_str(" || ");
240 let snip = snippet_opt(self.cx, self.terminals[n as usize].span)?;
241 self.output.push_str(&snip);
248 fn simplify_not(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<String> {
250 ExprKind::Binary(binop, lhs, rhs) => {
251 if !implements_ord(cx, lhs) {
256 BinOpKind::Eq => Some(" != "),
257 BinOpKind::Ne => Some(" == "),
258 BinOpKind::Lt => Some(" >= "),
259 BinOpKind::Gt => Some(" <= "),
260 BinOpKind::Le => Some(" > "),
261 BinOpKind::Ge => Some(" < "),
267 snippet_opt(cx, lhs.span)?,
269 snippet_opt(cx, rhs.span)?
273 ExprKind::MethodCall(path, args, _) if args.len() == 1 => {
274 let type_of_receiver = cx.typeck_results().expr_ty(&args[0]);
275 if !is_type_diagnostic_item(cx, type_of_receiver, sym::Option)
276 && !is_type_diagnostic_item(cx, type_of_receiver, sym::Result)
280 METHODS_WITH_NEGATION
283 .flat_map(|(a, b)| vec![(a, b), (b, a)])
285 let path: &str = path.ident.name.as_str();
288 .and_then(|(_, neg_method)| Some(format!("{}.{}()", snippet_opt(cx, args[0].span)?, neg_method)))
294 fn suggest(cx: &LateContext<'_>, suggestion: &Bool, terminals: &[&Expr<'_>]) -> String {
295 let mut suggest_context = SuggestContext {
298 output: String::new(),
300 suggest_context.recurse(suggestion);
301 suggest_context.output
304 fn simple_negate(b: Bool) -> Bool {
305 use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
309 t @ Term(_) => Not(Box::new(t)),
312 *el = simple_negate(::std::mem::replace(el, True));
318 *el = simple_negate(::std::mem::replace(el, True));
322 Not(inner) => *inner,
328 terminals: [usize; 32],
333 fn terminal_stats(b: &Bool) -> Stats {
334 fn recurse(b: &Bool, stats: &mut Stats) {
336 True | False => stats.ops += 1,
339 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
340 _ => stats.negations += 1,
342 recurse(inner, stats);
345 stats.ops += v.len() - 1;
347 recurse(inner, stats);
350 &Term(n) => stats.terminals[n as usize] += 1,
353 use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
354 let mut stats = Stats::default();
355 recurse(b, &mut stats);
359 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
360 fn bool_expr(&self, e: &'tcx Expr<'_>) {
361 let mut h2q = Hir2Qmm {
362 terminals: Vec::new(),
365 if let Ok(expr) = h2q.run(e) {
366 if h2q.terminals.len() > 8 {
367 // QMC has exponentially slow behavior as the number of terminals increases
368 // 8 is reasonable, it takes approximately 0.2 seconds.
373 let stats = terminal_stats(&expr);
374 let mut simplified = expr.simplify();
375 for simple in Bool::Not(Box::new(expr)).simplify() {
377 Bool::Not(_) | Bool::True | Bool::False => {},
378 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
380 let simple_negated = simple_negate(simple);
381 if simplified.iter().any(|s| *s == simple_negated) {
384 simplified.push(simple_negated);
386 let mut improvements = Vec::with_capacity(simplified.len());
387 'simplified: for suggestion in &simplified {
388 let simplified_stats = terminal_stats(suggestion);
389 let mut improvement = false;
391 // ignore any "simplifications" that end up requiring a terminal more often
392 // than in the original expression
393 if stats.terminals[i] < simplified_stats.terminals[i] {
394 continue 'simplified;
396 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
401 "this boolean expression contains a logic bug",
404 h2q.terminals[i].span,
405 "this expression can be optimized out by applying boolean operations to the \
408 diag.span_suggestion(
410 "it would look like the following",
411 suggest(self.cx, suggestion, &h2q.terminals),
412 // nonminimal_bool can produce minimal but
413 // not human readable expressions (#3141)
414 Applicability::Unspecified,
418 // don't also lint `NONMINIMAL_BOOL`
421 // if the number of occurrences of a terminal decreases or any of the stats
422 // decreases while none increases
423 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
424 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
425 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
428 improvements.push(suggestion);
431 let nonminimal_bool_lint = |suggestions: Vec<_>| {
436 "this boolean expression can be simplified",
438 diag.span_suggestions(
441 suggestions.into_iter(),
442 // nonminimal_bool can produce minimal but
443 // not human readable expressions (#3141)
444 Applicability::Unspecified,
449 if improvements.is_empty() {
450 let mut visitor = NotSimplificationVisitor { cx: self.cx };
451 visitor.visit_expr(e);
453 nonminimal_bool_lint(
456 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
464 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
465 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
466 if !e.span.from_expansion() {
468 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
471 ExprKind::Unary(UnOp::Not, inner) => {
472 if self.cx.typeck_results().node_types()[inner.hir_id].is_bool() {
483 fn implements_ord<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
484 let ty = cx.typeck_results().expr_ty(expr);
485 get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))
488 struct NotSimplificationVisitor<'a, 'tcx> {
489 cx: &'a LateContext<'tcx>,
492 impl<'a, 'tcx> Visitor<'tcx> for NotSimplificationVisitor<'a, 'tcx> {
493 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
494 if let ExprKind::Unary(UnOp::Not, inner) = &expr.kind {
495 if let Some(suggestion) = simplify_not(self.cx, inner) {
500 "this boolean expression can be simplified",
503 Applicability::MachineApplicable,
508 walk_expr(self, expr);