Skip to content

Commit 0cbbee1

Browse files
committed
Auto merge of rust-lang#13090 - J-ZhengLi:issue9790, r=blyxyas
[`unwrap_or_default`]: skip warning when calling inside of suggested method's implementation fixes: rust-lang#10228 --- changelog: [`unwrap_or_default`]: skip warning when calling inside of suggested method's implementation
2 parents 51a1cf0 + 983b4c3 commit 0cbbee1

File tree

3 files changed

+42
-5
lines changed

3 files changed

+42
-5
lines changed

clippy_lints/src/methods/or_fun_call.rs

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,18 +70,31 @@ pub(super) fn check<'tcx>(
7070
};
7171

7272
let receiver_ty = cx.typeck_results().expr_ty_adjusted(receiver).peel_refs();
73-
let has_suggested_method = receiver_ty.ty_adt_def().is_some_and(|adt_def| {
73+
let Some(suggested_method_def_id) = receiver_ty.ty_adt_def().and_then(|adt_def| {
7474
cx.tcx
7575
.inherent_impls(adt_def.did())
7676
.into_iter()
7777
.flatten()
7878
.flat_map(|impl_id| cx.tcx.associated_items(impl_id).filter_by_name_unhygienic(sugg))
79-
.any(|assoc| {
80-
assoc.fn_has_self_parameter
79+
.find_map(|assoc| {
80+
if assoc.fn_has_self_parameter
8181
&& cx.tcx.fn_sig(assoc.def_id).skip_binder().inputs().skip_binder().len() == 1
82+
{
83+
Some(assoc.def_id)
84+
} else {
85+
None
86+
}
8287
})
83-
});
84-
if !has_suggested_method {
88+
}) else {
89+
return false;
90+
};
91+
let in_sugg_method_implementation = {
92+
matches!(
93+
suggested_method_def_id.as_local(),
94+
Some(local_def_id) if local_def_id == cx.tcx.hir().get_parent_item(receiver.hir_id).def_id
95+
)
96+
};
97+
if in_sugg_method_implementation {
8598
return false;
8699
}
87100

tests/ui/or_fun_call.fixed

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,4 +318,16 @@ fn host_effect() {
318318
Add::<i32>::add(1, 1).add(i32::MIN);
319319
}
320320

321+
mod issue_10228 {
322+
struct Entry;
323+
324+
impl Entry {
325+
fn or_insert(self, _default: i32) {}
326+
fn or_default(self) {
327+
// Don't lint, suggested code is an infinite recursion
328+
self.or_insert(Default::default())
329+
}
330+
}
331+
}
332+
321333
fn main() {}

tests/ui/or_fun_call.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,4 +318,16 @@ fn host_effect() {
318318
Add::<i32>::add(1, 1).add(i32::MIN);
319319
}
320320

321+
mod issue_10228 {
322+
struct Entry;
323+
324+
impl Entry {
325+
fn or_insert(self, _default: i32) {}
326+
fn or_default(self) {
327+
// Don't lint, suggested code is an infinite recursion
328+
self.or_insert(Default::default())
329+
}
330+
}
331+
}
332+
321333
fn main() {}

0 commit comments

Comments
 (0)