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) => {
125 hir_id: DUMMY_HIR_ID,
127 attrs: ThinVec::new(),
128 node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
132 BiEq => mk_expr(BiNe),
133 BiNe => mk_expr(BiEq),
134 BiGt => mk_expr(BiLe),
135 BiGe => mk_expr(BiLt),
136 BiLt => mk_expr(BiGe),
137 BiLe => mk_expr(BiGt),
143 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
144 #[allow(cast_possible_truncation)] return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
147 let n = self.terminals.len();
148 self.terminals.push(e);
150 #[allow(cast_possible_truncation)] Ok(Bool::Term(n as u8))
152 Err("too many literals".to_owned())
157 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
158 fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
159 use quine_mc_cluskey::Bool::*;
160 let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
174 recurse(true, cx, inner, terminals, s)
177 if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
178 let op = match binop.node {
187 return recurse(true, cx, inner, terminals, s);
190 s.push_str(&snip(lhs));
192 s.push_str(&snip(rhs));
196 recurse(false, cx, inner, terminals, s)
201 recurse(false, cx, inner, terminals, s)
209 if let Or(_) = v[0] {
210 s = recurse(true, cx, &v[0], terminals, s);
212 s = recurse(false, cx, &v[0], terminals, s);
214 for inner in &v[1..] {
216 if let Or(_) = *inner {
217 s = recurse(true, cx, inner, terminals, s);
219 s = recurse(false, cx, inner, terminals, s);
231 s = recurse(false, cx, &v[0], terminals, s);
232 for inner in &v[1..] {
234 s = recurse(false, cx, inner, terminals, s);
243 if let ExprBinary(..) = terminals[n as usize].node {
247 s.push_str(&snip(terminals[n as usize]));
249 if let ExprBinary(..) = terminals[n as usize].node {
257 recurse(false, cx, suggestion, terminals, String::new())
260 fn simple_negate(b: Bool) -> Bool {
261 use quine_mc_cluskey::Bool::*;
265 t @ Term(_) => Not(Box::new(t)),
268 *el = simple_negate(::std::mem::replace(el, True));
274 *el = simple_negate(::std::mem::replace(el, True));
278 Not(inner) => *inner,
284 terminals: [usize; 32],
289 fn terminal_stats(b: &Bool) -> Stats {
290 fn recurse(b: &Bool, stats: &mut Stats) {
292 True | False => stats.ops += 1,
295 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
296 _ => stats.negations += 1,
298 recurse(inner, stats);
300 And(ref v) | Or(ref v) => {
301 stats.ops += v.len() - 1;
303 recurse(inner, stats);
306 Term(n) => stats.terminals[n as usize] += 1,
309 use quine_mc_cluskey::Bool::*;
310 let mut stats = Stats::default();
311 recurse(b, &mut stats);
315 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
316 fn bool_expr(&self, e: &Expr) {
317 let mut h2q = Hir2Qmm {
318 terminals: Vec::new(),
321 if let Ok(expr) = h2q.run(e) {
323 if h2q.terminals.len() > 8 {
324 // QMC has exponentially slow behavior as the number of terminals increases
325 // 8 is reasonable, it takes approximately 0.2 seconds.
330 let stats = terminal_stats(&expr);
331 let mut simplified = expr.simplify();
332 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
334 Bool::Not(_) | Bool::True | Bool::False => {},
335 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
337 let simple_negated = simple_negate(simple);
338 if simplified.iter().any(|s| *s == simple_negated) {
341 simplified.push(simple_negated);
343 let mut improvements = Vec::new();
344 'simplified: for suggestion in &simplified {
345 let simplified_stats = terminal_stats(suggestion);
346 let mut improvement = false;
348 // ignore any "simplifications" that end up requiring a terminal more often
349 // than in the original expression
350 if stats.terminals[i] < simplified_stats.terminals[i] {
351 continue 'simplified;
353 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
358 "this boolean expression contains a logic bug",
361 h2q.terminals[i].span,
362 "this expression can be optimized out by applying boolean operations to the \
367 "it would look like the following",
368 suggest(self.cx, suggestion, &h2q.terminals),
372 // don't also lint `NONMINIMAL_BOOL`
375 // if the number of occurrences of a terminal decreases or any of the stats
376 // decreases while none increases
377 improvement |= (stats.terminals[i] > simplified_stats.terminals[i]) ||
378 (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops) ||
379 (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
382 improvements.push(suggestion);
385 if !improvements.is_empty() {
390 "this boolean expression can be simplified",
397 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
407 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
408 fn visit_expr(&mut self, e: &'tcx Expr) {
409 if in_macro(e.span) {
413 ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
414 ExprUnary(UnNot, ref inner) => {
415 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
421 _ => walk_expr(self, e),
424 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
425 NestedVisitorMap::None