-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
new lint that detects useless match expression #8471
Merged
Merged
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
30fb822
add tests, add base bone for the new lint
J-ZhengLi db3fcf8
add basic code to check nop match blocks
J-ZhengLi 6bfc112
add nop if-let expression check.
J-ZhengLi 750204e
fix a bug that caused internal test fail
J-ZhengLi ec91164
rename lint to `needless_match`
J-ZhengLi 086b045
add checking for `x -> x` and `ref x -> x` and related test cases.
J-ZhengLi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,6 +16,7 @@ mod match_same_arms; | |
mod match_single_binding; | ||
mod match_wild_enum; | ||
mod match_wild_err_arm; | ||
mod nop_match; | ||
mod overlapping_arms; | ||
mod redundant_pattern_match; | ||
mod rest_pat_in_fully_bound_struct; | ||
|
@@ -566,6 +567,49 @@ declare_clippy_lint! { | |
"`match` with identical arm bodies" | ||
} | ||
|
||
declare_clippy_lint! { | ||
/// ### What it does | ||
/// Checks for unnecessary `match` or match-like `if let` returns for `Option` and `Result` | ||
/// when function signatures are the same. | ||
/// | ||
/// ### Why is this bad? | ||
/// This `match` block does nothing and might not be what the coder intended. | ||
/// | ||
/// ### Example | ||
/// ```rust,ignore | ||
/// fn foo() -> Result<(), i32> { | ||
/// match result { | ||
/// Ok(val) => Ok(val), | ||
/// Err(err) => Err(err), | ||
/// } | ||
/// } | ||
/// | ||
/// fn bar() -> Option<i32> { | ||
/// if let Some(val) = option { | ||
/// Some(val) | ||
/// } else { | ||
/// None | ||
/// } | ||
/// } | ||
/// ``` | ||
/// | ||
/// Could be replaced as | ||
/// | ||
/// ```rust,ignore | ||
/// fn foo() -> Result<(), i32> { | ||
/// result | ||
/// } | ||
/// | ||
/// fn bar() -> Option<i32> { | ||
/// option | ||
/// } | ||
/// ``` | ||
#[clippy::version = "1.61.0"] | ||
pub NOP_MATCH, | ||
correctness, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't see this as a correctness lint. At best, it's suspicious, or complexity. |
||
"`match` or match-like `if let` that are unnecessary" | ||
} | ||
|
||
#[derive(Default)] | ||
pub struct Matches { | ||
msrv: Option<RustcVersion>, | ||
|
@@ -599,6 +643,7 @@ impl_lint_pass!(Matches => [ | |
REDUNDANT_PATTERN_MATCHING, | ||
MATCH_LIKE_MATCHES_MACRO, | ||
MATCH_SAME_ARMS, | ||
NOP_MATCH, | ||
]); | ||
|
||
impl<'tcx> LateLintPass<'tcx> for Matches { | ||
|
@@ -622,6 +667,7 @@ impl<'tcx> LateLintPass<'tcx> for Matches { | |
overlapping_arms::check(cx, ex, arms); | ||
match_wild_enum::check(cx, ex, arms); | ||
match_as_ref::check(cx, ex, arms, expr); | ||
nop_match::check_match(cx, ex, arms); | ||
|
||
if self.infallible_destructuring_match_linted { | ||
self.infallible_destructuring_match_linted = false; | ||
|
@@ -640,6 +686,7 @@ impl<'tcx> LateLintPass<'tcx> for Matches { | |
match_like_matches::check(cx, expr); | ||
} | ||
redundant_pattern_match::check(cx, expr); | ||
nop_match::check(cx, expr); | ||
} | ||
} | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
use super::NOP_MATCH; | ||
use clippy_utils::diagnostics::span_lint_and_sugg; | ||
use clippy_utils::source::snippet_with_applicability; | ||
use clippy_utils::ty::is_type_diagnostic_item; | ||
use clippy_utils::{eq_expr_value, get_parent_expr, higher, is_else_clause, is_lang_ctor, peel_blocks_with_stmt}; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::LangItem::OptionNone; | ||
use rustc_hir::{Arm, BindingAnnotation, Expr, ExprKind, Pat, PatKind, Path, PathSegment, QPath}; | ||
use rustc_lint::LateContext; | ||
use rustc_span::sym; | ||
|
||
pub(crate) fn check_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) { | ||
// This is for avoiding collision with `match_single_binding`. | ||
if arms.len() < 2 { | ||
return; | ||
} | ||
|
||
for arm in arms { | ||
if let PatKind::Wild = arm.pat.kind { | ||
let ret_expr = strip_return(arm.body); | ||
if !eq_expr_value(cx, ex, ret_expr) { | ||
return; | ||
} | ||
} else if !pat_same_as_expr(arm.pat, arm.body) { | ||
return; | ||
} | ||
} | ||
|
||
if let Some(match_expr) = get_parent_expr(cx, ex) { | ||
let mut applicability = Applicability::MachineApplicable; | ||
span_lint_and_sugg( | ||
cx, | ||
NOP_MATCH, | ||
match_expr.span, | ||
"this match expression is unnecessary", | ||
"replace it with", | ||
snippet_with_applicability(cx, ex.span, "..", &mut applicability).to_string(), | ||
applicability, | ||
); | ||
} | ||
} | ||
|
||
/// Check for nop `if let` expression that assembled as unnecessary match | ||
/// | ||
/// ```rust,ignore | ||
/// if let Some(a) = option { | ||
/// Some(a) | ||
/// } else { | ||
/// None | ||
/// } | ||
/// ``` | ||
/// OR | ||
/// ```rust,ignore | ||
/// if let SomeEnum::A = some_enum { | ||
/// SomeEnum::A | ||
/// } else if let SomeEnum::B = some_enum { | ||
/// SomeEnum::B | ||
/// } else { | ||
/// some_enum | ||
/// } | ||
/// ``` | ||
pub(crate) fn check(cx: &LateContext<'_>, ex: &Expr<'_>) { | ||
if_chain! { | ||
if let Some(ref if_let) = higher::IfLet::hir(cx, ex); | ||
if !is_else_clause(cx.tcx, ex); | ||
if check_if_let(cx, if_let); | ||
then { | ||
let mut applicability = Applicability::MachineApplicable; | ||
span_lint_and_sugg( | ||
cx, | ||
NOP_MATCH, | ||
ex.span, | ||
"this if-let expression is unnecessary", | ||
"replace it with", | ||
snippet_with_applicability(cx, if_let.let_expr.span, "..", &mut applicability).to_string(), | ||
applicability, | ||
); | ||
} | ||
} | ||
} | ||
|
||
fn check_if_let(cx: &LateContext<'_>, if_let: &higher::IfLet<'_>) -> bool { | ||
if let Some(if_else) = if_let.if_else { | ||
if !pat_same_as_expr(if_let.let_pat, peel_blocks_with_stmt(if_let.if_then)) { | ||
return false; | ||
} | ||
|
||
// Recurrsively check for each `else if let` phrase, | ||
if let Some(ref nested_if_let) = higher::IfLet::hir(cx, if_else) { | ||
return check_if_let(cx, nested_if_let); | ||
} | ||
|
||
if matches!(if_else.kind, ExprKind::Block(..)) { | ||
let else_expr = peel_blocks_with_stmt(if_else); | ||
let ret = strip_return(else_expr); | ||
let let_expr_ty = cx.typeck_results().expr_ty(if_let.let_expr); | ||
if is_type_diagnostic_item(cx, let_expr_ty, sym::Option) { | ||
if let ExprKind::Path(ref qpath) = ret.kind { | ||
return is_lang_ctor(cx, qpath, OptionNone) || eq_expr_value(cx, if_let.let_expr, ret); | ||
} | ||
} else { | ||
return eq_expr_value(cx, if_let.let_expr, ret); | ||
} | ||
return true; | ||
} | ||
} | ||
false | ||
} | ||
|
||
fn strip_return<'hir>(expr: &'hir Expr<'hir>) -> &'hir Expr<'hir> { | ||
if let ExprKind::Ret(Some(ret)) = expr.kind { | ||
ret | ||
} else { | ||
expr | ||
} | ||
} | ||
|
||
fn pat_same_as_expr(pat: &Pat<'_>, expr: &Expr<'_>) -> bool { | ||
let expr = strip_return(expr); | ||
match (&pat.kind, &expr.kind) { | ||
( | ||
PatKind::TupleStruct(QPath::Resolved(_, path), [first_pat, ..], _), | ||
ExprKind::Call(call_expr, [first_param, ..]), | ||
) => { | ||
if let ExprKind::Path(QPath::Resolved(_, call_path)) = call_expr.kind { | ||
if has_identical_segments(path.segments, call_path.segments) | ||
&& has_same_non_ref_symbol(first_pat, first_param) | ||
{ | ||
return true; | ||
} | ||
} | ||
}, | ||
(PatKind::Path(QPath::Resolved(_, p_path)), ExprKind::Path(QPath::Resolved(_, e_path))) => { | ||
return has_identical_segments(p_path.segments, e_path.segments); | ||
}, | ||
(PatKind::Lit(pat_lit_expr), ExprKind::Lit(expr_spanned)) => { | ||
if let ExprKind::Lit(pat_spanned) = &pat_lit_expr.kind { | ||
return pat_spanned.node == expr_spanned.node; | ||
} | ||
}, | ||
_ => {}, | ||
} | ||
|
||
false | ||
} | ||
|
||
fn has_identical_segments(left_segs: &[PathSegment<'_>], right_segs: &[PathSegment<'_>]) -> bool { | ||
if left_segs.len() != right_segs.len() { | ||
return false; | ||
} | ||
for i in 0..left_segs.len() { | ||
if left_segs[i].ident.name != right_segs[i].ident.name { | ||
return false; | ||
} | ||
} | ||
true | ||
} | ||
|
||
fn has_same_non_ref_symbol(pat: &Pat<'_>, expr: &Expr<'_>) -> bool { | ||
if_chain! { | ||
if let PatKind::Binding(annot, _, pat_ident, _) = pat.kind; | ||
if !matches!(annot, BindingAnnotation::Ref | BindingAnnotation::RefMut); | ||
if let ExprKind::Path(QPath::Resolved(_, Path {segments: [first_seg, ..], .. })) = expr.kind; | ||
then { | ||
return pat_ident.name == first_seg.ident.name; | ||
} | ||
} | ||
|
||
false | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
// run-rustfix | ||
#![warn(clippy::nop_match)] | ||
#![allow(clippy::manual_map)] | ||
#![allow(dead_code)] | ||
|
||
#[derive(Clone, Copy)] | ||
enum Choice { | ||
A, | ||
B, | ||
C, | ||
D, | ||
} | ||
|
||
fn useless_match(x: i32) { | ||
let _: i32 = x; | ||
} | ||
|
||
fn custom_type_match(se: Choice) { | ||
let _: Choice = se; | ||
// Don't trigger | ||
let _: Choice = match se { | ||
Choice::A => Choice::A, | ||
Choice::B => Choice::B, | ||
_ => Choice::C, | ||
}; | ||
// Mingled, don't trigger | ||
let _: Choice = match se { | ||
Choice::A => Choice::B, | ||
Choice::B => Choice::C, | ||
Choice::C => Choice::D, | ||
Choice::D => Choice::A, | ||
}; | ||
} | ||
|
||
fn option_match(x: Option<i32>) { | ||
let _: Option<i32> = x; | ||
// Don't trigger, this is the case for manual_map_option | ||
let _: Option<i32> = match x { | ||
Some(a) => Some(-a), | ||
None => None, | ||
}; | ||
} | ||
|
||
fn func_ret_err<T>(err: T) -> Result<i32, T> { | ||
Err(err) | ||
} | ||
|
||
fn result_match() { | ||
let _: Result<i32, i32> = Ok(1); | ||
let _: Result<i32, i32> = func_ret_err(0_i32); | ||
} | ||
|
||
fn if_let_option() -> Option<i32> { | ||
Some(1) | ||
} | ||
|
||
fn if_let_result(x: Result<(), i32>) { | ||
let _: Result<(), i32> = x; | ||
let _: Result<(), i32> = x; | ||
// Input type mismatch, don't trigger | ||
let _: Result<(), i32> = if let Err(e) = Ok(1) { Err(e) } else { x }; | ||
} | ||
|
||
fn if_let_custom_enum(x: Choice) { | ||
let _: Choice = x; | ||
// Don't trigger | ||
let _: Choice = if let Choice::A = x { | ||
Choice::A | ||
} else if true { | ||
Choice::B | ||
} else { | ||
x | ||
}; | ||
} | ||
|
||
fn main() {} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
NOP is uncommon vocabulary. I'd suggest naming it
needless_match
ormatch_identity
(as we already have the quite similarmap_identity
).