Fix match_same_arms to fail late

Changes:
- Add a function search_same_list which return a list of matched expressions
- Change the match_same_arms implementation behaviour. It will lint each same arms found.
This commit is contained in:
Vincent Dal Maso 2019-05-16 11:27:45 +02:00
parent f49d878ce5
commit 902726c38d

View File

@ -185,7 +185,10 @@ fn lint_match_arms(cx: &LateContext<'_, '_>, expr: &Expr) {
}; };
let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect(); let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
if let Some((&(_, i), &(_, j))) = search_same(&indexed_arms, hash, eq) { search_same_list(&indexed_arms, hash, eq).map(|item| {
for match_expr in item {
let (&(_, i), &(_, j)) = match_expr;
span_lint_and_then( span_lint_and_then(
cx, cx,
MATCH_SAME_ARMS, MATCH_SAME_ARMS,
@ -223,6 +226,7 @@ fn lint_match_arms(cx: &LateContext<'_, '_>, expr: &Expr) {
}, },
); );
} }
});
} }
} }
@ -360,3 +364,36 @@ where
None None
} }
fn search_same_list<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<Vec<(&T, &T)>>
where
Hash: Fn(&T) -> u64,
Eq: Fn(&T, &T) -> bool,
{
let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
let mut map: FxHashMap<_, Vec<&_>> =
FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
for expr in exprs {
match map.entry(hash(expr)) {
Entry::Occupied(mut o) => {
for o in o.get() {
if eq(o, expr) {
match_expr_list.push((o, expr));
}
}
o.get_mut().push(expr);
},
Entry::Vacant(v) => {
v.insert(vec![expr]);
},
}
}
if match_expr_list.is_empty() {
None
} else {
Some(match_expr_list)
}
}