1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::hir::intravisit::*;
4 use syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
5 use syntax::codemap::{dummy_spanned, Span, DUMMY_SP};
6 use syntax::util::ThinVec;
7 use utils::{in_macro, snippet_opt, span_lint_and_then, 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) => match binop.node {
100 BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
101 BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
104 ExprLit(ref lit) => match lit.node {
105 LitKind::Bool(true) => return Ok(Bool::True),
106 LitKind::Bool(false) => return Ok(Bool::False),
112 for (n, expr) in self.terminals.iter().enumerate() {
113 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
114 #[allow(cast_possible_truncation)]
115 return Ok(Bool::Term(n as u8));
117 let negated = match e.node {
118 ExprBinary(binop, ref lhs, ref rhs) => {
122 hir_id: DUMMY_HIR_ID,
124 attrs: ThinVec::new(),
125 node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
129 BiEq => mk_expr(BiNe),
130 BiNe => mk_expr(BiEq),
131 BiGt => mk_expr(BiLe),
132 BiGe => mk_expr(BiLt),
133 BiLt => mk_expr(BiGe),
134 BiLe => mk_expr(BiGt),
140 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
141 #[allow(cast_possible_truncation)]
142 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
145 let n = self.terminals.len();
146 self.terminals.push(e);
148 #[allow(cast_possible_truncation)]
149 Ok(Bool::Term(n as u8))
151 Err("too many literals".to_owned())
156 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
157 fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
158 use quine_mc_cluskey::Bool::*;
159 let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
169 Not(ref inner) => match **inner {
172 recurse(true, cx, inner, terminals, s)
174 Term(n) => if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
175 let op = match binop.node {
184 return recurse(true, cx, inner, terminals, s);
187 s.push_str(&snip(lhs));
189 s.push_str(&snip(rhs));
193 recurse(false, cx, inner, terminals, s)
197 recurse(false, cx, inner, terminals, s)
204 if let Or(_) = v[0] {
205 s = recurse(true, cx, &v[0], terminals, s);
207 s = recurse(false, cx, &v[0], terminals, s);
209 for inner in &v[1..] {
211 if let Or(_) = *inner {
212 s = recurse(true, cx, inner, terminals, s);
214 s = recurse(false, cx, inner, terminals, s);
226 s = recurse(false, cx, &v[0], terminals, s);
227 for inner in &v[1..] {
229 s = recurse(false, cx, inner, terminals, s);
238 if let ExprBinary(..) = terminals[n as usize].node {
242 s.push_str(&snip(terminals[n as usize]));
244 if let ExprBinary(..) = terminals[n as usize].node {
252 recurse(false, cx, suggestion, terminals, String::new())
255 fn simple_negate(b: Bool) -> Bool {
256 use quine_mc_cluskey::Bool::*;
260 t @ Term(_) => Not(Box::new(t)),
263 *el = simple_negate(::std::mem::replace(el, True));
269 *el = simple_negate(::std::mem::replace(el, True));
273 Not(inner) => *inner,
279 terminals: [usize; 32],
284 fn terminal_stats(b: &Bool) -> Stats {
285 fn recurse(b: &Bool, stats: &mut Stats) {
287 True | False => stats.ops += 1,
290 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
291 _ => stats.negations += 1,
293 recurse(inner, stats);
295 And(ref v) | Or(ref v) => {
296 stats.ops += v.len() - 1;
298 recurse(inner, stats);
301 Term(n) => stats.terminals[n as usize] += 1,
304 use quine_mc_cluskey::Bool::*;
305 let mut stats = Stats::default();
306 recurse(b, &mut stats);
310 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
311 fn bool_expr(&self, e: &Expr) {
312 let mut h2q = Hir2Qmm {
313 terminals: Vec::new(),
316 if let Ok(expr) = h2q.run(e) {
317 if h2q.terminals.len() > 8 {
318 // QMC has exponentially slow behavior as the number of terminals increases
319 // 8 is reasonable, it takes approximately 0.2 seconds.
324 let stats = terminal_stats(&expr);
325 let mut simplified = expr.simplify();
326 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
328 Bool::Not(_) | Bool::True | Bool::False => {},
329 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
331 let simple_negated = simple_negate(simple);
332 if simplified.iter().any(|s| *s == simple_negated) {
335 simplified.push(simple_negated);
337 let mut improvements = Vec::new();
338 'simplified: for suggestion in &simplified {
339 let simplified_stats = terminal_stats(suggestion);
340 let mut improvement = false;
342 // ignore any "simplifications" that end up requiring a terminal more often
343 // than in the original expression
344 if stats.terminals[i] < simplified_stats.terminals[i] {
345 continue 'simplified;
347 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
352 "this boolean expression contains a logic bug",
355 h2q.terminals[i].span,
356 "this expression can be optimized out by applying boolean operations to the \
361 "it would look like the following",
362 suggest(self.cx, suggestion, &h2q.terminals),
366 // don't also lint `NONMINIMAL_BOOL`
369 // if the number of occurrences of a terminal decreases or any of the stats
370 // decreases while none increases
371 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
372 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
373 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
376 improvements.push(suggestion);
379 if !improvements.is_empty() {
384 "this boolean expression can be simplified",
391 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
401 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
402 fn visit_expr(&mut self, e: &'tcx Expr) {
403 if in_macro(e.span) {
407 ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
408 ExprUnary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
413 _ => walk_expr(self, e),
416 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
417 NestedVisitorMap::None