@@ -7,7 +7,7 @@ use clippy_utils::{
77use if_chain:: if_chain;
88use rustc_errors:: Applicability ;
99use rustc_hir:: intravisit:: { walk_expr, ErasedMap , NestedVisitorMap , Visitor } ;
10- use rustc_hir:: { def:: Res , Expr , ExprKind , HirId , Local , MatchSource , Node , PatKind , QPath , UnOp } ;
10+ use rustc_hir:: { def:: Res , Expr , ExprKind , HirId , Local , MatchSource , Mutability , Node , PatKind , QPath , UnOp } ;
1111use rustc_lint:: LateContext ;
1212use rustc_span:: { symbol:: sym, Span , Symbol } ;
1313
@@ -48,7 +48,12 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
4848 // borrowed mutably. TODO: If the struct can be partially moved from and the struct isn't used
4949 // afterwards a mutable borrow of a field isn't necessary.
5050 let ref_mut = if !iter_expr. fields . is_empty ( ) || needs_mutable_borrow ( cx, & iter_expr, loop_expr) {
51- "&mut "
51+ if cx. typeck_results ( ) . node_type ( iter_expr. hir_id ) . ref_mutability ( ) == Some ( Mutability :: Mut ) {
52+ // Reborrow for mutable references. It may not be possible to get a mutable reference here.
53+ "&mut *"
54+ } else {
55+ "&mut "
56+ }
5257 } else {
5358 ""
5459 } ;
@@ -69,6 +74,8 @@ pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
6974struct IterExpr {
7075 /// The span of the whole expression, not just the path and fields stored here.
7176 span : Span ,
77+ /// The HIR id of the whole expression, not just the path and fields stored here.
78+ hir_id : HirId ,
7279 /// The fields used, in order of child to parent.
7380 fields : Vec < Symbol > ,
7481 /// The path being used.
@@ -78,12 +85,14 @@ struct IterExpr {
7885/// the expression might have side effects.
7986fn try_parse_iter_expr ( cx : & LateContext < ' _ > , mut e : & Expr < ' _ > ) -> Option < IterExpr > {
8087 let span = e. span ;
88+ let hir_id = e. hir_id ;
8189 let mut fields = Vec :: new ( ) ;
8290 loop {
8391 match e. kind {
8492 ExprKind :: Path ( ref path) => {
8593 break Some ( IterExpr {
8694 span,
95+ hir_id,
8796 fields,
8897 path : cx. qpath_res ( path, e. hir_id ) ,
8998 } ) ;
0 commit comments