1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::hir::intravisit::*;
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc_data_structures::thin_vec::ThinVec;
15 use crate::rustc_errors::Applicability;
16 use crate::syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
17 use crate::syntax::source_map::{dummy_spanned, Span, DUMMY_SP};
19 get_trait_def_id, implements_trait, in_macro, match_type, paths, snippet_opt, span_lint_and_then, SpanlessEq,
22 /// **What it does:** Checks for boolean expressions that can be written more
25 /// **Why is this bad?** Readability of boolean expressions suffers from
26 /// unnecessary duplication.
28 /// **Known problems:** Ignores short circuiting behavior of `||` and
29 /// `&&`. Ignores `|`, `&` and `^`.
33 /// if a && true // should be: if a
34 /// if !(a == b) // should be: if a != b
36 declare_clippy_lint! {
39 "boolean expressions that can be written more concisely"
42 /// **What it does:** Checks for boolean expressions that contain terminals that
43 /// can be eliminated.
45 /// **Why is this bad?** This is most likely a logic bug.
47 /// **Known problems:** Ignores short circuiting behavior.
51 /// if a && b || a { ... }
53 /// The `b` is unnecessary, the expression is equivalent to `if a`.
54 declare_clippy_lint! {
57 "boolean expressions that contain terminals which can be eliminated"
60 // For each pairs, both orders are considered.
61 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
63 #[derive(Copy, Clone)]
64 pub struct NonminimalBool;
66 impl LintPass for NonminimalBool {
67 fn get_lints(&self) -> LintArray {
68 lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
72 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
75 cx: &LateContext<'a, 'tcx>,
76 _: intravisit::FnKind<'tcx>,
82 NonminimalBoolVisitor { cx }.visit_body(body)
86 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
87 cx: &'a LateContext<'a, 'tcx>,
90 use quine_mc_cluskey::Bool;
91 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
92 terminals: Vec<&'v Expr>,
93 cx: &'a LateContext<'a, 'tcx>,
96 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
97 fn extract(&mut self, op: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
99 if let ExprKind::Binary(binop, ref lhs, ref rhs) = a.node {
100 if binop.node == op {
101 v = self.extract(op, &[lhs, rhs], v)?;
105 v.push(self.run(a)?);
110 fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
111 // prevent folding of `cfg!` macros and the like
112 if !in_macro(e.span) {
114 ExprKind::Unary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
115 ExprKind::Binary(binop, ref lhs, ref rhs) => match binop.node {
116 BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
117 BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
120 ExprKind::Lit(ref lit) => match lit.node {
121 LitKind::Bool(true) => return Ok(Bool::True),
122 LitKind::Bool(false) => return Ok(Bool::False),
128 for (n, expr) in self.terminals.iter().enumerate() {
129 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
130 #[allow(clippy::cast_possible_truncation)]
131 return Ok(Bool::Term(n as u8));
133 let negated = match e.node {
134 ExprKind::Binary(binop, ref lhs, ref rhs) => {
135 if !implements_ord(self.cx, lhs) {
139 let mk_expr = |op| Expr {
141 hir_id: DUMMY_HIR_ID,
143 attrs: ThinVec::new(),
144 node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
147 BinOpKind::Eq => mk_expr(BinOpKind::Ne),
148 BinOpKind::Ne => mk_expr(BinOpKind::Eq),
149 BinOpKind::Gt => mk_expr(BinOpKind::Le),
150 BinOpKind::Ge => mk_expr(BinOpKind::Lt),
151 BinOpKind::Lt => mk_expr(BinOpKind::Ge),
152 BinOpKind::Le => mk_expr(BinOpKind::Gt),
158 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
159 #[allow(clippy::cast_possible_truncation)]
160 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
163 let n = self.terminals.len();
164 self.terminals.push(e);
166 #[allow(clippy::cast_possible_truncation)]
167 Ok(Bool::Term(n as u8))
169 Err("too many literals".to_owned())
174 struct SuggestContext<'a, 'tcx: 'a, 'v> {
175 terminals: &'v [&'v Expr],
176 cx: &'a LateContext<'a, 'tcx>,
181 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
182 fn snip(&self, e: &Expr) -> Option<String> {
183 snippet_opt(self.cx, e.span)
186 fn simplify_not(&self, expr: &Expr) -> Option<String> {
188 ExprKind::Binary(binop, ref lhs, ref rhs) => {
189 if !implements_ord(self.cx, lhs) {
194 BinOpKind::Eq => Some(" != "),
195 BinOpKind::Ne => Some(" == "),
196 BinOpKind::Lt => Some(" >= "),
197 BinOpKind::Gt => Some(" <= "),
198 BinOpKind::Le => Some(" > "),
199 BinOpKind::Ge => Some(" < "),
202 .and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
204 ExprKind::MethodCall(ref path, _, ref args) if args.len() == 1 => {
205 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
206 if !match_type(self.cx, type_of_receiver, &paths::OPTION)
207 && !match_type(self.cx, type_of_receiver, &paths::RESULT)
211 METHODS_WITH_NEGATION
214 .flat_map(|(a, b)| vec![(a, b), (b, a)])
215 .find(|&(a, _)| a == path.ident.as_str())
216 .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
222 fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
223 use quine_mc_cluskey::Bool::*;
226 self.output.push_str("true");
229 self.output.push_str("false");
231 Not(ref inner) => match **inner {
233 self.output.push('!');
234 self.output.push('(');
236 self.output.push(')');
239 let terminal = self.terminals[n as usize];
240 if let Some(str) = self.simplify_not(terminal) {
241 self.simplified = true;
242 self.output.push_str(&str)
244 self.output.push('!');
245 let snip = self.snip(terminal)?;
246 self.output.push_str(&snip);
249 True | False | Not(_) => {
250 self.output.push('!');
251 self.recurse(inner)?;
255 for (index, inner) in v.iter().enumerate() {
257 self.output.push_str(" && ");
259 if let Or(_) = *inner {
260 self.output.push('(');
262 self.output.push(')');
269 for (index, inner) in v.iter().enumerate() {
271 self.output.push_str(" || ");
277 let snip = self.snip(self.terminals[n as usize])?;
278 self.output.push_str(&snip);
285 // The boolean part of the return indicates whether some simplifications have been applied.
286 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
287 let mut suggest_context = SuggestContext {
290 output: String::new(),
293 suggest_context.recurse(suggestion);
294 (suggest_context.output, suggest_context.simplified)
297 fn simple_negate(b: Bool) -> Bool {
298 use quine_mc_cluskey::Bool::*;
302 t @ Term(_) => Not(Box::new(t)),
305 *el = simple_negate(::std::mem::replace(el, True));
311 *el = simple_negate(::std::mem::replace(el, True));
315 Not(inner) => *inner,
321 terminals: [usize; 32],
326 fn terminal_stats(b: &Bool) -> Stats {
327 fn recurse(b: &Bool, stats: &mut Stats) {
329 True | False => stats.ops += 1,
332 And(_) | Or(_) => stats.ops += 1, // brackets are also operations
333 _ => stats.negations += 1,
335 recurse(inner, stats);
337 And(ref v) | Or(ref v) => {
338 stats.ops += v.len() - 1;
340 recurse(inner, stats);
343 Term(n) => stats.terminals[n as usize] += 1,
346 use quine_mc_cluskey::Bool::*;
347 let mut stats = Stats::default();
348 recurse(b, &mut stats);
352 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
353 fn bool_expr(&self, e: &Expr) {
354 let mut h2q = Hir2Qmm {
355 terminals: Vec::new(),
358 if let Ok(expr) = h2q.run(e) {
359 if h2q.terminals.len() > 8 {
360 // QMC has exponentially slow behavior as the number of terminals increases
361 // 8 is reasonable, it takes approximately 0.2 seconds.
366 let stats = terminal_stats(&expr);
367 let mut simplified = expr.simplify();
368 for simple in Bool::Not(Box::new(expr.clone())).simplify() {
370 Bool::Not(_) | Bool::True | Bool::False => {},
371 _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
373 let simple_negated = simple_negate(simple);
374 if simplified.iter().any(|s| *s == simple_negated) {
377 simplified.push(simple_negated);
379 let mut improvements = Vec::new();
380 'simplified: for suggestion in &simplified {
381 let simplified_stats = terminal_stats(suggestion);
382 let mut improvement = false;
384 // ignore any "simplifications" that end up requiring a terminal more often
385 // than in the original expression
386 if stats.terminals[i] < simplified_stats.terminals[i] {
387 continue 'simplified;
389 if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
394 "this boolean expression contains a logic bug",
397 h2q.terminals[i].span,
398 "this expression can be optimized out by applying boolean operations to the \
401 db.span_suggestion_with_applicability(
403 "it would look like the following",
404 suggest(self.cx, suggestion, &h2q.terminals).0,
405 // nonminimal_bool can produce minimal but
406 // not human readable expressions (#3141)
407 Applicability::Unspecified,
411 // don't also lint `NONMINIMAL_BOOL`
414 // if the number of occurrences of a terminal decreases or any of the stats
415 // decreases while none increases
416 improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
417 || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
418 || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
421 improvements.push(suggestion);
424 let nonminimal_bool_lint = |suggestions: Vec<_>| {
429 "this boolean expression can be simplified",
431 db.span_suggestions_with_applicability(
434 suggestions.into_iter(),
435 // nonminimal_bool can produce minimal but
436 // not human readable expressions (#3141)
437 Applicability::Unspecified,
442 if improvements.is_empty() {
443 let suggest = suggest(self.cx, &expr, &h2q.terminals);
445 nonminimal_bool_lint(vec![suggest.0])
448 nonminimal_bool_lint(
451 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
459 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
460 fn visit_expr(&mut self, e: &'tcx Expr) {
461 if in_macro(e.span) {
465 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
468 ExprKind::Unary(UnNot, ref inner) => {
469 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
475 _ => walk_expr(self, e),
478 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
479 NestedVisitorMap::None
483 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
484 let ty = cx.tables.expr_ty(expr);
485 get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))