Skip to content

Commit d3905af

Browse files
committed
Auto merge of #7806 - Serial-ATA:lint-match-case-mismatch, r=llogiq
Add match_str_case_mismatch lint changelog: Added a new lint [`match_str_case_mismatch`] Fixes #7440
2 parents 5c97b27 + 0c99de0 commit d3905af

8 files changed

+311
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2837,6 +2837,7 @@ Released 2018-09-13
28372837
[`match_result_ok`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_result_ok
28382838
[`match_same_arms`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_same_arms
28392839
[`match_single_binding`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_single_binding
2840+
[`match_str_case_mismatch`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_str_case_mismatch
28402841
[`match_wild_err_arm`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_wild_err_arm
28412842
[`match_wildcard_for_single_variants`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_wildcard_for_single_variants
28422843
[`maybe_infinite_iter`]: https://rust-lang.github.io/rust-clippy/master/index.html#maybe_infinite_iter

clippy_lints/src/lib.register_all.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
118118
LintId::of(map_unit_fn::OPTION_MAP_UNIT_FN),
119119
LintId::of(map_unit_fn::RESULT_MAP_UNIT_FN),
120120
LintId::of(match_result_ok::MATCH_RESULT_OK),
121+
LintId::of(match_str_case_mismatch::MATCH_STR_CASE_MISMATCH),
121122
LintId::of(matches::INFALLIBLE_DESTRUCTURING_MATCH),
122123
LintId::of(matches::MATCH_AS_REF),
123124
LintId::of(matches::MATCH_LIKE_MATCHES_MACRO),

clippy_lints/src/lib.register_correctness.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ store.register_group(true, "clippy::correctness", Some("clippy_correctness"), ve
3636
LintId::of(loops::ITER_NEXT_LOOP),
3737
LintId::of(loops::NEVER_LOOP),
3838
LintId::of(loops::WHILE_IMMUTABLE_CONDITION),
39+
LintId::of(match_str_case_mismatch::MATCH_STR_CASE_MISMATCH),
3940
LintId::of(mem_discriminant::MEM_DISCRIMINANT_NON_ENUM),
4041
LintId::of(mem_replace::MEM_REPLACE_WITH_UNINIT),
4142
LintId::of(methods::CLONE_DOUBLE_REF),

clippy_lints/src/lib.register_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,7 @@ store.register_lints(&[
226226
map_unit_fn::RESULT_MAP_UNIT_FN,
227227
match_on_vec_items::MATCH_ON_VEC_ITEMS,
228228
match_result_ok::MATCH_RESULT_OK,
229+
match_str_case_mismatch::MATCH_STR_CASE_MISMATCH,
229230
matches::INFALLIBLE_DESTRUCTURING_MATCH,
230231
matches::MATCH_AS_REF,
231232
matches::MATCH_BOOL,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@ mod map_err_ignore;
265265
mod map_unit_fn;
266266
mod match_on_vec_items;
267267
mod match_result_ok;
268+
mod match_str_case_mismatch;
268269
mod matches;
269270
mod mem_discriminant;
270271
mod mem_forget;
@@ -771,6 +772,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
771772
let enable_raw_pointer_heuristic_for_send = conf.enable_raw_pointer_heuristic_for_send;
772773
store.register_late_pass(move || Box::new(non_send_fields_in_send_ty::NonSendFieldInSendTy::new(enable_raw_pointer_heuristic_for_send)));
773774
store.register_late_pass(move || Box::new(undocumented_unsafe_blocks::UndocumentedUnsafeBlocks::default()));
775+
store.register_late_pass(|| Box::new(match_str_case_mismatch::MatchStrCaseMismatch));
774776
}
775777

776778
#[rustfmt::skip]
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::ty::is_type_diagnostic_item;
3+
use rustc_ast::ast::LitKind;
4+
use rustc_errors::Applicability;
5+
use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
6+
use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind};
7+
use rustc_lint::{LateContext, LateLintPass};
8+
use rustc_middle::hir::map::Map;
9+
use rustc_middle::lint::in_external_macro;
10+
use rustc_middle::ty;
11+
use rustc_session::{declare_lint_pass, declare_tool_lint};
12+
use rustc_span::symbol::SymbolStr;
13+
use rustc_span::{sym, Span};
14+
15+
declare_clippy_lint! {
16+
/// ### What it does
17+
/// Checks for `match` expressions modifying the case of a string with non-compliant arms
18+
///
19+
/// ### Why is this bad?
20+
/// The arm is unreachable, which is likely a mistake
21+
///
22+
/// ### Example
23+
/// ```rust
24+
/// # let text = "Foo";
25+
///
26+
/// match &*text.to_ascii_lowercase() {
27+
/// "foo" => {},
28+
/// "Bar" => {},
29+
/// _ => {},
30+
/// }
31+
/// ```
32+
/// Use instead:
33+
/// ```rust
34+
/// # let text = "Foo";
35+
///
36+
/// match &*text.to_ascii_lowercase() {
37+
/// "foo" => {},
38+
/// "bar" => {},
39+
/// _ => {},
40+
/// }
41+
/// ```
42+
pub MATCH_STR_CASE_MISMATCH,
43+
correctness,
44+
"creation of a case altering match expression with non-compliant arms"
45+
}
46+
47+
declare_lint_pass!(MatchStrCaseMismatch => [MATCH_STR_CASE_MISMATCH]);
48+
49+
#[derive(Debug)]
50+
enum CaseMethod {
51+
LowerCase,
52+
AsciiLowerCase,
53+
UpperCase,
54+
AsciiUppercase,
55+
}
56+
57+
impl LateLintPass<'_> for MatchStrCaseMismatch {
58+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
59+
if_chain! {
60+
if !in_external_macro(cx.tcx.sess, expr.span);
61+
if let ExprKind::Match(match_expr, arms, MatchSource::Normal) = expr.kind;
62+
if let ty::Ref(_, ty, _) = cx.typeck_results().expr_ty(match_expr).kind();
63+
if let ty::Str = ty.kind();
64+
then {
65+
let mut visitor = MatchExprVisitor {
66+
cx,
67+
case_method: None,
68+
};
69+
70+
visitor.visit_expr(match_expr);
71+
72+
if let Some(case_method) = visitor.case_method {
73+
if let Some((bad_case_span, bad_case_str)) = verify_case(&case_method, arms) {
74+
lint(cx, &case_method, bad_case_span, &bad_case_str);
75+
}
76+
}
77+
}
78+
}
79+
}
80+
}
81+
82+
struct MatchExprVisitor<'a, 'tcx> {
83+
cx: &'a LateContext<'tcx>,
84+
case_method: Option<CaseMethod>,
85+
}
86+
87+
impl<'a, 'tcx> Visitor<'tcx> for MatchExprVisitor<'a, 'tcx> {
88+
type Map = Map<'tcx>;
89+
90+
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
91+
NestedVisitorMap::None
92+
}
93+
94+
fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
95+
match ex.kind {
96+
ExprKind::MethodCall(segment, _, [receiver], _)
97+
if self.case_altered(&*segment.ident.as_str(), receiver) => {},
98+
_ => walk_expr(self, ex),
99+
}
100+
}
101+
}
102+
103+
impl<'a, 'tcx> MatchExprVisitor<'a, 'tcx> {
104+
fn case_altered(&mut self, segment_ident: &str, receiver: &Expr<'_>) -> bool {
105+
if let Some(case_method) = get_case_method(segment_ident) {
106+
let ty = self.cx.typeck_results().expr_ty(receiver).peel_refs();
107+
108+
if is_type_diagnostic_item(self.cx, ty, sym::String) || ty.kind() == &ty::Str {
109+
self.case_method = Some(case_method);
110+
return true;
111+
}
112+
}
113+
114+
false
115+
}
116+
}
117+
118+
fn get_case_method(segment_ident_str: &str) -> Option<CaseMethod> {
119+
match segment_ident_str {
120+
"to_lowercase" => Some(CaseMethod::LowerCase),
121+
"to_ascii_lowercase" => Some(CaseMethod::AsciiLowerCase),
122+
"to_uppercase" => Some(CaseMethod::UpperCase),
123+
"to_ascii_uppercase" => Some(CaseMethod::AsciiUppercase),
124+
_ => None,
125+
}
126+
}
127+
128+
fn verify_case<'a>(case_method: &'a CaseMethod, arms: &'a [Arm<'_>]) -> Option<(Span, SymbolStr)> {
129+
let case_check = match case_method {
130+
CaseMethod::LowerCase => |input: &str| -> bool { input.chars().all(char::is_lowercase) },
131+
CaseMethod::AsciiLowerCase => |input: &str| -> bool { input.chars().all(|c| matches!(c, 'a'..='z')) },
132+
CaseMethod::UpperCase => |input: &str| -> bool { input.chars().all(char::is_uppercase) },
133+
CaseMethod::AsciiUppercase => |input: &str| -> bool { input.chars().all(|c| matches!(c, 'A'..='Z')) },
134+
};
135+
136+
for arm in arms {
137+
if_chain! {
138+
if let PatKind::Lit(Expr {
139+
kind: ExprKind::Lit(lit),
140+
..
141+
}) = arm.pat.kind;
142+
if let LitKind::Str(symbol, _) = lit.node;
143+
let input = symbol.as_str();
144+
if !case_check(&input);
145+
then {
146+
return Some((lit.span, input));
147+
}
148+
}
149+
}
150+
151+
None
152+
}
153+
154+
fn lint(cx: &LateContext<'_>, case_method: &CaseMethod, bad_case_span: Span, bad_case_str: &str) {
155+
let (method_str, suggestion) = match case_method {
156+
CaseMethod::LowerCase => ("to_lower_case", bad_case_str.to_lowercase()),
157+
CaseMethod::AsciiLowerCase => ("to_ascii_lowercase", bad_case_str.to_ascii_lowercase()),
158+
CaseMethod::UpperCase => ("to_uppercase", bad_case_str.to_uppercase()),
159+
CaseMethod::AsciiUppercase => ("to_ascii_uppercase", bad_case_str.to_ascii_uppercase()),
160+
};
161+
162+
span_lint_and_sugg(
163+
cx,
164+
MATCH_STR_CASE_MISMATCH,
165+
bad_case_span,
166+
"this `match` arm has a differing case than its expression",
167+
&*format!("consider changing the case of this arm to respect `{}`", method_str),
168+
format!("\"{}\"", suggestion),
169+
Applicability::MachineApplicable,
170+
);
171+
}

