2 get_trait_def_id, implements_trait, in_macro, match_type, paths, snippet_opt, span_lint_and_then, SpanlessEq,
4 use rustc::hir::intravisit::*;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_lint_pass, declare_tool_lint};
8 use rustc_data_structures::thin_vec::ThinVec;
9 use rustc_errors::Applicability;
10 use syntax::ast::LitKind;
11 use syntax::source_map::{dummy_spanned, Span, DUMMY_SP};
13 declare_clippy_lint! {
14 /// **What it does:** Checks for boolean expressions that can be written more
17 /// **Why is this bad?** Readability of boolean expressions suffers from
18 /// unnecessary duplication.
20 /// **Known problems:** Ignores short circuiting behavior of `||` and
21 /// `&&`. Ignores `|`, `&` and `^`.
25 /// if a && true // should be: if a
26 /// if !(a == b) // should be: if a != b
30 "boolean expressions that can be written more concisely"
33 declare_clippy_lint! {
34 /// **What it does:** Checks for boolean expressions that contain terminals that
35 /// can be eliminated.
37 /// **Why is this bad?** This is most likely a logic bug.
39 /// **Known problems:** Ignores short circuiting behavior.
43 /// if a && b || a { ... }
45 /// The `b` is unnecessary, the expression is equivalent to `if a`.
48 "boolean expressions that contain terminals which can be eliminated"
51 // For each pairs, both orders are considered.
52 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
54 declare_lint_pass!(NonminimalBool => [NONMINIMAL_BOOL, LOGIC_BUG]);
56 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
59 cx: &LateContext<'a, 'tcx>,
60 _: intravisit::FnKind<'tcx>,
66 NonminimalBoolVisitor { cx }.visit_body(body)
70 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
71 cx: &'a LateContext<'a, 'tcx>,
74 use quine_mc_cluskey::Bool;
75 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
76 terminals: Vec<&'v Expr>,
77 cx: &'a LateContext<'a, 'tcx>,
80 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
81 fn extract(&mut self, op: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
83 if let ExprKind::Binary(binop, lhs, rhs) = &a.node {
85 v = self.extract(op, &[lhs, rhs], v)?;
94 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
95 // prevent folding of `cfg!` macros and the like
96 if !in_macro(e.span) {
98 ExprKind::Unary(UnNot, inner) => return Ok(Bool::Not(box self.run(inner)?)),
99 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
100 BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
101 BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
104 ExprKind::Lit(lit) => match lit.node {
105 LitKind::Bool(true) => return Ok(Bool::True),
106 LitKind::Bool(false) => return Ok(Bool::False),
112 for (n, expr) in self.terminals.iter().enumerate() {
113 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
114 #[allow(clippy::cast_possible_truncation)]
115 return Ok(Bool::Term(n as u8));
117 let negated = match &e.node {
118 ExprKind::Binary(binop, lhs, rhs) => {
119 if !implements_ord(self.cx, lhs) {
123 let mk_expr = |op| Expr {
124 hir_id: DUMMY_HIR_ID,
126 attrs: ThinVec::new(),
127 node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
130 BinOpKind::Eq => mk_expr(BinOpKind::Ne),
131 BinOpKind::Ne => mk_expr(BinOpKind::Eq),
132 BinOpKind::Gt => mk_expr(BinOpKind::Le),
133 BinOpKind::Ge => mk_expr(BinOpKind::Lt),
134 BinOpKind::Lt => mk_expr(BinOpKind::Ge),
135 BinOpKind::Le => mk_expr(BinOpKind::Gt),
141 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
142 #[allow(clippy::cast_possible_truncation)]
143 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
146 let n = self.terminals.len();
147 self.terminals.push(e);
149 #[allow(clippy::cast_possible_truncation)]
150 Ok(Bool::Term(n as u8))
152 Err("too many literals".to_owned())
157 struct SuggestContext<'a, 'tcx: 'a, 'v> {
158 terminals: &'v [&'v Expr],
159 cx: &'a LateContext<'a, 'tcx>,
164 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
165 fn snip(&self, e: &Expr) -> Option<String> {
166 snippet_opt(self.cx, e.span)
169 fn simplify_not(&self, expr: &Expr) -> Option<String> {
171 ExprKind::Binary(binop, lhs, rhs) => {
172 if !implements_ord(self.cx, lhs) {
177 BinOpKind::Eq => Some(" != "),
178 BinOpKind::Ne => Some(" == "),
179 BinOpKind::Lt => Some(" >= "),
180 BinOpKind::Gt => Some(" <= "),
181 BinOpKind::Le => Some(" > "),
182 BinOpKind::Ge => Some(" < "),
185 .and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
187 ExprKind::MethodCall(path, _, args) if args.len() == 1 => {
188 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
189 if !match_type(self.cx, type_of_receiver, &paths::OPTION)
190 && !match_type(self.cx, type_of_receiver, &paths::RESULT)
194 METHODS_WITH_NEGATION
197 .flat_map(|(a, b)| vec![(a, b), (b, a)])
198 .find(|&(a, _)| a == path.ident.as_str())
199 .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
205 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
206 use quine_mc_cluskey::Bool::*;
209 self.output.push_str("true");
212 self.output.push_str("false");
214 Not(inner) => match **inner {
216 self.output.push('!');
217 self.output.push('(');
219 self.output.push(')');
222 let terminal = self.terminals[n as usize];
223 if let Some(str) = self.simplify_not(terminal) {
224 self.simplified = true;
225 self.output.push_str(&str)
227 self.output.push('!');
228 let snip = self.snip(terminal)?;
229 self.output.push_str(&snip);
232 True | False | Not(_) => {
233 self.output.push('!');
234 self.recurse(inner)?;
238 for (index, inner) in v.iter().enumerate() {
240 self.output.push_str(" && ");
242 if let Or(_) = *inner {
243 self.output.push('(');
245 self.output.push(')');
252 for (index, inner) in v.iter().enumerate() {
254 self.output.push_str(" || ");
260 let snip = self.snip(self.terminals[n as usize])?;
261 self.output.push_str(&snip);
268 // The boolean part of the return indicates whether some simplifications have been applied.
269 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
270 let mut suggest_context = SuggestContext {
273 output: String::new(),
276 suggest_context.recurse(suggestion);
277 (suggest_context.output, suggest_context.simplified)
280 fn simple_negate(b: Bool) -> Bool {
281 use quine_mc_cluskey::Bool::*;
285 t @ Term(_) => Not(Box::new(t)),
288 *el = simple_negate(::std::mem::replace(el, True));
294 *el = simple_negate(::std::mem::replace(el, True));
298 Not(inner) => *inner,
304 terminals: [usize; 32],
309 fn terminal_stats(b: &Bool) -> Stats {
310 fn recurse(b: &Bool, stats: &mut Stats) {
312 True | False => stats.ops += 1,
315 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
316 _ => stats.negations += 1,
318 recurse(inner, stats);
321 stats.ops += v.len() - 1;
323 recurse(inner, stats);
326 &Term(n) => stats.terminals[n as usize] += 1,
329 use quine_mc_cluskey::Bool::*;
330 let mut stats = Stats::default();
331 recurse(b, &mut stats);
335 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
336 fn bool_expr(&self, e: &Expr) {
337 let mut h2q = Hir2Qmm {
338 terminals: Vec::new(),
341 if let Ok(expr) = h2q.run(e) {
342 if h2q.terminals.len() > 8 {
343 // QMC has exponentially slow behavior as the number of terminals increases
344 // 8 is reasonable, it takes approximately 0.2 seconds.
349 let stats = terminal_stats(&expr);
350 let mut simplified = expr.simplify();
351 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
353 Bool::Not(_) | Bool::True | Bool::False => {},
354 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
356 let simple_negated = simple_negate(simple);
357 if simplified.iter().any(|s| *s == simple_negated) {
360 simplified.push(simple_negated);
362 let mut improvements = Vec::new();
363 'simplified: for suggestion in &simplified {
364 let simplified_stats = terminal_stats(suggestion);
365 let mut improvement = false;
367 // ignore any "simplifications" that end up requiring a terminal more often
368 // than in the original expression
369 if stats.terminals[i] < simplified_stats.terminals[i] {
370 continue 'simplified;
372 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
377 "this boolean expression contains a logic bug",
380 h2q.terminals[i].span,
381 "this expression can be optimized out by applying boolean operations to the \
386 "it would look like the following",
387 suggest(self.cx, suggestion, &h2q.terminals).0,
388 // nonminimal_bool can produce minimal but
389 // not human readable expressions (#3141)
390 Applicability::Unspecified,
394 // don't also lint `NONMINIMAL_BOOL`
397 // if the number of occurrences of a terminal decreases or any of the stats
398 // decreases while none increases
399 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
400 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
401 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
404 improvements.push(suggestion);
407 let nonminimal_bool_lint = |suggestions: Vec<_>| {
412 "this boolean expression can be simplified",
417 suggestions.into_iter(),
418 // nonminimal_bool can produce minimal but
419 // not human readable expressions (#3141)
420 Applicability::Unspecified,
425 if improvements.is_empty() {
426 let suggest = suggest(self.cx, &expr, &h2q.terminals);
428 nonminimal_bool_lint(vec![suggest.0])
431 nonminimal_bool_lint(
434 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
442 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
443 fn visit_expr(&mut self, e: &'tcx Expr) {
444 if in_macro(e.span) {
448 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
451 ExprKind::Unary(UnNot, inner) => {
452 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
458 _ => walk_expr(self, e),
461 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
462 NestedVisitorMap::None
466 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
467 let ty = cx.tables.expr_ty(expr);
468 get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))