1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::{declare_lint, lint_array};
4 use rustc::hir::intravisit::*;
5 use syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
6 use syntax::codemap::{dummy_spanned, Span, DUMMY_SP};
7 use syntax::util::ThinVec;
8 use crate::utils::{in_macro, paths, match_type, snippet_opt, span_lint_and_then, SpanlessEq, get_trait_def_id, implements_trait};
10 /// **What it does:** Checks for boolean expressions that can be written more
13 /// **Why is this bad?** Readability of boolean expressions suffers from
14 /// unnecessary duplication.
16 /// **Known problems:** Ignores short circuiting behavior of `||` and
17 /// `&&`. Ignores `|`, `&` and `^`.
21 /// if a && true // should be: if a
22 /// if !(a == b) // should be: if a != b
24 declare_clippy_lint! {
27 "boolean expressions that can be written more concisely"
30 /// **What it does:** Checks for boolean expressions that contain terminals that
31 /// can be eliminated.
33 /// **Why is this bad?** This is most likely a logic bug.
35 /// **Known problems:** Ignores short circuiting behavior.
39 /// if a && b || a { ... }
41 /// The `b` is unnecessary, the expression is equivalent to `if a`.
42 declare_clippy_lint! {
45 "boolean expressions that contain terminals which can be eliminated"
48 // For each pairs, both orders are considered.
49 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [
50 ("is_some", "is_none"),
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, ref lhs, ref 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, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
106 ExprKind::Binary(binop, ref lhs, ref 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(ref 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(cast_possible_truncation)]
122 return Ok(Bool::Term(n as u8));
124 let negated = match e.node {
125 ExprKind::Binary(binop, ref lhs, ref rhs) => {
127 if !implements_ord(self.cx, lhs) {
134 hir_id: DUMMY_HIR_ID,
136 attrs: ThinVec::new(),
137 node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
141 BinOpKind::Eq => mk_expr(BinOpKind::Ne),
142 BinOpKind::Ne => mk_expr(BinOpKind::Eq),
143 BinOpKind::Gt => mk_expr(BinOpKind::Le),
144 BinOpKind::Ge => mk_expr(BinOpKind::Lt),
145 BinOpKind::Lt => mk_expr(BinOpKind::Ge),
146 BinOpKind::Le => mk_expr(BinOpKind::Gt),
152 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
153 #[allow(cast_possible_truncation)]
154 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
157 let n = self.terminals.len();
158 self.terminals.push(e);
160 #[allow(cast_possible_truncation)]
161 Ok(Bool::Term(n as u8))
163 Err("too many literals".to_owned())
168 struct SuggestContext<'a, 'tcx: 'a, 'v> {
169 terminals: &'v [&'v Expr],
170 cx: &'a LateContext<'a, 'tcx>,
175 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
176 fn snip(&self, e: &Expr) -> Option<String> {
177 snippet_opt(self.cx, e.span)
180 fn simplify_not(&self, expr: &Expr) -> Option<String> {
182 ExprKind::Binary(binop, ref lhs, ref rhs) => {
184 if !implements_ord(self.cx, lhs) {
189 BinOpKind::Eq => Some(" != "),
190 BinOpKind::Ne => Some(" == "),
191 BinOpKind::Lt => Some(" >= "),
192 BinOpKind::Gt => Some(" <= "),
193 BinOpKind::Le => Some(" > "),
194 BinOpKind::Ge => Some(" < "),
196 }.and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
198 ExprKind::MethodCall(ref path, _, ref args) if args.len() == 1 => {
199 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
200 if !match_type(self.cx, type_of_receiver, &paths::OPTION) &&
201 !match_type(self.cx, type_of_receiver, &paths::RESULT) {
204 METHODS_WITH_NEGATION
206 .flat_map(|(a, b)| vec![(a, b), (b, a)])
207 .find(|&(a, _)| a == path.ident.as_str())
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(ref 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);
329 And(ref v) | Or(ref v) => {
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,
400 // don't also lint `NONMINIMAL_BOOL`
403 // if the number of occurrences of a terminal decreases or any of the stats
404 // decreases while none increases
405 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
406 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
407 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
410 improvements.push(suggestion);
413 let nonminimal_bool_lint = |suggestions| {
418 "this boolean expression can be simplified",
419 |db| { db.span_suggestions(e.span, "try", suggestions); },
422 if improvements.is_empty() {
423 let suggest = suggest(self.cx, &expr, &h2q.terminals);
425 nonminimal_bool_lint(vec![suggest.0])
428 nonminimal_bool_lint(
431 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
439 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
440 fn visit_expr(&mut self, e: &'tcx Expr) {
441 if in_macro(e.span) {
445 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => self.bool_expr(e),
446 ExprKind::Unary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
451 _ => walk_expr(self, e),
454 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
455 NestedVisitorMap::None
460 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
461 let ty = cx.tables.expr_ty(expr);
462 get_trait_def_id(cx, &paths::ORD)
463 .map_or(false, |id| implements_trait(cx, ty, id, &[]))