Skip to content

Commit 6c10620

Browse files
committed
Auto merge of #3729 - illicitonion:match_enum_wildcard, r=flip1995
wildcard_enum_match_arm gives suggestions And is also more robust
2 parents 2139fbd + 4009a44 commit 6c10620

File tree

3 files changed

+125
-15
lines changed

3 files changed

+125
-15
lines changed

clippy_lints/src/matches.rs

Lines changed: 85 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,15 @@ use crate::utils::{
66
snippet_with_applicability, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty,
77
};
88
use if_chain::if_chain;
9+
use rustc::hir::def::CtorKind;
910
use rustc::hir::*;
1011
use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
11-
use rustc::ty::{self, Ty};
12+
use rustc::ty::{self, Ty, TyKind};
1213
use rustc::{declare_tool_lint, lint_array};
1314
use rustc_errors::Applicability;
1415
use std::cmp::Ordering;
1516
use std::collections::Bound;
17+
use std::ops::Deref;
1618
use syntax::ast::LitKind;
1719
use syntax::source_map::Span;
1820

@@ -191,7 +193,8 @@ declare_clippy_lint! {
191193
///
192194
/// **Why is this bad?** New enum variants added by library updates can be missed.
193195
///
194-
/// **Known problems:** Nested wildcards a la `Foo(_)` are currently not detected.
196+
/// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
197+
/// variants, and also may not use correct path to enum if it's not present in the current scope.
195198
///
196199
/// **Example:**
197200
/// ```rust
@@ -464,19 +467,89 @@ fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
464467
}
465468

