Auto merge of #13324 - WeiTheShinobi:single_match, r=dswij
[`single_match`, `single_match_else`] fix suggestion when match irrefutable fixes #13012 changelog:[`single_match`, `single_match_else`]: fix suggestion when `match` irrefutable
This commit is contained in:
commit
bcf528bdef
7 changed files with 184 additions and 4 deletions
|
|
@ -1,5 +1,5 @@
|
|||
use clippy_utils::diagnostics::span_lint_and_sugg;
|
||||
use clippy_utils::source::{expr_block, snippet, SpanRangeExt};
|
||||
use clippy_utils::source::{expr_block, snippet, snippet_block_with_context, SpanRangeExt};
|
||||
use clippy_utils::ty::implements_trait;
|
||||
use clippy_utils::{
|
||||
is_lint_allowed, is_unit_expr, peel_blocks, peel_hir_pat_refs, peel_middle_ty_refs, peel_n_hir_expr_refs,
|
||||
|
|
@ -9,7 +9,7 @@ use rustc_arena::DroplessArena;
|
|||
use rustc_errors::Applicability;
|
||||
use rustc_hir::def::{DefKind, Res};
|
||||
use rustc_hir::intravisit::{walk_pat, Visitor};
|
||||
use rustc_hir::{Arm, Expr, ExprKind, HirId, Pat, PatKind, QPath};
|
||||
use rustc_hir::{Arm, Expr, ExprKind, HirId, Node, Pat, PatKind, QPath, StmtKind};
|
||||
use rustc_lint::LateContext;
|
||||
use rustc_middle::ty::{self, AdtDef, ParamEnv, TyCtxt, TypeckResults, VariantDef};
|
||||
use rustc_span::{sym, Span};
|
||||
|
|
@ -91,6 +91,29 @@ fn report_single_pattern(cx: &LateContext<'_>, ex: &Expr<'_>, arm: &Arm<'_>, exp
|
|||
format!(" else {}", expr_block(cx, els, ctxt, "..", Some(expr.span), &mut app))
|
||||
});
|
||||
|
||||
if snippet(cx, ex.span, "..") == snippet(cx, arm.pat.span, "..") {
|
||||
let msg = "this pattern is irrefutable, `match` is useless";
|
||||
let (sugg, help) = if is_unit_expr(arm.body) {
|
||||
(String::new(), "`match` expression can be removed")
|
||||
} else {
|
||||
let mut sugg = snippet_block_with_context(cx, arm.body.span, ctxt, "..", Some(expr.span), &mut app)
|
||||
.0
|
||||
.to_string();
|
||||
if let Node::Stmt(stmt) = cx.tcx.parent_hir_node(expr.hir_id)
|
||||
&& let StmtKind::Expr(_) = stmt.kind
|
||||
&& match arm.body.kind {
|
||||
ExprKind::Block(block, _) => block.span.from_expansion(),
|
||||
_ => true,
|
||||
}
|
||||
{
|
||||
sugg.push(';');
|
||||
}
|
||||
(sugg, "try")
|
||||
};
|
||||
span_lint_and_sugg(cx, lint, expr.span, msg, help, sugg.to_string(), app);
|
||||
return;
|
||||
}
|
||||
|
||||
let (pat, pat_ref_count) = peel_hir_pat_refs(arm.pat);
|
||||
let (msg, sugg) = if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind
|
||||
&& let (ty, ty_ref_count) = peel_middle_ty_refs(cx.typeck_results().expr_ty(ex))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue