2 get_trait_def_id, implements_trait, in_macro, match_type, paths, snippet_opt, span_lint_and_then, SpanlessEq,
4 use if_chain::if_chain;
5 use rustc::hir::intravisit::*;
7 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8 use rustc::{declare_lint_pass, declare_tool_lint};
9 use rustc_errors::Applicability;
10 use syntax::ast::LitKind;
11 use syntax::source_map::Span;
13 declare_clippy_lint! {
14 /// **What it does:** Checks for boolean expressions that can be written more
17 /// **Why is this bad?** Readability of boolean expressions suffers from
18 /// unnecessary duplication.
20 /// **Known problems:** Ignores short circuiting behavior of `||` and
21 /// `&&`. Ignores `|`, `&` and `^`.
25 /// if a && true // should be: if a
26 /// if !(a == b) // should be: if a != b
30 "boolean expressions that can be written more concisely"
33 declare_clippy_lint! {
34 /// **What it does:** Checks for boolean expressions that contain terminals that
35 /// can be eliminated.
37 /// **Why is this bad?** This is most likely a logic bug.
39 /// **Known problems:** Ignores short circuiting behavior.
43 /// if a && b || a { ... }
45 /// The `b` is unnecessary, the expression is equivalent to `if a`.
48 "boolean expressions that contain terminals which can be eliminated"
51 // For each pairs, both orders are considered.
52 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
54 declare_lint_pass!(NonminimalBool => [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 }.visit_body(body)
70 struct NonminimalBoolVisitor<'a, 'tcx> {
71 cx: &'a LateContext<'a, 'tcx>,
74 use quine_mc_cluskey::Bool;
75 struct Hir2Qmm<'a, 'tcx, '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: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
83 if let ExprKind::Binary(binop, lhs, rhs) = &a.node {
85 v = self.extract(op, &[lhs, rhs], v)?;
94 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
95 fn negate(bin_op_kind: BinOpKind) -> Option<BinOpKind> {
97 BinOpKind::Eq => Some(BinOpKind::Ne),
98 BinOpKind::Ne => Some(BinOpKind::Eq),
99 BinOpKind::Gt => Some(BinOpKind::Le),
100 BinOpKind::Ge => Some(BinOpKind::Lt),
101 BinOpKind::Lt => Some(BinOpKind::Ge),
102 BinOpKind::Le => Some(BinOpKind::Gt),
107 // prevent folding of `cfg!` macros and the like
108 if !e.span.from_expansion() {
110 ExprKind::Unary(UnNot, inner) => return Ok(Bool::Not(box self.run(inner)?)),
111 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
112 BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
113 BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
116 ExprKind::Lit(lit) => match lit.node {
117 LitKind::Bool(true) => return Ok(Bool::True),
118 LitKind::Bool(false) => return Ok(Bool::False),
124 for (n, expr) in self.terminals.iter().enumerate() {
125 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
126 #[allow(clippy::cast_possible_truncation)]
127 return Ok(Bool::Term(n as u8));
131 if let ExprKind::Binary(e_binop, e_lhs, e_rhs) = &e.node;
132 if implements_ord(self.cx, e_lhs);
133 if let ExprKind::Binary(expr_binop, expr_lhs, expr_rhs) = &expr.node;
134 if negate(e_binop.node) == Some(expr_binop.node);
135 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e_lhs, expr_lhs);
136 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e_rhs, expr_rhs);
138 #[allow(clippy::cast_possible_truncation)]
139 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
143 let n = self.terminals.len();
144 self.terminals.push(e);
146 #[allow(clippy::cast_possible_truncation)]
147 Ok(Bool::Term(n as u8))
149 Err("too many literals".to_owned())
154 struct SuggestContext<'a, 'tcx, 'v> {
155 terminals: &'v [&'v Expr],
156 cx: &'a LateContext<'a, 'tcx>,
161 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
162 fn snip(&self, e: &Expr) -> Option<String> {
163 snippet_opt(self.cx, e.span)
166 fn simplify_not(&self, expr: &Expr) -> Option<String> {
168 ExprKind::Binary(binop, lhs, rhs) => {
169 if !implements_ord(self.cx, lhs) {
174 BinOpKind::Eq => Some(" != "),
175 BinOpKind::Ne => Some(" == "),
176 BinOpKind::Lt => Some(" >= "),
177 BinOpKind::Gt => Some(" <= "),
178 BinOpKind::Le => Some(" > "),
179 BinOpKind::Ge => Some(" < "),
182 .and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
184 ExprKind::MethodCall(path, _, args) if args.len() == 1 => {
185 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
186 if !match_type(self.cx, type_of_receiver, &paths::OPTION)
187 && !match_type(self.cx, type_of_receiver, &paths::RESULT)
191 METHODS_WITH_NEGATION
194 .flat_map(|(a, b)| vec![(a, b), (b, a)])
195 .find(|&(a, _)| a == path.ident.name.as_str())
196 .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
202 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
203 use quine_mc_cluskey::Bool::*;
206 self.output.push_str("true");
209 self.output.push_str("false");
211 Not(inner) => match **inner {
213 self.output.push('!');
214 self.output.push('(');
216 self.output.push(')');
219 let terminal = self.terminals[n as usize];
220 if let Some(str) = self.simplify_not(terminal) {
221 self.simplified = true;
222 self.output.push_str(&str)
224 self.output.push('!');
225 let snip = self.snip(terminal)?;
226 self.output.push_str(&snip);
229 True | False | Not(_) => {
230 self.output.push('!');
231 self.recurse(inner)?;
235 for (index, inner) in v.iter().enumerate() {
237 self.output.push_str(" && ");
239 if let Or(_) = *inner {
240 self.output.push('(');
242 self.output.push(')');
249 for (index, inner) in v.iter().enumerate() {
251 self.output.push_str(" || ");
257 let snip = self.snip(self.terminals[n as usize])?;
258 self.output.push_str(&snip);
265 // The boolean part of the return indicates whether some simplifications have been applied.
266 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
267 let mut suggest_context = SuggestContext {
270 output: String::new(),
273 suggest_context.recurse(suggestion);
274 (suggest_context.output, suggest_context.simplified)
277 fn simple_negate(b: Bool) -> Bool {
278 use quine_mc_cluskey::Bool::*;
282 t @ Term(_) => Not(Box::new(t)),
285 *el = simple_negate(::std::mem::replace(el, True));
291 *el = simple_negate(::std::mem::replace(el, True));
295 Not(inner) => *inner,
301 terminals: [usize; 32],
306 fn terminal_stats(b: &Bool) -> Stats {
307 fn recurse(b: &Bool, stats: &mut Stats) {
309 True | False => stats.ops += 1,
312 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
313 _ => stats.negations += 1,
315 recurse(inner, stats);
318 stats.ops += v.len() - 1;
320 recurse(inner, stats);
323 &Term(n) => stats.terminals[n as usize] += 1,
326 use quine_mc_cluskey::Bool::*;
327 let mut stats = Stats::default();
328 recurse(b, &mut stats);
332 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
333 fn bool_expr(&self, e: &Expr) {
334 let mut h2q = Hir2Qmm {
335 terminals: Vec::new(),
338 if let Ok(expr) = h2q.run(e) {
339 if h2q.terminals.len() > 8 {
340 // QMC has exponentially slow behavior as the number of terminals increases
341 // 8 is reasonable, it takes approximately 0.2 seconds.
346 let stats = terminal_stats(&expr);
347 let mut simplified = expr.simplify();
348 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
350 Bool::Not(_) | Bool::True | Bool::False => {},
351 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
353 let simple_negated = simple_negate(simple);
354 if simplified.iter().any(|s| *s == simple_negated) {
357 simplified.push(simple_negated);
359 let mut improvements = Vec::new();
360 'simplified: for suggestion in &simplified {
361 let simplified_stats = terminal_stats(suggestion);
362 let mut improvement = false;
364 // ignore any "simplifications" that end up requiring a terminal more often
365 // than in the original expression
366 if stats.terminals[i] < simplified_stats.terminals[i] {
367 continue 'simplified;
369 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
374 "this boolean expression contains a logic bug",
377 h2q.terminals[i].span,
378 "this expression can be optimized out by applying boolean operations to the \
383 "it would look like the following",
384 suggest(self.cx, suggestion, &h2q.terminals).0,
385 // nonminimal_bool can produce minimal but
386 // not human readable expressions (#3141)
387 Applicability::Unspecified,
391 // don't also lint `NONMINIMAL_BOOL`
394 // if the number of occurrences of a terminal decreases or any of the stats
395 // decreases while none increases
396 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
397 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
398 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
401 improvements.push(suggestion);
404 let nonminimal_bool_lint = |suggestions: Vec<_>| {
409 "this boolean expression can be simplified",
414 suggestions.into_iter(),
415 // nonminimal_bool can produce minimal but
416 // not human readable expressions (#3141)
417 Applicability::Unspecified,
422 if improvements.is_empty() {
423 let suggest = suggest(self.cx, &expr, &h2q.terminals);
425 nonminimal_bool_lint(vec![suggest.0])
428 nonminimal_bool_lint(
431 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
439 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
440 fn visit_expr(&mut self, e: &'tcx Expr) {
441 if in_macro(e.span) {
445 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
448 ExprKind::Unary(UnNot, inner) => {
449 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
455 _ => walk_expr(self, e),
458 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
459 NestedVisitorMap::None
463 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
464 let ty = cx.tables.expr_ty(expr);
465 get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))