Skip to content

Commit

Permalink
Auto merge of rust-lang#5908 - giraffate:fix_fp_for_same_item_push, r…
Browse files Browse the repository at this point in the history
…=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.
  • Loading branch information
bors committed Aug 17, 2020
2 parents 838c201 + 99ba290 commit 9360ca6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
30 changes: 25 additions & 5 deletions clippy_lints/src/loops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1141,11 +1141,31 @@ fn detect_same_item_push<'tcx>(
if same_item_push_visitor.should_lint {
if let Some((vec, pushed_item)) = same_item_push_visitor.vec_push {
// Make sure that the push does not involve possibly mutating values
if mutated_variables(pushed_item, cx).map_or(false, |mutvars| mutvars.is_empty()) {
if let PatKind::Wild = pat.kind {
let vec_str = snippet_with_macro_callsite(cx, vec.span, "");
let item_str = snippet_with_macro_callsite(cx, pushed_item.span, "");

if let PatKind::Wild = pat.kind {
let vec_str = snippet_with_macro_callsite(cx, vec.span, "");
let item_str = snippet_with_macro_callsite(cx, pushed_item.span, "");
if let ExprKind::Path(ref qpath) = pushed_item.kind {
if_chain! {
if let Res::Local(hir_id) = qpath_res(cx, qpath, pushed_item.hir_id);
let node = cx.tcx.hir().get(hir_id);
if let Node::Binding(pat) = node;
if let PatKind::Binding(bind_ann, ..) = pat.kind;
if !matches!(bind_ann, BindingAnnotation::RefMut | BindingAnnotation::Mutable);
then {
span_lint_and_help(
cx,
SAME_ITEM_PUSH,
vec.span,
"it looks like the same item is being pushed into this Vec",
None,
&format!(
"try using vec![{};SIZE] or {}.resize(NEW_SIZE, {})",
item_str, vec_str, item_str
),
)
}
}
} else if mutated_variables(pushed_item, cx).map_or(false, |mutvars| mutvars.is_empty()) {
span_lint_and_help(
cx,
SAME_ITEM_PUSH,
Expand Down
8 changes: 8 additions & 0 deletions tests/ui/same_item_push.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,12 @@ fn main() {
for a in vec_a {
vec12.push(2u8.pow(a.kind));
}

// Fix #5902
let mut vec13: Vec<u8> = Vec::new();
let mut item = 0;
for _ in 0..10 {
vec13.push(item);
item += 10;
}
}

0 comments on commit 9360ca6

Please sign in to comment.