1 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use crate::rustc::{declare_tool_lint, lint_array};
3 use crate::rustc::hir::*;
4 use crate::rustc::hir::intravisit::*;
5 use crate::syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
6 use crate::syntax::source_map::{dummy_spanned, Span, DUMMY_SP};
7 use crate::rustc_data_structures::thin_vec::ThinVec;
8 use crate::utils::{in_macro, paths, match_type, snippet_opt, span_lint_and_then, SpanlessEq, get_trait_def_id, implements_trait};
9 use crate::rustc_errors::Applicability;
11 /// **What it does:** Checks for boolean expressions that can be written more
14 /// **Why is this bad?** Readability of boolean expressions suffers from
15 /// unnecessary duplication.
17 /// **Known problems:** Ignores short circuiting behavior of `||` and
18 /// `&&`. Ignores `|`, `&` and `^`.
22 /// if a && true // should be: if a
23 /// if !(a == b) // should be: if a != b
25 declare_clippy_lint! {
28 "boolean expressions that can be written more concisely"
31 /// **What it does:** Checks for boolean expressions that contain terminals that
32 /// can be eliminated.
34 /// **Why is this bad?** This is most likely a logic bug.
36 /// **Known problems:** Ignores short circuiting behavior.
40 /// if a && b || a { ... }
42 /// The `b` is unnecessary, the expression is equivalent to `if a`.
43 declare_clippy_lint! {
46 "boolean expressions that contain terminals which can be eliminated"
49 // For each pairs, both orders are considered.
50 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [
51 ("is_some", "is_none"),
55 #[derive(Copy, Clone)]
56 pub struct NonminimalBool;
58 impl LintPass for NonminimalBool {
59 fn get_lints(&self) -> LintArray {
60 lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
64 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
67 cx: &LateContext<'a, 'tcx>,
68 _: intravisit::FnKind<'tcx>,
74 NonminimalBoolVisitor { cx }.visit_body(body)
78 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
79 cx: &'a LateContext<'a, 'tcx>,
82 use quine_mc_cluskey::Bool;
83 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
84 terminals: Vec<&'v Expr>,
85 cx: &'a LateContext<'a, 'tcx>,
88 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
89 fn extract(&mut self, op: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
91 if let ExprKind::Binary(binop, ref lhs, ref rhs) = a.node {
93 v = self.extract(op, &[lhs, rhs], v)?;
102 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
103 // prevent folding of `cfg!` macros and the like
104 if !in_macro(e.span) {
106 ExprKind::Unary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
107 ExprKind::Binary(binop, ref lhs, ref rhs) => match binop.node {
108 BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
109 BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
112 ExprKind::Lit(ref lit) => match lit.node {
113 LitKind::Bool(true) => return Ok(Bool::True),
114 LitKind::Bool(false) => return Ok(Bool::False),
120 for (n, expr) in self.terminals.iter().enumerate() {
121 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
122 #[allow(clippy::cast_possible_truncation)]
123 return Ok(Bool::Term(n as u8));
125 let negated = match e.node {
126 ExprKind::Binary(binop, ref lhs, ref rhs) => {
128 if !implements_ord(self.cx, lhs) {
135 hir_id: DUMMY_HIR_ID,
137 attrs: ThinVec::new(),
138 node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
142 BinOpKind::Eq => mk_expr(BinOpKind::Ne),
143 BinOpKind::Ne => mk_expr(BinOpKind::Eq),
144 BinOpKind::Gt => mk_expr(BinOpKind::Le),
145 BinOpKind::Ge => mk_expr(BinOpKind::Lt),
146 BinOpKind::Lt => mk_expr(BinOpKind::Ge),
147 BinOpKind::Le => mk_expr(BinOpKind::Gt),
153 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
154 #[allow(clippy::cast_possible_truncation)]
155 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
158 let n = self.terminals.len();
159 self.terminals.push(e);
161 #[allow(clippy::cast_possible_truncation)]
162 Ok(Bool::Term(n as u8))
164 Err("too many literals".to_owned())
169 struct SuggestContext<'a, 'tcx: 'a, 'v> {
170 terminals: &'v [&'v Expr],
171 cx: &'a LateContext<'a, 'tcx>,
176 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
177 fn snip(&self, e: &Expr) -> Option<String> {
178 snippet_opt(self.cx, e.span)
181 fn simplify_not(&self, expr: &Expr) -> Option<String> {
183 ExprKind::Binary(binop, ref lhs, ref rhs) => {
185 if !implements_ord(self.cx, lhs) {
190 BinOpKind::Eq => Some(" != "),
191 BinOpKind::Ne => Some(" == "),
192 BinOpKind::Lt => Some(" >= "),
193 BinOpKind::Gt => Some(" <= "),
194 BinOpKind::Le => Some(" > "),
195 BinOpKind::Ge => Some(" < "),
197 }.and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
199 ExprKind::MethodCall(ref path, _, ref args) if args.len() == 1 => {
200 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
201 if !match_type(self.cx, type_of_receiver, &paths::OPTION) &&
202 !match_type(self.cx, type_of_receiver, &paths::RESULT) {
205 METHODS_WITH_NEGATION
207 .flat_map(|(a, b)| vec![(a, b), (b, a)])
208 .find(|&(a, _)| a == path.ident.as_str())
209 .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
215 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
216 use quine_mc_cluskey::Bool::*;
219 self.output.push_str("true");
222 self.output.push_str("false");
224 Not(ref inner) => match **inner {
226 self.output.push('!');
227 self.output.push('(');
229 self.output.push(')');
232 let terminal = self.terminals[n as usize];
233 if let Some(str) = self.simplify_not(terminal) {
234 self.simplified = true;
235 self.output.push_str(&str)
237 self.output.push('!');
238 let snip = self.snip(terminal)?;
239 self.output.push_str(&snip);
242 True | False | Not(_) => {
243 self.output.push('!');
244 self.recurse(inner)?;
248 for (index, inner) in v.iter().enumerate() {
250 self.output.push_str(" && ");
252 if let Or(_) = *inner {
253 self.output.push('(');
255 self.output.push(')');
262 for (index, inner) in v.iter().enumerate() {
264 self.output.push_str(" || ");
270 let snip = self.snip(self.terminals[n as usize])?;
271 self.output.push_str(&snip);
278 // The boolean part of the return indicates whether some simplifications have been applied.
279 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
280 let mut suggest_context = SuggestContext {
283 output: String::new(),
286 suggest_context.recurse(suggestion);
287 (suggest_context.output, suggest_context.simplified)
290 fn simple_negate(b: Bool) -> Bool {
291 use quine_mc_cluskey::Bool::*;
295 t @ Term(_) => Not(Box::new(t)),
298 *el = simple_negate(::std::mem::replace(el, True));
304 *el = simple_negate(::std::mem::replace(el, True));
308 Not(inner) => *inner,
314 terminals: [usize; 32],
319 fn terminal_stats(b: &Bool) -> Stats {
320 fn recurse(b: &Bool, stats: &mut Stats) {
322 True | False => stats.ops += 1,
325 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
326 _ => stats.negations += 1,
328 recurse(inner, stats);
330 And(ref v) | Or(ref v) => {
331 stats.ops += v.len() - 1;
333 recurse(inner, stats);
336 Term(n) => stats.terminals[n as usize] += 1,
339 use quine_mc_cluskey::Bool::*;
340 let mut stats = Stats::default();
341 recurse(b, &mut stats);
345 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
346 fn bool_expr(&self, e: &Expr) {
347 let mut h2q = Hir2Qmm {
348 terminals: Vec::new(),
351 if let Ok(expr) = h2q.run(e) {
352 if h2q.terminals.len() > 8 {
353 // QMC has exponentially slow behavior as the number of terminals increases
354 // 8 is reasonable, it takes approximately 0.2 seconds.
359 let stats = terminal_stats(&expr);
360 let mut simplified = expr.simplify();
361 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
363 Bool::Not(_) | Bool::True | Bool::False => {},
364 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
366 let simple_negated = simple_negate(simple);
367 if simplified.iter().any(|s| *s == simple_negated) {
370 simplified.push(simple_negated);
372 let mut improvements = Vec::new();
373 'simplified: for suggestion in &simplified {
374 let simplified_stats = terminal_stats(suggestion);
375 let mut improvement = false;
377 // ignore any "simplifications" that end up requiring a terminal more often
378 // than in the original expression
379 if stats.terminals[i] < simplified_stats.terminals[i] {
380 continue 'simplified;
382 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
387 "this boolean expression contains a logic bug",
390 h2q.terminals[i].span,
391 "this expression can be optimized out by applying boolean operations to the \
394 db.span_suggestion_with_applicability(
396 "it would look like the following",
397 suggest(self.cx, suggestion, &h2q.terminals).0,
398 Applicability::Unspecified,
402 // don't also lint `NONMINIMAL_BOOL`
405 // if the number of occurrences of a terminal decreases or any of the stats
406 // decreases while none increases
407 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
408 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
409 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
412 improvements.push(suggestion);
415 let nonminimal_bool_lint = |suggestions| {
420 "this boolean expression can be simplified",
421 |db| { db.span_suggestions_with_applicability(
425 Applicability::Unspecified,
429 if improvements.is_empty() {
430 let suggest = suggest(self.cx, &expr, &h2q.terminals);
432 nonminimal_bool_lint(vec![suggest.0])
435 nonminimal_bool_lint(
438 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
446 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
447 fn visit_expr(&mut self, e: &'tcx Expr) {
448 if in_macro(e.span) {
452 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => self.bool_expr(e),
453 ExprKind::Unary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
458 _ => walk_expr(self, e),
461 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
462 NestedVisitorMap::None
467 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
468 let ty = cx.tables.expr_ty(expr);
469 get_trait_def_id(cx, &paths::ORD)
470 .map_or(false, |id| implements_trait(cx, ty, id, &[]))