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
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"
48 pub struct NonminimalBool;
50 impl LintPass for NonminimalBool {
51 fn get_lints(&self) -> LintArray {
52 lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
56 impl LateLintPass for NonminimalBool {
57 fn check_item(&mut self, cx: &LateContext, item: &Item) {
58 NonminimalBoolVisitor(cx).visit_item(item)
62 struct NonminimalBoolVisitor<'a, 'tcx: 'a>(&'a LateContext<'a, 'tcx>);
64 use quine_mc_cluskey::Bool;
65 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
66 terminals: Vec<&'v Expr>,
67 cx: &'a LateContext<'a, 'tcx>,
70 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
71 fn extract(&mut self, op: BinOp_, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
73 if let ExprBinary(binop, ref lhs, ref rhs) = a.node {
75 v = self.extract(op, &[lhs, rhs], v)?;
84 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
85 // prevent folding of `cfg!` macros and the like
86 if !in_macro(self.cx, e.span) {
88 ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
89 ExprBinary(binop, ref lhs, ref rhs) => {
91 BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
92 BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
98 LitKind::Bool(true) => return Ok(Bool::True),
99 LitKind::Bool(false) => return Ok(Bool::False),
106 for (n, expr) in self.terminals.iter().enumerate() {
107 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
108 #[allow(cast_possible_truncation)]
109 return Ok(Bool::Term(n as u8));
111 let negated = match e.node {
112 ExprBinary(binop, ref lhs, ref rhs) => {
117 attrs: ThinVec::new(),
118 node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
122 BiEq => mk_expr(BiNe),
123 BiNe => mk_expr(BiEq),
124 BiGt => mk_expr(BiLe),
125 BiGe => mk_expr(BiLt),
126 BiLt => mk_expr(BiGe),
127 BiLe => mk_expr(BiGt),
133 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
134 #[allow(cast_possible_truncation)]
135 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
138 let n = self.terminals.len();
139 self.terminals.push(e);
141 #[allow(cast_possible_truncation)]
142 Ok(Bool::Term(n as u8))
144 Err("too many literals".to_owned())
149 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
150 fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
151 use quine_mc_cluskey::Bool::*;
152 let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
166 recurse(true, cx, inner, terminals, s)
169 if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
170 let op = match binop.node {
179 return recurse(true, cx, inner, terminals, s);
182 s.push_str(&snip(lhs));
184 s.push_str(&snip(rhs));
188 recurse(false, cx, inner, terminals, s)
193 recurse(false, cx, inner, terminals, s)
201 if let Or(_) = v[0] {
202 s = recurse(true, cx, &v[0], terminals, s);
204 s = recurse(false, cx, &v[0], terminals, s);
206 for inner in &v[1..] {
208 if let Or(_) = *inner {
209 s = recurse(true, cx, inner, terminals, s);
211 s = recurse(false, cx, inner, terminals, s);
223 s = recurse(false, cx, &v[0], terminals, s);
224 for inner in &v[1..] {
226 s = recurse(false, cx, inner, terminals, s);
235 if let ExprBinary(..) = terminals[n as usize].node {
239 s.push_str(&snip(terminals[n as usize]));
241 if let ExprBinary(..) = terminals[n as usize].node {
249 recurse(false, cx, suggestion, terminals, String::new())
252 fn simple_negate(b: Bool) -> Bool {
253 use quine_mc_cluskey::Bool::*;
257 t @ Term(_) => Not(Box::new(t)),
260 *el = simple_negate(::std::mem::replace(el, True));
266 *el = simple_negate(::std::mem::replace(el, True));
270 Not(inner) => *inner,
276 terminals: [usize; 32],
281 fn terminal_stats(b: &Bool) -> Stats {
282 fn recurse(b: &Bool, stats: &mut Stats) {
284 True | False => stats.ops += 1,
287 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
288 _ => stats.negations += 1,
290 recurse(inner, stats);
292 And(ref v) | Or(ref v) => {
293 stats.ops += v.len() - 1;
295 recurse(inner, stats);
298 Term(n) => stats.terminals[n as usize] += 1,
301 use quine_mc_cluskey::Bool::*;
302 let mut stats = Stats::default();
303 recurse(b, &mut stats);
307 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
308 fn bool_expr(&self, e: &Expr) {
309 let mut h2q = Hir2Qmm {
310 terminals: Vec::new(),
313 if let Ok(expr) = h2q.run(e) {
315 if h2q.terminals.len() > 8 {
316 // QMC has exponentially slow behavior as the number of terminals increases
317 // 8 is reasonable, it takes approximately 0.2 seconds.
322 let stats = terminal_stats(&expr);
323 let mut simplified = expr.simplify();
324 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
326 Bool::Not(_) | Bool::True | Bool::False => {}
327 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
329 let simple_negated = simple_negate(simple);
330 if simplified.iter().any(|s| *s == simple_negated) {
333 simplified.push(simple_negated);
335 let mut improvements = Vec::new();
336 'simplified: for suggestion in &simplified {
337 let simplified_stats = terminal_stats(suggestion);
338 let mut improvement = false;
340 // ignore any "simplifications" that end up requiring a terminal more often
341 // than in the original expression
342 if stats.terminals[i] < simplified_stats.terminals[i] {
343 continue 'simplified;
345 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
346 span_lint_and_then(self.0,
349 "this boolean expression contains a logic bug",
351 db.span_help(h2q.terminals[i].span,
352 "this expression can be optimized out by applying boolean operations to the \
354 db.span_suggestion(e.span,
355 "it would look like the following",
356 suggest(self.0, suggestion, &h2q.terminals));
358 // don't also lint `NONMINIMAL_BOOL`
361 // if the number of occurrences of a terminal decreases or any of the stats
362 // decreases while none increases
363 improvement |= (stats.terminals[i] > simplified_stats.terminals[i]) ||
364 (stats.negations > simplified_stats.negations &&
365 stats.ops == simplified_stats.ops) ||
366 (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
369 improvements.push(suggestion);
372 if !improvements.is_empty() {
373 span_lint_and_then(self.0,
376 "this boolean expression can be simplified",
378 for suggestion in &improvements {
379 db.span_suggestion(e.span, "try", suggest(self.0, suggestion, &h2q.terminals));
387 impl<'a, 'v, 'tcx> Visitor<'v> for NonminimalBoolVisitor<'a, 'tcx> {
388 fn visit_expr(&mut self, e: &'v Expr) {
389 if in_macro(self.0, e.span) {
393 ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
394 ExprUnary(UnNot, ref inner) => {
395 if self.0.tcx.node_types()[&inner.id].is_bool() {
401 _ => walk_expr(self, e),