Skip to content

Commit 283d07e

Browse files
committed
fix(map_entry): don't autofix when {e.insert(_); None } would be required
1 parent 816cc54 commit 283d07e

File tree

3 files changed

+31
-4
lines changed

3 files changed

+31
-4
lines changed

clippy_lints/src/entry.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,8 @@ impl<'tcx> InsertSearchResults<'tcx> {
682682
} else {
683683
write!(res, "{{ e.insert({value_str}); None }}")
684684
};
685+
// This might leave `None`'s type ambiguous, so reduce applicability
686+
*app = Applicability::MaybeIncorrect;
685687
}),
686688
"Vacant(e)",
687689
)

tests/ui/entry_unfixable.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//@no-rustfix
12
#![allow(clippy::needless_pass_by_value, clippy::collapsible_if)]
23
#![warn(clippy::map_entry)]
34

@@ -90,4 +91,11 @@ mod issue13306 {
9091
}
9192
}
9293

94+
fn issue15307<K: Eq + Hash, V>(mut m: HashMap<K, V>, k: K, v: V) {
95+
if !m.contains_key(&k) {
96+
//~^ map_entry
97+
assert!(m.insert(k, v).is_none());
98+
}
99+
}
100+
93101
fn main() {}

tests/ui/entry_unfixable.stderr

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: usage of `contains_key` followed by `insert` on a `HashMap`
2-
--> tests/ui/entry_unfixable.rs:46:13
2+
--> tests/ui/entry_unfixable.rs:47:13
33
|
44
LL | / if self.globals.contains_key(&name) {
55
LL | |
@@ -15,7 +15,7 @@ LL | | }
1515
= help: to override `-D warnings` add `#[allow(clippy::map_entry)]`
1616

1717
error: usage of `contains_key` followed by `insert` on a `HashMap`
18-
--> tests/ui/entry_unfixable.rs:61:5
18+
--> tests/ui/entry_unfixable.rs:62:5
1919
|
2020
LL | / if hm.contains_key(&key) {
2121
LL | |
@@ -29,7 +29,7 @@ LL | | }
2929
= help: consider using the `Entry` API: https://doc.rust-lang.org/std/collections/struct.HashMap.html#entry-api
3030

3131
error: usage of `contains_key` followed by `insert` on a `HashMap`
32-
--> tests/ui/entry_unfixable.rs:80:13
32+
--> tests/ui/entry_unfixable.rs:81:13
3333
|
3434
LL | / if !self.values.contains_key(&name) {
3535
LL | |
@@ -42,5 +42,22 @@ LL | | }
4242
|
4343
= help: consider using the `Entry` API: https://doc.rust-lang.org/std/collections/struct.HashMap.html#entry-api
4444

45-
error: aborting due to 3 previous errors
45+
error: usage of `contains_key` followed by `insert` on a `HashMap`
46+
--> tests/ui/entry_unfixable.rs:95:5
47+
|
48+
LL | / if !m.contains_key(&k) {
49+
LL | |
50+
LL | | assert!(m.insert(k, v).is_none());
51+
LL | | }
52+
| |_____^
53+
|
54+
help: try
55+
|
56+
LL ~ if let std::collections::hash_map::Entry::Vacant(e) = m.entry(k) {
57+
LL +
58+
LL + assert!({ e.insert(v); None }.is_none());
59+
LL + }
60+
|
61+
62+
error: aborting due to 4 previous errors
4663

0 commit comments

Comments
 (0)