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
This commit is contained in:
bors 2024-07-13 15:59:11 +00:00
commit e7d17e6cb2
3 changed files with 43 additions and 0 deletions

View File

@ -35,6 +35,17 @@ pub(super) fn check_if_let<'tcx>(
else_expr: &'tcx Expr<'_>,
) {
let ty = cx.typeck_results().expr_ty(let_expr);
let then_ty = cx.typeck_results().expr_ty(then_expr);
// The signature is `fn unwrap_or<T>(self: Option<T>, default: T) -> T`.
// When `expr_adjustments(then_expr).is_empty()`, `T` should equate to `default`'s type.
// Otherwise, type error will occur.
if cx.typeck_results().expr_adjustments(then_expr).is_empty()
&& let rustc_middle::ty::Adt(_did, args) = ty.kind()
&& let Some(some_ty) = args.first().and_then(|arg| arg.as_type())
&& some_ty != then_ty
{
return;
}
check_and_lint(cx, expr, let_pat, let_expr, then_expr, peel_blocks(else_expr), ty);
}

View File

@ -234,4 +234,20 @@ fn implicit_deref_ref() {
};
}
mod issue_13018 {
use std::collections::HashMap;
type RefName = i32;
pub fn get(index: &HashMap<usize, Vec<RefName>>, id: usize) -> &[RefName] {
if let Some(names) = index.get(&id) { names } else { &[] }
}
pub fn get_match(index: &HashMap<usize, Vec<RefName>>, id: usize) -> &[RefName] {
match index.get(&id) {
Some(names) => names,
None => &[],
}
}
}
fn main() {}

View File

@ -284,4 +284,20 @@ fn implicit_deref_ref() {
};
}
mod issue_13018 {
use std::collections::HashMap;
type RefName = i32;
pub fn get(index: &HashMap<usize, Vec<RefName>>, id: usize) -> &[RefName] {
if let Some(names) = index.get(&id) { names } else { &[] }
}
pub fn get_match(index: &HashMap<usize, Vec<RefName>>, id: usize) -> &[RefName] {
match index.get(&id) {
Some(names) => names,
None => &[],
}
}
}
fn main() {}