Skip to content

Commit e7d17e6

Browse files
committed
Auto merge of #13061 - tesuji:fix-map-unwrap-or-13018, r=dswij
Fix `manual_unwrap_or` false positive changelog: [`manual_unwrap_or`]: fix false positive of `if let Option<T>` Closes #13018
2 parents 1aac778 + c46c1f6 commit e7d17e6

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

clippy_lints/src/matches/manual_unwrap_or.rs

+11
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@ pub(super) fn check_if_let<'tcx>(
3535
else_expr: &'tcx Expr<'_>,
3636
) {
3737
let ty = cx.typeck_results().expr_ty(let_expr);
38+
let then_ty = cx.typeck_results().expr_ty(then_expr);
39+
// The signature is `fn unwrap_or<T>(self: Option<T>, default: T) -> T`.
40+
// When `expr_adjustments(then_expr).is_empty()`, `T` should equate to `default`'s type.
41+
// Otherwise, type error will occur.
42+
if cx.typeck_results().expr_adjustments(then_expr).is_empty()
43+
&& let rustc_middle::ty::Adt(_did, args) = ty.kind()
44+
&& let Some(some_ty) = args.first().and_then(|arg| arg.as_type())
45+
&& some_ty != then_ty
46+
{
47+
return;
48+
}
3849
check_and_lint(cx, expr, let_pat, let_expr, then_expr, peel_blocks(else_expr), ty);
3950
}
4051

tests/ui/manual_unwrap_or.fixed

+16
Original file line numberDiff line numberDiff line change
@@ -234,4 +234,20 @@ fn implicit_deref_ref() {
234234
};
235235
}
236236

237+
mod issue_13018 {
238+
use std::collections::HashMap;
239+
240+
type RefName = i32;
241+
pub fn get(index: &HashMap<usize, Vec<RefName>>, id: usize) -> &[RefName] {
242+
if let Some(names) = index.get(&id) { names } else { &[] }
243+
}
244+
245+
pub fn get_match(index: &HashMap<usize, Vec<RefName>>, id: usize) -> &[RefName] {
246+
match index.get(&id) {
247+
Some(names) => names,
248+
None => &[],
249+
}
250+
}
251+
}
252+
237253
fn main() {}

tests/ui/manual_unwrap_or.rs

+16
Original file line numberDiff line numberDiff line change
@@ -284,4 +284,20 @@ fn implicit_deref_ref() {
284284
};
285285
}
286286

287+
mod issue_13018 {
288+
use std::collections::HashMap;
289+
290+
type RefName = i32;
291+
pub fn get(index: &HashMap<usize, Vec<RefName>>, id: usize) -> &[RefName] {
292+
if let Some(names) = index.get(&id) { names } else { &[] }
293+
}
294+
295+
pub fn get_match(index: &HashMap<usize, Vec<RefName>>, id: usize) -> &[RefName] {
296+
match index.get(&id) {
297+
Some(names) => names,
298+
None => &[],
299+
}
300+
}
301+
}
302+
287303
fn main() {}

0 commit comments

Comments
 (0)