1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::hir::intravisit::*;
4 use syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
5 use syntax::codemap::{dummy_spanned, Span, DUMMY_SP};
6 use syntax::util::ThinVec;
7 use utils::{in_macro, snippet_opt, span_lint_and_then, SpanlessEq};
9 /// **What it does:** Checks for boolean expressions that can be written more
12 /// **Why is this bad?** Readability of boolean expressions suffers from
13 /// unnecessary duplication.
15 /// **Known problems:** Ignores short circuiting behavior of `||` and
16 /// `&&`. Ignores `|`, `&` and `^`.
20 /// if a && true // should be: if a
21 /// if !(a == b) // should be: if a != b
26 "boolean expressions that can be written more concisely"
29 /// **What it does:** Checks for boolean expressions that contain terminals that
30 /// can be eliminated.
32 /// **Why is this bad?** This is most likely a logic bug.
34 /// **Known problems:** Ignores short circuiting behavior.
38 /// if a && b || a { ... }
40 /// The `b` is unnecessary, the expression is equivalent to `if a`.
44 "boolean expressions that contain terminals which can be eliminated"
47 // For each pairs, both orders are considered.
48 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [
49 ("is_some", "is_none"),
53 #[derive(Copy, Clone)]
54 pub struct NonminimalBool;
56 impl LintPass for NonminimalBool {
57 fn get_lints(&self) -> LintArray {
58 lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
65 cx: &LateContext<'a, 'tcx>,
66 _: intravisit::FnKind<'tcx>,
72 NonminimalBoolVisitor { cx: cx }.visit_body(body)
76 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
77 cx: &'a LateContext<'a, 'tcx>,
80 use quine_mc_cluskey::Bool;
81 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
82 terminals: Vec<&'v Expr>,
83 cx: &'a LateContext<'a, 'tcx>,
86 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
87 fn extract(&mut self, op: BinOp_, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
89 if let ExprBinary(binop, ref lhs, ref rhs) = a.node {
91 v = self.extract(op, &[lhs, rhs], v)?;
100 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
101 // prevent folding of `cfg!` macros and the like
102 if !in_macro(e.span) {
104 ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
105 ExprBinary(binop, ref lhs, ref rhs) => match binop.node {
106 BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
107 BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
110 ExprLit(ref lit) => match lit.node {
111 LitKind::Bool(true) => return Ok(Bool::True),
112 LitKind::Bool(false) => return Ok(Bool::False),
118 for (n, expr) in self.terminals.iter().enumerate() {
119 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
120 #[allow(cast_possible_truncation)]
121 return Ok(Bool::Term(n as u8));
123 let negated = match e.node {
124 ExprBinary(binop, ref lhs, ref rhs) => {
128 hir_id: DUMMY_HIR_ID,
130 attrs: ThinVec::new(),
131 node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
135 BiEq => mk_expr(BiNe),
136 BiNe => mk_expr(BiEq),
137 BiGt => mk_expr(BiLe),
138 BiGe => mk_expr(BiLt),
139 BiLt => mk_expr(BiGe),
140 BiLe => mk_expr(BiGt),
146 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
147 #[allow(cast_possible_truncation)]
148 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
151 let n = self.terminals.len();
152 self.terminals.push(e);
154 #[allow(cast_possible_truncation)]
155 Ok(Bool::Term(n as u8))
157 Err("too many literals".to_owned())
162 // The boolean part of the return indicates whether some simplifications have been applied.
163 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
170 simplified: &mut bool,
172 use quine_mc_cluskey::Bool::*;
173 let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
183 Not(ref inner) => match **inner {
186 recurse(true, cx, inner, terminals, s, simplified)
188 Term(n) => match terminals[n as usize].node {
189 ExprBinary(binop, ref lhs, ref rhs) => {
190 let op = match binop.node {
199 return recurse(true, cx, inner, terminals, s, simplified);
203 s.push_str(&snip(lhs));
205 s.push_str(&snip(rhs));
208 ExprMethodCall(ref path, _, ref args) if args.len() == 1 => {
209 let negation = METHODS_WITH_NEGATION
211 .flat_map(|(a, b)| vec![(a, b), (b, a)])
212 .find(|&(a, _)| a == path.name.as_str());
213 if let Some((_, negation_method)) = negation {
215 s.push_str(&snip(&args[0]));
217 s.push_str(negation_method);
222 recurse(false, cx, inner, terminals, s, simplified)
227 recurse(false, cx, inner, terminals, s, simplified)
232 recurse(false, cx, inner, terminals, s, simplified)
239 if let Or(_) = v[0] {
240 s = recurse(true, cx, &v[0], terminals, s, simplified);
242 s = recurse(false, cx, &v[0], terminals, s, simplified);
244 for inner in &v[1..] {
246 if let Or(_) = *inner {
247 s = recurse(true, cx, inner, terminals, s, simplified);
249 s = recurse(false, cx, inner, terminals, s, simplified);
261 s = recurse(false, cx, &v[0], terminals, s, simplified);
262 for inner in &v[1..] {
264 s = recurse(false, cx, inner, terminals, s, simplified);
273 if let ExprBinary(..) = terminals[n as usize].node {
277 s.push_str(&snip(terminals[n as usize]));
279 if let ExprBinary(..) = terminals[n as usize].node {
287 let mut simplified = false;
288 let s = recurse(false, cx, suggestion, terminals, String::new(), &mut simplified);
292 fn simple_negate(b: Bool) -> Bool {
293 use quine_mc_cluskey::Bool::*;
297 t @ Term(_) => Not(Box::new(t)),
300 *el = simple_negate(::std::mem::replace(el, True));
306 *el = simple_negate(::std::mem::replace(el, True));
310 Not(inner) => *inner,
316 terminals: [usize; 32],
321 fn terminal_stats(b: &Bool) -> Stats {
322 fn recurse(b: &Bool, stats: &mut Stats) {
324 True | False => stats.ops += 1,
327 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
328 _ => stats.negations += 1,
330 recurse(inner, stats);
332 And(ref v) | Or(ref v) => {
333 stats.ops += v.len() - 1;
335 recurse(inner, stats);
338 Term(n) => stats.terminals[n as usize] += 1,
341 use quine_mc_cluskey::Bool::*;
342 let mut stats = Stats::default();
343 recurse(b, &mut stats);
347 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
348 fn bool_expr(&self, e: &Expr) {
349 let mut h2q = Hir2Qmm {
350 terminals: Vec::new(),
353 if let Ok(expr) = h2q.run(e) {
354 if h2q.terminals.len() > 8 {
355 // QMC has exponentially slow behavior as the number of terminals increases
356 // 8 is reasonable, it takes approximately 0.2 seconds.
361 let stats = terminal_stats(&expr);
362 let mut simplified = expr.simplify();
363 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
365 Bool::Not(_) | Bool::True | Bool::False => {},
366 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
368 let simple_negated = simple_negate(simple);
369 if simplified.iter().any(|s| *s == simple_negated) {
372 simplified.push(simple_negated);
374 let mut improvements = Vec::new();
375 'simplified: for suggestion in &simplified {
376 let simplified_stats = terminal_stats(suggestion);
377 let mut improvement = false;
379 // ignore any "simplifications" that end up requiring a terminal more often
380 // than in the original expression
381 if stats.terminals[i] < simplified_stats.terminals[i] {
382 continue 'simplified;
384 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
389 "this boolean expression contains a logic bug",
392 h2q.terminals[i].span,
393 "this expression can be optimized out by applying boolean operations to the \
398 "it would look like the following",
399 suggest(self.cx, suggestion, &h2q.terminals).0,
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| {
421 "this boolean expression can be simplified",
422 |db| { db.span_suggestions(e.span, "try", suggestions); },
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 ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
449 ExprUnary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
454 _ => walk_expr(self, e),
457 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
458 NestedVisitorMap::None