Fix 13018: self should be T

with `Option::unwrap_or(self, T) -> T`.
This commit is contained in:
Lzu Tao 2024-07-07 20:41:55 +07:00
parent e864519fbc
commit c46c1f6da6
4 changed files with 27 additions and 16 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

@ -239,7 +239,14 @@ mod issue_13018 {
type RefName = i32;
pub fn get(index: &HashMap<usize, Vec<RefName>>, id: usize) -> &[RefName] {
index.get(&id).unwrap_or(&[])
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 => &[],
}
}
}

View file

@ -289,10 +289,13 @@ mod issue_13018 {
type RefName = i32;
pub fn get(index: &HashMap<usize, Vec<RefName>>, id: usize) -> &[RefName] {
if let Some(names) = index.get(&id) {
names
} else {
&[]
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 => &[],
}
}
}

View file

@ -172,15 +172,5 @@ LL | | None => 0,
LL | | };
| |_________^ help: replace with: `some_macro!().unwrap_or(0)`
error: this pattern reimplements `Option::unwrap_or`
--> tests/ui/manual_unwrap_or.rs:292:9
|
LL | / if let Some(names) = index.get(&id) {
LL | | names
LL | | } else {
LL | | &[]
LL | | }
| |_________^ help: replace with: `index.get(&id).unwrap_or(&[])`
error: aborting due to 17 previous errors
error: aborting due to 16 previous errors