@@ -1085,12 +1085,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1085
1085
false
1086
1086
}
1087
1087
1088
- pub ( crate ) fn suggest_copied_or_cloned (
1088
+ pub ( crate ) fn suggest_copied_cloned_or_as_ref (
1089
1089
& self ,
1090
1090
diag : & mut Diagnostic ,
1091
1091
expr : & hir:: Expr < ' _ > ,
1092
1092
expr_ty : Ty < ' tcx > ,
1093
1093
expected_ty : Ty < ' tcx > ,
1094
+ expected_ty_expr : Option < & ' tcx hir:: Expr < ' tcx > > ,
1094
1095
) -> bool {
1095
1096
let ty:: Adt ( adt_def, args) = expr_ty. kind ( ) else {
1096
1097
return false ;
@@ -1102,7 +1103,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1102
1103
return false ;
1103
1104
}
1104
1105
1105
- let mut suggest_copied_or_cloned = || {
1106
+ let mut suggest_copied_cloned_or_as_ref = || {
1106
1107
let expr_inner_ty = args. type_at ( 0 ) ;
1107
1108
let expected_inner_ty = expected_args. type_at ( 0 ) ;
1108
1109
if let & ty:: Ref ( _, ty, hir:: Mutability :: Not ) = expr_inner_ty. kind ( )
@@ -1119,6 +1120,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1119
1120
Applicability :: MachineApplicable ,
1120
1121
) ;
1121
1122
return true ;
1123
+ } else if let Some ( expected_ty_expr) = expected_ty_expr {
1124
+ diag. span_suggestion_verbose (
1125
+ expected_ty_expr. span . shrink_to_hi ( ) ,
1126
+ format ! (
1127
+ "use `{def_path}::as_ref()` to convert `{expected_ty}` to `{expr_ty}`"
1128
+ ) ,
1129
+ ".as_ref()" ,
1130
+ Applicability :: MachineApplicable ,
1131
+ ) ;
1132
+ return true ;
1122
1133
} else if let Some ( clone_did) = self . tcx . lang_items ( ) . clone_trait ( )
1123
1134
&& rustc_trait_selection:: traits:: type_known_to_meet_bound_modulo_regions (
1124
1135
self ,
@@ -1146,11 +1157,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1146
1157
// Check that the error types are equal
1147
1158
&& self . can_eq ( self . param_env , args. type_at ( 1 ) , expected_args. type_at ( 1 ) )
1148
1159
{
1149
- return suggest_copied_or_cloned ( ) ;
1160
+ return suggest_copied_cloned_or_as_ref ( ) ;
1150
1161
} else if let Some ( option_did) = self . tcx . get_diagnostic_item ( sym:: Option )
1151
1162
&& adt_def. did ( ) == option_did
1152
1163
{
1153
- return suggest_copied_or_cloned ( ) ;
1164
+ return suggest_copied_cloned_or_as_ref ( ) ;
1154
1165
}
1155
1166
1156
1167
false
0 commit comments