11use clippy_utils:: diagnostics:: { span_lint_and_sugg, span_lint_hir_and_then} ;
2+ use clippy_utils:: mir:: { dropped_without_further_use, enclosing_mir, expr_local, local_assignments} ;
23use clippy_utils:: source:: { snippet_with_applicability, snippet_with_context} ;
34use clippy_utils:: sugg:: has_enclosing_paren;
45use clippy_utils:: ty:: { expr_sig, is_copy, peel_mid_ty_refs, ty_sig, variant_of_res} ;
@@ -18,6 +19,7 @@ use rustc_hir::{
1819use rustc_index:: bit_set:: BitSet ;
1920use rustc_infer:: infer:: TyCtxtInferExt ;
2021use rustc_lint:: { LateContext , LateLintPass } ;
22+ use rustc_middle:: mir:: { Rvalue , StatementKind } ;
2123use rustc_middle:: ty:: adjustment:: { Adjust , Adjustment , AutoBorrow , AutoBorrowMutability } ;
2224use rustc_middle:: ty:: {
2325 self , Binder , BoundVariableKind , EarlyBinder , FnSig , GenericArgKind , List , ParamTy , PredicateKind ,
@@ -1082,10 +1084,10 @@ fn needless_borrow_impl_arg_position<'tcx>(
10821084 // elements are modified each time `check_referent` is called.
10831085 let mut substs_with_referent_ty = substs_with_expr_ty. to_vec ( ) ;
10841086
1085- let mut check_referent = |referent| {
1087+ let mut check_reference_and_referent = |reference , referent| {
10861088 let referent_ty = cx. typeck_results ( ) . expr_ty ( referent) ;
10871089
1088- if !is_copy ( cx, referent_ty) {
1090+ if !( is_copy ( cx, referent_ty) || referent_dropped_without_further_use ( cx . tcx , reference ) ) {
10891091 return false ;
10901092 }
10911093
@@ -1127,7 +1129,7 @@ fn needless_borrow_impl_arg_position<'tcx>(
11271129
11281130 let mut needless_borrow = false ;
11291131 while let ExprKind :: AddrOf ( _, _, referent) = expr. kind {
1130- if !check_referent ( referent) {
1132+ if !check_reference_and_referent ( expr , referent) {
11311133 break ;
11321134 }
11331135 expr = referent;
@@ -1155,6 +1157,20 @@ fn has_ref_mut_self_method(cx: &LateContext<'_>, trait_def_id: DefId) -> bool {
11551157 } )
11561158}
11571159
1160+ fn referent_dropped_without_further_use ( tcx : TyCtxt < ' _ > , reference : & Expr < ' _ > ) -> bool {
1161+ let mir = enclosing_mir ( tcx, reference. hir_id ) ;
1162+ if let Some ( local) = expr_local ( tcx, reference)
1163+ && let [ location] = * local_assignments ( mir, local) . as_slice ( )
1164+ && let StatementKind :: Assign ( box ( _, Rvalue :: Ref ( _, _, place) ) ) =
1165+ mir. basic_blocks [ location. block ] . statements [ location. statement_index ] . kind
1166+ && !place. has_deref ( )
1167+ {
1168+ dropped_without_further_use ( mir, place. local , location) . unwrap_or ( false )
1169+ } else {
1170+ false
1171+ }
1172+ }
1173+
11581174// Iteratively replaces `param_ty` with `new_ty` in `substs`, and similarly for each resulting
11591175// projected type that is a type parameter. Returns `false` if replacing the types would have an
11601176// effect on the function signature beyond substituting `new_ty` for `param_ty`.
0 commit comments