@@ -58,7 +58,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
58
58
|| self . suggest_into ( err, expr, expr_ty, expected)
59
59
|| self . suggest_floating_point_literal ( err, expr, expected)
60
60
|| self . suggest_null_ptr_for_literal_zero_given_to_ptr_arg ( err, expr, expected)
61
- || self . suggest_coercing_result_via_try_operator ( err, expr, expected, expr_ty) ;
61
+ || self . suggest_coercing_result_via_try_operator ( err, expr, expected, expr_ty)
62
+ || self . suggest_missing_unwrap_expect ( err, expr, expected, expr_ty) ;
62
63
63
64
if !suggested {
64
65
self . note_source_of_type_mismatch_constraint (
@@ -954,6 +955,53 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
954
955
) ;
955
956
}
956
957
958
+ pub ( crate ) fn suggest_missing_unwrap_expect (
959
+ & self ,
960
+ err : & mut Diagnostic ,
961
+ expr : & hir:: Expr < ' tcx > ,
962
+ expected : Ty < ' tcx > ,
963
+ found : Ty < ' tcx > ,
964
+ ) -> bool {
965
+ if let ty:: Adt ( adt, args) = found. kind ( ) {
966
+ if self . tcx . is_diagnostic_item ( sym:: Option , adt. did ( ) )
967
+ || self . tcx . is_diagnostic_item ( sym:: Result , adt. did ( ) )
968
+ {
969
+ // don't suggest anything like `Ok(ok_val).unwrap()` , `Some(some_val).unwrap()`, `None.unwrap()` etc.
970
+ let is_ctor = match expr. kind {
971
+ hir:: ExprKind :: Call (
972
+ hir:: Expr {
973
+ kind :
974
+ hir:: ExprKind :: Path ( hir:: QPath :: Resolved (
975
+ None ,
976
+ hir:: Path {
977
+ res : Res :: Def ( hir:: def:: DefKind :: Ctor ( _, _) , _) ,
978
+ ..
979
+ } ,
980
+ ) ) ,
981
+ ..
982
+ } ,
983
+ ..,
984
+ ) => true ,
985
+ hir:: ExprKind :: Path ( hir:: QPath :: Resolved (
986
+ None ,
987
+ hir:: Path { res : Res :: Def ( hir:: def:: DefKind :: Ctor ( _, _) , _) , .. } ,
988
+ ) ) => true ,
989
+ _ => false ,
990
+ } ;
991
+ if !is_ctor && self . can_coerce ( args. type_at ( 0 ) , expected) {
992
+ err. span_suggestion_verbose (
993
+ expr. span . shrink_to_hi ( ) ,
994
+ "you may missing `unwrap` or `expect(...)` here" ,
995
+ ".unwrap()" ,
996
+ Applicability :: MaybeIncorrect ,
997
+ ) ;
998
+ return true ;
999
+ } ;
1000
+ }
1001
+ }
1002
+ return false ;
1003
+ }
1004
+
957
1005
pub ( crate ) fn suggest_coercing_result_via_try_operator (
958
1006
& self ,
959
1007
err : & mut Diagnostic ,
0 commit comments