1 use rustc::lint::{LintArray, LateLintPass, LateContext, LintPass};
3 use rustc::hir::intravisit::*;
4 use syntax::ast::{LitKind, DUMMY_NODE_ID};
5 use syntax::codemap::{DUMMY_SP, dummy_spanned};
6 use utils::{span_lint_and_then, in_macro, snippet_opt, SpanlessEq};
8 /// **What it does:** This lint checks for boolean expressions that can be written more concisely
10 /// **Why is this bad?** Readability of boolean expressions suffers from unnecesessary duplication
12 /// **Known problems:** Ignores short circuting behavior of `||` and `&&`. Ignores `|`, `&` and `^`.
14 /// **Example:** `if a && true` should be `if a` and `!(a == b)` should be `a != b`
16 pub NONMINIMAL_BOOL, Allow,
17 "checks for boolean expressions that can be written more concisely"
20 /// **What it does:** This lint checks for boolean expressions that contain terminals that can be eliminated
22 /// **Why is this bad?** This is most likely a logic bug
24 /// **Known problems:** Ignores short circuiting behavior
26 /// **Example:** The `b` in `if a && b || a` is unnecessary because the expression is equivalent to `if a`
29 "checks for boolean expressions that contain terminals which can be eliminated"
33 pub struct NonminimalBool;
35 impl LintPass for NonminimalBool {
36 fn get_lints(&self) -> LintArray {
37 lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
41 impl LateLintPass for NonminimalBool {
42 fn check_item(&mut self, cx: &LateContext, item: &Item) {
43 NonminimalBoolVisitor(cx).visit_item(item)
47 struct NonminimalBoolVisitor<'a, 'tcx: 'a>(&'a LateContext<'a, 'tcx>);
49 use quine_mc_cluskey::Bool;
50 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
51 terminals: Vec<&'v Expr>,
52 cx: &'a LateContext<'a, 'tcx>,
55 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
56 fn extract(&mut self, op: BinOp_, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
58 if let ExprBinary(binop, ref lhs, ref rhs) = a.node {
60 v = self.extract(op, &[lhs, rhs], v)?;
69 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
70 // prevent folding of `cfg!` macros and the like
71 if !in_macro(self.cx, e.span) {
73 ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
74 ExprBinary(binop, ref lhs, ref rhs) => {
76 BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
77 BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
83 LitKind::Bool(true) => return Ok(Bool::True),
84 LitKind::Bool(false) => return Ok(Bool::False),
91 for (n, expr) in self.terminals.iter().enumerate() {
92 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
93 #[allow(cast_possible_truncation)]
94 return Ok(Bool::Term(n as u8));
96 let negated = match e.node {
97 ExprBinary(binop, ref lhs, ref rhs) => {
103 node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
107 BiEq => mk_expr(BiNe),
108 BiNe => mk_expr(BiEq),
109 BiGt => mk_expr(BiLe),
110 BiGe => mk_expr(BiLt),
111 BiLt => mk_expr(BiGe),
112 BiLe => mk_expr(BiGt),
118 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
119 #[allow(cast_possible_truncation)]
120 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
123 let n = self.terminals.len();
124 self.terminals.push(e);
126 #[allow(cast_possible_truncation)]
127 Ok(Bool::Term(n as u8))
129 Err("too many literals".to_owned())
134 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
135 fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
136 use quine_mc_cluskey::Bool::*;
137 let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
151 recurse(true, cx, inner, terminals, s)
154 if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
155 let op = match binop.node {
164 return recurse(true, cx, inner, terminals, s);
167 s.push_str(&snip(lhs));
169 s.push_str(&snip(rhs));
173 recurse(false, cx, inner, terminals, s)
178 recurse(false, cx, inner, terminals, s)
186 if let Or(_) = v[0] {
187 s = recurse(true, cx, &v[0], terminals, s);
189 s = recurse(false, cx, &v[0], terminals, s);
191 for inner in &v[1..] {
193 if let Or(_) = *inner {
194 s = recurse(true, cx, inner, terminals, s);
196 s = recurse(false, cx, inner, terminals, s);
208 s = recurse(false, cx, &v[0], terminals, s);
209 for inner in &v[1..] {
211 s = recurse(false, cx, inner, terminals, s);
220 if let ExprBinary(..) = terminals[n as usize].node {
224 s.push_str(&snip(terminals[n as usize]));
226 if let ExprBinary(..) = terminals[n as usize].node {
234 recurse(false, cx, suggestion, terminals, String::new())
237 fn simple_negate(b: Bool) -> Bool {
238 use quine_mc_cluskey::Bool::*;
242 t @ Term(_) => Not(Box::new(t)),
245 *el = simple_negate(::std::mem::replace(el, True));
251 *el = simple_negate(::std::mem::replace(el, True));
255 Not(inner) => *inner,
261 terminals: [usize; 32],
266 fn terminal_stats(b: &Bool) -> Stats {
267 fn recurse(b: &Bool, stats: &mut Stats) {
269 True | False => stats.ops += 1,
272 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
273 _ => stats.negations += 1,
275 recurse(inner, stats);
277 And(ref v) | Or(ref v) => {
278 stats.ops += v.len() - 1;
280 recurse(inner, stats);
283 Term(n) => stats.terminals[n as usize] += 1,
286 use quine_mc_cluskey::Bool::*;
287 let mut stats = Stats::default();
288 recurse(b, &mut stats);
292 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
293 fn bool_expr(&self, e: &Expr) {
294 let mut h2q = Hir2Qmm {
295 terminals: Vec::new(),
298 if let Ok(expr) = h2q.run(e) {
300 if h2q.terminals.len() > 8 {
301 // QMC has exponentially slow behavior as the number of terminals increases
302 // 8 is reasonable, it takes approximately 0.2 seconds.
307 let stats = terminal_stats(&expr);
308 let mut simplified = expr.simplify();
309 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
311 Bool::Not(_) | Bool::True | Bool::False => {}
312 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
314 let simple_negated = simple_negate(simple);
315 if simplified.iter().any(|s| *s == simple_negated) {
318 simplified.push(simple_negated);
320 let mut improvements = Vec::new();
321 'simplified: for suggestion in &simplified {
322 let simplified_stats = terminal_stats(suggestion);
323 let mut improvement = false;
325 // ignore any "simplifications" that end up requiring a terminal more often than in the original expression
326 if stats.terminals[i] < simplified_stats.terminals[i] {
327 continue 'simplified;
329 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
330 span_lint_and_then(self.0,
333 "this boolean expression contains a logic bug",
335 db.span_help(h2q.terminals[i].span,
336 "this expression can be optimized out by applying \
337 boolean operations to the outer expression");
338 db.span_suggestion(e.span,
339 "it would look like the following",
340 suggest(self.0, suggestion, &h2q.terminals));
342 // don't also lint `NONMINIMAL_BOOL`
345 // if the number of occurrences of a terminal decreases or any of the stats decreases while none increases
346 improvement |= (stats.terminals[i] > simplified_stats.terminals[i]) ||
347 (stats.negations > simplified_stats.negations &&
348 stats.ops == simplified_stats.ops) ||
349 (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
352 improvements.push(suggestion);
355 if !improvements.is_empty() {
356 span_lint_and_then(self.0,
359 "this boolean expression can be simplified",
361 for suggestion in &improvements {
362 db.span_suggestion(e.span,
364 suggest(self.0, suggestion, &h2q.terminals));
372 impl<'a, 'v, 'tcx> Visitor<'v> for NonminimalBoolVisitor<'a, 'tcx> {
373 fn visit_expr(&mut self, e: &'v Expr) {
374 if in_macro(self.0, e.span) {
378 ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
379 ExprUnary(UnNot, ref inner) => {
380 if self.0.tcx.node_types()[&inner.id].is_bool() {
386 _ => walk_expr(self, e),