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 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
25 "boolean expressions that can be written more concisely"
28 /// **What it does:** Checks for boolean expressions that contain terminals that
29 /// can be eliminated.
31 /// **Why is this bad?** This is most likely a logic bug.
33 /// **Known problems:** Ignores short circuiting behavior.
37 /// if a && b || a { ... }
39 /// The `b` is unnecessary, the expression is equivalent to `if a`.
43 "boolean expressions that contain terminals which can be eliminated"
47 pub struct NonminimalBool;
49 impl LintPass for NonminimalBool {
50 fn get_lints(&self) -> LintArray {
51 lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
55 impl LateLintPass for NonminimalBool {
56 fn check_item(&mut self, cx: &LateContext, item: &Item) {
57 NonminimalBoolVisitor(cx).visit_item(item)
61 struct NonminimalBoolVisitor<'a, 'tcx: 'a>(&'a LateContext<'a, 'tcx>);
63 use quine_mc_cluskey::Bool;
64 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
65 terminals: Vec<&'v Expr>,
66 cx: &'a LateContext<'a, 'tcx>,
69 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
70 fn extract(&mut self, op: BinOp_, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
72 if let ExprBinary(binop, ref lhs, ref rhs) = a.node {
74 v = self.extract(op, &[lhs, rhs], v)?;
83 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
84 // prevent folding of `cfg!` macros and the like
85 if !in_macro(self.cx, e.span) {
87 ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
88 ExprBinary(binop, ref lhs, ref rhs) => {
90 BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
91 BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
97 LitKind::Bool(true) => return Ok(Bool::True),
98 LitKind::Bool(false) => return Ok(Bool::False),
105 for (n, expr) in self.terminals.iter().enumerate() {
106 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
107 #[allow(cast_possible_truncation)]
108 return Ok(Bool::Term(n as u8));
110 let negated = match e.node {
111 ExprBinary(binop, ref lhs, ref rhs) => {
116 attrs: ThinVec::new(),
117 node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
121 BiEq => mk_expr(BiNe),
122 BiNe => mk_expr(BiEq),
123 BiGt => mk_expr(BiLe),
124 BiGe => mk_expr(BiLt),
125 BiLt => mk_expr(BiGe),
126 BiLe => mk_expr(BiGt),
132 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
133 #[allow(cast_possible_truncation)]
134 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
137 let n = self.terminals.len();
138 self.terminals.push(e);
140 #[allow(cast_possible_truncation)]
141 Ok(Bool::Term(n as u8))
143 Err("too many literals".to_owned())
148 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
149 fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
150 use quine_mc_cluskey::Bool::*;
151 let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
165 recurse(true, cx, inner, terminals, s)
168 if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
169 let op = match binop.node {
178 return recurse(true, cx, inner, terminals, s);
181 s.push_str(&snip(lhs));
183 s.push_str(&snip(rhs));
187 recurse(false, cx, inner, terminals, s)
192 recurse(false, cx, inner, terminals, s)
200 if let Or(_) = v[0] {
201 s = recurse(true, cx, &v[0], terminals, s);
203 s = recurse(false, cx, &v[0], terminals, s);
205 for inner in &v[1..] {
207 if let Or(_) = *inner {
208 s = recurse(true, cx, inner, terminals, s);
210 s = recurse(false, cx, inner, terminals, s);
222 s = recurse(false, cx, &v[0], terminals, s);
223 for inner in &v[1..] {
225 s = recurse(false, cx, inner, terminals, s);
234 if let ExprBinary(..) = terminals[n as usize].node {
238 s.push_str(&snip(terminals[n as usize]));
240 if let ExprBinary(..) = terminals[n as usize].node {
248 recurse(false, cx, suggestion, terminals, String::new())
251 fn simple_negate(b: Bool) -> Bool {
252 use quine_mc_cluskey::Bool::*;
256 t @ Term(_) => Not(Box::new(t)),
259 *el = simple_negate(::std::mem::replace(el, True));
265 *el = simple_negate(::std::mem::replace(el, True));
269 Not(inner) => *inner,
275 terminals: [usize; 32],
280 fn terminal_stats(b: &Bool) -> Stats {
281 fn recurse(b: &Bool, stats: &mut Stats) {
283 True | False => stats.ops += 1,
286 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
287 _ => stats.negations += 1,
289 recurse(inner, stats);
291 And(ref v) | Or(ref v) => {
292 stats.ops += v.len() - 1;
294 recurse(inner, stats);
297 Term(n) => stats.terminals[n as usize] += 1,
300 use quine_mc_cluskey::Bool::*;
301 let mut stats = Stats::default();
302 recurse(b, &mut stats);
306 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
307 fn bool_expr(&self, e: &Expr) {
308 let mut h2q = Hir2Qmm {
309 terminals: Vec::new(),
312 if let Ok(expr) = h2q.run(e) {
314 if h2q.terminals.len() > 8 {
315 // QMC has exponentially slow behavior as the number of terminals increases
316 // 8 is reasonable, it takes approximately 0.2 seconds.
321 let stats = terminal_stats(&expr);
322 let mut simplified = expr.simplify();
323 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
325 Bool::Not(_) | Bool::True | Bool::False => {}
326 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
328 let simple_negated = simple_negate(simple);
329 if simplified.iter().any(|s| *s == simple_negated) {
332 simplified.push(simple_negated);
334 let mut improvements = Vec::new();
335 'simplified: for suggestion in &simplified {
336 let simplified_stats = terminal_stats(suggestion);
337 let mut improvement = false;
339 // ignore any "simplifications" that end up requiring a terminal more often
340 // than in the original expression
341 if stats.terminals[i] < simplified_stats.terminals[i] {
342 continue 'simplified;
344 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
345 span_lint_and_then(self.0,
348 "this boolean expression contains a logic bug",
350 db.span_help(h2q.terminals[i].span,
351 "this expression can be optimized out by applying boolean operations to the \
353 db.span_suggestion(e.span,
354 "it would look like the following",
355 suggest(self.0, suggestion, &h2q.terminals));
357 // don't also lint `NONMINIMAL_BOOL`
360 // if the number of occurrences of a terminal decreases or any of the stats
361 // decreases while none increases
362 improvement |= (stats.terminals[i] > simplified_stats.terminals[i]) ||
363 (stats.negations > simplified_stats.negations &&
364 stats.ops == simplified_stats.ops) ||
365 (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
368 improvements.push(suggestion);
371 if !improvements.is_empty() {
372 span_lint_and_then(self.0,
375 "this boolean expression can be simplified",
377 for suggestion in &improvements {
378 db.span_suggestion(e.span, "try", suggest(self.0, suggestion, &h2q.terminals));
386 impl<'a, 'v, 'tcx> Visitor<'v> for NonminimalBoolVisitor<'a, 'tcx> {
387 fn visit_expr(&mut self, e: &'v Expr) {
388 if in_macro(self.0, e.span) {
392 ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
393 ExprUnary(UnNot, ref inner) => {
394 if self.0.tcx.node_types()[&inner.id].is_bool() {
400 _ => walk_expr(self, e),