Skip to content

needless_else: new lint to check for empty else clauses #10810

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

Merged
merged 1 commit into from
May 23, 2023
Merged
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 @@ -4874,6 +4874,7 @@ Released 2018-09-13
[`needless_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
[`needless_continue`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_continue
[`needless_doctest_main`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_doctest_main
[`needless_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_else
[`needless_for_each`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_for_each
[`needless_late_init`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_late_init
[`needless_lifetimes`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes
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 @@ -449,6 +449,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
crate::needless_bool::NEEDLESS_BOOL_ASSIGN_INFO,
crate::needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE_INFO,
crate::needless_continue::NEEDLESS_CONTINUE_INFO,
crate::needless_else::NEEDLESS_ELSE_INFO,
crate::needless_for_each::NEEDLESS_FOR_EACH_INFO,
crate::needless_late_init::NEEDLESS_LATE_INIT_INFO,
crate::needless_parens_on_range_literals::NEEDLESS_PARENS_ON_RANGE_LITERALS_INFO,
Expand Down
2 changes: 2 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ mod needless_arbitrary_self_type;
mod needless_bool;
mod needless_borrowed_ref;
mod needless_continue;
mod needless_else;
mod needless_for_each;
mod needless_late_init;
mod needless_parens_on_range_literals;
Expand Down Expand Up @@ -992,6 +993,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
store.register_late_pass(|_| Box::new(items_after_test_module::ItemsAfterTestModule));
store.register_early_pass(|| Box::new(ref_patterns::RefPatterns));
store.register_late_pass(|_| Box::new(default_constructed_unit_structs::DefaultConstructedUnitStructs));
store.register_early_pass(|| Box::new(needless_else::NeedlessElse));
// add lints here, do not remove this comment, it's used in `new_lint`
}

Expand Down
57 changes: 57 additions & 0 deletions clippy_lints/src/needless_else.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use clippy_utils::{diagnostics::span_lint_and_sugg, source::trim_span, span_extract_comment};
use rustc_ast::ast::{Expr, ExprKind};
use rustc_errors::Applicability;
use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
use rustc_session::{declare_lint_pass, declare_tool_lint};

declare_clippy_lint! {
/// ### What it does
/// Checks for empty `else` branches.
///
/// ### Why is this bad?
/// An empty else branch does nothing and can be removed.
///
/// ### Example
/// ```rust
///# fn check() -> bool { true }
/// if check() {
/// println!("Check successful!");
/// } else {
/// }
/// ```
/// Use instead:
/// ```rust
///# fn check() -> bool { true }
/// if check() {
/// println!("Check successful!");
/// }
/// ```
#[clippy::version = "1.71.0"]
pub NEEDLESS_ELSE,
style,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder how often that happens. Given that it's a style lint (which is warn by default), I worry that it might drown out more important messages if we leave it that way. On the other hand, if it's rare anyway, perhaps it's not a big deal. I'll run lintcheck and report back.

"empty else branch"
}
declare_lint_pass!(NeedlessElse => [NEEDLESS_ELSE]);

impl EarlyLintPass for NeedlessElse {
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
if let ExprKind::If(_, then_block, Some(else_clause)) = &expr.kind &&
let ExprKind::Block(block, _) = &else_clause.kind &&
!expr.span.from_expansion() &&
!else_clause.span.from_expansion() &&
block.stmts.is_empty() {
let span = trim_span(cx.sess().source_map(), expr.span.trim_start(then_block.span).unwrap());
if span_extract_comment(cx.sess().source_map(), span).is_empty() {
span_lint_and_sugg(
cx,
NEEDLESS_ELSE,
span,
"this else branch is empty",
"you can remove it",
String::new(),
Applicability::MachineApplicable,
);
}
}
}
}
2 changes: 1 addition & 1 deletion tests/ui-toml/ifs_same_cond/ifs_same_cond.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![warn(clippy::ifs_same_cond)]
#![allow(clippy::if_same_then_else, clippy::comparison_chain)]
#![allow(clippy::if_same_then_else, clippy::comparison_chain, clippy::needless_else)]

fn main() {}

Expand Down
6 changes: 5 additions & 1 deletion tests/ui/branches_sharing_code/valid_if_blocks.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
#![deny(clippy::branches_sharing_code, clippy::if_same_then_else)]
#![allow(dead_code)]
#![allow(clippy::mixed_read_write_in_expression, clippy::uninlined_format_args)]
#![allow(
clippy::mixed_read_write_in_expression,
clippy::uninlined_format_args,
clippy::needless_else
)]

// This tests valid if blocks that shouldn't trigger the lint

