2023-07-03 12:42:48 -05:00
|
|
|
use clippy_utils::diagnostics::span_lint_and_sugg;
|
2024-06-19 19:43:33 -05:00
|
|
|
use clippy_utils::source::{IntoSpan, SpanRangeExt};
|
2023-05-22 02:38:16 -05:00
|
|
|
use rustc_ast::ast::{Expr, ExprKind};
|
|
|
|
use rustc_errors::Applicability;
|
2024-06-19 19:43:33 -05:00
|
|
|
use rustc_lint::{EarlyContext, EarlyLintPass};
|
2023-11-25 11:45:27 -06:00
|
|
|
use rustc_session::declare_lint_pass;
|
2023-05-22 02:38:16 -05:00
|
|
|
|
|
|
|
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
|
2023-10-23 08:49:18 -05:00
|
|
|
/// ```no_run
|
2023-05-22 02:38:16 -05:00
|
|
|
///# fn check() -> bool { true }
|
|
|
|
/// if check() {
|
|
|
|
/// println!("Check successful!");
|
|
|
|
/// } else {
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
/// Use instead:
|
2023-10-23 08:49:18 -05:00
|
|
|
/// ```no_run
|
2023-05-22 02:38:16 -05:00
|
|
|
///# fn check() -> bool { true }
|
|
|
|
/// if check() {
|
|
|
|
/// println!("Check successful!");
|
|
|
|
/// }
|
|
|
|
/// ```
|
2023-08-18 10:07:43 -05:00
|
|
|
#[clippy::version = "1.72.0"]
|
2023-05-22 02:38:16 -05:00
|
|
|
pub NEEDLESS_ELSE,
|
|
|
|
style,
|
|
|
|
"empty else branch"
|
|
|
|
}
|
|
|
|
declare_lint_pass!(NeedlessElse => [NEEDLESS_ELSE]);
|
|
|
|
|
|
|
|
impl EarlyLintPass for NeedlessElse {
|
|
|
|
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
|
2023-05-24 16:39:06 -05:00
|
|
|
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()
|
2024-06-19 19:43:33 -05:00
|
|
|
&& let range = (then_block.span.hi()..expr.span.hi()).trim_start(cx)
|
|
|
|
&& range.clone().check_source_text(cx, |src| {
|
|
|
|
// Ignore else blocks that contain comments or #[cfg]s
|
|
|
|
!src.contains(['/', '#'])
|
|
|
|
})
|
2023-05-24 16:39:06 -05:00
|
|
|
{
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
NEEDLESS_ELSE,
|
2024-06-19 19:43:33 -05:00
|
|
|
range.with_ctxt(expr.span.ctxt()),
|
2023-07-01 19:33:08 -05:00
|
|
|
"this `else` branch is empty",
|
2023-05-24 16:39:06 -05:00
|
|
|
"you can remove it",
|
|
|
|
String::new(),
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
}
|
2023-05-22 02:38:16 -05:00
|
|
|
}
|
|
|
|
}
|