2 get_trait_def_id, implements_trait, in_macro, match_type, paths, snippet_opt, span_lint_and_sugg,
3 span_lint_and_then, SpanlessEq,
5 use if_chain::if_chain;
6 use rustc::hir::map::Map;
7 use rustc_errors::Applicability;
8 use rustc_hir::intravisit;
9 use rustc_hir::intravisit::*;
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::source_map::Span;
14 use syntax::ast::LitKind;
16 declare_clippy_lint! {
17 /// **What it does:** Checks for boolean expressions that can be written more
20 /// **Why is this bad?** Readability of boolean expressions suffers from
21 /// unnecessary duplication.
23 /// **Known problems:** Ignores short circuiting behavior of `||` and
24 /// `&&`. Ignores `|`, `&` and `^`.
28 /// if a && true // should be: if a
29 /// if !(a == b) // should be: if a != b
33 "boolean expressions that can be written more concisely"
36 declare_clippy_lint! {
37 /// **What it does:** Checks for boolean expressions that contain terminals that
38 /// can be eliminated.
40 /// **Why is this bad?** This is most likely a logic bug.
42 /// **Known problems:** Ignores short circuiting behavior.
46 /// if a && b || a { ... }
48 /// The `b` is unnecessary, the expression is equivalent to `if a`.
51 "boolean expressions that contain terminals which can be eliminated"
54 // For each pairs, both orders are considered.
55 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
57 declare_lint_pass!(NonminimalBool => [NONMINIMAL_BOOL, LOGIC_BUG]);
59 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
62 cx: &LateContext<'a, 'tcx>,
63 _: intravisit::FnKind<'tcx>,
69 NonminimalBoolVisitor { cx }.visit_body(body)
73 struct NonminimalBoolVisitor<'a, 'tcx> {
74 cx: &'a LateContext<'a, 'tcx>,
77 use quine_mc_cluskey::Bool;
78 struct Hir2Qmm<'a, 'tcx, 'v> {
79 terminals: Vec<&'v Expr<'v>>,
80 cx: &'a LateContext<'a, 'tcx>,
83 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
84 fn extract(&mut self, op: BinOpKind, a: &[&'v Expr<'_>], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
86 if let ExprKind::Binary(binop, lhs, rhs) = &a.kind {
88 v = self.extract(op, &[lhs, rhs], v)?;
97 fn run(&mut self, e: &'v Expr<'_>) -> Result<Bool, String> {
98 fn negate(bin_op_kind: BinOpKind) -> Option<BinOpKind> {
100 BinOpKind::Eq => Some(BinOpKind::Ne),
101 BinOpKind::Ne => Some(BinOpKind::Eq),
102 BinOpKind::Gt => Some(BinOpKind::Le),
103 BinOpKind::Ge => Some(BinOpKind::Lt),
104 BinOpKind::Lt => Some(BinOpKind::Ge),
105 BinOpKind::Le => Some(BinOpKind::Gt),
110 // prevent folding of `cfg!` macros and the like
111 if !e.span.from_expansion() {
113 ExprKind::Unary(UnOp::UnNot, inner) => return Ok(Bool::Not(box self.run(inner)?)),
114 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
115 BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
116 BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
119 ExprKind::Lit(lit) => match lit.node {
120 LitKind::Bool(true) => return Ok(Bool::True),
121 LitKind::Bool(false) => return Ok(Bool::False),
127 for (n, expr) in self.terminals.iter().enumerate() {
128 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
129 #[allow(clippy::cast_possible_truncation)]
130 return Ok(Bool::Term(n as u8));
134 if let ExprKind::Binary(e_binop, e_lhs, e_rhs) = &e.kind;
135 if implements_ord(self.cx, e_lhs);
136 if let ExprKind::Binary(expr_binop, expr_lhs, expr_rhs) = &expr.kind;
137 if negate(e_binop.node) == Some(expr_binop.node);
138 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e_lhs, expr_lhs);
139 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e_rhs, expr_rhs);
141 #[allow(clippy::cast_possible_truncation)]
142 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
146 let n = self.terminals.len();
147 self.terminals.push(e);
149 #[allow(clippy::cast_possible_truncation)]
150 Ok(Bool::Term(n as u8))
152 Err("too many literals".to_owned())
157 struct SuggestContext<'a, 'tcx, 'v> {
158 terminals: &'v [&'v Expr<'v>],
159 cx: &'a LateContext<'a, 'tcx>,
163 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
164 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
165 use quine_mc_cluskey::Bool::*;
168 self.output.push_str("true");
171 self.output.push_str("false");
173 Not(inner) => match **inner {
175 self.output.push('!');
176 self.output.push('(');
178 self.output.push(')');
181 let terminal = self.terminals[n as usize];
182 if let Some(str) = simplify_not(self.cx, terminal) {
183 self.output.push_str(&str)
185 self.output.push('!');
186 let snip = snippet_opt(self.cx, terminal.span)?;
187 self.output.push_str(&snip);
190 True | False | Not(_) => {
191 self.output.push('!');
192 self.recurse(inner)?;
196 for (index, inner) in v.iter().enumerate() {
198 self.output.push_str(" && ");
200 if let Or(_) = *inner {
201 self.output.push('(');
203 self.output.push(')');
210 for (index, inner) in v.iter().rev().enumerate() {
212 self.output.push_str(" || ");
218 let snip = snippet_opt(self.cx, self.terminals[n as usize].span)?;
219 self.output.push_str(&snip);
226 fn simplify_not(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Option<String> {
228 ExprKind::Binary(binop, lhs, rhs) => {
229 if !implements_ord(cx, lhs) {
234 BinOpKind::Eq => Some(" != "),
235 BinOpKind::Ne => Some(" == "),
236 BinOpKind::Lt => Some(" >= "),
237 BinOpKind::Gt => Some(" <= "),
238 BinOpKind::Le => Some(" > "),
239 BinOpKind::Ge => Some(" < "),
245 snippet_opt(cx, lhs.span)?,
247 snippet_opt(cx, rhs.span)?
251 ExprKind::MethodCall(path, _, args) if args.len() == 1 => {
252 let type_of_receiver = cx.tables.expr_ty(&args[0]);
253 if !match_type(cx, type_of_receiver, &paths::OPTION) && !match_type(cx, type_of_receiver, &paths::RESULT) {
256 METHODS_WITH_NEGATION
259 .flat_map(|(a, b)| vec![(a, b), (b, a)])
261 let path: &str = &path.ident.name.as_str();
264 .and_then(|(_, neg_method)| Some(format!("{}.{}()", snippet_opt(cx, args[0].span)?, neg_method)))
270 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr<'_>]) -> String {
271 let mut suggest_context = SuggestContext {
274 output: String::new(),
276 suggest_context.recurse(suggestion);
277 suggest_context.output
280 fn simple_negate(b: Bool) -> Bool {
281 use quine_mc_cluskey::Bool::*;
285 t @ Term(_) => Not(Box::new(t)),
288 *el = simple_negate(::std::mem::replace(el, True));
294 *el = simple_negate(::std::mem::replace(el, True));
298 Not(inner) => *inner,
304 terminals: [usize; 32],
309 fn terminal_stats(b: &Bool) -> Stats {
310 fn recurse(b: &Bool, stats: &mut Stats) {
312 True | False => stats.ops += 1,
315 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
316 _ => stats.negations += 1,
318 recurse(inner, stats);
321 stats.ops += v.len() - 1;
323 recurse(inner, stats);
326 &Term(n) => stats.terminals[n as usize] += 1,
329 use quine_mc_cluskey::Bool::*;
330 let mut stats = Stats::default();
331 recurse(b, &mut stats);
335 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
336 fn bool_expr(&self, e: &'tcx Expr<'_>) {
337 let mut h2q = Hir2Qmm {
338 terminals: Vec::new(),
341 if let Ok(expr) = h2q.run(e) {
342 if h2q.terminals.len() > 8 {
343 // QMC has exponentially slow behavior as the number of terminals increases
344 // 8 is reasonable, it takes approximately 0.2 seconds.
349 let stats = terminal_stats(&expr);
350 let mut simplified = expr.simplify();
351 for simple in Bool::Not(Box::new(expr)).simplify() {
353 Bool::Not(_) | Bool::True | Bool::False => {},
354 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
356 let simple_negated = simple_negate(simple);
357 if simplified.iter().any(|s| *s == simple_negated) {
360 simplified.push(simple_negated);
362 let mut improvements = Vec::new();
363 'simplified: for suggestion in &simplified {
364 let simplified_stats = terminal_stats(suggestion);
365 let mut improvement = false;
367 // ignore any "simplifications" that end up requiring a terminal more often
368 // than in the original expression
369 if stats.terminals[i] < simplified_stats.terminals[i] {
370 continue 'simplified;
372 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
377 "this boolean expression contains a logic bug",
380 h2q.terminals[i].span,
381 "this expression can be optimized out by applying boolean operations to the \
386 "it would look like the following",
387 suggest(self.cx, suggestion, &h2q.terminals),
388 // nonminimal_bool can produce minimal but
389 // not human readable expressions (#3141)
390 Applicability::Unspecified,
394 // don't also lint `NONMINIMAL_BOOL`
397 // if the number of occurrences of a terminal decreases or any of the stats
398 // decreases while none increases
399 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
400 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
401 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
404 improvements.push(suggestion);
407 let nonminimal_bool_lint = |suggestions: Vec<_>| {
412 "this boolean expression can be simplified",
417 suggestions.into_iter(),
418 // nonminimal_bool can produce minimal but
419 // not human readable expressions (#3141)
420 Applicability::Unspecified,
425 if improvements.is_empty() {
426 let mut visitor = NotSimplificationVisitor { cx: self.cx };
427 visitor.visit_expr(e);
429 nonminimal_bool_lint(
432 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
440 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
441 type Map = Map<'tcx>;
443 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
444 if in_macro(e.span) {
448 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
451 ExprKind::Unary(UnOp::UnNot, inner) => {
452 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
458 _ => walk_expr(self, e),
461 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
462 NestedVisitorMap::None
466 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr<'_>) -> bool {
467 let ty = cx.tables.expr_ty(expr);
468 get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))
471 struct NotSimplificationVisitor<'a, 'tcx> {
472 cx: &'a LateContext<'a, 'tcx>,
475 impl<'a, 'tcx> Visitor<'tcx> for NotSimplificationVisitor<'a, 'tcx> {
476 type Map = Map<'tcx>;
478 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
479 if let ExprKind::Unary(UnOp::UnNot, inner) = &expr.kind {
480 if let Some(suggestion) = simplify_not(self.cx, inner) {
485 "this boolean expression can be simplified",
488 Applicability::MachineApplicable,
493 walk_expr(self, expr);
495 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
496 NestedVisitorMap::None