1 use rustc::lint::{LintArray, LateLintPass, LateContext, LintPass};
3 use rustc::hir::intravisit::*;
4 use syntax::ast::{LitKind, DUMMY_NODE_ID, NodeId};
5 use syntax::codemap::{DUMMY_SP, dummy_spanned, Span};
6 use syntax::util::ThinVec;
7 use utils::{span_lint_and_then, in_macro, snippet_opt, 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 #[derive(Copy, Clone)]
48 pub struct NonminimalBool;
50 impl LintPass for NonminimalBool {
51 fn get_lints(&self) -> LintArray {
52 lint_array!(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: 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: BinOp_, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
83 if let ExprBinary(binop, ref lhs, ref 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 ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
99 ExprBinary(binop, ref lhs, ref rhs) => {
101 BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
102 BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
106 ExprLit(ref lit) => {
108 LitKind::Bool(true) => return Ok(Bool::True),
109 LitKind::Bool(false) => return Ok(Bool::False),
116 for (n, expr) in self.terminals.iter().enumerate() {
117 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
118 #[allow(cast_possible_truncation)] return Ok(Bool::Term(n as u8));
120 let negated = match e.node {
121 ExprBinary(binop, ref lhs, ref rhs) => {
126 attrs: ThinVec::new(),
127 node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
131 BiEq => mk_expr(BiNe),
132 BiNe => mk_expr(BiEq),
133 BiGt => mk_expr(BiLe),
134 BiGe => mk_expr(BiLt),
135 BiLt => mk_expr(BiGe),
136 BiLe => mk_expr(BiGt),
142 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
143 #[allow(cast_possible_truncation)] return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
146 let n = self.terminals.len();
147 self.terminals.push(e);
149 #[allow(cast_possible_truncation)] Ok(Bool::Term(n as u8))
151 Err("too many literals".to_owned())
156 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
157 fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
158 use quine_mc_cluskey::Bool::*;
159 let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
173 recurse(true, cx, inner, terminals, s)
176 if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
177 let op = match binop.node {
186 return recurse(true, cx, inner, terminals, s);
189 s.push_str(&snip(lhs));
191 s.push_str(&snip(rhs));
195 recurse(false, cx, inner, terminals, s)
200 recurse(false, cx, inner, terminals, s)
208 if let Or(_) = v[0] {
209 s = recurse(true, cx, &v[0], terminals, s);
211 s = recurse(false, cx, &v[0], terminals, s);
213 for inner in &v[1..] {
215 if let Or(_) = *inner {
216 s = recurse(true, cx, inner, terminals, s);
218 s = recurse(false, cx, inner, terminals, s);
230 s = recurse(false, cx, &v[0], terminals, s);
231 for inner in &v[1..] {
233 s = recurse(false, cx, inner, terminals, s);
242 if let ExprBinary(..) = terminals[n as usize].node {
246 s.push_str(&snip(terminals[n as usize]));
248 if let ExprBinary(..) = terminals[n as usize].node {
256 recurse(false, cx, suggestion, terminals, String::new())
259 fn simple_negate(b: Bool) -> Bool {
260 use quine_mc_cluskey::Bool::*;
264 t @ Term(_) => Not(Box::new(t)),
267 *el = simple_negate(::std::mem::replace(el, True));
273 *el = simple_negate(::std::mem::replace(el, True));
277 Not(inner) => *inner,
283 terminals: [usize; 32],
288 fn terminal_stats(b: &Bool) -> Stats {
289 fn recurse(b: &Bool, stats: &mut Stats) {
291 True | False => stats.ops += 1,
294 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
295 _ => stats.negations += 1,
297 recurse(inner, stats);
299 And(ref v) | Or(ref v) => {
300 stats.ops += v.len() - 1;
302 recurse(inner, stats);
305 Term(n) => stats.terminals[n as usize] += 1,
308 use quine_mc_cluskey::Bool::*;
309 let mut stats = Stats::default();
310 recurse(b, &mut stats);
314 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
315 fn bool_expr(&self, e: &Expr) {
316 let mut h2q = Hir2Qmm {
317 terminals: Vec::new(),
320 if let Ok(expr) = h2q.run(e) {
322 if h2q.terminals.len() > 8 {
323 // QMC has exponentially slow behavior as the number of terminals increases
324 // 8 is reasonable, it takes approximately 0.2 seconds.
329 let stats = terminal_stats(&expr);
330 let mut simplified = expr.simplify();
331 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
333 Bool::Not(_) | Bool::True | Bool::False => {},
334 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
336 let simple_negated = simple_negate(simple);
337 if simplified.iter().any(|s| *s == simple_negated) {
340 simplified.push(simple_negated);
342 let mut improvements = Vec::new();
343 'simplified: for suggestion in &simplified {
344 let simplified_stats = terminal_stats(suggestion);
345 let mut improvement = false;
347 // ignore any "simplifications" that end up requiring a terminal more often
348 // than in the original expression
349 if stats.terminals[i] < simplified_stats.terminals[i] {
350 continue 'simplified;
352 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
357 "this boolean expression contains a logic bug",
360 h2q.terminals[i].span,
361 "this expression can be optimized out by applying boolean operations to the \
366 "it would look like the following",
367 suggest(self.cx, suggestion, &h2q.terminals),
371 // don't also lint `NONMINIMAL_BOOL`
374 // if the number of occurrences of a terminal decreases or any of the stats
375 // decreases while none increases
376 improvement |= (stats.terminals[i] > simplified_stats.terminals[i]) ||
377 (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops) ||
378 (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
381 improvements.push(suggestion);
384 if !improvements.is_empty() {
389 "this boolean expression can be simplified",
396 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
406 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
407 fn visit_expr(&mut self, e: &'tcx Expr) {
408 if in_macro(e.span) {
412 ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
413 ExprUnary(UnNot, ref inner) => {
414 if self.cx.tables.node_types[&inner.id].is_bool() {
420 _ => walk_expr(self, e),
423 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
424 NestedVisitorMap::None