Skip to content

Commit be09bb4

Browse files
committed
Auto merge of #5034 - ThibsG:MatchWildErrArmImprove5024, r=flip1995
Match wild err arm improvements This lint should trigger on other identifiers which have `_` prefix (such as `_e`) and only if they are unused in the panic block. _Note_: the `is_unused` function is greatly inspired from `pat_is_wild` function in [loops lints](https://github.com/rust-lang/rust-clippy/blob/43ac9416d935942d6c7d2b2e0c876c551652c4ec/clippy_lints/src/loops.rs#L1689). I've been considering doing some refactoring, maybe in utils. Maybe this PR or a new one. What do you think ? fixes #5024 changelog: none
2 parents d13b678 + 44fb8b5 commit be09bb4

File tree

6 files changed

+166
-88
lines changed

6 files changed

+166
-88
lines changed

clippy_lints/src/loops.rs

+15-45
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,35 @@
1+
use crate::consts::{constant, Constant};
12
use crate::reexport::*;
3+
use crate::utils::paths;
4+
use crate::utils::usage::{is_unused, mutated_variables};
5+
use crate::utils::{
6+
get_enclosing_block, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
7+
is_integer_const, is_refutable, last_path_segment, match_trait_method, match_type, match_var, multispan_sugg,
8+
snippet, snippet_opt, snippet_with_applicability, span_help_and_lint, span_lint, span_lint_and_sugg,
9+
span_lint_and_then, SpanlessEq,
10+
};
11+
use crate::utils::{is_type_diagnostic_item, qpath_res, same_tys, sext, sugg};
212
use if_chain::if_chain;
313
use itertools::Itertools;
14+
use rustc::hir::map::Map;
415
use rustc::lint::in_external_macro;
516
use rustc::middle::region;
17+
use rustc::ty::{self, Ty};
18+
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
19+
use rustc_errors::Applicability;
620
use rustc_hir::def::{DefKind, Res};
721
use rustc_hir::def_id;
822
use rustc_hir::intravisit::{walk_block, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
923
use rustc_hir::*;
1024
use rustc_lint::{LateContext, LateLintPass, LintContext};
1125
use rustc_session::{declare_lint_pass, declare_tool_lint};
12-
// use rustc::middle::region::CodeExtent;
13-
use crate::consts::{constant, Constant};
14-
use crate::utils::usage::mutated_variables;
15-
use crate::utils::{is_type_diagnostic_item, qpath_res, same_tys, sext, sugg};
16-
use rustc::hir::map::Map;
17-
use rustc::ty::{self, Ty};
18-
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
19-
use rustc_errors::Applicability;
2026
use rustc_span::source_map::Span;
2127
use rustc_span::{BytePos, Symbol};
2228
use rustc_typeck::expr_use_visitor::*;
2329
use std::iter::{once, Iterator};
2430
use std::mem;
2531
use syntax::ast;
2632

27-
use crate::utils::paths;
28-
use crate::utils::{
29-
get_enclosing_block, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
30-
is_integer_const, is_refutable, last_path_segment, match_trait_method, match_type, match_var, multispan_sugg,
31-
snippet, snippet_opt, snippet_with_applicability, span_help_and_lint, span_lint, span_lint_and_sugg,
32-
span_lint_and_then, SpanlessEq,
33-
};
34-
3533
declare_clippy_lint! {
3634
/// **What it does:** Checks for for-loops that manually copy items between
3735
/// slices that could be optimized by having a memcpy.
@@ -1689,39 +1687,11 @@ fn check_for_mutation(
16891687
fn pat_is_wild<'tcx>(pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool {
16901688
match *pat {
16911689
PatKind::Wild => true,
1692-
PatKind::Binding(.., ident, None) if ident.as_str().starts_with('_') => {
1693-
let mut visitor = UsedVisitor {
1694-
var: ident.name,
1695-
used: false,
1696-
};
1697-
walk_expr(&mut visitor, body);
1698-
!visitor.used
1699-
},
1690+
PatKind::Binding(.., ident, None) if ident.as_str().starts_with('_') => is_unused(&ident, body),
17001691
_ => false,
17011692
}
17021693
}
17031694

1704-
struct UsedVisitor {
1705-
var: ast::Name, // var to look for
1706-
used: bool, // has the var been used otherwise?
1707-
}
1708-
1709-
impl<'tcx> Visitor<'tcx> for UsedVisitor {
1710-
type Map = Map<'tcx>;
1711-
1712-
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1713-
if match_var(expr, self.var) {
1714-
self.used = true;
1715-
} else {
1716-
walk_expr(self, expr);
1717-
}
1718-
}
1719-
1720-
fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
1721-
NestedVisitorMap::None
1722-
}
1723-
}
1724-
17251695
struct LocalUsedVisitor<'a, 'tcx> {
17261696
cx: &'a LateContext<'a, 'tcx>,
17271697
local: HirId,

clippy_lints/src/matches.rs

+30-22
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
use crate::consts::{constant, miri_to_const, Constant};
22
use crate::utils::paths;
33
use crate::utils::sugg::Sugg;
4+
use crate::utils::usage::is_unused;
45
use crate::utils::{
5-
expr_block, is_allowed, is_expn_of, match_qpath, match_type, multispan_sugg, remove_blocks, snippet,
6+
expr_block, is_allowed, is_expn_of, is_wild, match_qpath, match_type, multispan_sugg, remove_blocks, snippet,
67
snippet_with_applicability, span_help_and_lint, span_lint_and_sugg, span_lint_and_then, span_note_and_lint,
78
walk_ptrs_ty,
89
};
@@ -461,33 +462,40 @@ fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr<'
461462
}
462463
}
463464

