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::intravisit::*;
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
9 use rustc::{declare_lint_pass, declare_tool_lint};
10 use rustc_errors::Applicability;
11 use syntax::ast::LitKind;
12 use syntax::source_map::Span;
14 declare_clippy_lint! {
15 /// **What it does:** Checks for boolean expressions that can be written more
18 /// **Why is this bad?** Readability of boolean expressions suffers from
19 /// unnecessary duplication.
21 /// **Known problems:** Ignores short circuiting behavior of `||` and
22 /// `&&`. Ignores `|`, `&` and `^`.
26 /// if a && true // should be: if a
27 /// if !(a == b) // should be: if a != b
31 "boolean expressions that can be written more concisely"
34 declare_clippy_lint! {
35 /// **What it does:** Checks for boolean expressions that contain terminals that
36 /// can be eliminated.
38 /// **Why is this bad?** This is most likely a logic bug.
40 /// **Known problems:** Ignores short circuiting behavior.
44 /// if a && b || a { ... }
46 /// The `b` is unnecessary, the expression is equivalent to `if a`.
49 "boolean expressions that contain terminals which can be eliminated"
52 // For each pairs, both orders are considered.
53 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
55 declare_lint_pass!(NonminimalBool => [NONMINIMAL_BOOL, LOGIC_BUG]);
57 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
60 cx: &LateContext<'a, 'tcx>,
61 _: intravisit::FnKind<'tcx>,
67 NonminimalBoolVisitor { cx }.visit_body(body)
71 struct NonminimalBoolVisitor<'a, 'tcx> {
72 cx: &'a LateContext<'a, 'tcx>,
75 use quine_mc_cluskey::Bool;
76 struct Hir2Qmm<'a, 'tcx, 'v> {
77 terminals: Vec<&'v Expr>,
78 cx: &'a LateContext<'a, 'tcx>,
81 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
82 fn extract(&mut self, op: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
84 if let ExprKind::Binary(binop, lhs, rhs) = &a.kind {
86 v = self.extract(op, &[lhs, rhs], v)?;
95 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
96 fn negate(bin_op_kind: BinOpKind) -> Option<BinOpKind> {
98 BinOpKind::Eq => Some(BinOpKind::Ne),
99 BinOpKind::Ne => Some(BinOpKind::Eq),
100 BinOpKind::Gt => Some(BinOpKind::Le),
101 BinOpKind::Ge => Some(BinOpKind::Lt),
102 BinOpKind::Lt => Some(BinOpKind::Ge),
103 BinOpKind::Le => Some(BinOpKind::Gt),
108 // prevent folding of `cfg!` macros and the like
109 if !e.span.from_expansion() {
111 ExprKind::Unary(UnNot, inner) => return Ok(Bool::Not(box self.run(inner)?)),
112 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
113 BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
114 BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
117 ExprKind::Lit(lit) => match lit.node {
118 LitKind::Bool(true) => return Ok(Bool::True),
119 LitKind::Bool(false) => return Ok(Bool::False),
125 for (n, expr) in self.terminals.iter().enumerate() {
126 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
127 #[allow(clippy::cast_possible_truncation)]
128 return Ok(Bool::Term(n as u8));
132 if let ExprKind::Binary(e_binop, e_lhs, e_rhs) = &e.kind;
133 if implements_ord(self.cx, e_lhs);
134 if let ExprKind::Binary(expr_binop, expr_lhs, expr_rhs) = &expr.kind;
135 if negate(e_binop.node) == Some(expr_binop.node);
136 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e_lhs, expr_lhs);
137 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e_rhs, expr_rhs);
139 #[allow(clippy::cast_possible_truncation)]
140 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
144 let n = self.terminals.len();
145 self.terminals.push(e);
147 #[allow(clippy::cast_possible_truncation)]
148 Ok(Bool::Term(n as u8))
150 Err("too many literals".to_owned())
155 struct SuggestContext<'a, 'tcx, 'v> {
156 terminals: &'v [&'v Expr],
157 cx: &'a LateContext<'a, 'tcx>,
161 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
162 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
163 use quine_mc_cluskey::Bool::*;
166 self.output.push_str("true");
169 self.output.push_str("false");
171 Not(inner) => match **inner {
173 self.output.push('!');
174 self.output.push('(');
176 self.output.push(')');
179 let terminal = self.terminals[n as usize];
180 if let Some(str) = simplify_not(self.cx, terminal) {
181 self.output.push_str(&str)
183 self.output.push('!');
184 let snip = snippet_opt(self.cx, terminal.span)?;
185 self.output.push_str(&snip);
188 True | False | Not(_) => {
189 self.output.push('!');
190 self.recurse(inner)?;
194 for (index, inner) in v.iter().enumerate() {
196 self.output.push_str(" && ");
198 if let Or(_) = *inner {
199 self.output.push('(');
201 self.output.push(')');
208 for (index, inner) in v.iter().enumerate() {
210 self.output.push_str(" || ");
216 let snip = snippet_opt(self.cx, self.terminals[n as usize].span)?;
217 self.output.push_str(&snip);
224 fn simplify_not(cx: &LateContext<'_, '_>, expr: &Expr) -> Option<String> {
226 ExprKind::Binary(binop, lhs, rhs) => {
227 if !implements_ord(cx, lhs) {
232 BinOpKind::Eq => Some(" != "),
233 BinOpKind::Ne => Some(" == "),
234 BinOpKind::Lt => Some(" >= "),
235 BinOpKind::Gt => Some(" <= "),
236 BinOpKind::Le => Some(" > "),
237 BinOpKind::Ge => Some(" < "),
243 snippet_opt(cx, lhs.span)?,
245 snippet_opt(cx, rhs.span)?
249 ExprKind::MethodCall(path, _, args) if args.len() == 1 => {
250 let type_of_receiver = cx.tables.expr_ty(&args[0]);
251 if !match_type(cx, type_of_receiver, &paths::OPTION) && !match_type(cx, type_of_receiver, &paths::RESULT) {
254 METHODS_WITH_NEGATION
257 .flat_map(|(a, b)| vec![(a, b), (b, a)])
259 let path: &str = &path.ident.name.as_str();
262 .and_then(|(_, neg_method)| Some(format!("{}.{}()", snippet_opt(cx, args[0].span)?, neg_method)))
268 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> String {
269 let mut suggest_context = SuggestContext {
272 output: String::new(),
274 suggest_context.recurse(suggestion);
275 suggest_context.output
278 fn simple_negate(b: Bool) -> Bool {
279 use quine_mc_cluskey::Bool::*;
283 t @ Term(_) => Not(Box::new(t)),
286 *el = simple_negate(::std::mem::replace(el, True));
292 *el = simple_negate(::std::mem::replace(el, True));
296 Not(inner) => *inner,
302 terminals: [usize; 32],
307 fn terminal_stats(b: &Bool) -> Stats {
308 fn recurse(b: &Bool, stats: &mut Stats) {
310 True | False => stats.ops += 1,
313 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
314 _ => stats.negations += 1,
316 recurse(inner, stats);
319 stats.ops += v.len() - 1;
321 recurse(inner, stats);
324 &Term(n) => stats.terminals[n as usize] += 1,
327 use quine_mc_cluskey::Bool::*;
328 let mut stats = Stats::default();
329 recurse(b, &mut stats);
333 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
334 fn bool_expr(&self, e: &'tcx Expr) {
335 let mut h2q = Hir2Qmm {
336 terminals: Vec::new(),
339 if let Ok(expr) = h2q.run(e) {
340 if h2q.terminals.len() > 8 {
341 // QMC has exponentially slow behavior as the number of terminals increases
342 // 8 is reasonable, it takes approximately 0.2 seconds.
347 let stats = terminal_stats(&expr);
348 let mut simplified = expr.simplify();
349 for simple in Bool::Not(Box::new(expr)).simplify() {
351 Bool::Not(_) | Bool::True | Bool::False => {},
352 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
354 let simple_negated = simple_negate(simple);
355 if simplified.iter().any(|s| *s == simple_negated) {
358 simplified.push(simple_negated);
360 let mut improvements = Vec::new();
361 'simplified: for suggestion in &simplified {
362 let simplified_stats = terminal_stats(suggestion);
363 let mut improvement = false;
365 // ignore any "simplifications" that end up requiring a terminal more often
366 // than in the original expression
367 if stats.terminals[i] < simplified_stats.terminals[i] {
368 continue 'simplified;
370 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
375 "this boolean expression contains a logic bug",
378 h2q.terminals[i].span,
379 "this expression can be optimized out by applying boolean operations to the \
384 "it would look like the following",
385 suggest(self.cx, suggestion, &h2q.terminals),
386 // nonminimal_bool can produce minimal but
387 // not human readable expressions (#3141)
388 Applicability::Unspecified,
392 // don't also lint `NONMINIMAL_BOOL`
395 // if the number of occurrences of a terminal decreases or any of the stats
396 // decreases while none increases
397 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
398 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
399 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
402 improvements.push(suggestion);
405 let nonminimal_bool_lint = |suggestions: Vec<_>| {
410 "this boolean expression can be simplified",
415 suggestions.into_iter(),
416 // nonminimal_bool can produce minimal but
417 // not human readable expressions (#3141)
418 Applicability::Unspecified,
423 if improvements.is_empty() {
424 let mut visitor = NotSimplificationVisitor { cx: self.cx };
425 visitor.visit_expr(e);
427 nonminimal_bool_lint(
430 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
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 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
447 ExprKind::Unary(UnNot, inner) => {
448 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
454 _ => walk_expr(self, e),
457 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
458 NestedVisitorMap::None
462 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
463 let ty = cx.tables.expr_ty(expr);
464 get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))
467 struct NotSimplificationVisitor<'a, 'tcx> {
468 cx: &'a LateContext<'a, 'tcx>,
471 impl<'a, 'tcx> Visitor<'tcx> for NotSimplificationVisitor<'a, 'tcx> {
472 fn visit_expr(&mut self, expr: &'tcx Expr) {
473 if let ExprKind::Unary(UnNot, inner) = &expr.kind {
474 if let Some(suggestion) = simplify_not(self.cx, inner) {
479 "this boolean expression can be simplified",
482 Applicability::MachineApplicable,
487 walk_expr(self, expr);
489 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
490 NestedVisitorMap::None