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<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
57 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
58 NonminimalBoolVisitor { cx: cx }.visit_item(item)
62 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
63 cx: &'a LateContext<'a, 'tcx>,
66 use quine_mc_cluskey::Bool;
67 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
68 terminals: Vec<&'v Expr>,
69 cx: &'a LateContext<'a, 'tcx>,
72 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
73 fn extract(&mut self, op: BinOp_, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
75 if let ExprBinary(binop, ref lhs, ref rhs) = a.node {
77 v = self.extract(op, &[lhs, rhs], v)?;
86 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
87 // prevent folding of `cfg!` macros and the like
88 if !in_macro(self.cx, e.span) {
90 ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
91 ExprBinary(binop, ref lhs, ref rhs) => {
93 BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
94 BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
100 LitKind::Bool(true) => return Ok(Bool::True),
101 LitKind::Bool(false) => return Ok(Bool::False),
108 for (n, expr) in self.terminals.iter().enumerate() {
109 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
110 #[allow(cast_possible_truncation)]
111 return Ok(Bool::Term(n as u8));
113 let negated = match e.node {
114 ExprBinary(binop, ref lhs, ref rhs) => {
119 attrs: ThinVec::new(),
120 node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
124 BiEq => mk_expr(BiNe),
125 BiNe => mk_expr(BiEq),
126 BiGt => mk_expr(BiLe),
127 BiGe => mk_expr(BiLt),
128 BiLt => mk_expr(BiGe),
129 BiLe => mk_expr(BiGt),
135 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
136 #[allow(cast_possible_truncation)]
137 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
140 let n = self.terminals.len();
141 self.terminals.push(e);
143 #[allow(cast_possible_truncation)]
144 Ok(Bool::Term(n as u8))
146 Err("too many literals".to_owned())
151 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
152 fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
153 use quine_mc_cluskey::Bool::*;
154 let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
168 recurse(true, cx, inner, terminals, s)
171 if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
172 let op = match binop.node {
181 return recurse(true, cx, inner, terminals, s);
184 s.push_str(&snip(lhs));
186 s.push_str(&snip(rhs));
190 recurse(false, cx, inner, terminals, s)
195 recurse(false, cx, inner, terminals, s)
203 if let Or(_) = v[0] {
204 s = recurse(true, cx, &v[0], terminals, s);
206 s = recurse(false, cx, &v[0], terminals, s);
208 for inner in &v[1..] {
210 if let Or(_) = *inner {
211 s = recurse(true, cx, inner, terminals, s);
213 s = recurse(false, cx, inner, terminals, s);
225 s = recurse(false, cx, &v[0], terminals, s);
226 for inner in &v[1..] {
228 s = recurse(false, cx, inner, terminals, s);
237 if let ExprBinary(..) = terminals[n as usize].node {
241 s.push_str(&snip(terminals[n as usize]));
243 if let ExprBinary(..) = terminals[n as usize].node {
251 recurse(false, cx, suggestion, terminals, String::new())
254 fn simple_negate(b: Bool) -> Bool {
255 use quine_mc_cluskey::Bool::*;
259 t @ Term(_) => Not(Box::new(t)),
262 *el = simple_negate(::std::mem::replace(el, True));
268 *el = simple_negate(::std::mem::replace(el, True));
272 Not(inner) => *inner,
278 terminals: [usize; 32],
283 fn terminal_stats(b: &Bool) -> Stats {
284 fn recurse(b: &Bool, stats: &mut Stats) {
286 True | False => stats.ops += 1,
289 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
290 _ => stats.negations += 1,
292 recurse(inner, stats);
294 And(ref v) | Or(ref v) => {
295 stats.ops += v.len() - 1;
297 recurse(inner, stats);
300 Term(n) => stats.terminals[n as usize] += 1,
303 use quine_mc_cluskey::Bool::*;
304 let mut stats = Stats::default();
305 recurse(b, &mut stats);
309 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
310 fn bool_expr(&self, e: &Expr) {
311 let mut h2q = Hir2Qmm {
312 terminals: Vec::new(),
315 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 {
348 span_lint_and_then(self.cx,
351 "this boolean expression contains a logic bug",
353 db.span_help(h2q.terminals[i].span,
354 "this expression can be optimized out by applying boolean operations to the \
356 db.span_suggestion(e.span,
357 "it would look like the following",
358 suggest(self.cx, suggestion, &h2q.terminals));
360 // don't also lint `NONMINIMAL_BOOL`
363 // if the number of occurrences of a terminal decreases or any of the stats
364 // decreases while none increases
365 improvement |= (stats.terminals[i] > simplified_stats.terminals[i]) ||
366 (stats.negations > simplified_stats.negations &&
367 stats.ops == simplified_stats.ops) ||
368 (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
371 improvements.push(suggestion);
374 if !improvements.is_empty() {
375 span_lint_and_then(self.cx,
378 "this boolean expression can be simplified",
380 for suggestion in &improvements {
381 db.span_suggestion(e.span, "try", suggest(self.cx, suggestion, &h2q.terminals));
389 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
390 fn visit_expr(&mut self, e: &'tcx Expr) {
391 if in_macro(self.cx, e.span) {
395 ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
396 ExprUnary(UnNot, ref inner) => {
397 if self.cx.tcx.tables.borrow().node_types[&inner.id].is_bool() {
403 _ => walk_expr(self, e),
406 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
407 NestedVisitorMap::All(&self.cx.tcx.map)