rust-clippy/clippy_lints/src/booleans.rs

500 lines
18 KiB
Rust
Raw Normal View History

use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
use clippy_utils::{eq_expr_value, get_trait_def_id, paths};
use if_chain::if_chain;
2020-03-01 03:23:33 +00:00
use rustc_ast::ast::LitKind;
use rustc_errors::Applicability;
2022-01-15 22:07:52 +00:00
use rustc_hir::intravisit::{walk_expr, FnKind, Visitor};
2020-02-21 08:39:38 +00:00
use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, UnOp};
2020-01-12 06:08:41 +00:00
use rustc_lint::{LateContext, LateLintPass};
2020-01-11 11:37:08 +00:00
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::sym;
2016-03-23 11:19:13 +00:00
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
/// ### What it does
/// Checks for boolean expressions that can be written more
/// concisely.
///
/// ### Why is this bad?
/// Readability of boolean expressions suffers from
/// unnecessary duplication.
///
/// ### Known problems
/// Ignores short circuiting behavior of `||` and
/// `&&`. Ignores `|`, `&` and `^`.
///
/// ### Example
2019-03-05 22:23:50 +00:00
/// ```ignore
/// if a && true // should be: if a
/// if !(a == b) // should be: if a != b
/// ```
#[clippy::version = "pre 1.29.0"]
pub NONMINIMAL_BOOL,
2018-03-28 13:24:26 +00:00
complexity,
"boolean expressions that can be written more concisely"
2016-03-23 11:19:13 +00:00
}
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
/// ### What it does
/// Checks for boolean expressions that contain terminals that
/// can be eliminated.
///
/// ### Why is this bad?
/// This is most likely a logic bug.
///
/// ### Known problems
/// Ignores short circuiting behavior.
///
/// ### Example
2019-03-05 22:23:50 +00:00
/// ```ignore
/// if a && b || a { ... }
/// ```
/// The `b` is unnecessary, the expression is equivalent to `if a`.
#[clippy::version = "pre 1.29.0"]
pub LOGIC_BUG,
2018-03-28 13:24:26 +00:00
correctness,
"boolean expressions that contain terminals which can be eliminated"
}
2017-11-10 19:55:15 +00:00
// For each pairs, both orders are considered.
2019-05-17 22:58:25 +00:00
const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
2019-04-08 20:43:55 +00:00
declare_lint_pass!(NonminimalBool => [NONMINIMAL_BOOL, LOGIC_BUG]);
2016-03-23 11:19:13 +00:00
impl<'tcx> LateLintPass<'tcx> for NonminimalBool {
2017-01-13 16:04:56 +00:00
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
2020-02-18 13:28:18 +00:00
_: FnKind<'tcx>,
2019-12-30 04:02:10 +00:00
_: &'tcx FnDecl<'_>,
2019-12-22 14:42:41 +00:00
body: &'tcx Body<'_>,
2017-01-13 16:04:56 +00:00
_: Span,
2019-02-20 10:11:11 +00:00
_: HirId,
2017-01-13 16:04:56 +00:00
) {
NonminimalBoolVisitor { cx }.visit_body(body);
2016-03-23 11:19:13 +00:00
}
}
struct NonminimalBoolVisitor<'a, 'tcx> {
cx: &'a LateContext<'tcx>,
}
2016-03-23 11:19:13 +00:00
use quine_mc_cluskey::Bool;
struct Hir2Qmm<'a, 'tcx, 'v> {
2019-12-27 07:12:26 +00:00
terminals: Vec<&'v Expr<'v>>,
cx: &'a LateContext<'tcx>,
}
2016-03-23 11:19:13 +00:00
impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
2019-12-27 07:12:26 +00:00
fn extract(&mut self, op: BinOpKind, a: &[&'v Expr<'_>], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
2016-03-23 11:19:13 +00:00
for a in a {
2019-09-27 15:16:06 +00:00
if let ExprKind::Binary(binop, lhs, rhs) = &a.kind {
2016-03-23 11:19:13 +00:00
if binop.node == op {
v = self.extract(op, &[lhs, rhs], v)?;
continue;
}
}
v.push(self.run(a)?);
}
Ok(v)
}
2019-12-27 07:12:26 +00:00
fn run(&mut self, e: &'v Expr<'_>) -> Result<Bool, String> {
fn negate(bin_op_kind: BinOpKind) -> Option<BinOpKind> {
match bin_op_kind {
BinOpKind::Eq => Some(BinOpKind::Ne),
BinOpKind::Ne => Some(BinOpKind::Eq),
BinOpKind::Gt => Some(BinOpKind::Le),
BinOpKind::Ge => Some(BinOpKind::Lt),
BinOpKind::Lt => Some(BinOpKind::Ge),
BinOpKind::Le => Some(BinOpKind::Gt),
_ => None,
}
}
// prevent folding of `cfg!` macros and the like
2019-08-19 16:30:32 +00:00
if !e.span.from_expansion() {
2019-09-27 15:16:06 +00:00
match &e.kind {
ExprKind::Unary(UnOp::Not, inner) => return Ok(Bool::Not(Box::new(self.run(inner)?))),
2018-12-29 16:34:56 +00:00
ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
2020-07-17 08:47:04 +00:00
BinOpKind::Or => {
return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?));
},
BinOpKind::And => {
return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?));
},
2017-09-05 09:33:04 +00:00
_ => (),
2016-12-20 17:21:30 +00:00
},
2018-12-29 16:34:56 +00:00
ExprKind::Lit(lit) => match lit.node {
2017-09-05 09:33:04 +00:00
LitKind::Bool(true) => return Ok(Bool::True),
LitKind::Bool(false) => return Ok(Bool::False),
_ => (),
2016-12-20 17:21:30 +00:00
},
2016-04-14 18:14:03 +00:00
_ => (),
}
2016-03-23 11:19:13 +00:00
}
2016-03-24 15:02:26 +00:00
for (n, expr) in self.terminals.iter().enumerate() {
if eq_expr_value(self.cx, e, expr) {
2018-08-01 20:48:41 +00:00
#[allow(clippy::cast_possible_truncation)]
2017-09-05 09:33:04 +00:00
return Ok(Bool::Term(n as u8));
2016-03-24 15:02:26 +00:00
}
if_chain! {
2019-09-27 15:16:06 +00:00
if let ExprKind::Binary(e_binop, e_lhs, e_rhs) = &e.kind;
if implements_ord(self.cx, e_lhs);
2019-09-27 15:16:06 +00:00
if let ExprKind::Binary(expr_binop, expr_lhs, expr_rhs) = &expr.kind;
if negate(e_binop.node) == Some(expr_binop.node);
if eq_expr_value(self.cx, e_lhs, expr_lhs);
if eq_expr_value(self.cx, e_rhs, expr_rhs);
then {
#[allow(clippy::cast_possible_truncation)]
return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
}
}
}
let n = self.terminals.len();
self.terminals.push(e);
2016-03-23 11:19:13 +00:00
if n < 32 {
2018-08-01 20:48:41 +00:00
#[allow(clippy::cast_possible_truncation)]
2017-09-05 09:33:04 +00:00
Ok(Bool::Term(n as u8))
2016-03-23 11:19:13 +00:00
} else {
Err("too many literals".to_owned())
}
}
}
struct SuggestContext<'a, 'tcx, 'v> {
2019-12-27 07:12:26 +00:00
terminals: &'v [&'v Expr<'v>],
cx: &'a LateContext<'tcx>,
output: String,
}
impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
2017-11-29 15:03:05 +00:00
fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
2020-02-21 08:39:38 +00:00
use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
2018-12-29 16:34:56 +00:00
match suggestion {
2016-03-23 11:19:13 +00:00
True => {
self.output.push_str("true");
2016-12-20 17:21:30 +00:00
},
2016-03-23 11:19:13 +00:00
False => {
self.output.push_str("false");
2016-12-20 17:21:30 +00:00
},
2018-12-29 16:34:56 +00:00
Not(inner) => match **inner {
2017-09-05 09:33:04 +00:00
And(_) | Or(_) => {
self.output.push('!');
2017-11-17 21:42:25 +00:00
self.output.push('(');
self.recurse(inner);
self.output.push(')');
2017-09-05 09:33:04 +00:00
},
Term(n) => {
2017-11-17 21:42:25 +00:00
let terminal = self.terminals[n as usize];
if let Some(str) = simplify_not(self.cx, terminal) {
self.output.push_str(&str);
} else {
self.output.push('!');
let snip = snippet_opt(self.cx, terminal.span)?;
2017-11-17 21:52:11 +00:00
self.output.push_str(&snip);
}
2017-09-05 09:33:04 +00:00
},
True | False | Not(_) => {
self.output.push('!');
2017-11-29 15:03:05 +00:00
self.recurse(inner)?;
2017-09-05 09:33:04 +00:00
},
2016-12-20 17:21:30 +00:00
},
2018-12-29 16:34:56 +00:00
And(v) => {
for (index, inner) in v.iter().enumerate() {
if index > 0 {
self.output.push_str(" && ");
}
2016-03-29 15:18:47 +00:00
if let Or(_) = *inner {
2017-11-17 21:42:25 +00:00
self.output.push('(');
self.recurse(inner);
self.output.push(')');
2016-03-29 15:18:47 +00:00
} else {
2017-11-17 21:42:25 +00:00
self.recurse(inner);
2016-03-29 15:18:47 +00:00
}
2016-03-23 11:49:16 +00:00
}
2016-12-20 17:21:30 +00:00
},
2018-12-29 16:34:56 +00:00
Or(v) => {
2020-01-13 22:08:45 +00:00
for (index, inner) in v.iter().rev().enumerate() {
if index > 0 {
self.output.push_str(" || ");
}
2017-11-17 21:42:25 +00:00
self.recurse(inner);
2016-03-23 11:19:13 +00:00
}
2016-12-20 17:21:30 +00:00
},
2018-12-29 16:34:56 +00:00
&Term(n) => {
let snip = snippet_opt(self.cx, self.terminals[n as usize].span)?;
self.output.push_str(&snip);
2016-12-20 17:21:30 +00:00
},
2016-03-23 11:19:13 +00:00
}
2017-11-29 15:03:05 +00:00
Some(())
2016-03-23 11:19:13 +00:00
}
}
fn simplify_not(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<String> {
2019-09-27 15:16:06 +00:00
match &expr.kind {
ExprKind::Binary(binop, lhs, rhs) => {
if !implements_ord(cx, lhs) {
return None;
}
match binop.node {
BinOpKind::Eq => Some(" != "),
BinOpKind::Ne => Some(" == "),
BinOpKind::Lt => Some(" >= "),
BinOpKind::Gt => Some(" <= "),
BinOpKind::Le => Some(" > "),
BinOpKind::Ge => Some(" < "),
_ => None,
}
.and_then(|op| {
Some(format!(
"{}{}{}",
snippet_opt(cx, lhs.span)?,
op,
snippet_opt(cx, rhs.span)?
))
})
},
ExprKind::MethodCall(path, args, _) if args.len() == 1 => {
2020-07-17 08:47:04 +00:00
let type_of_receiver = cx.typeck_results().expr_ty(&args[0]);
2021-10-02 23:51:01 +00:00
if !is_type_diagnostic_item(cx, type_of_receiver, sym::Option)
&& !is_type_diagnostic_item(cx, type_of_receiver, sym::Result)
2020-04-12 13:23:54 +00:00
{
return None;
}
METHODS_WITH_NEGATION
.iter()
.copied()
.flat_map(|(a, b)| vec![(a, b), (b, a)])
.find(|&(a, _)| {
let path: &str = path.ident.name.as_str();
a == path
})
.and_then(|(_, neg_method)| Some(format!("{}.{}()", snippet_opt(cx, args[0].span)?, neg_method)))
},
_ => None,
}
}
fn suggest(cx: &LateContext<'_>, suggestion: &Bool, terminals: &[&Expr<'_>]) -> String {
let mut suggest_context = SuggestContext {
terminals,
cx,
output: String::new(),
};
2017-11-17 21:42:25 +00:00
suggest_context.recurse(suggestion);
suggest_context.output
2016-03-23 11:19:13 +00:00
}
fn simple_negate(b: Bool) -> Bool {
2020-02-21 08:39:38 +00:00
use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
match b {
True => False,
False => True,
t @ Term(_) => Not(Box::new(t)),
And(mut v) => {
for el in &mut v {
*el = simple_negate(::std::mem::replace(el, True));
}
Or(v)
2016-12-20 17:21:30 +00:00
},
Or(mut v) => {
for el in &mut v {
*el = simple_negate(::std::mem::replace(el, True));
}
And(v)
2016-12-20 17:21:30 +00:00
},
Not(inner) => *inner,
}
}
#[derive(Default)]
struct Stats {
terminals: [usize; 32],
negations: usize,
ops: usize,
}
fn terminal_stats(b: &Bool) -> Stats {
fn recurse(b: &Bool, stats: &mut Stats) {
2018-12-29 16:34:56 +00:00
match b {
True | False => stats.ops += 1,
2018-12-29 16:34:56 +00:00
Not(inner) => {
match **inner {
And(_) | Or(_) => stats.ops += 1, // brackets are also operations
_ => stats.negations += 1,
}
recurse(inner, stats);
2016-12-20 17:21:30 +00:00
},
2018-12-29 16:34:56 +00:00
And(v) | Or(v) => {
stats.ops += v.len() - 1;
for inner in v {
recurse(inner, stats);
}
2016-12-20 17:21:30 +00:00
},
2018-12-29 16:34:56 +00:00
&Term(n) => stats.terminals[n as usize] += 1,
}
}
2020-02-21 08:39:38 +00:00
use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
let mut stats = Stats::default();
recurse(b, &mut stats);
stats
}
2016-03-23 11:19:13 +00:00
impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
2019-12-27 07:12:26 +00:00
fn bool_expr(&self, e: &'tcx Expr<'_>) {
let mut h2q = Hir2Qmm {
terminals: Vec::new(),
cx: self.cx,
};
2016-03-23 11:19:13 +00:00
if let Ok(expr) = h2q.run(e) {
if h2q.terminals.len() > 8 {
// QMC has exponentially slow behavior as the number of terminals increases
// 8 is reasonable, it takes approximately 0.2 seconds.
// See #825
return;
}
let stats = terminal_stats(&expr);
let mut simplified = expr.simplify();
2019-09-28 11:29:35 +00:00
for simple in Bool::Not(Box::new(expr)).simplify() {
match simple {
2016-12-20 17:21:30 +00:00
Bool::Not(_) | Bool::True | Bool::False => {},
_ => simplified.push(Bool::Not(Box::new(simple.clone()))),
}
let simple_negated = simple_negate(simple);
if simplified.iter().any(|s| *s == simple_negated) {
continue;
}
simplified.push(simple_negated);
}
2020-02-18 11:50:10 +00:00
let mut improvements = Vec::with_capacity(simplified.len());
'simplified: for suggestion in &simplified {
2016-04-26 15:05:39 +00:00
let simplified_stats = terminal_stats(suggestion);
let mut improvement = false;
for i in 0..32 {
// ignore any "simplifications" that end up requiring a terminal more often
// than in the original expression
if stats.terminals[i] < simplified_stats.terminals[i] {
continue 'simplified;
2016-03-23 11:19:13 +00:00
}
if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
2017-08-09 07:30:56 +00:00
span_lint_and_then(
self.cx,
LOGIC_BUG,
e.span,
"this boolean expression contains a logic bug",
|diag| {
diag.span_help(
2017-08-09 07:30:56 +00:00
h2q.terminals[i].span,
"this expression can be optimized out by applying boolean operations to the \
2017-09-05 09:33:04 +00:00
outer expression",
2017-08-09 07:30:56 +00:00
);
diag.span_suggestion(
2017-08-09 07:30:56 +00:00
e.span,
"it would look like the following",
suggest(self.cx, suggestion, &h2q.terminals),
// nonminimal_bool can produce minimal but
// not human readable expressions (#3141)
Applicability::Unspecified,
2017-08-09 07:30:56 +00:00
);
},
);
// don't also lint `NONMINIMAL_BOOL`
return;
}
// if the number of occurrences of a terminal decreases or any of the stats
// decreases while none increases
2017-11-04 19:55:56 +00:00
improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
|| (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
|| (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
}
if improvement {
improvements.push(suggestion);
}
2016-03-23 11:19:13 +00:00
}
let nonminimal_bool_lint = |suggestions: Vec<_>| {
2017-08-09 07:30:56 +00:00
span_lint_and_then(
self.cx,
NONMINIMAL_BOOL,
e.span,
"this boolean expression can be simplified",
|diag| {
diag.span_suggestions(
e.span,
"try",
suggestions.into_iter(),
// nonminimal_bool can produce minimal but
// not human readable expressions (#3141)
Applicability::Unspecified,
2018-09-18 15:07:54 +00:00
);
},
);
};
if improvements.is_empty() {
let mut visitor = NotSimplificationVisitor { cx: self.cx };
visitor.visit_expr(e);
} else {
nonminimal_bool_lint(
improvements
.into_iter()
.map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
2018-11-27 20:14:15 +00:00
.collect(),
2017-08-09 07:30:56 +00:00
);
}
2016-03-23 11:19:13 +00:00
}
}
}
impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
2019-12-27 07:12:26 +00:00
fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
if !e.span.from_expansion() {
match &e.kind {
ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
2018-11-27 20:14:15 +00:00
self.bool_expr(e);
},
ExprKind::Unary(UnOp::Not, inner) => {
if self.cx.typeck_results().node_types()[inner.hir_id].is_bool() {
self.bool_expr(e);
}
},
_ => {},
}
2016-03-23 11:19:13 +00:00
}
walk_expr(self, e);
2016-03-23 11:19:13 +00:00
}
}
fn implements_ord<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
2020-07-17 08:47:04 +00:00
let ty = cx.typeck_results().expr_ty(expr);
2019-05-17 21:53:54 +00:00
get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))
}
struct NotSimplificationVisitor<'a, 'tcx> {
cx: &'a LateContext<'tcx>,
}
impl<'a, 'tcx> Visitor<'tcx> for NotSimplificationVisitor<'a, 'tcx> {
2019-12-27 07:12:26 +00:00
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
if let ExprKind::Unary(UnOp::Not, inner) = &expr.kind {
if let Some(suggestion) = simplify_not(self.cx, inner) {
span_lint_and_sugg(
self.cx,
NONMINIMAL_BOOL,
expr.span,
"this boolean expression can be simplified",
"try",
suggestion,
Applicability::MachineApplicable,
);
}
}
walk_expr(self, expr);
}
}