2 get_trait_def_id, implements_trait, in_macro, in_macro_or_desugar, match_type, paths, snippet_opt,
3 span_lint_and_then, SpanlessEq,
5 use rustc::hir::intravisit::*;
7 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8 use rustc::{declare_lint_pass, declare_tool_lint};
9 use rustc_data_structures::thin_vec::ThinVec;
10 use rustc_errors::Applicability;
11 use syntax::ast::LitKind;
12 use syntax::source_map::{dummy_spanned, Span, DUMMY_SP};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for boolean expressions that can be written more
18 /// **Why is this bad?** Readability of boolean expressions suffers from
19 /// unnecessary duplication.
21 /// **Known problems:** Ignores short circuiting behavior of `||` and
22 /// `&&`. Ignores `|`, `&` and `^`.
26 /// if a && true // should be: if a
27 /// if !(a == b) // should be: if a != b
31 "boolean expressions that can be written more concisely"
34 declare_clippy_lint! {
35 /// **What it does:** Checks for boolean expressions that contain terminals that
36 /// can be eliminated.
38 /// **Why is this bad?** This is most likely a logic bug.
40 /// **Known problems:** Ignores short circuiting behavior.
44 /// if a && b || a { ... }
46 /// The `b` is unnecessary, the expression is equivalent to `if a`.
49 "boolean expressions that contain terminals which can be eliminated"
52 // For each pairs, both orders are considered.
53 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
55 declare_lint_pass!(NonminimalBool => [NONMINIMAL_BOOL, LOGIC_BUG]);
57 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
60 cx: &LateContext<'a, 'tcx>,
61 _: intravisit::FnKind<'tcx>,
67 NonminimalBoolVisitor { cx }.visit_body(body)
71 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
72 cx: &'a LateContext<'a, 'tcx>,
75 use quine_mc_cluskey::Bool;
76 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
77 terminals: Vec<&'v Expr>,
78 cx: &'a LateContext<'a, 'tcx>,
81 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
82 fn extract(&mut self, op: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
84 if let ExprKind::Binary(binop, lhs, rhs) = &a.node {
86 v = self.extract(op, &[lhs, rhs], v)?;
95 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
96 // prevent folding of `cfg!` macros and the like
97 if !in_macro_or_desugar(e.span) {
99 ExprKind::Unary(UnNot, inner) => return Ok(Bool::Not(box self.run(inner)?)),
100 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
101 BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
102 BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
105 ExprKind::Lit(lit) => match lit.node {
106 LitKind::Bool(true) => return Ok(Bool::True),
107 LitKind::Bool(false) => return Ok(Bool::False),
113 for (n, expr) in self.terminals.iter().enumerate() {
114 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
115 #[allow(clippy::cast_possible_truncation)]
116 return Ok(Bool::Term(n as u8));
118 let negated = match &e.node {
119 ExprKind::Binary(binop, lhs, rhs) => {
120 if !implements_ord(self.cx, lhs) {
124 let mk_expr = |op| Expr {
125 hir_id: DUMMY_HIR_ID,
127 attrs: ThinVec::new(),
128 node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
131 BinOpKind::Eq => mk_expr(BinOpKind::Ne),
132 BinOpKind::Ne => mk_expr(BinOpKind::Eq),
133 BinOpKind::Gt => mk_expr(BinOpKind::Le),
134 BinOpKind::Ge => mk_expr(BinOpKind::Lt),
135 BinOpKind::Lt => mk_expr(BinOpKind::Ge),
136 BinOpKind::Le => mk_expr(BinOpKind::Gt),
142 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
143 #[allow(clippy::cast_possible_truncation)]
144 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
147 let n = self.terminals.len();
148 self.terminals.push(e);
150 #[allow(clippy::cast_possible_truncation)]
151 Ok(Bool::Term(n as u8))
153 Err("too many literals".to_owned())
158 struct SuggestContext<'a, 'tcx: 'a, 'v> {
159 terminals: &'v [&'v Expr],
160 cx: &'a LateContext<'a, 'tcx>,
165 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
166 fn snip(&self, e: &Expr) -> Option<String> {
167 snippet_opt(self.cx, e.span)
170 fn simplify_not(&self, expr: &Expr) -> Option<String> {
172 ExprKind::Binary(binop, lhs, rhs) => {
173 if !implements_ord(self.cx, lhs) {
178 BinOpKind::Eq => Some(" != "),
179 BinOpKind::Ne => Some(" == "),
180 BinOpKind::Lt => Some(" >= "),
181 BinOpKind::Gt => Some(" <= "),
182 BinOpKind::Le => Some(" > "),
183 BinOpKind::Ge => Some(" < "),
186 .and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
188 ExprKind::MethodCall(path, _, args) if args.len() == 1 => {
189 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
190 if !match_type(self.cx, type_of_receiver, &paths::OPTION)
191 && !match_type(self.cx, type_of_receiver, &paths::RESULT)
195 METHODS_WITH_NEGATION
198 .flat_map(|(a, b)| vec![(a, b), (b, a)])
199 .find(|&(a, _)| a == path.ident.name.as_str())
200 .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
206 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
207 use quine_mc_cluskey::Bool::*;
210 self.output.push_str("true");
213 self.output.push_str("false");
215 Not(inner) => match **inner {
217 self.output.push('!');
218 self.output.push('(');
220 self.output.push(')');
223 let terminal = self.terminals[n as usize];
224 if let Some(str) = self.simplify_not(terminal) {
225 self.simplified = true;
226 self.output.push_str(&str)
228 self.output.push('!');
229 let snip = self.snip(terminal)?;
230 self.output.push_str(&snip);
233 True | False | Not(_) => {
234 self.output.push('!');
235 self.recurse(inner)?;
239 for (index, inner) in v.iter().enumerate() {
241 self.output.push_str(" && ");
243 if let Or(_) = *inner {
244 self.output.push('(');
246 self.output.push(')');
253 for (index, inner) in v.iter().enumerate() {
255 self.output.push_str(" || ");
261 let snip = self.snip(self.terminals[n as usize])?;
262 self.output.push_str(&snip);
269 // The boolean part of the return indicates whether some simplifications have been applied.
270 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
271 let mut suggest_context = SuggestContext {
274 output: String::new(),
277 suggest_context.recurse(suggestion);
278 (suggest_context.output, suggest_context.simplified)
281 fn simple_negate(b: Bool) -> Bool {
282 use quine_mc_cluskey::Bool::*;
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::*;
331 let mut stats = Stats::default();
332 recurse(b, &mut stats);
336 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
337 fn bool_expr(&self, e: &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.clone())).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::new();
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 \
387 "it would look like the following",
388 suggest(self.cx, suggestion, &h2q.terminals).0,
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",
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 suggest = suggest(self.cx, &expr, &h2q.terminals);
429 nonminimal_bool_lint(vec![suggest.0])
432 nonminimal_bool_lint(
435 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
443 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, '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(UnNot, inner) => {
453 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
459 _ => walk_expr(self, e),
462 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
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, &[]))