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 crate::utils::{in_macro, paths, match_type, snippet_opt, span_lint_and_then, SpanlessEq, get_trait_def_id, implements_trait};
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
23 declare_clippy_lint! {
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`.
41 declare_clippy_lint! {
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 }.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) => {
126 if !implements_ord(self.cx, lhs) {
133 hir_id: DUMMY_HIR_ID,
135 attrs: ThinVec::new(),
136 node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
140 BiEq => mk_expr(BiNe),
141 BiNe => mk_expr(BiEq),
142 BiGt => mk_expr(BiLe),
143 BiGe => mk_expr(BiLt),
144 BiLt => mk_expr(BiGe),
145 BiLe => mk_expr(BiGt),
151 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
152 #[allow(cast_possible_truncation)]
153 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
156 let n = self.terminals.len();
157 self.terminals.push(e);
159 #[allow(cast_possible_truncation)]
160 Ok(Bool::Term(n as u8))
162 Err("too many literals".to_owned())
167 struct SuggestContext<'a, 'tcx: 'a, 'v> {
168 terminals: &'v [&'v Expr],
169 cx: &'a LateContext<'a, 'tcx>,
174 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
175 fn snip(&self, e: &Expr) -> Option<String> {
176 snippet_opt(self.cx, e.span)
179 fn simplify_not(&self, expr: &Expr) -> Option<String> {
181 ExprBinary(binop, ref lhs, ref rhs) => {
183 if !implements_ord(self.cx, lhs) {
188 BiEq => Some(" != "),
189 BiNe => Some(" == "),
190 BiLt => Some(" >= "),
191 BiGt => Some(" <= "),
195 }.and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
197 ExprMethodCall(ref path, _, ref args) if args.len() == 1 => {
198 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
199 if !match_type(self.cx, type_of_receiver, &paths::OPTION) &&
200 !match_type(self.cx, type_of_receiver, &paths::RESULT) {
203 METHODS_WITH_NEGATION
205 .flat_map(|(a, b)| vec![(a, b), (b, a)])
206 .find(|&(a, _)| a == path.ident.as_str())
207 .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
213 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
214 use quine_mc_cluskey::Bool::*;
217 self.output.push_str("true");
220 self.output.push_str("false");
222 Not(ref inner) => match **inner {
224 self.output.push('!');
225 self.output.push('(');
227 self.output.push(')');
230 let terminal = self.terminals[n as usize];
231 if let Some(str) = self.simplify_not(terminal) {
232 self.simplified = true;
233 self.output.push_str(&str)
235 self.output.push('!');
236 let snip = self.snip(terminal)?;
237 self.output.push_str(&snip);
240 True | False | Not(_) => {
241 self.output.push('!');
242 self.recurse(inner)?;
246 for (index, inner) in v.iter().enumerate() {
248 self.output.push_str(" && ");
250 if let Or(_) = *inner {
251 self.output.push('(');
253 self.output.push(')');
260 for (index, inner) in v.iter().enumerate() {
262 self.output.push_str(" || ");
268 let snip = self.snip(self.terminals[n as usize])?;
269 self.output.push_str(&snip);
276 // The boolean part of the return indicates whether some simplifications have been applied.
277 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
278 let mut suggest_context = SuggestContext {
281 output: String::new(),
284 suggest_context.recurse(suggestion);
285 (suggest_context.output, suggest_context.simplified)
288 fn simple_negate(b: Bool) -> Bool {
289 use quine_mc_cluskey::Bool::*;
293 t @ Term(_) => Not(Box::new(t)),
296 *el = simple_negate(::std::mem::replace(el, True));
302 *el = simple_negate(::std::mem::replace(el, True));
306 Not(inner) => *inner,
312 terminals: [usize; 32],
317 fn terminal_stats(b: &Bool) -> Stats {
318 fn recurse(b: &Bool, stats: &mut Stats) {
320 True | False => stats.ops += 1,
323 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
324 _ => stats.negations += 1,
326 recurse(inner, stats);
328 And(ref v) | Or(ref v) => {
329 stats.ops += v.len() - 1;
331 recurse(inner, stats);
334 Term(n) => stats.terminals[n as usize] += 1,
337 use quine_mc_cluskey::Bool::*;
338 let mut stats = Stats::default();
339 recurse(b, &mut stats);
343 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
344 fn bool_expr(&self, e: &Expr) {
345 let mut h2q = Hir2Qmm {
346 terminals: Vec::new(),
349 if let Ok(expr) = h2q.run(e) {
350 if h2q.terminals.len() > 8 {
351 // QMC has exponentially slow behavior as the number of terminals increases
352 // 8 is reasonable, it takes approximately 0.2 seconds.
357 let stats = terminal_stats(&expr);
358 let mut simplified = expr.simplify();
359 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
361 Bool::Not(_) | Bool::True | Bool::False => {},
362 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
364 let simple_negated = simple_negate(simple);
365 if simplified.iter().any(|s| *s == simple_negated) {
368 simplified.push(simple_negated);
370 let mut improvements = Vec::new();
371 'simplified: for suggestion in &simplified {
372 let simplified_stats = terminal_stats(suggestion);
373 let mut improvement = false;
375 // ignore any "simplifications" that end up requiring a terminal more often
376 // than in the original expression
377 if stats.terminals[i] < simplified_stats.terminals[i] {
378 continue 'simplified;
380 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
385 "this boolean expression contains a logic bug",
388 h2q.terminals[i].span,
389 "this expression can be optimized out by applying boolean operations to the \
394 "it would look like the following",
395 suggest(self.cx, suggestion, &h2q.terminals).0,
399 // don't also lint `NONMINIMAL_BOOL`
402 // if the number of occurrences of a terminal decreases or any of the stats
403 // decreases while none increases
404 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
405 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
406 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
409 improvements.push(suggestion);
412 let nonminimal_bool_lint = |suggestions| {
417 "this boolean expression can be simplified",
418 |db| { db.span_suggestions(e.span, "try", suggestions); },
421 if improvements.is_empty() {
422 let suggest = suggest(self.cx, &expr, &h2q.terminals);
424 nonminimal_bool_lint(vec![suggest.0])
427 nonminimal_bool_lint(
430 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
438 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
439 fn visit_expr(&mut self, e: &'tcx Expr) {
440 if in_macro(e.span) {
444 ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
445 ExprUnary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
450 _ => walk_expr(self, e),
453 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
454 NestedVisitorMap::None
459 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
460 let ty = cx.tables.expr_ty(expr);
461 get_trait_def_id(cx, &paths::ORD)
462 .map_or(false, |id| implements_trait(cx, ty, id, &[]))