Skip to content

Commit f309dc3

Browse files
committed
Add the MATCH_SAME_ARMS lint
1 parent cbbc667 commit f309dc3

File tree

4 files changed

+162
-39
lines changed

4 files changed

+162
-39
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ A collection of lints to catch common mistakes and improve your Rust code.
66
[Jump to usage instructions](#usage)
77

88
##Lints
9-
There are 119 lints included in this crate:
9+
There are 120 lints included in this crate:
1010

1111
name | default | meaning
1212
---------------------------------------------------------------------------------------------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -65,6 +65,7 @@ name
6565
[match_bool](https://github.com/Manishearth/rust-clippy/wiki#match_bool) | warn | a match on boolean expression; recommends `if..else` block instead
6666
[match_overlapping_arm](https://github.com/Manishearth/rust-clippy/wiki#match_overlapping_arm) | warn | a match has overlapping arms
6767
[match_ref_pats](https://github.com/Manishearth/rust-clippy/wiki#match_ref_pats) | warn | a match or `if let` has all arms prefixed with `&`; the match expression can be dereferenced instead
68+
[match_same_arms](https://github.com/Manishearth/rust-clippy/wiki#match_same_arms) | warn | `match` with identical arm bodies
6869
[min_max](https://github.com/Manishearth/rust-clippy/wiki#min_max) | warn | `min(_, max(_, _))` (or vice versa) with bounds clamping the result to a constant
6970
[modulo_one](https://github.com/Manishearth/rust-clippy/wiki#modulo_one) | warn | taking a number modulo 1, which always returns 0
7071
[mut_mut](https://github.com/Manishearth/rust-clippy/wiki#mut_mut) | allow | usage of double-mut refs, e.g. `&mut &mut ...` (either copy'n'paste error, or shows a fundamental misunderstanding of references)

src/copies.rs

Lines changed: 110 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
use rustc::lint::*;
2+
use rustc::middle::ty;
23
use rustc_front::hir::*;
34
use std::collections::HashMap;
45
use std::collections::hash_map::Entry;
6+
use syntax::parse::token::InternedString;
57
use utils::{SpanlessEq, SpanlessHash};
68
use utils::{get_parent_expr, in_macro, span_note_and_lint};
79

@@ -33,14 +35,34 @@ declare_lint! {
3335
"if with the same *then* and *else* blocks"
3436
}
3537

38+
/// **What it does:** This lint checks for `match` with identical arm bodies.
39+
///
40+
/// **Why is this bad?** This is probably a copy & paste error.
41+
///
42+
/// **Known problems:** Hopefully none.
43+
///
44+
/// **Example:**
45+
/// ```rust,ignore
46+
/// match foo {
47+
/// Bar => bar(),
48+
/// Quz => quz(),
49+
/// Baz => bar(), // <= oups
50+
/// ```
51+
declare_lint! {
52+
pub MATCH_SAME_ARMS,
53+
Warn,
54+
"`match` with identical arm bodies"
55+
}
56+
3657
#[derive(Copy, Clone, Debug)]
3758
pub struct CopyAndPaste;
3859

3960
impl LintPass for CopyAndPaste {
4061
fn get_lints(&self) -> LintArray {
4162
lint_array![
4263
IFS_SAME_COND,
43-
IF_SAME_THEN_ELSE
64+
IF_SAME_THEN_ELSE,
65+
MATCH_SAME_ARMS
4466
]
4567
}
4668
}
@@ -58,39 +80,63 @@ impl LateLintPass for CopyAndPaste {
5880
let (conds, blocks) = if_sequence(expr);
5981
lint_same_then_else(cx, &blocks);
6082
lint_same_cond(cx, &conds);
83+
lint_match_arms(cx, expr);
6184
}
6285
}
6386
}
6487

6588
/// Implementation of `IF_SAME_THEN_ELSE`.
6689
fn lint_same_then_else(cx: &LateContext, blocks: &[&Block]) {
67-
let hash = |block| -> u64 {
90+
let hash : &Fn(&&Block) -> u64 = &|block| -> u64 {
6891
let mut h = SpanlessHash::new(cx);
6992
h.hash_block(block);
7093
h.finish()
7194
};
72-
let eq = |lhs, rhs| -> bool {
95+
96+
let eq : &Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool {
7397
SpanlessEq::new(cx).eq_block(lhs, rhs)
7498
};
7599

76100
if let Some((i, j)) = search_same(blocks, hash, eq) {
77-
span_note_and_lint(cx, IF_SAME_THEN_ELSE, j.span, "this if has identical blocks", i.span, "same as this");
101+
span_note_and_lint(cx, IF_SAME_THEN_ELSE, j.span, "this `if` has identical blocks", i.span, "same as this");
78102
}
79103
}
80104

81105
/// Implementation of `IFS_SAME_COND`.
82106
fn lint_same_cond(cx: &LateContext, conds: &[&Expr]) {
83-
let hash = |expr| -> u64 {
107+
let hash : &Fn(&&Expr) -> u64 = &|expr| -> u64 {
84108
let mut h = SpanlessHash::new(cx);
85109
h.hash_expr(expr);
86110
h.finish()
87111
};
88-
let eq = |lhs, rhs| -> bool {
112+
113+
let eq : &Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool {
89114
SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs)
90115
};
91116

92117
if let Some((i, j)) = search_same(conds, hash, eq) {
93-
span_note_and_lint(cx, IFS_SAME_COND, j.span, "this if has the same condition as a previous if", i.span, "same as this");
118+
span_note_and_lint(cx, IFS_SAME_COND, j.span, "this `if` has the same condition as a previous if", i.span, "same as this");
119+
}
120+
}
121+
122+
/// Implementation if `MATCH_SAME_ARMS`.
123+
fn lint_match_arms(cx: &LateContext, expr: &Expr) {
124+
let hash = |arm: &Arm| -> u64 {
125+
let mut h = SpanlessHash::new(cx);
126+
h.hash_expr(&arm.body);
127+
h.finish()
128+
};
129+
130+
let eq = |lhs: &Arm, rhs: &Arm| -> bool {
131+
SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
132+
// all patterns should have the same bindings
133+
bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
134+
};
135+
136+
if let ExprMatch(_, ref arms, MatchSource::Normal) = expr.node {
137+
if let Some((i, j)) = search_same(&**arms, hash, eq) {
138+
span_note_and_lint(cx, MATCH_SAME_ARMS, j.body.span, "this `match` has identical arm bodies", i.body.span, "same as this");
139+
}
94140
}
95141
}
96142

@@ -123,11 +169,59 @@ fn if_sequence(mut expr: &Expr) -> (Vec<&Expr>, Vec<&Block>) {
123169
(conds, blocks)
124170
}
125171

126-
fn search_same<'a, T, Hash, Eq>(exprs: &[&'a T],
127-
hash: Hash,
128-
eq: Eq) -> Option<(&'a T, &'a T)>
129-
where Hash: Fn(&'a T) -> u64,
130-
Eq: Fn(&'a T, &'a T) -> bool {
172+
/// Return the list of bindings in a pattern.
173+
fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<InternedString, ty::Ty<'tcx>> {
174+
fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<InternedString, ty::Ty<'tcx>>) {
175+
match pat.node {
176+
PatBox(ref pat) | PatRegion(ref pat, _) => bindings_impl(cx, pat, map),
177+
PatEnum(_, Some(ref pats)) => {
178+
for pat in pats {
179+
bindings_impl(cx, pat, map);
180+
}
181+
}
182+
PatIdent(_, ref ident, ref as_pat) => {
183+
if let Entry::Vacant(v) = map.entry(ident.node.name.as_str()) {
184+
v.insert(cx.tcx.pat_ty(pat));
185+
}
186+
if let Some(ref as_pat) = *as_pat {
187+
bindings_impl(cx, as_pat, map);
188+
}
189+
},
190+
PatStruct(_, ref fields, _) => {
191+
for pat in fields {
192+
bindings_impl(cx, &pat.node.pat, map);
193+
}
194+
}
195+
PatTup(ref fields) => {
196+
for pat in fields {
197+
bindings_impl(cx, pat, map);
198+
}
199+
}
200+
PatVec(ref lhs, ref mid, ref rhs) => {
201+
for pat in lhs {
202+
bindings_impl(cx, pat, map);
203+
}
204+
if let Some(ref mid) = *mid {
205+
bindings_impl(cx, mid, map);
206+
}
207+
for pat in rhs {
208+
bindings_impl(cx, pat, map);
209+
}
210+
}
211+
PatEnum(..) | PatLit(..) | PatQPath(..) | PatRange(..) | PatWild => (),
212+
}
213+
}
214+
215+
let mut result = HashMap::new();
216+
bindings_impl(cx, pat, &mut result);
217+
result
218+
}
219+
220+
fn search_same<T, Hash, Eq>(exprs: &[T],
221+
hash: Hash,
222+
eq: Eq) -> Option<(&T, &T)>
223+
where Hash: Fn(&T) -> u64,
224+
Eq: Fn(&T, &T) -> bool {
131225
// common cases
132226
if exprs.len() < 2 {
133227
return None;
@@ -141,14 +235,14 @@ where Hash: Fn(&'a T) -> u64,
141235
}
142236
}
143237

144-
let mut map : HashMap<_, Vec<&'a _>> = HashMap::with_capacity(exprs.len());
238+
let mut map : HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
145239

146-
for &expr in exprs {
240+
for expr in exprs {
147241
match map.entry(hash(expr)) {
148242
Entry::Occupied(o) => {
149243
for o in o.get() {
150-
if eq(o, expr) {
151-
return Some((o, expr))
244+
if eq(&o, expr) {
245+
return Some((&o, expr))
152246
}
153247
}
154248
}

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ pub fn plugin_registrar(reg: &mut Registry) {
196196
collapsible_if::COLLAPSIBLE_IF,
197197
copies::IF_SAME_THEN_ELSE,
198198
copies::IFS_SAME_COND,
199+
copies::MATCH_SAME_ARMS,
199200
cyclomatic_complexity::CYCLOMATIC_COMPLEXITY,
200201
derive::DERIVE_HASH_NOT_EQ,
201202
derive::EXPL_IMPL_CLONE_ON_COPY,

tests/compile-fail/copies.rs

Lines changed: 49 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,18 @@
55
#![allow(let_and_return)]
66
#![allow(needless_return)]
77
#![allow(unused_variables)]
8+
#![allow(cyclomatic_complexity)]
89

10+
fn bar<T>(_: T) {}
911
fn foo() -> bool { unimplemented!() }
1012

1113
#[deny(if_same_then_else)]
14+
#[deny(match_same_arms)]
1215
fn if_same_then_else() -> &'static str {
1316
if true {
1417
foo();
1518
}
16-
else { //~ERROR this if has identical blocks
19+
else { //~ERROR this `if` has identical blocks
1720
foo();
1821
}
1922

@@ -29,7 +32,7 @@ fn if_same_then_else() -> &'static str {
2932
foo();
3033
42
3134
}
32-
else { //~ERROR this if has identical blocks
35+
else { //~ERROR this `if` has identical blocks
3336
foo();
3437
42
3538
};
@@ -41,7 +44,7 @@ fn if_same_then_else() -> &'static str {
4144
let _ = if true {
4245
42
4346
}
44-
else { //~ERROR this if has identical blocks
47+
else { //~ERROR this `if` has identical blocks
4548
42
4649
};
4750

@@ -56,7 +59,7 @@ fn if_same_then_else() -> &'static str {
5659
while foo() { break; }
5760
bar + 1;
5861
}
59-
else { //~ERROR this if has identical blocks
62+
else { //~ERROR this `if` has identical blocks
6063
let bar = if true {
6164
42
6265
}
@@ -69,29 +72,29 @@ fn if_same_then_else() -> &'static str {
6972
}
7073

7174
if true {
72-
match 42 {
73-
42 => (),
74-
a if a > 0 => (),
75-
10...15 => (),
76-
_ => (),
77-
}
75+
let _ = match 42 {
76+
42 => 1,
77+
a if a > 0 => 2,
78+
10...15 => 3,
79+
_ => 4,
80+
};
7881
}
7982
else if false {
8083
foo();
8184
}
82-
else if foo() { //~ERROR this if has identical blocks
83-
match 42 {
84-
42 => (),
85-
a if a > 0 => (),
86-
10...15 => (),
87-
_ => (),
88-
}
85+
else if foo() { //~ERROR this `if` has identical blocks
86+
let _ = match 42 {
87+
42 => 1,
88+
a if a > 0 => 2,
89+
10...15 => 3,
90+
_ => 4,
91+
};
8992
}
9093

9194
if true {
9295
if let Some(a) = Some(42) {}
9396
}
94-
else { //~ERROR this if has identical blocks
97+
else { //~ERROR this `if` has identical blocks
9598
if let Some(a) = Some(42) {}
9699
}
97100

@@ -102,6 +105,30 @@ fn if_same_then_else() -> &'static str {
102105
if let Some(a) = Some(43) {}
103106
}
104107

108+
let _ = match 42 {
109+
42 => foo(),
110+
51 => foo(), //~ERROR this `match` has identical arm bodies
111+
_ => true,
112+
};
113+
114+
let _ = match Some(42) {
115+
Some(42) => 24,
116+
Some(a) => 24, // bindings are different
117+
None => 0,
118+
};
119+
120+
match (Some(42), Some(42)) {
121+
(Some(a), None) => bar(a),
122+
(None, Some(a)) => bar(a), //~ERROR this `match` has identical arm bodies
123+
_ => (),
124+
}
125+
126+
match (Some(42), Some("")) {
127+
(Some(a), None) => bar(a),
128+
(None, Some(a)) => bar(a), // bindings have different types
129+
_ => (),
130+
}
131+
105132
if true {
106133
let foo = "";
107134
return &foo[0..];
@@ -110,7 +137,7 @@ fn if_same_then_else() -> &'static str {
110137
let foo = "bar";
111138
return &foo[0..];
112139
}
113-
else { //~ERROR this if has identical blocks
140+
else { //~ERROR this `if` has identical blocks
114141
let foo = "";
115142
return &foo[0..];
116143
}
@@ -124,19 +151,19 @@ fn ifs_same_cond() {
124151

125152
if b {
126153
}
127-
else if b { //~ERROR this if has the same condition as a previous if
154+
else if b { //~ERROR this `if` has the same condition as a previous if
128155
}
129156

130157
if a == 1 {
131158
}
132-
else if a == 1 { //~ERROR this if has the same condition as a previous if
159+
else if a == 1 { //~ERROR this `if` has the same condition as a previous if
133160
}
134161

135162
if 2*a == 1 {
136163
}
137164
else if 2*a == 2 {
138165
}
139-
else if 2*a == 1 { //~ERROR this if has the same condition as a previous if
166+
else if 2*a == 1 { //~ERROR this `if` has the same condition as a previous if
140167
}
141168
else if a == 1 {
142169
}

0 commit comments

Comments
 (0)