Skip to content

Add ifs_as_logical_ops lint #14904

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5838,6 +5838,7 @@ Released 2018-09-13
[`if_not_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_not_else
[`if_same_then_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_same_then_else
[`if_then_some_else_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_then_some_else_none
[`ifs_as_logical_ops`]: https://rust-lang.github.io/rust-clippy/master/index.html#ifs_as_logical_ops
[`ifs_same_cond`]: https://rust-lang.github.io/rust-clippy/master/index.html#ifs_same_cond
[`ignore_without_reason`]: https://rust-lang.github.io/rust-clippy/master/index.html#ignore_without_reason
[`ignored_unit_patterns`]: https://rust-lang.github.io/rust-clippy/master/index.html#ignored_unit_patterns
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
crate::if_let_mutex::IF_LET_MUTEX_INFO,
crate::if_not_else::IF_NOT_ELSE_INFO,
crate::if_then_some_else_none::IF_THEN_SOME_ELSE_NONE_INFO,
crate::ifs_as_logical_ops::IFS_AS_LOGICAL_OPS_INFO,
crate::ignored_unit_patterns::IGNORED_UNIT_PATTERNS_INFO,
crate::impl_hash_with_borrow_str_and_bytes::IMPL_HASH_BORROW_WITH_STR_AND_BYTES_INFO,
crate::implicit_hasher::IMPLICIT_HASHER_INFO,
Expand Down
67 changes: 67 additions & 0 deletions clippy_lints/src/ifs_as_logical_ops.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_never_expr;
use clippy_utils::source::SpanRangeExt;
use clippy_utils::sym::clippy_utils;
use rustc_ast::LitKind;
use rustc_errors::Applicability;
use rustc_hir::*;
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;

declare_clippy_lint! {
/// ### What it does
///
/// ### Why is this bad?
///
/// ### Example
/// ```no_run
/// // example code where clippy issues a warning
/// ```
/// Use instead:
/// ```no_run
/// // example code which does not raise clippy warning
/// ```
#[clippy::version = "1.89.0"]
pub IFS_AS_LOGICAL_OPS,
nursery,
"default lint description"
}
declare_lint_pass!(IfsAsLogicalOps => [IFS_AS_LOGICAL_OPS]);

impl<'tcx> LateLintPass<'tcx> for IfsAsLogicalOps {
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) {
if let ExprKind::If(cond, cond_inner, Some(els)) = e.kind
&& let ExprKind::Block(if_block, _label) = cond_inner.kind
// Check if the if-block has only a return statement
&& if_block.stmts.len() == 0
&& let Some(if_expr) = if_block.expr
// and does not diverge.
&& is_never_expr(cx, if_expr).is_none()
// And that the else block consists of only the boolean 'false'.
&& let ExprKind::Block(else_block, _label) = els.kind
&& else_block.stmts.len() == 0
&& let Some(else_expr) = else_block.expr
&& let ExprKind::Lit(lit) = else_expr.kind
&& let LitKind::Bool(value) = lit.node
&& value == false
{
let maybe_lhs_snippet = if_expr.span.get_source_text(cx);
let maybe_rhs_snippet = lit.span.get_source_text(cx);
if let Some(lhs_snippet) = maybe_lhs_snippet
&& let Some(rhs_snippet) = maybe_rhs_snippet
{
let lhs_text = lhs_snippet.as_str();
let rhs_text = rhs_snippet.as_str();
span_lint_and_sugg(
cx,
IFS_AS_LOGICAL_OPS,
e.span,
"Logical operations are clearer than if conditions in this instance",
"try",
format!("{lhs_text} && {rhs_text}"),
Applicability::MachineApplicable,
);
}
}
}
}
2 changes: 2 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ mod future_not_send;
mod if_let_mutex;
mod if_not_else;
mod if_then_some_else_none;
mod ifs_as_logical_ops;
mod ignored_unit_patterns;
mod impl_hash_with_borrow_str_and_bytes;
mod implicit_hasher;
Expand Down Expand Up @@ -948,5 +949,6 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(move |_| Box::new(redundant_test_prefix::RedundantTestPrefix));
store.register_late_pass(|_| Box::new(cloned_ref_to_slice_refs::ClonedRefToSliceRefs::new(conf)));
store.register_late_pass(|_| Box::new(infallible_try_from::InfallibleTryFrom));
store.register_late_pass(|_| Box::new(ifs_as_logical_ops::IfsAsLogicalOps));
// add lints here, do not remove this comment, it's used in `new_lint`
}
23 changes: 23 additions & 0 deletions output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.03s
Running `target/debug/clippy_dev lint /Users/barun511/open_source/clippy-examples/src/main.rs`
Compiling clippy_lints v0.1.89 (/Users/barun511/open_source/rust-clippy/clippy_lints)
warning: unused import: `clippy_utils::sym::clippy_utils`
--> clippy_lints/src/ifs_as_logical_ops.rs:3:5
|
3 | use clippy_utils::sym::clippy_utils;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default

warning: unused variable: `cond`
--> clippy_lints/src/ifs_as_logical_ops.rs:31:29
|
31 | if let ExprKind::If(cond, cond_inner, Some(els)) = e.kind
| ^^^^ help: if this is intentional, prefix it with an underscore: `_cond`
|
= note: `#[warn(unused_variables)]` on by default

warning: `clippy_lints` (lib) generated 2 warnings (run `cargo fix --lib -p clippy_lints` to apply 1 suggestion)
Compiling clippy v0.1.89 (/Users/barun511/open_source/rust-clippy)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.81s
Running `target/debug/clippy-driver -L ./target/debug -Z no-codegen --edition 2024 /Users/barun511/open_source/clippy-examples/src/main.rs`
10 changes: 10 additions & 0 deletions tests/ui/ifs_as_logical_ops.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#![warn(clippy::ifs_as_logical_ops)]

fn main() {
// test code goes here
}

fn john(b1: bool, b2: bool) -> bool {
b2 && false
//~^ ifs_as_logical_ops
}
10 changes: 10 additions & 0 deletions tests/ui/ifs_as_logical_ops.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#![warn(clippy::ifs_as_logical_ops)]

fn main() {
// test code goes here
}

fn john(b1: bool, b2: bool) -> bool {
if b1 { b2 } else { false }
//~^ ifs_as_logical_ops
}
11 changes: 11 additions & 0 deletions tests/ui/ifs_as_logical_ops.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
error: Logical operations are clearer than if conditions in this instance
--> tests/ui/ifs_as_logical_ops.rs:8:5
|
LL | if b1 { b2 } else { false }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `b2 && false`
|
= note: `-D clippy::ifs-as-logical-ops` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::ifs_as_logical_ops)]`

error: aborting due to 1 previous error