2 get_trait_def_id, implements_trait, in_macro, match_type, paths, snippet_opt, span_lint_and_then, SpanlessEq,
4 use rustc::hir::intravisit::*;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_tool_lint, lint_array};
8 use rustc_data_structures::thin_vec::ThinVec;
9 use rustc_errors::Applicability;
10 use syntax::ast::LitKind;
11 use syntax::source_map::{dummy_spanned, Span, DUMMY_SP};
13 /// **What it does:** Checks for boolean expressions that can be written more
16 /// **Why is this bad?** Readability of boolean expressions suffers from
17 /// unnecessary duplication.
19 /// **Known problems:** Ignores short circuiting behavior of `||` and
20 /// `&&`. Ignores `|`, `&` and `^`.
24 /// if a && true // should be: if a
25 /// if !(a == b) // should be: if a != b
27 declare_clippy_lint! {
30 "boolean expressions that can be written more concisely"
33 /// **What it does:** Checks for boolean expressions that contain terminals that
34 /// can be eliminated.
36 /// **Why is this bad?** This is most likely a logic bug.
38 /// **Known problems:** Ignores short circuiting behavior.
42 /// if a && b || a { ... }
44 /// The `b` is unnecessary, the expression is equivalent to `if a`.
45 declare_clippy_lint! {
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 #[derive(Copy, Clone)]
55 pub struct NonminimalBool;
57 impl LintPass for NonminimalBool {
58 fn get_lints(&self) -> LintArray {
59 lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
62 fn name(&self) -> &'static str {
67 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
70 cx: &LateContext<'a, 'tcx>,
71 _: intravisit::FnKind<'tcx>,
77 NonminimalBoolVisitor { cx }.visit_body(body)
81 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
82 cx: &'a LateContext<'a, 'tcx>,
85 use quine_mc_cluskey::Bool;
86 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
87 terminals: Vec<&'v Expr>,
88 cx: &'a LateContext<'a, 'tcx>,
91 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
92 fn extract(&mut self, op: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
94 if let ExprKind::Binary(binop, lhs, rhs) = &a.node {
96 v = self.extract(op, &[lhs, rhs], v)?;
100 v.push(self.run(a)?);
105 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
106 // prevent folding of `cfg!` macros and the like
107 if !in_macro(e.span) {
109 ExprKind::Unary(UnNot, inner) => return Ok(Bool::Not(box self.run(inner)?)),
110 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
111 BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
112 BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
115 ExprKind::Lit(lit) => match lit.node {
116 LitKind::Bool(true) => return Ok(Bool::True),
117 LitKind::Bool(false) => return Ok(Bool::False),
123 for (n, expr) in self.terminals.iter().enumerate() {
124 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
125 #[allow(clippy::cast_possible_truncation)]
126 return Ok(Bool::Term(n as u8));
128 let negated = match &e.node {
129 ExprKind::Binary(binop, lhs, rhs) => {
130 if !implements_ord(self.cx, lhs) {
134 let mk_expr = |op| Expr {
135 hir_id: DUMMY_HIR_ID,
137 attrs: ThinVec::new(),
138 node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
141 BinOpKind::Eq => mk_expr(BinOpKind::Ne),
142 BinOpKind::Ne => mk_expr(BinOpKind::Eq),
143 BinOpKind::Gt => mk_expr(BinOpKind::Le),
144 BinOpKind::Ge => mk_expr(BinOpKind::Lt),
145 BinOpKind::Lt => mk_expr(BinOpKind::Ge),
146 BinOpKind::Le => mk_expr(BinOpKind::Gt),
152 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
153 #[allow(clippy::cast_possible_truncation)]
154 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
157 let n = self.terminals.len();
158 self.terminals.push(e);
160 #[allow(clippy::cast_possible_truncation)]
161 Ok(Bool::Term(n as u8))
163 Err("too many literals".to_owned())
168 struct SuggestContext<'a, 'tcx: 'a, 'v> {
169 terminals: &'v [&'v Expr],
170 cx: &'a LateContext<'a, 'tcx>,
175 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
176 fn snip(&self, e: &Expr) -> Option<String> {
177 snippet_opt(self.cx, e.span)
180 fn simplify_not(&self, expr: &Expr) -> Option<String> {
182 ExprKind::Binary(binop, lhs, rhs) => {
183 if !implements_ord(self.cx, lhs) {
188 BinOpKind::Eq => Some(" != "),
189 BinOpKind::Ne => Some(" == "),
190 BinOpKind::Lt => Some(" >= "),
191 BinOpKind::Gt => Some(" <= "),
192 BinOpKind::Le => Some(" > "),
193 BinOpKind::Ge => Some(" < "),
196 .and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
198 ExprKind::MethodCall(path, _, args) if args.len() == 1 => {
199 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
200 if !match_type(self.cx, type_of_receiver, &paths::OPTION)
201 && !match_type(self.cx, type_of_receiver, &paths::RESULT)
205 METHODS_WITH_NEGATION
208 .flat_map(|(a, b)| vec![(a, b), (b, a)])
209 .find(|&(a, _)| a == path.ident.as_str())
210 .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
216 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
217 use quine_mc_cluskey::Bool::*;
220 self.output.push_str("true");
223 self.output.push_str("false");
225 Not(inner) => match **inner {
227 self.output.push('!');
228 self.output.push('(');
230 self.output.push(')');
233 let terminal = self.terminals[n as usize];
234 if let Some(str) = self.simplify_not(terminal) {
235 self.simplified = true;
236 self.output.push_str(&str)
238 self.output.push('!');
239 let snip = self.snip(terminal)?;
240 self.output.push_str(&snip);
243 True | False | Not(_) => {
244 self.output.push('!');
245 self.recurse(inner)?;
249 for (index, inner) in v.iter().enumerate() {
251 self.output.push_str(" && ");
253 if let Or(_) = *inner {
254 self.output.push('(');
256 self.output.push(')');
263 for (index, inner) in v.iter().enumerate() {
265 self.output.push_str(" || ");
271 let snip = self.snip(self.terminals[n as usize])?;
272 self.output.push_str(&snip);
279 // The boolean part of the return indicates whether some simplifications have been applied.
280 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
281 let mut suggest_context = SuggestContext {
284 output: String::new(),
287 suggest_context.recurse(suggestion);
288 (suggest_context.output, suggest_context.simplified)
291 fn simple_negate(b: Bool) -> Bool {
292 use quine_mc_cluskey::Bool::*;
296 t @ Term(_) => Not(Box::new(t)),
299 *el = simple_negate(::std::mem::replace(el, True));
305 *el = simple_negate(::std::mem::replace(el, True));
309 Not(inner) => *inner,
315 terminals: [usize; 32],
320 fn terminal_stats(b: &Bool) -> Stats {
321 fn recurse(b: &Bool, stats: &mut Stats) {
323 True | False => stats.ops += 1,
326 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
327 _ => stats.negations += 1,
329 recurse(inner, stats);
332 stats.ops += v.len() - 1;
334 recurse(inner, stats);
337 &Term(n) => stats.terminals[n as usize] += 1,
340 use quine_mc_cluskey::Bool::*;
341 let mut stats = Stats::default();
342 recurse(b, &mut stats);
346 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
347 fn bool_expr(&self, e: &Expr) {
348 let mut h2q = Hir2Qmm {
349 terminals: Vec::new(),
352 if let Ok(expr) = h2q.run(e) {
353 if h2q.terminals.len() > 8 {
354 // QMC has exponentially slow behavior as the number of terminals increases
355 // 8 is reasonable, it takes approximately 0.2 seconds.
360 let stats = terminal_stats(&expr);
361 let mut simplified = expr.simplify();
362 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
364 Bool::Not(_) | Bool::True | Bool::False => {},
365 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
367 let simple_negated = simple_negate(simple);
368 if simplified.iter().any(|s| *s == simple_negated) {
371 simplified.push(simple_negated);
373 let mut improvements = Vec::new();
374 'simplified: for suggestion in &simplified {
375 let simplified_stats = terminal_stats(suggestion);
376 let mut improvement = false;
378 // ignore any "simplifications" that end up requiring a terminal more often
379 // than in the original expression
380 if stats.terminals[i] < simplified_stats.terminals[i] {
381 continue 'simplified;
383 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
388 "this boolean expression contains a logic bug",
391 h2q.terminals[i].span,
392 "this expression can be optimized out by applying boolean operations to the \
397 "it would look like the following",
398 suggest(self.cx, suggestion, &h2q.terminals).0,
399 // nonminimal_bool can produce minimal but
400 // not human readable expressions (#3141)
401 Applicability::Unspecified,
405 // don't also lint `NONMINIMAL_BOOL`
408 // if the number of occurrences of a terminal decreases or any of the stats
409 // decreases while none increases
410 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
411 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
412 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
415 improvements.push(suggestion);
418 let nonminimal_bool_lint = |suggestions: Vec<_>| {
423 "this boolean expression can be simplified",
428 suggestions.into_iter(),
429 // nonminimal_bool can produce minimal but
430 // not human readable expressions (#3141)
431 Applicability::Unspecified,
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 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
462 ExprKind::Unary(UnNot, inner) => {
463 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
469 _ => walk_expr(self, e),
472 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
473 NestedVisitorMap::None
477 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
478 let ty = cx.tables.expr_ty(expr);
479 get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))