464-
fn is_wild<'tcx>(pat: &impl std::ops::Deref<Target = Pat<'tcx>>) -> bool {
465-
match pat.kind {
466-
PatKind::Wild => true,
467-
_ => false,
468-
}
469-
}
470-
471465
fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
472466
let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
473467
if match_type(cx, ex_ty, &paths::RESULT) {
474468
for arm in arms {
475469
if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
476470
let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
477-
if_chain! {
478-
if path_str == "Err";
479-
if inner.iter().any(is_wild);
480-
if let ExprKind::Block(ref block, _) = arm.body.kind;
481-
if is_panic_block(block);
482-
then {
483-
// `Err(_)` arm with `panic!` found
484-
span_note_and_lint(cx,
485-
MATCH_WILD_ERR_ARM,
486-
arm.pat.span,
487-
"`Err(_)` will match all errors, maybe not a good idea",
488-
arm.pat.span,
489-
"to remove this warning, match each error separately \
490-
or use `unreachable!` macro");
471+
if path_str == "Err" {
472+
let mut matching_wild = inner.iter().any(is_wild);
473+
let mut ident_bind_name = String::from("_");
474+
if !matching_wild {
475+
// Looking for unused bindings (i.e.: `_e`)
476+
inner.iter().for_each(|pat| {
477+
if let PatKind::Binding(.., ident, None) = &pat.kind {
478+
if ident.as_str().starts_with('_') && is_unused(ident, arm.body) {
479+
ident_bind_name = (&ident.name.as_str()).to_string();
480+
matching_wild = true;
481+
}
482+
}
483+
});
484+
}
485+
if_chain! {
486+
if matching_wild;
487+
if let ExprKind::Block(ref block, _) = arm.body.kind;
488+
if is_panic_block(block);
489+
then {
490+
// `Err(_)` or `Err(_e)` arm with `panic!` found
491+
span_note_and_lint(cx,
492+
MATCH_WILD_ERR_ARM,
493+
arm.pat.span,
494+
&format!("`Err({})` matches all errors", &ident_bind_name),
495+
arm.pat.span,
496+
"match each error separately or use the error output",
497+
);
498+
}
491499
}
492500
}
493501
}

clippy_lints/src/utils/mod.rs

+8
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,14 @@ pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
127127
true
128128
}
129129

130+
/// Checks if given pattern is a wildcard (`_`)
131+
pub fn is_wild<'tcx>(pat: &impl std::ops::Deref<Target = Pat<'tcx>>) -> bool {
132+
match pat.kind {
133+
PatKind::Wild => true,
134+
_ => false,
135+
}
136+
}
137+
130138
/// Checks if type is struct, enum or union type with the given def path.
131139
pub fn match_type(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
132140
match ty.kind {

clippy_lints/src/utils/usage.rs

+35
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
1+
use crate::utils::match_var;
2+
use rustc::hir::map::Map;
13
use rustc::ty;
24
use rustc_data_structures::fx::FxHashSet;
35
use rustc_hir::def::Res;
6+
use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
47
use rustc_hir::*;
58
use rustc_lint::LateContext;
9+
use rustc_span::symbol::Ident;
610
use rustc_typeck::expr_use_visitor::*;
11+
use syntax::ast;
712

813
/// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined.
914
pub fn mutated_variables<'a, 'tcx>(expr: &'tcx Expr<'_>, cx: &'a LateContext<'a, 'tcx>) -> Option<FxHashSet<HirId>> {
@@ -70,3 +75,33 @@ impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
7075
self.update(&cmt)
7176
}
7277
}
78+
79+
pub struct UsedVisitor {
80+
pub var: ast::Name, // var to look for
81+
pub used: bool, // has the var been used otherwise?
82+
}
83+
84+
impl<'tcx> Visitor<'tcx> for UsedVisitor {
85+
type Map = Map<'tcx>;
86+
87+
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
88+
if match_var(expr, self.var) {
89+
self.used = true;
90+
} else {
91+
walk_expr(self, expr);
92+
}
93+
}
94+
95+
fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
96+
NestedVisitorMap::None
97+
}
98+
}
99+
100+
pub fn is_unused<'tcx>(ident: &'tcx Ident, body: &'tcx Expr<'_>) -> bool {
101+
let mut visitor = UsedVisitor {
102+
var: ident.name,
103+
used: false,
104+
};
105+
walk_expr(&mut visitor, body);
106+
!visitor.used
107+
}

tests/ui/matches.rs

+13
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,19 @@ fn match_wild_err_arm() {
2828
},
2929
}
3030

31+
match x {
32+
Ok(3) => println!("ok"),
33+
Ok(_) => println!("ok"),
34+
Err(_e) => panic!(),
35+
}
36+
37+
// Allowed when used in `panic!`.
38+
match x {
39+
Ok(3) => println!("ok"),
40+
Ok(_) => println!("ok"),
41+
Err(_e) => panic!("{}", _e),
42+
}
43+
3144
// Allowed when not with `panic!` block.
3245
match x {
3346
Ok(3) => println!("ok"),

0 commit comments

Comments
 (0)