466469
fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
467-
if cx.tables.expr_ty(ex).is_enum() {
470+
let ty = cx.tables.expr_ty(ex);
471+
if !ty.is_enum() {
472+
// If there isn't a nice closed set of possible values that can be conveniently enumerated,
473+
// don't complain about not enumerating the mall.
474+
return;
475+
}
476+
477+
// First pass - check for violation, but don't do much book-keeping because this is hopefully
478+
// the uncommon case, and the book-keeping is slightly expensive.
479+
let mut wildcard_span = None;
480+
let mut wildcard_ident = None;
481+
for arm in arms {
482+
for pat in &arm.pats {
483+
if let PatKind::Wild = pat.node {
484+
wildcard_span = Some(pat.span);
485+
} else if let PatKind::Binding(_, _, _, ident, None) = pat.node {
486+
wildcard_span = Some(pat.span);
487+
wildcard_ident = Some(ident);
488+
}
489+
}
490+
}
491+
492+
if let Some(wildcard_span) = wildcard_span {
493+
// Accumulate the variants which should be put in place of the wildcard because they're not
494+
// already covered.
495+
496+
let mut missing_variants = vec![];
497+
if let TyKind::Adt(def, _) = ty.sty {
498+
for variant in &def.variants {
499+
missing_variants.push(variant);
500+
}
501+
}
502+
468503
for arm in arms {
469-
if is_wild(&arm.pats[0]) {
470-
span_note_and_lint(
471-
cx,
472-
WILDCARD_ENUM_MATCH_ARM,
473-
arm.pats[0].span,
474-
"wildcard match will miss any future added variants.",
475-
arm.pats[0].span,
476-
"to resolve, match each variant explicitly",
477-
);
504+
if arm.guard.is_some() {
505+
// Guards mean that this case probably isn't exhaustively covered. Technically
506+
// this is incorrect, as we should really check whether each variant is exhaustively
507+
// covered by the set of guards that cover it, but that's really hard to do.
508+
continue;
478509
}
510+
for pat in &arm.pats {
511+
if let PatKind::Path(ref path) = pat.deref().node {
512+
if let QPath::Resolved(_, p) = path {
513+
missing_variants.retain(|e| e.did != p.def.def_id());
514+
}
515+
} else if let PatKind::TupleStruct(ref path, ..) = pat.deref().node {
516+
if let QPath::Resolved(_, p) = path {
517+
missing_variants.retain(|e| e.did != p.def.def_id());
518+
}
519+
}
520+
}
521+
}
522+
523+
let suggestion: Vec<String> = missing_variants
524+
.iter()
525+
.map(|v| {
526+
let suffix = match v.ctor_kind {
527+
CtorKind::Fn => "(..)",
528+
CtorKind::Const | CtorKind::Fictive => "",
529+
};
530+
let ident_str = if let Some(ident) = wildcard_ident {
531+
format!("{} @ ", ident.name)
532+
} else {
533+
String::new()
534+
};
535+
// This path assumes that the enum type is imported into scope.
536+
format!("{}{}{}", ident_str, cx.tcx.item_path_str(v.did), suffix)
537+
})
538+
.collect();
539+
540+
if suggestion.is_empty() {
541+
return;
479542
}
543+
544+
span_lint_and_sugg(
545+
cx,
546+
WILDCARD_ENUM_MATCH_ARM,
547+
wildcard_span,
548+
"wildcard match will miss any future added variants.",
549+
"try this",
550+
suggestion.join(" | "),
551+
Applicability::MachineApplicable,
552+
)
480553
}
481554
}
482555

tests/ui/wildcard_enum_match_arm.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,14 @@ fn main() {
2525
Color::Red => println!("Red"),
2626
_ => eprintln!("Not red"),
2727
};
28+
match color {
29+
Color::Red => println!("Red"),
30+
_not_red => eprintln!("Not red"),
31+
};
32+
let _str = match color {
33+
Color::Red => "Red".to_owned(),
34+
not_red => format!("{:?}", not_red),
35+
};
2836
match color {
2937
Color::Red => {},
3038
Color::Green => {},
@@ -33,6 +41,18 @@ fn main() {
3341
c if c.is_monochrome() => {},
3442
Color::Rgb(_, _, _) => {},
3543
};
44+
let _str = match color {
45+
Color::Red => "Red",
46+
c @ Color::Green | c @ Color::Blue | c @ Color::Rgb(_, _, _) | c @ Color::Cyan => "Not red",
47+
};
48+
match color {
49+
Color::Rgb(r, _, _) if r > 0 => "Some red",
50+
_ => "No red",
51+
};
52+
match color {
53+
Color::Red | Color::Green | Color::Blue | Color::Cyan => {},
54+
Color::Rgb(..) => {},
55+
};
3656
let x: u8 = unimplemented!();
3757
match x {
3858
0 => {},

tests/ui/wildcard_enum_match_arm.stderr

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,31 @@ error: wildcard match will miss any future added variants.
22
--> $DIR/wildcard_enum_match_arm.rs:26:9
33
|
44
LL | _ => eprintln!("Not red"),
5-
| ^
5+
| ^ help: try this: `Color::Green | Color::Blue | Color::Rgb(..) | Color::Cyan`
66
|
77
note: lint level defined here
88
--> $DIR/wildcard_enum_match_arm.rs:1:9
99
|
1010
LL | #![deny(clippy::wildcard_enum_match_arm)]
1111
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12-
= note: to resolve, match each variant explicitly
1312

14-
error: aborting due to previous error
13+
error: wildcard match will miss any future added variants.
14+
--> $DIR/wildcard_enum_match_arm.rs:30:9
15+
|
16+
LL | _not_red => eprintln!("Not red"),
17+
| ^^^^^^^^ help: try this: `_not_red @ Color::Green | _not_red @ Color::Blue | _not_red @ Color::Rgb(..) | _not_red @ Color::Cyan`
18+
19+
error: wildcard match will miss any future added variants.
20+
--> $DIR/wildcard_enum_match_arm.rs:34:9
21+
|
22+
LL | not_red => format!("{:?}", not_red),
23+
| ^^^^^^^ help: try this: `not_red @ Color::Green | not_red @ Color::Blue | not_red @ Color::Rgb(..) | not_red @ Color::Cyan`
24+
25+
error: wildcard match will miss any future added variants.
26+
--> $DIR/wildcard_enum_match_arm.rs:50:9
27+
|
28+
LL | _ => "No red",
29+
| ^ help: try this: `Color::Red | Color::Green | Color::Blue | Color::Rgb(..) | Color::Cyan`
30+
31+
error: aborting due to 4 previous errors
1532

0 commit comments

Comments
 (0)