tests/ui/match_str_case_mismatch.rs

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#![warn(clippy::match_str_case_mismatch)]
2+
3+
// Valid
4+
5+
fn as_str_match() {
6+
let var = "BAR";
7+
8+
match var.to_ascii_lowercase().as_str() {
9+
"foo" => {},
10+
"bar" => {},
11+
_ => {},
12+
}
13+
}
14+
15+
fn addrof_unary_match() {
16+
let var = "BAR";
17+
18+
match &*var.to_ascii_lowercase() {
19+
"foo" => {},
20+
"bar" => {},
21+
_ => {},
22+
}
23+
}
24+
25+
fn alternating_chain() {
26+
let var = "BAR";
27+
28+
match &*var
29+
.to_ascii_lowercase()
30+
.to_uppercase()
31+
.to_lowercase()
32+
.to_ascii_uppercase()
33+
{
34+
"FOO" => {},
35+
"BAR" => {},
36+
_ => {},
37+
}
38+
}
39+
40+
fn unrelated_method() {
41+
struct Item {
42+
a: String,
43+
}
44+
45+
impl Item {
46+
#[allow(clippy::wrong_self_convention)]
47+
fn to_lowercase(self) -> String {
48+
self.a
49+
}
50+
}
51+
52+
let item = Item { a: String::from("BAR") };
53+
54+
match &*item.to_lowercase() {
55+
"FOO" => {},
56+
"BAR" => {},
57+
_ => {},
58+
}
59+
}
60+
61+
// Invalid
62+
63+
fn as_str_match_mismatch() {
64+
let var = "BAR";
65+
66+
match var.to_ascii_lowercase().as_str() {
67+
"foo" => {},
68+
"Bar" => {},
69+
_ => {},
70+
}
71+
}
72+
73+
fn addrof_unary_match_mismatch() {
74+
let var = "BAR";
75+
76+
match &*var.to_ascii_lowercase() {
77+
"foo" => {},
78+
"Bar" => {},
79+
_ => {},
80+
}
81+
}
82+
83+
fn alternating_chain_mismatch() {
84+
let var = "BAR";
85+
86+
match &*var
87+
.to_ascii_lowercase()
88+
.to_uppercase()
89+
.to_lowercase()
90+
.to_ascii_uppercase()
91+
{
92+
"FOO" => {},
93+
"bAR" => {},
94+
_ => {},
95+
}
96+
}
97+
98+
fn main() {}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
error: this `match` arm has a differing case than its expression
2+
--> $DIR/match_str_case_mismatch.rs:68:9
3+
|
4+
LL | "Bar" => {},
5+
| ^^^^^
6+
|
7+
= note: `-D clippy::match-str-case-mismatch` implied by `-D warnings`
8+
help: consider changing the case of this arm to respect `to_ascii_lowercase`
9+
|
10+
LL | "bar" => {},
11+
| ~~~~~
12+
13+
error: this `match` arm has a differing case than its expression
14+
--> $DIR/match_str_case_mismatch.rs:78:9
15+
|
16+
LL | "Bar" => {},
17+
| ^^^^^
18+
|
19+
help: consider changing the case of this arm to respect `to_ascii_lowercase`
20+
|
21+
LL | "bar" => {},
22+
| ~~~~~
23+
24+
error: this `match` arm has a differing case than its expression
25+
--> $DIR/match_str_case_mismatch.rs:93:9
26+
|
27+
LL | "bAR" => {},
28+
| ^^^^^
29+
|
30+
help: consider changing the case of this arm to respect `to_ascii_uppercase`
31+
|
32+
LL | "BAR" => {},
33+
| ~~~~~
34+
35+
error: aborting due to 3 previous errors
36+

0 commit comments

Comments
 (0)