Expand Down
20 changes: 10 additions & 10 deletions tests/ui/branches_sharing_code/valid_if_blocks.stderr
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
error: this `if` has identical blocks
--> $DIR/valid_if_blocks.rs:105:14
--> $DIR/valid_if_blocks.rs:109:14
|
LL | if false {
| ______________^
LL | | } else {
| |_____^
|
note: same as this
--> $DIR/valid_if_blocks.rs:106:12
--> $DIR/valid_if_blocks.rs:110:12
|
LL | } else {
| ____________^
Expand All @@ -20,7 +20,7 @@ LL | #![deny(clippy::branches_sharing_code, clippy::if_same_then_else)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^

error: this `if` has identical blocks
--> $DIR/valid_if_blocks.rs:116:15
--> $DIR/valid_if_blocks.rs:120:15
|
LL | if x == 0 {
| _______________^
Expand All @@ -31,7 +31,7 @@ LL | | } else {
| |_____^
|
note: same as this
--> $DIR/valid_if_blocks.rs:120:12
--> $DIR/valid_if_blocks.rs:124:12
|
LL | } else {
| ____________^
Expand All @@ -42,19 +42,19 @@ LL | | }
| |_____^

error: this `if` has identical blocks
--> $DIR/valid_if_blocks.rs:127:23
--> $DIR/valid_if_blocks.rs:131:23
|
LL | let _ = if x == 6 { 7 } else { 7 };
| ^^^^^
|
note: same as this
--> $DIR/valid_if_blocks.rs:127:34
--> $DIR/valid_if_blocks.rs:131:34
|
LL | let _ = if x == 6 { 7 } else { 7 };
| ^^^^^

error: this `if` has identical blocks
--> $DIR/valid_if_blocks.rs:133:23
--> $DIR/valid_if_blocks.rs:137:23
|
LL | } else if x == 68 {
| _______________________^
Expand All @@ -66,7 +66,7 @@ LL | | } else {
| |_____^
|
note: same as this
--> $DIR/valid_if_blocks.rs:138:12
--> $DIR/valid_if_blocks.rs:142:12
|
LL | } else {
| ____________^
Expand All @@ -78,7 +78,7 @@ LL | | };
| |_____^

error: this `if` has identical blocks
--> $DIR/valid_if_blocks.rs:147:23
--> $DIR/valid_if_blocks.rs:151:23
|
LL | } else if x == 68 {
| _______________________^
Expand All @@ -88,7 +88,7 @@ LL | | } else {
| |_____^
|
note: same as this
--> $DIR/valid_if_blocks.rs:150:12
--> $DIR/valid_if_blocks.rs:154:12
|
LL | } else {
| ____________^
Expand Down
1 change: 1 addition & 0 deletions tests/ui/crashes/ice-7410.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#![no_std]
#![allow(clippy::if_same_then_else)]
#![allow(clippy::redundant_pattern_matching)]
#![allow(clippy::needless_else)]

use core::panic::PanicInfo;

Expand Down
2 changes: 1 addition & 1 deletion tests/ui/ifs_same_cond.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![warn(clippy::ifs_same_cond)]
#![allow(clippy::if_same_then_else, clippy::comparison_chain)] // all empty blocks
#![allow(clippy::if_same_then_else, clippy::comparison_chain, clippy::needless_else)] // all empty blocks

fn ifs_same_cond() {
let a = 0;
Expand Down
40 changes: 40 additions & 0 deletions tests/ui/needless_else.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//@run-rustfix
#![allow(unused)]
#![warn(clippy::needless_else)]
#![allow(clippy::suspicious_else_formatting)]

macro_rules! mac {
($test:expr) => {
if $test {
println!("Test successful!");
} else {
}
};
}

fn main() {
let b = std::hint::black_box(true);

if b {
println!("Foobar");
}

if b {
println!("Foobar");
} else {
// Do not lint because this comment might be important
}

if b {
println!("Foobar");
} else
/* Do not lint because this comment might be important */
{
}

// Do not lint because of the expression
let _ = if b { 1 } else { 2 };

// Do not lint because inside a macro
mac!(b);
}
41 changes: 41 additions & 0 deletions tests/ui/needless_else.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//@run-rustfix
#![allow(unused)]
#![warn(clippy::needless_else)]
#![allow(clippy::suspicious_else_formatting)]

macro_rules! mac {
($test:expr) => {
if $test {
println!("Test successful!");
} else {
}
};
}

fn main() {
let b = std::hint::black_box(true);

if b {
println!("Foobar");
} else {
}

if b {
println!("Foobar");
} else {
// Do not lint because this comment might be important
}

if b {
println!("Foobar");
} else
/* Do not lint because this comment might be important */
{
}

// Do not lint because of the expression
let _ = if b { 1 } else { 2 };

// Do not lint because inside a macro
mac!(b);
}
12 changes: 12 additions & 0 deletions tests/ui/needless_else.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
error: this else branch is empty
--> $DIR/needless_else.rs:20:7
|
LL | } else {
| _______^
LL | | }
| |_____^ help: you can remove it
|
= note: `-D clippy::needless-else` implied by `-D warnings`

error: aborting due to previous error

3 changes: 2 additions & 1 deletion tests/ui/needless_return.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
clippy::if_same_then_else,
clippy::single_match,
clippy::needless_bool,
clippy::equatable_if_let
clippy::equatable_if_let,
clippy::needless_else
)]
#![warn(clippy::needless_return)]

Expand Down
3 changes: 2 additions & 1 deletion tests/ui/needless_return.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
clippy::if_same_then_else,
clippy::single_match,
clippy::needless_bool,
clippy::equatable_if_let
clippy::equatable_if_let,
clippy::needless_else
)]
#![warn(clippy::needless_return)]

Expand Down
Loading