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"
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)]
119 return Ok(Bool::Term(n as u8));
121 let negated = match e.node {
122 ExprBinary(binop, ref lhs, ref rhs) => {
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)]
145 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
148 let n = self.terminals.len();
149 self.terminals.push(e);
151 #[allow(cast_possible_truncation)]
152 Ok(Bool::Term(n as u8))
154 Err("too many literals".to_owned())
159 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
160 fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
161 use quine_mc_cluskey::Bool::*;
162 let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
176 recurse(true, cx, inner, terminals, s)
179 if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
180 let op = match binop.node {
189 return recurse(true, cx, inner, terminals, s);
192 s.push_str(&snip(lhs));
194 s.push_str(&snip(rhs));
198 recurse(false, cx, inner, terminals, s)
203 recurse(false, cx, inner, terminals, s)
211 if let Or(_) = v[0] {
212 s = recurse(true, cx, &v[0], terminals, s);
214 s = recurse(false, cx, &v[0], terminals, s);
216 for inner in &v[1..] {
218 if let Or(_) = *inner {
219 s = recurse(true, cx, inner, terminals, s);
221 s = recurse(false, cx, inner, terminals, s);
233 s = recurse(false, cx, &v[0], terminals, s);
234 for inner in &v[1..] {
236 s = recurse(false, cx, inner, terminals, s);
245 if let ExprBinary(..) = terminals[n as usize].node {
249 s.push_str(&snip(terminals[n as usize]));
251 if let ExprBinary(..) = terminals[n as usize].node {
259 recurse(false, cx, suggestion, terminals, String::new())
262 fn simple_negate(b: Bool) -> Bool {
263 use quine_mc_cluskey::Bool::*;
267 t @ Term(_) => Not(Box::new(t)),
270 *el = simple_negate(::std::mem::replace(el, True));
276 *el = simple_negate(::std::mem::replace(el, True));
280 Not(inner) => *inner,
286 terminals: [usize; 32],
291 fn terminal_stats(b: &Bool) -> Stats {
292 fn recurse(b: &Bool, stats: &mut Stats) {
294 True | False => stats.ops += 1,
297 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
298 _ => stats.negations += 1,
300 recurse(inner, stats);
302 And(ref v) | Or(ref v) => {
303 stats.ops += v.len() - 1;
305 recurse(inner, stats);
308 Term(n) => stats.terminals[n as usize] += 1,
311 use quine_mc_cluskey::Bool::*;
312 let mut stats = Stats::default();
313 recurse(b, &mut stats);
317 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
318 fn bool_expr(&self, e: &Expr) {
319 let mut h2q = Hir2Qmm {
320 terminals: Vec::new(),
323 if let Ok(expr) = h2q.run(e) {
325 if h2q.terminals.len() > 8 {
326 // QMC has exponentially slow behavior as the number of terminals increases
327 // 8 is reasonable, it takes approximately 0.2 seconds.
332 let stats = terminal_stats(&expr);
333 let mut simplified = expr.simplify();
334 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
336 Bool::Not(_) | Bool::True | Bool::False => {},
337 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
339 let simple_negated = simple_negate(simple);
340 if simplified.iter().any(|s| *s == simple_negated) {
343 simplified.push(simple_negated);
345 let mut improvements = Vec::new();
346 'simplified: for suggestion in &simplified {
347 let simplified_stats = terminal_stats(suggestion);
348 let mut improvement = false;
350 // ignore any "simplifications" that end up requiring a terminal more often
351 // than in the original expression
352 if stats.terminals[i] < simplified_stats.terminals[i] {
353 continue 'simplified;
355 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
356 span_lint_and_then(self.cx,
359 "this boolean expression contains a logic bug",
361 db.span_help(h2q.terminals[i].span,
362 "this expression can be optimized out by applying boolean operations to the \
364 db.span_suggestion(e.span,
365 "it would look like the following",
366 suggest(self.cx, suggestion, &h2q.terminals));
368 // don't also lint `NONMINIMAL_BOOL`
371 // if the number of occurrences of a terminal decreases or any of the stats
372 // decreases while none increases
373 improvement |= (stats.terminals[i] > simplified_stats.terminals[i]) ||
374 (stats.negations > simplified_stats.negations &&
375 stats.ops == simplified_stats.ops) ||
376 (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
379 improvements.push(suggestion);
382 if !improvements.is_empty() {
383 span_lint_and_then(self.cx,
386 "this boolean expression can be simplified",
387 |db| for suggestion in &improvements {
388 db.span_suggestion(e.span, "try", suggest(self.cx, suggestion, &h2q.terminals));
389 break; // FIXME: multiple suggestions in rustc are broken
396 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
397 fn visit_expr(&mut self, e: &'tcx Expr) {
398 if in_macro(e.span) {
402 ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
403 ExprUnary(UnNot, ref inner) => {
404 if self.cx.tables.node_types[&inner.id].is_bool() {
410 _ => walk_expr(self, e),
413 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
414 NestedVisitorMap::None