@@ -1085,12 +1085,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
10851085 false
10861086 }
10871087
1088- pub ( crate ) fn suggest_copied_or_cloned (
1088+ pub ( crate ) fn suggest_copied_cloned_or_as_ref (
10891089 & self ,
10901090 diag : & mut Diagnostic ,
10911091 expr : & hir:: Expr < ' _ > ,
10921092 expr_ty : Ty < ' tcx > ,
10931093 expected_ty : Ty < ' tcx > ,
1094+ expected_ty_expr : Option < & ' tcx hir:: Expr < ' tcx > > ,
10941095 ) -> bool {
10951096 let ty:: Adt ( adt_def, args) = expr_ty. kind ( ) else {
10961097 return false ;
@@ -1102,7 +1103,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
11021103 return false ;
11031104 }
11041105
1105- let mut suggest_copied_or_cloned = || {
1106+ let mut suggest_copied_cloned_or_as_ref = || {
11061107 let expr_inner_ty = args. type_at ( 0 ) ;
11071108 let expected_inner_ty = expected_args. type_at ( 0 ) ;
11081109 if let & ty:: Ref ( _, ty, hir:: Mutability :: Not ) = expr_inner_ty. kind ( )
@@ -1119,6 +1120,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
11191120 Applicability :: MachineApplicable ,
11201121 ) ;
11211122 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 ;
11221133 } else if let Some ( clone_did) = self . tcx . lang_items ( ) . clone_trait ( )
11231134 && rustc_trait_selection:: traits:: type_known_to_meet_bound_modulo_regions (
11241135 self ,
@@ -1146,11 +1157,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
11461157 // Check that the error types are equal
11471158 && self . can_eq ( self . param_env , args. type_at ( 1 ) , expected_args. type_at ( 1 ) )
11481159 {
1149- return suggest_copied_or_cloned ( ) ;
1160+ return suggest_copied_cloned_or_as_ref ( ) ;
11501161 } else if let Some ( option_did) = self . tcx . get_diagnostic_item ( sym:: Option )
11511162 && adt_def. did ( ) == option_did
11521163 {
1153- return suggest_copied_or_cloned ( ) ;
1164+ return suggest_copied_cloned_or_as_ref ( ) ;
11541165 }
11551166
11561167 false
0 commit comments