2 get_trait_def_id, implements_trait, in_macro, is_type_diagnostic_item, paths, snippet_opt, span_lint_and_sugg,
3 span_lint_and_then, SpanlessEq,
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, NestedVisitorMap, Visitor};
9 use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, UnOp};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::hir::map::Map;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::source_map::Span;
15 declare_clippy_lint! {
16 /// **What it does:** Checks for boolean expressions that can be written more
19 /// **Why is this bad?** Readability of boolean expressions suffers from
20 /// unnecessary duplication.
22 /// **Known problems:** Ignores short circuiting behavior of `||` and
23 /// `&&`. Ignores `|`, `&` and `^`.
27 /// if a && true // should be: if a
28 /// if !(a == b) // should be: if a != b
32 "boolean expressions that can be written more concisely"
35 declare_clippy_lint! {
36 /// **What it does:** Checks for boolean expressions that contain terminals that
37 /// can be eliminated.
39 /// **Why is this bad?** This is most likely a logic bug.
41 /// **Known problems:** Ignores short circuiting behavior.
45 /// if a && b || a { ... }
47 /// The `b` is unnecessary, the expression is equivalent to `if a`.
50 "boolean expressions that contain terminals which can be eliminated"
53 // For each pairs, both orders are considered.
54 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
56 declare_lint_pass!(NonminimalBool => [NONMINIMAL_BOOL, LOGIC_BUG]);
58 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
61 cx: &LateContext<'a, 'tcx>,
68 NonminimalBoolVisitor { cx }.visit_body(body)
72 struct NonminimalBoolVisitor<'a, 'tcx> {
73 cx: &'a LateContext<'a, 'tcx>,
76 use quine_mc_cluskey::Bool;
77 struct Hir2Qmm<'a, 'tcx, 'v> {
78 terminals: Vec<&'v Expr<'v>>,
79 cx: &'a LateContext<'a, 'tcx>,
82 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
83 fn extract(&mut self, op: BinOpKind, a: &[&'v Expr<'_>], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
85 if let ExprKind::Binary(binop, lhs, rhs) = &a.kind {
87 v = self.extract(op, &[lhs, rhs], v)?;
96 fn run(&mut self, e: &'v Expr<'_>) -> Result<Bool, String> {
97 fn negate(bin_op_kind: BinOpKind) -> Option<BinOpKind> {
99 BinOpKind::Eq => Some(BinOpKind::Ne),
100 BinOpKind::Ne => Some(BinOpKind::Eq),
101 BinOpKind::Gt => Some(BinOpKind::Le),
102 BinOpKind::Ge => Some(BinOpKind::Lt),
103 BinOpKind::Lt => Some(BinOpKind::Ge),
104 BinOpKind::Le => Some(BinOpKind::Gt),
109 // prevent folding of `cfg!` macros and the like
110 if !e.span.from_expansion() {
112 ExprKind::Unary(UnOp::UnNot, inner) => return Ok(Bool::Not(box self.run(inner)?)),
113 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
114 BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
115 BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
118 ExprKind::Lit(lit) => match lit.node {
119 LitKind::Bool(true) => return Ok(Bool::True),
120 LitKind::Bool(false) => return Ok(Bool::False),
126 for (n, expr) in self.terminals.iter().enumerate() {
127 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
128 #[allow(clippy::cast_possible_truncation)]
129 return Ok(Bool::Term(n as u8));
133 if let ExprKind::Binary(e_binop, e_lhs, e_rhs) = &e.kind;
134 if implements_ord(self.cx, e_lhs);
135 if let ExprKind::Binary(expr_binop, expr_lhs, expr_rhs) = &expr.kind;
136 if negate(e_binop.node) == Some(expr_binop.node);
137 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e_lhs, expr_lhs);
138 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e_rhs, expr_rhs);
140 #[allow(clippy::cast_possible_truncation)]
141 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
145 let n = self.terminals.len();
146 self.terminals.push(e);
148 #[allow(clippy::cast_possible_truncation)]
149 Ok(Bool::Term(n as u8))
151 Err("too many literals".to_owned())
156 struct SuggestContext<'a, 'tcx, 'v> {
157 terminals: &'v [&'v Expr<'v>],
158 cx: &'a LateContext<'a, 'tcx>,
162 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
163 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
164 use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
167 self.output.push_str("true");
170 self.output.push_str("false");
172 Not(inner) => match **inner {
174 self.output.push('!');
175 self.output.push('(');
177 self.output.push(')');
180 let terminal = self.terminals[n as usize];
181 if let Some(str) = simplify_not(self.cx, terminal) {
182 self.output.push_str(&str)
184 self.output.push('!');
185 let snip = snippet_opt(self.cx, terminal.span)?;
186 self.output.push_str(&snip);
189 True | False | Not(_) => {
190 self.output.push('!');
191 self.recurse(inner)?;
195 for (index, inner) in v.iter().enumerate() {
197 self.output.push_str(" && ");
199 if let Or(_) = *inner {
200 self.output.push('(');
202 self.output.push(')');
209 for (index, inner) in v.iter().rev().enumerate() {
211 self.output.push_str(" || ");
217 let snip = snippet_opt(self.cx, self.terminals[n as usize].span)?;
218 self.output.push_str(&snip);
225 fn simplify_not(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Option<String> {
227 ExprKind::Binary(binop, lhs, rhs) => {
228 if !implements_ord(cx, lhs) {
233 BinOpKind::Eq => Some(" != "),
234 BinOpKind::Ne => Some(" == "),
235 BinOpKind::Lt => Some(" >= "),
236 BinOpKind::Gt => Some(" <= "),
237 BinOpKind::Le => Some(" > "),
238 BinOpKind::Ge => Some(" < "),
244 snippet_opt(cx, lhs.span)?,
246 snippet_opt(cx, rhs.span)?
250 ExprKind::MethodCall(path, _, args) if args.len() == 1 => {
251 let type_of_receiver = cx.tables.expr_ty(&args[0]);
252 if !is_type_diagnostic_item(cx, type_of_receiver, sym!(option_type))
253 && !is_type_diagnostic_item(cx, type_of_receiver, sym!(result_type))
257 METHODS_WITH_NEGATION
260 .flat_map(|(a, b)| vec![(a, b), (b, a)])
262 let path: &str = &path.ident.name.as_str();
265 .and_then(|(_, neg_method)| Some(format!("{}.{}()", snippet_opt(cx, args[0].span)?, neg_method)))
271 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr<'_>]) -> String {
272 let mut suggest_context = SuggestContext {
275 output: String::new(),
277 suggest_context.recurse(suggestion);
278 suggest_context.output
281 fn simple_negate(b: Bool) -> Bool {
282 use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
286 t @ Term(_) => Not(Box::new(t)),
289 *el = simple_negate(::std::mem::replace(el, True));
295 *el = simple_negate(::std::mem::replace(el, True));
299 Not(inner) => *inner,
305 terminals: [usize; 32],
310 fn terminal_stats(b: &Bool) -> Stats {
311 fn recurse(b: &Bool, stats: &mut Stats) {
313 True | False => stats.ops += 1,
316 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
317 _ => stats.negations += 1,
319 recurse(inner, stats);
322 stats.ops += v.len() - 1;
324 recurse(inner, stats);
327 &Term(n) => stats.terminals[n as usize] += 1,
330 use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
331 let mut stats = Stats::default();
332 recurse(b, &mut stats);
336 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
337 fn bool_expr(&self, e: &'tcx Expr<'_>) {
338 let mut h2q = Hir2Qmm {
339 terminals: Vec::new(),
342 if let Ok(expr) = h2q.run(e) {
343 if h2q.terminals.len() > 8 {
344 // QMC has exponentially slow behavior as the number of terminals increases
345 // 8 is reasonable, it takes approximately 0.2 seconds.
350 let stats = terminal_stats(&expr);
351 let mut simplified = expr.simplify();
352 for simple in Bool::Not(Box::new(expr)).simplify() {
354 Bool::Not(_) | Bool::True | Bool::False => {},
355 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
357 let simple_negated = simple_negate(simple);
358 if simplified.iter().any(|s| *s == simple_negated) {
361 simplified.push(simple_negated);
363 let mut improvements = Vec::with_capacity(simplified.len());
364 'simplified: for suggestion in &simplified {
365 let simplified_stats = terminal_stats(suggestion);
366 let mut improvement = false;
368 // ignore any "simplifications" that end up requiring a terminal more often
369 // than in the original expression
370 if stats.terminals[i] < simplified_stats.terminals[i] {
371 continue 'simplified;
373 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
378 "this boolean expression contains a logic bug",
381 h2q.terminals[i].span,
382 "this expression can be optimized out by applying boolean operations to the \
385 diag.span_suggestion(
387 "it would look like the following",
388 suggest(self.cx, suggestion, &h2q.terminals),
389 // nonminimal_bool can produce minimal but
390 // not human readable expressions (#3141)
391 Applicability::Unspecified,
395 // don't also lint `NONMINIMAL_BOOL`
398 // if the number of occurrences of a terminal decreases or any of the stats
399 // decreases while none increases
400 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
401 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
402 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
405 improvements.push(suggestion);
408 let nonminimal_bool_lint = |suggestions: Vec<_>| {
413 "this boolean expression can be simplified",
415 diag.span_suggestions(
418 suggestions.into_iter(),
419 // nonminimal_bool can produce minimal but
420 // not human readable expressions (#3141)
421 Applicability::Unspecified,
426 if improvements.is_empty() {
427 let mut visitor = NotSimplificationVisitor { cx: self.cx };
428 visitor.visit_expr(e);
430 nonminimal_bool_lint(
433 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
441 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
442 type Map = Map<'tcx>;
444 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
445 if in_macro(e.span) {
449 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
452 ExprKind::Unary(UnOp::UnNot, inner) => {
453 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
459 _ => walk_expr(self, e),
462 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
463 NestedVisitorMap::None
467 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr<'_>) -> bool {
468 let ty = cx.tables.expr_ty(expr);
469 get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))
472 struct NotSimplificationVisitor<'a, 'tcx> {
473 cx: &'a LateContext<'a, 'tcx>,
476 impl<'a, 'tcx> Visitor<'tcx> for NotSimplificationVisitor<'a, 'tcx> {
477 type Map = Map<'tcx>;
479 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
480 if let ExprKind::Unary(UnOp::UnNot, inner) = &expr.kind {
481 if let Some(suggestion) = simplify_not(self.cx, inner) {
486 "this boolean expression can be simplified",
489 Applicability::MachineApplicable,
494 walk_expr(self, expr);
496 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
497 NestedVisitorMap::None