Skip to content

Commit 9360ca6

Browse files
committed
Auto merge of rust-lang#5908 - giraffate:fix_fp_for_same_item_push, r=flip1995
Fix FP for `same_item_push` Fixes rust-lang/rust-clippy#5902 changelog: Fix FP for `same_item_push` where the pushed variable is mutated.
2 parents 838c201 + 99ba290 commit 9360ca6

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

clippy_lints/src/loops.rs

+25-5
Original file line numberDiff line numberDiff line change
@@ -1141,11 +1141,31 @@ fn detect_same_item_push<'tcx>(
11411141
if same_item_push_visitor.should_lint {
11421142
if let Some((vec, pushed_item)) = same_item_push_visitor.vec_push {
11431143
// Make sure that the push does not involve possibly mutating values
1144-
if mutated_variables(pushed_item, cx).map_or(false, |mutvars| mutvars.is_empty()) {
1145-
if let PatKind::Wild = pat.kind {
1146-
let vec_str = snippet_with_macro_callsite(cx, vec.span, "");
1147-
let item_str = snippet_with_macro_callsite(cx, pushed_item.span, "");
1148-
1144+
if let PatKind::Wild = pat.kind {
1145+
let vec_str = snippet_with_macro_callsite(cx, vec.span, "");
1146+
let item_str = snippet_with_macro_callsite(cx, pushed_item.span, "");
1147+
if let ExprKind::Path(ref qpath) = pushed_item.kind {
1148+
if_chain! {
1149+
if let Res::Local(hir_id) = qpath_res(cx, qpath, pushed_item.hir_id);
1150+
let node = cx.tcx.hir().get(hir_id);
1151+
if let Node::Binding(pat) = node;
1152+
if let PatKind::Binding(bind_ann, ..) = pat.kind;
1153+
if !matches!(bind_ann, BindingAnnotation::RefMut | BindingAnnotation::Mutable);
1154+
then {
1155+
span_lint_and_help(
1156+
cx,
1157+
SAME_ITEM_PUSH,
1158+
vec.span,
1159+
"it looks like the same item is being pushed into this Vec",
1160+
None,
1161+
&format!(
1162+
"try using vec![{};SIZE] or {}.resize(NEW_SIZE, {})",
1163+
item_str, vec_str, item_str
1164+
),
1165+
)
1166+
}
1167+
}
1168+
} else if mutated_variables(pushed_item, cx).map_or(false, |mutvars| mutvars.is_empty()) {
11491169
span_lint_and_help(
11501170
cx,
11511171
SAME_ITEM_PUSH,

tests/ui/same_item_push.rs

+8
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,12 @@ fn main() {
8686
for a in vec_a {
8787
vec12.push(2u8.pow(a.kind));
8888
}
89+
90+
// Fix #5902
91+
let mut vec13: Vec<u8> = Vec::new();
92+
let mut item = 0;
93+
for _ in 0..10 {
94+
vec13.push(item);
95+
item += 10;
96+
}
8997
}

0 commit comments

Comments
 (0)