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 // For each pairs, both orders are considered.
48 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [
49 ("is_some", "is_none"),
53 #[derive(Copy, Clone)]
54 pub struct NonminimalBool;
56 impl LintPass for NonminimalBool {
57 fn get_lints(&self) -> LintArray {
58 lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
65 cx: &LateContext<'a, 'tcx>,
66 _: intravisit::FnKind<'tcx>,
72 NonminimalBoolVisitor { cx: cx }.visit_body(body)
76 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
77 cx: &'a LateContext<'a, 'tcx>,
80 use quine_mc_cluskey::Bool;
81 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
82 terminals: Vec<&'v Expr>,
83 cx: &'a LateContext<'a, 'tcx>,
86 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
87 fn extract(&mut self, op: BinOp_, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
89 if let ExprBinary(binop, ref lhs, ref rhs) = a.node {
91 v = self.extract(op, &[lhs, rhs], v)?;
100 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
101 // prevent folding of `cfg!` macros and the like
102 if !in_macro(e.span) {
104 ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
105 ExprBinary(binop, ref lhs, ref rhs) => match binop.node {
106 BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
107 BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
110 ExprLit(ref lit) => match lit.node {
111 LitKind::Bool(true) => return Ok(Bool::True),
112 LitKind::Bool(false) => return Ok(Bool::False),
118 for (n, expr) in self.terminals.iter().enumerate() {
119 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
120 #[allow(cast_possible_truncation)]
121 return Ok(Bool::Term(n as u8));
123 let negated = match e.node {
124 ExprBinary(binop, ref lhs, ref rhs) => {
128 hir_id: DUMMY_HIR_ID,
130 attrs: ThinVec::new(),
131 node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
135 BiEq => mk_expr(BiNe),
136 BiNe => mk_expr(BiEq),
137 BiGt => mk_expr(BiLe),
138 BiGe => mk_expr(BiLt),
139 BiLt => mk_expr(BiGe),
140 BiLe => mk_expr(BiGt),
146 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
147 #[allow(cast_possible_truncation)]
148 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
151 let n = self.terminals.len();
152 self.terminals.push(e);
154 #[allow(cast_possible_truncation)]
155 Ok(Bool::Term(n as u8))
157 Err("too many literals".to_owned())
162 // A very simple expression type used for straightforward simplifications.
163 enum BinaryOrCall<'a> {
164 Binary(&'a str, &'a Expr, &'a Expr),
165 MethodCall(&'a str, &'a Expr),
168 impl<'a> BinaryOrCall<'a> {
169 fn to_string(&self, cx: &LateContext, s: &mut String) {
170 let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
172 BinaryOrCall::Binary(op, lhs, rhs) => {
173 s.push_str(&snip(lhs));
175 s.push_str(&snip(rhs));
177 BinaryOrCall::MethodCall(method, arg) => {
178 s.push_str(&snip(arg));
187 fn simplify_not(expr: &Expr) -> Option<BinaryOrCall> {
189 ExprBinary(binop, ref lhs, ref rhs) => {
190 let neg_op = match binop.node {
191 BiEq => Some(" != "),
192 BiNe => Some(" == "),
193 BiLt => Some(" >= "),
194 BiGt => Some(" <= "),
199 neg_op.map(|op| BinaryOrCall::Binary(op, lhs, rhs))
201 ExprMethodCall(ref path, _, ref args) if args.len() == 1 => {
202 METHODS_WITH_NEGATION
204 .flat_map(|(a, b)| vec![(a, b), (b, a)])
205 .find(|&(a, _)| a == path.name.as_str())
206 .map(|(_, neg_method)| BinaryOrCall::MethodCall(neg_method, &args[0]))
212 // The boolean part of the return indicates whether some simplifications have been applied.
213 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
220 simplified: &mut bool,
222 use quine_mc_cluskey::Bool::*;
223 let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
231 Not(ref inner) => match **inner {
234 recurse(true, cx, inner, terminals, s, simplified)
237 if let Some(binary_or_call) = simplify_not(terminals[n as usize]) {
239 binary_or_call.to_string(cx, s)
242 recurse(false, cx, inner, terminals, s, simplified)
245 True | False | Not(_) => {
247 recurse(false, cx, inner, terminals, s, simplified)
254 for (index, inner) in v.iter().enumerate() {
258 if let Or(_) = *inner {
259 recurse(true, cx, inner, terminals, s, simplified);
261 recurse(false, cx, inner, terminals, s, simplified);
272 for (index, inner) in v.iter().enumerate() {
276 recurse(false, cx, inner, terminals, s, simplified);
283 let brackets = brackets && match terminals[n as usize].node {
284 ExprBinary(..) => true,
290 s.push_str(&snip(terminals[n as usize]));
297 let mut simplified = false;
298 let mut s = String::new();
299 recurse(false, cx, suggestion, terminals, &mut s, &mut simplified);
303 fn simple_negate(b: Bool) -> Bool {
304 use quine_mc_cluskey::Bool::*;
308 t @ Term(_) => Not(Box::new(t)),
311 *el = simple_negate(::std::mem::replace(el, True));
317 *el = simple_negate(::std::mem::replace(el, True));
321 Not(inner) => *inner,
327 terminals: [usize; 32],
332 fn terminal_stats(b: &Bool) -> Stats {
333 fn recurse(b: &Bool, stats: &mut Stats) {
335 True | False => stats.ops += 1,
338 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
339 _ => stats.negations += 1,
341 recurse(inner, stats);
343 And(ref v) | Or(ref v) => {
344 stats.ops += v.len() - 1;
346 recurse(inner, stats);
349 Term(n) => stats.terminals[n as usize] += 1,
352 use quine_mc_cluskey::Bool::*;
353 let mut stats = Stats::default();
354 recurse(b, &mut stats);
358 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
359 fn bool_expr(&self, e: &Expr) {
360 let mut h2q = Hir2Qmm {
361 terminals: Vec::new(),
364 if let Ok(expr) = h2q.run(e) {
365 if h2q.terminals.len() > 8 {
366 // QMC has exponentially slow behavior as the number of terminals increases
367 // 8 is reasonable, it takes approximately 0.2 seconds.
372 let stats = terminal_stats(&expr);
373 let mut simplified = expr.simplify();
374 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
376 Bool::Not(_) | Bool::True | Bool::False => {},
377 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
379 let simple_negated = simple_negate(simple);
380 if simplified.iter().any(|s| *s == simple_negated) {
383 simplified.push(simple_negated);
385 let mut improvements = Vec::new();
386 'simplified: for suggestion in &simplified {
387 let simplified_stats = terminal_stats(suggestion);
388 let mut improvement = false;
390 // ignore any "simplifications" that end up requiring a terminal more often
391 // than in the original expression
392 if stats.terminals[i] < simplified_stats.terminals[i] {
393 continue 'simplified;
395 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
400 "this boolean expression contains a logic bug",
403 h2q.terminals[i].span,
404 "this expression can be optimized out by applying boolean operations to the \
409 "it would look like the following",
410 suggest(self.cx, suggestion, &h2q.terminals).0,
414 // don't also lint `NONMINIMAL_BOOL`
417 // if the number of occurrences of a terminal decreases or any of the stats
418 // decreases while none increases
419 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
420 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
421 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
424 improvements.push(suggestion);
427 let nonminimal_bool_lint = |suggestions| {
432 "this boolean expression can be simplified",
433 |db| { db.span_suggestions(e.span, "try", suggestions); },
436 if improvements.is_empty() {
437 let suggest = suggest(self.cx, &expr, &h2q.terminals);
439 nonminimal_bool_lint(vec![suggest.0])
442 nonminimal_bool_lint(
445 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
453 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
454 fn visit_expr(&mut self, e: &'tcx Expr) {
455 if in_macro(e.span) {
459 ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
460 ExprUnary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
465 _ => walk_expr(self, e),
468 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
469 NestedVisitorMap::None