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_tool_lint, lint_array};
8 use rustc_data_structures::thin_vec::ThinVec;
9 use rustc_errors::Applicability;
10 use syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
11 use syntax::source_map::{dummy_spanned, Span, DUMMY_SP};
13 /// **What it does:** Checks for boolean expressions that can be written more
16 /// **Why is this bad?** Readability of boolean expressions suffers from
17 /// unnecessary duplication.
19 /// **Known problems:** Ignores short circuiting behavior of `||` and
20 /// `&&`. Ignores `|`, `&` and `^`.
24 /// if a && true // should be: if a
25 /// if !(a == b) // should be: if a != b
27 declare_clippy_lint! {
30 "boolean expressions that can be written more concisely"
33 /// **What it does:** Checks for boolean expressions that contain terminals that
34 /// can be eliminated.
36 /// **Why is this bad?** This is most likely a logic bug.
38 /// **Known problems:** Ignores short circuiting behavior.
42 /// if a && b || a { ... }
44 /// The `b` is unnecessary, the expression is equivalent to `if a`.
45 declare_clippy_lint! {
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 #[derive(Copy, Clone)]
55 pub struct NonminimalBool;
57 impl LintPass for NonminimalBool {
58 fn get_lints(&self) -> LintArray {
59 lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
63 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
66 cx: &LateContext<'a, 'tcx>,
67 _: intravisit::FnKind<'tcx>,
73 NonminimalBoolVisitor { cx }.visit_body(body)
77 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
78 cx: &'a LateContext<'a, 'tcx>,
81 use quine_mc_cluskey::Bool;
82 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
83 terminals: Vec<&'v Expr>,
84 cx: &'a LateContext<'a, 'tcx>,
87 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
88 fn extract(&mut self, op: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
90 if let ExprKind::Binary(binop, lhs, rhs) = &a.node {
92 v = self.extract(op, &[lhs, rhs], v)?;
101 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
102 // prevent folding of `cfg!` macros and the like
103 if !in_macro(e.span) {
105 ExprKind::Unary(UnNot, inner) => return Ok(Bool::Not(box self.run(inner)?)),
106 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
107 BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
108 BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
111 ExprKind::Lit(lit) => match lit.node {
112 LitKind::Bool(true) => return Ok(Bool::True),
113 LitKind::Bool(false) => return Ok(Bool::False),
119 for (n, expr) in self.terminals.iter().enumerate() {
120 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
121 #[allow(clippy::cast_possible_truncation)]
122 return Ok(Bool::Term(n as u8));
124 let negated = match &e.node {
125 ExprKind::Binary(binop, lhs, rhs) => {
126 if !implements_ord(self.cx, lhs) {
130 let mk_expr = |op| Expr {
132 hir_id: DUMMY_HIR_ID,
134 attrs: ThinVec::new(),
135 node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
138 BinOpKind::Eq => mk_expr(BinOpKind::Ne),
139 BinOpKind::Ne => mk_expr(BinOpKind::Eq),
140 BinOpKind::Gt => mk_expr(BinOpKind::Le),
141 BinOpKind::Ge => mk_expr(BinOpKind::Lt),
142 BinOpKind::Lt => mk_expr(BinOpKind::Ge),
143 BinOpKind::Le => mk_expr(BinOpKind::Gt),
149 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
150 #[allow(clippy::cast_possible_truncation)]
151 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
154 let n = self.terminals.len();
155 self.terminals.push(e);
157 #[allow(clippy::cast_possible_truncation)]
158 Ok(Bool::Term(n as u8))
160 Err("too many literals".to_owned())
165 struct SuggestContext<'a, 'tcx: 'a, 'v> {
166 terminals: &'v [&'v Expr],
167 cx: &'a LateContext<'a, 'tcx>,
172 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
173 fn snip(&self, e: &Expr) -> Option<String> {
174 snippet_opt(self.cx, e.span)
177 fn simplify_not(&self, expr: &Expr) -> Option<String> {
179 ExprKind::Binary(binop, lhs, rhs) => {
180 if !implements_ord(self.cx, lhs) {
185 BinOpKind::Eq => Some(" != "),
186 BinOpKind::Ne => Some(" == "),
187 BinOpKind::Lt => Some(" >= "),
188 BinOpKind::Gt => Some(" <= "),
189 BinOpKind::Le => Some(" > "),
190 BinOpKind::Ge => Some(" < "),
193 .and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
195 ExprKind::MethodCall(path, _, args) if args.len() == 1 => {
196 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
197 if !match_type(self.cx, type_of_receiver, &paths::OPTION)
198 && !match_type(self.cx, type_of_receiver, &paths::RESULT)
202 METHODS_WITH_NEGATION
205 .flat_map(|(a, b)| vec![(a, b), (b, a)])
206 .find(|&(a, _)| a == path.ident.as_str())
207 .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
213 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
214 use quine_mc_cluskey::Bool::*;
217 self.output.push_str("true");
220 self.output.push_str("false");
222 Not(inner) => match **inner {
224 self.output.push('!');
225 self.output.push('(');
227 self.output.push(')');
230 let terminal = self.terminals[n as usize];
231 if let Some(str) = self.simplify_not(terminal) {
232 self.simplified = true;
233 self.output.push_str(&str)
235 self.output.push('!');
236 let snip = self.snip(terminal)?;
237 self.output.push_str(&snip);
240 True | False | Not(_) => {
241 self.output.push('!');
242 self.recurse(inner)?;
246 for (index, inner) in v.iter().enumerate() {
248 self.output.push_str(" && ");
250 if let Or(_) = *inner {
251 self.output.push('(');
253 self.output.push(')');
260 for (index, inner) in v.iter().enumerate() {
262 self.output.push_str(" || ");
268 let snip = self.snip(self.terminals[n as usize])?;
269 self.output.push_str(&snip);
276 // The boolean part of the return indicates whether some simplifications have been applied.
277 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
278 let mut suggest_context = SuggestContext {
281 output: String::new(),
284 suggest_context.recurse(suggestion);
285 (suggest_context.output, suggest_context.simplified)
288 fn simple_negate(b: Bool) -> Bool {
289 use quine_mc_cluskey::Bool::*;
293 t @ Term(_) => Not(Box::new(t)),
296 *el = simple_negate(::std::mem::replace(el, True));
302 *el = simple_negate(::std::mem::replace(el, True));
306 Not(inner) => *inner,
312 terminals: [usize; 32],
317 fn terminal_stats(b: &Bool) -> Stats {
318 fn recurse(b: &Bool, stats: &mut Stats) {
320 True | False => stats.ops += 1,
323 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
324 _ => stats.negations += 1,
326 recurse(inner, stats);
329 stats.ops += v.len() - 1;
331 recurse(inner, stats);
334 &Term(n) => stats.terminals[n as usize] += 1,
337 use quine_mc_cluskey::Bool::*;
338 let mut stats = Stats::default();
339 recurse(b, &mut stats);
343 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
344 fn bool_expr(&self, e: &Expr) {
345 let mut h2q = Hir2Qmm {
346 terminals: Vec::new(),
349 if let Ok(expr) = h2q.run(e) {
350 if h2q.terminals.len() > 8 {
351 // QMC has exponentially slow behavior as the number of terminals increases
352 // 8 is reasonable, it takes approximately 0.2 seconds.
357 let stats = terminal_stats(&expr);
358 let mut simplified = expr.simplify();
359 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
361 Bool::Not(_) | Bool::True | Bool::False => {},
362 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
364 let simple_negated = simple_negate(simple);
365 if simplified.iter().any(|s| *s == simple_negated) {
368 simplified.push(simple_negated);
370 let mut improvements = Vec::new();
371 'simplified: for suggestion in &simplified {
372 let simplified_stats = terminal_stats(suggestion);
373 let mut improvement = false;
375 // ignore any "simplifications" that end up requiring a terminal more often
376 // than in the original expression
377 if stats.terminals[i] < simplified_stats.terminals[i] {
378 continue 'simplified;
380 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
385 "this boolean expression contains a logic bug",
388 h2q.terminals[i].span,
389 "this expression can be optimized out by applying boolean operations to the \
392 db.span_suggestion_with_applicability(
394 "it would look like the following",
395 suggest(self.cx, suggestion, &h2q.terminals).0,
396 // nonminimal_bool can produce minimal but
397 // not human readable expressions (#3141)
398 Applicability::Unspecified,
402 // don't also lint `NONMINIMAL_BOOL`
405 // if the number of occurrences of a terminal decreases or any of the stats
406 // decreases while none increases
407 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
408 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
409 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
412 improvements.push(suggestion);
415 let nonminimal_bool_lint = |suggestions: Vec<_>| {
420 "this boolean expression can be simplified",
422 db.span_suggestions_with_applicability(
425 suggestions.into_iter(),
426 // nonminimal_bool can produce minimal but
427 // not human readable expressions (#3141)
428 Applicability::Unspecified,
433 if improvements.is_empty() {
434 let suggest = suggest(self.cx, &expr, &h2q.terminals);
436 nonminimal_bool_lint(vec![suggest.0])
439 nonminimal_bool_lint(
442 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
450 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
451 fn visit_expr(&mut self, e: &'tcx Expr) {
452 if in_macro(e.span) {
456 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
459 ExprKind::Unary(UnNot, inner) => {
460 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
466 _ => walk_expr(self, e),
469 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
470 NestedVisitorMap::None
474 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
475 let ty = cx.tables.expr_ty(expr);
476 get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))