Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions clippy_lints/src/matches/manual_unwrap_or.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
16 changes: 16 additions & 0 deletions tests/ui/manual_unwrap_or.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -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() {}
16 changes: 16 additions & 0 deletions tests/ui/manual_unwrap_or.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {}