Skip to content

Commit c2aaa62

Browse files
committed
Fix ICE on None.unwrap_or_default()
1 parent 7ccf5d4 commit c2aaa62

6 files changed

+165
-123
lines changed

clippy_lints/src/methods/unnecessary_literal_unwrap.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ use clippy_utils::{is_res_lang_ctor, last_path_segment, path_res, MaybePath};
33
use rustc_errors::Applicability;
44
use rustc_hir as hir;
55
use rustc_lint::LateContext;
6+
use rustc_middle::ty;
7+
use rustc_middle::ty::print::with_forced_trimmed_paths;
68

79
use super::UNNECESSARY_LITERAL_UNWRAP;
810

@@ -84,6 +86,16 @@ pub(super) fn check(
8486
}
8587
Some(suggs)
8688
},
89+
("None", "unwrap_or_default", _) => {
90+
let ty = cx.typeck_results().expr_ty(expr);
91+
let default_ty_string = if let ty::Adt(def, ..) = ty.kind() {
92+
with_forced_trimmed_paths!(format!("{}", cx.tcx.def_path_str(def.did())))
93+
} else {
94+
"Default".to_string()
95+
};
96+
Some(vec![(expr.span, format!("{default_ty_string}::default()"))])
97+
},
98+
_ if call_args.is_empty() => None,
8799
(_, _, Some(_)) => None,
88100
("Ok", "unwrap_err", None) | ("Err", "unwrap", None) => Some(vec![
89101
(

tests/ui/unnecessary_literal_unwrap.fixed

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@ fn unwrap_option_some() {
1919
fn unwrap_option_none() {
2020
let _val = panic!();
2121
let _val = panic!("this always happens");
22+
let _val: String = String::default();
2223

2324
panic!();
2425
panic!("this always happens");
26+
String::default();
2527
}
2628

2729
fn unwrap_result_ok() {

tests/ui/unnecessary_literal_unwrap.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@ fn unwrap_option_some() {
1919
fn unwrap_option_none() {
2020
let _val = None::<()>.unwrap();
2121
let _val = None::<()>.expect("this always happens");
22+
let _val: String = None.unwrap_or_default();
2223

2324
None::<()>.unwrap();
2425
None::<()>.expect("this always happens");
26+
None::<String>.unwrap_or_default();
2527
}
2628

2729
fn unwrap_result_ok() {

0 commit comments

Comments
 (0)