3 get_trait_def_id, implements_trait, in_macro, in_macro_or_desugar, match_type, paths, snippet_opt,
4 span_lint_and_then, SpanlessEq,
6 use lazy_static::lazy_static;
7 use rustc::hir::intravisit::*;
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::{declare_lint_pass, declare_tool_lint};
11 use rustc_data_structures::thin_vec::ThinVec;
12 use rustc_errors::Applicability;
13 use syntax::ast::LitKind;
14 use syntax::source_map::{dummy_spanned, Span, DUMMY_SP};
15 use syntax::symbol::Symbol;
17 declare_clippy_lint! {
18 /// **What it does:** Checks for boolean expressions that can be written more
21 /// **Why is this bad?** Readability of boolean expressions suffers from
22 /// unnecessary duplication.
24 /// **Known problems:** Ignores short circuiting behavior of `||` and
25 /// `&&`. Ignores `|`, `&` and `^`.
29 /// if a && true // should be: if a
30 /// if !(a == b) // should be: if a != b
34 "boolean expressions that can be written more concisely"
37 declare_clippy_lint! {
38 /// **What it does:** Checks for boolean expressions that contain terminals that
39 /// can be eliminated.
41 /// **Why is this bad?** This is most likely a logic bug.
43 /// **Known problems:** Ignores short circuiting behavior.
47 /// if a && b || a { ... }
49 /// The `b` is unnecessary, the expression is equivalent to `if a`.
52 "boolean expressions that contain terminals which can be eliminated"
56 // For each pairs, both orders are considered.
57 static ref METHODS_WITH_NEGATION: [(Symbol, Symbol); 2] = [
58 (*sym::is_some, *sym::is_none),
59 (*sym::is_err, *sym::is_ok),
63 declare_lint_pass!(NonminimalBool => [NONMINIMAL_BOOL, LOGIC_BUG]);
65 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
68 cx: &LateContext<'a, 'tcx>,
69 _: intravisit::FnKind<'tcx>,
75 NonminimalBoolVisitor { cx }.visit_body(body)
79 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
80 cx: &'a LateContext<'a, 'tcx>,
83 use quine_mc_cluskey::Bool;
84 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
85 terminals: Vec<&'v Expr>,
86 cx: &'a LateContext<'a, 'tcx>,
89 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
90 fn extract(&mut self, op: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
92 if let ExprKind::Binary(binop, lhs, rhs) = &a.node {
94 v = self.extract(op, &[lhs, rhs], v)?;
103 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
104 // prevent folding of `cfg!` macros and the like
105 if !in_macro_or_desugar(e.span) {
107 ExprKind::Unary(UnNot, inner) => return Ok(Bool::Not(box self.run(inner)?)),
108 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
109 BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
110 BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
113 ExprKind::Lit(lit) => match lit.node {
114 LitKind::Bool(true) => return Ok(Bool::True),
115 LitKind::Bool(false) => return Ok(Bool::False),
121 for (n, expr) in self.terminals.iter().enumerate() {
122 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
123 #[allow(clippy::cast_possible_truncation)]
124 return Ok(Bool::Term(n as u8));
126 let negated = match &e.node {
127 ExprKind::Binary(binop, lhs, rhs) => {
128 if !implements_ord(self.cx, lhs) {
132 let mk_expr = |op| Expr {
133 hir_id: DUMMY_HIR_ID,
135 attrs: ThinVec::new(),
136 node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
139 BinOpKind::Eq => mk_expr(BinOpKind::Ne),
140 BinOpKind::Ne => mk_expr(BinOpKind::Eq),
141 BinOpKind::Gt => mk_expr(BinOpKind::Le),
142 BinOpKind::Ge => mk_expr(BinOpKind::Lt),
143 BinOpKind::Lt => mk_expr(BinOpKind::Ge),
144 BinOpKind::Le => mk_expr(BinOpKind::Gt),
150 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
151 #[allow(clippy::cast_possible_truncation)]
152 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
155 let n = self.terminals.len();
156 self.terminals.push(e);
158 #[allow(clippy::cast_possible_truncation)]
159 Ok(Bool::Term(n as u8))
161 Err("too many literals".to_owned())
166 struct SuggestContext<'a, 'tcx: 'a, 'v> {
167 terminals: &'v [&'v Expr],
168 cx: &'a LateContext<'a, 'tcx>,
173 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
174 fn snip(&self, e: &Expr) -> Option<String> {
175 snippet_opt(self.cx, e.span)
178 fn simplify_not(&self, expr: &Expr) -> Option<String> {
180 ExprKind::Binary(binop, lhs, rhs) => {
181 if !implements_ord(self.cx, lhs) {
186 BinOpKind::Eq => Some(" != "),
187 BinOpKind::Ne => Some(" == "),
188 BinOpKind::Lt => Some(" >= "),
189 BinOpKind::Gt => Some(" <= "),
190 BinOpKind::Le => Some(" > "),
191 BinOpKind::Ge => Some(" < "),
194 .and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
196 ExprKind::MethodCall(path, _, args) if args.len() == 1 => {
197 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
198 if !match_type(self.cx, type_of_receiver, &*paths::OPTION)
199 && !match_type(self.cx, type_of_receiver, &*paths::RESULT)
203 METHODS_WITH_NEGATION
206 .flat_map(|(a, b)| vec![(a, b), (b, a)])
207 .find(|&(a, _)| a == path.ident.name)
208 .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
214 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
215 use quine_mc_cluskey::Bool::*;
218 self.output.push_str("true");
221 self.output.push_str("false");
223 Not(inner) => match **inner {
225 self.output.push('!');
226 self.output.push('(');
228 self.output.push(')');
231 let terminal = self.terminals[n as usize];
232 if let Some(str) = self.simplify_not(terminal) {
233 self.simplified = true;
234 self.output.push_str(&str)
236 self.output.push('!');
237 let snip = self.snip(terminal)?;
238 self.output.push_str(&snip);
241 True | False | Not(_) => {
242 self.output.push('!');
243 self.recurse(inner)?;
247 for (index, inner) in v.iter().enumerate() {
249 self.output.push_str(" && ");
251 if let Or(_) = *inner {
252 self.output.push('(');
254 self.output.push(')');
261 for (index, inner) in v.iter().enumerate() {
263 self.output.push_str(" || ");
269 let snip = self.snip(self.terminals[n as usize])?;
270 self.output.push_str(&snip);
277 // The boolean part of the return indicates whether some simplifications have been applied.
278 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
279 let mut suggest_context = SuggestContext {
282 output: String::new(),
285 suggest_context.recurse(suggestion);
286 (suggest_context.output, suggest_context.simplified)
289 fn simple_negate(b: Bool) -> Bool {
290 use quine_mc_cluskey::Bool::*;
294 t @ Term(_) => Not(Box::new(t)),
297 *el = simple_negate(::std::mem::replace(el, True));
303 *el = simple_negate(::std::mem::replace(el, True));
307 Not(inner) => *inner,
313 terminals: [usize; 32],
318 fn terminal_stats(b: &Bool) -> Stats {
319 fn recurse(b: &Bool, stats: &mut Stats) {
321 True | False => stats.ops += 1,
324 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
325 _ => stats.negations += 1,
327 recurse(inner, stats);
330 stats.ops += v.len() - 1;
332 recurse(inner, stats);
335 &Term(n) => stats.terminals[n as usize] += 1,
338 use quine_mc_cluskey::Bool::*;
339 let mut stats = Stats::default();
340 recurse(b, &mut stats);
344 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
345 fn bool_expr(&self, e: &Expr) {
346 let mut h2q = Hir2Qmm {
347 terminals: Vec::new(),
350 if let Ok(expr) = h2q.run(e) {
351 if h2q.terminals.len() > 8 {
352 // QMC has exponentially slow behavior as the number of terminals increases
353 // 8 is reasonable, it takes approximately 0.2 seconds.
358 let stats = terminal_stats(&expr);
359 let mut simplified = expr.simplify();
360 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
362 Bool::Not(_) | Bool::True | Bool::False => {},
363 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
365 let simple_negated = simple_negate(simple);
366 if simplified.iter().any(|s| *s == simple_negated) {
369 simplified.push(simple_negated);
371 let mut improvements = Vec::new();
372 'simplified: for suggestion in &simplified {
373 let simplified_stats = terminal_stats(suggestion);
374 let mut improvement = false;
376 // ignore any "simplifications" that end up requiring a terminal more often
377 // than in the original expression
378 if stats.terminals[i] < simplified_stats.terminals[i] {
379 continue 'simplified;
381 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
386 "this boolean expression contains a logic bug",
389 h2q.terminals[i].span,
390 "this expression can be optimized out by applying boolean operations to the \
395 "it would look like the following",
396 suggest(self.cx, suggestion, &h2q.terminals).0,
397 // nonminimal_bool can produce minimal but
398 // not human readable expressions (#3141)
399 Applicability::Unspecified,
403 // don't also lint `NONMINIMAL_BOOL`
406 // if the number of occurrences of a terminal decreases or any of the stats
407 // decreases while none increases
408 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
409 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
410 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
413 improvements.push(suggestion);
416 let nonminimal_bool_lint = |suggestions: Vec<_>| {
421 "this boolean expression can be simplified",
426 suggestions.into_iter(),
427 // nonminimal_bool can produce minimal but
428 // not human readable expressions (#3141)
429 Applicability::Unspecified,
434 if improvements.is_empty() {
435 let suggest = suggest(self.cx, &expr, &h2q.terminals);
437 nonminimal_bool_lint(vec![suggest.0])
440 nonminimal_bool_lint(
443 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
451 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
452 fn visit_expr(&mut self, e: &'tcx Expr) {
453 if in_macro(e.span) {
457 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
460 ExprKind::Unary(UnNot, inner) => {
461 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
467 _ => walk_expr(self, e),
470 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
471 NestedVisitorMap::None
475 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
476 let ty = cx.tables.expr_ty(expr);
477 get_trait_def_id(cx, &*paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))