]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/dereference.rs
Improve lint doc consistency
[rust.git] / clippy_lints / src / dereference.rs
1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
2 use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
3 use clippy_utils::sugg::has_enclosing_paren;
4 use clippy_utils::ty::peel_mid_ty_refs;
5 use clippy_utils::{get_parent_expr, get_parent_node, is_lint_allowed, path_to_local};
6 use rustc_ast::util::parser::{PREC_POSTFIX, PREC_PREFIX};
7 use rustc_data_structures::fx::FxIndexMap;
8 use rustc_errors::Applicability;
9 use rustc_hir::{
10     BindingAnnotation, Body, BodyId, BorrowKind, Destination, Expr, ExprKind, HirId, MatchSource, Mutability, Node,
11     Pat, PatKind, UnOp,
12 };
13 use rustc_lint::{LateContext, LateLintPass};
14 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
15 use rustc_middle::ty::{self, Ty, TyCtxt, TypeckResults};
16 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use rustc_span::{symbol::sym, Span};
18
19 declare_clippy_lint! {
20     /// ### What it does
21     /// Checks for explicit `deref()` or `deref_mut()` method calls.
22     ///
23     /// ### Why is this bad?
24     /// Dereferencing by `&*x` or `&mut *x` is clearer and more concise,
25     /// when not part of a method chain.
26     ///
27     /// ### Example
28     /// ```rust
29     /// use std::ops::Deref;
30     /// let a: &mut String = &mut String::from("foo");
31     /// let b: &str = a.deref();
32     /// ```
33     ///
34     /// Use instead:
35     /// ```rust
36     /// let a: &mut String = &mut String::from("foo");
37     /// let b = &*a;
38     /// ```
39     ///
40     /// This lint excludes:
41     /// ```rust,ignore
42     /// let _ = d.unwrap().deref();
43     /// ```
44     #[clippy::version = "1.44.0"]
45     pub EXPLICIT_DEREF_METHODS,
46     pedantic,
47     "Explicit use of deref or deref_mut method while not in a method chain."
48 }
49
50 declare_clippy_lint! {
51     /// ### What it does
52     /// Checks for address of operations (`&`) that are going to
53     /// be dereferenced immediately by the compiler.
54     ///
55     /// ### Why is this bad?
56     /// Suggests that the receiver of the expression borrows
57     /// the expression.
58     ///
59     /// ### Example
60     /// ```rust
61     /// fn fun(_a: &i32) {}
62     ///
63     /// let x: &i32 = &&&&&&5;
64     /// fun(&x);
65     /// ```
66     ///
67     /// Use instead:
68     /// ```rust
69     /// # fn fun(_a: &i32) {}
70     /// let x: &i32 = &5;
71     /// fun(x);
72     /// ```
73     #[clippy::version = "pre 1.29.0"]
74     pub NEEDLESS_BORROW,
75     style,
76     "taking a reference that is going to be automatically dereferenced"
77 }
78
79 declare_clippy_lint! {
80     /// ### What it does
81     /// Checks for `ref` bindings which create a reference to a reference.
82     ///
83     /// ### Why is this bad?
84     /// The address-of operator at the use site is clearer about the need for a reference.
85     ///
86     /// ### Example
87     /// ```rust
88     /// let x = Some("");
89     /// if let Some(ref x) = x {
90     ///     // use `x` here
91     /// }
92     /// ```
93     ///
94     /// Use instead:
95     /// ```rust
96     /// let x = Some("");
97     /// if let Some(x) = x {
98     ///     // use `&x` here
99     /// }
100     /// ```
101     #[clippy::version = "1.54.0"]
102     pub REF_BINDING_TO_REFERENCE,
103     pedantic,
104     "`ref` binding to a reference"
105 }
106
107 impl_lint_pass!(Dereferencing => [
108     EXPLICIT_DEREF_METHODS,
109     NEEDLESS_BORROW,
110     REF_BINDING_TO_REFERENCE,
111 ]);
112
113 #[derive(Default)]
114 pub struct Dereferencing {
115     state: Option<(State, StateData)>,
116
117     // While parsing a `deref` method call in ufcs form, the path to the function is itself an
118     // expression. This is to store the id of that expression so it can be skipped when
119     // `check_expr` is called for it.
120     skip_expr: Option<HirId>,
121
122     /// The body the first local was found in. Used to emit lints when the traversal of the body has
123     /// been finished. Note we can't lint at the end of every body as they can be nested within each
124     /// other.
125     current_body: Option<BodyId>,
126     /// The list of locals currently being checked by the lint.
127     /// If the value is `None`, then the binding has been seen as a ref pattern, but is not linted.
128     /// This is needed for or patterns where one of the branches can be linted, but another can not
129     /// be.
130     ///
131     /// e.g. `m!(x) | Foo::Bar(ref x)`
132     ref_locals: FxIndexMap<HirId, Option<RefPat>>,
133 }
134
135 struct StateData {
136     /// Span of the top level expression
137     span: Span,
138 }
139
140 enum State {
141     // Any number of deref method calls.
142     DerefMethod {
143         // The number of calls in a sequence which changed the referenced type
144         ty_changed_count: usize,
145         is_final_ufcs: bool,
146         /// The required mutability
147         target_mut: Mutability,
148     },
149     DerefedBorrow {
150         count: usize,
151         required_precedence: i8,
152         msg: &'static str,
153     },
154 }
155
156 // A reference operation considered by this lint pass
157 enum RefOp {
158     Method(Mutability),
159     Deref,
160     AddrOf,
161 }
162
163 struct RefPat {
164     /// Whether every usage of the binding is dereferenced.
165     always_deref: bool,
166     /// The spans of all the ref bindings for this local.
167     spans: Vec<Span>,
168     /// The applicability of this suggestion.
169     app: Applicability,
170     /// All the replacements which need to be made.
171     replacements: Vec<(Span, String)>,
172 }
173
174 impl<'tcx> LateLintPass<'tcx> for Dereferencing {
175     #[expect(clippy::too_many_lines)]
176     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
177         // Skip path expressions from deref calls. e.g. `Deref::deref(e)`
178         if Some(expr.hir_id) == self.skip_expr.take() {
179             return;
180         }
181
182         if let Some(local) = path_to_local(expr) {
183             self.check_local_usage(cx, expr, local);
184         }
185
186         // Stop processing sub expressions when a macro call is seen
187         if expr.span.from_expansion() {
188             if let Some((state, data)) = self.state.take() {
189                 report(cx, expr, state, data);
190             }
191             return;
192         }
193
194         let typeck = cx.typeck_results();
195         let (kind, sub_expr) = if let Some(x) = try_parse_ref_op(cx.tcx, typeck, expr) {
196             x
197         } else {
198             // The whole chain of reference operations has been seen
199             if let Some((state, data)) = self.state.take() {
200                 report(cx, expr, state, data);
201             }
202             return;
203         };
204
205         match (self.state.take(), kind) {
206             (None, kind) => {
207                 let parent = get_parent_node(cx.tcx, expr.hir_id);
208                 let expr_ty = typeck.expr_ty(expr);
209
210                 match kind {
211                     RefOp::Method(target_mut)
212                         if !is_lint_allowed(cx, EXPLICIT_DEREF_METHODS, expr.hir_id)
213                             && is_linted_explicit_deref_position(parent, expr.hir_id, expr.span) =>
214                     {
215                         self.state = Some((
216                             State::DerefMethod {
217                                 ty_changed_count: if deref_method_same_type(expr_ty, typeck.expr_ty(sub_expr)) {
218                                     0
219                                 } else {
220                                     1
221                                 },
222                                 is_final_ufcs: matches!(expr.kind, ExprKind::Call(..)),
223                                 target_mut,
224                             },
225                             StateData { span: expr.span },
226                         ));
227                     },
228                     RefOp::AddrOf => {
229                         // Find the number of times the borrow is auto-derefed.
230                         let mut iter = find_adjustments(cx.tcx, typeck, expr).iter();
231                         let mut deref_count = 0usize;
232                         let next_adjust = loop {
233                             match iter.next() {
234                                 Some(adjust) => {
235                                     if !matches!(adjust.kind, Adjust::Deref(_)) {
236                                         break Some(adjust);
237                                     } else if !adjust.target.is_ref() {
238                                         deref_count += 1;
239                                         break iter.next();
240                                     }
241                                     deref_count += 1;
242                                 },
243                                 None => break None,
244                             };
245                         };
246
247                         // Determine the required number of references before any can be removed. In all cases the
248                         // reference made by the current expression will be removed. After that there are four cases to
249                         // handle.
250                         //
251                         // 1. Auto-borrow will trigger in the current position, so no further references are required.
252                         // 2. Auto-deref ends at a reference, or the underlying type, so one extra needs to be left to
253                         //    handle the automatically inserted re-borrow.
254                         // 3. Auto-deref hits a user-defined `Deref` impl, so at least one reference needs to exist to
255                         //    start auto-deref.
256                         // 4. If the chain of non-user-defined derefs ends with a mutable re-borrow, and re-borrow
257                         //    adjustments will not be inserted automatically, then leave one further reference to avoid
258                         //    moving a mutable borrow.
259                         //    e.g.
260                         //        fn foo<T>(x: &mut Option<&mut T>, y: &mut T) {
261                         //            let x = match x {
262                         //                // Removing the borrow will cause `x` to be moved
263                         //                Some(x) => &mut *x,
264                         //                None => y
265                         //            };
266                         //        }
267                         let deref_msg =
268                             "this expression creates a reference which is immediately dereferenced by the compiler";
269                         let borrow_msg = "this expression borrows a value the compiler would automatically borrow";
270
271                         let (required_refs, required_precedence, msg) = if is_auto_borrow_position(parent, expr.hir_id)
272                         {
273                             (1, PREC_POSTFIX, if deref_count == 1 { borrow_msg } else { deref_msg })
274                         } else if let Some(&Adjust::Borrow(AutoBorrow::Ref(_, mutability))) =
275                             next_adjust.map(|a| &a.kind)
276                         {
277                             if matches!(mutability, AutoBorrowMutability::Mut { .. })
278                                 && !is_auto_reborrow_position(parent)
279                             {
280                                 (3, 0, deref_msg)
281                             } else {
282                                 (2, 0, deref_msg)
283                             }
284                         } else {
285                             (2, 0, deref_msg)
286                         };
287
288                         if deref_count >= required_refs {
289                             self.state = Some((
290                                 State::DerefedBorrow {
291                                     // One of the required refs is for the current borrow expression, the remaining ones
292                                     // can't be removed without breaking the code. See earlier comment.
293                                     count: deref_count - required_refs,
294                                     required_precedence,
295                                     msg,
296                                 },
297                                 StateData { span: expr.span },
298                             ));
299                         }
300                     },
301                     _ => (),
302                 }
303             },
304             (
305                 Some((
306                     State::DerefMethod {
307                         target_mut,
308                         ty_changed_count,
309                         ..
310                     },
311                     data,
312                 )),
313                 RefOp::Method(_),
314             ) => {
315                 self.state = Some((
316                     State::DerefMethod {
317                         ty_changed_count: if deref_method_same_type(typeck.expr_ty(expr), typeck.expr_ty(sub_expr)) {
318                             ty_changed_count
319                         } else {
320                             ty_changed_count + 1
321                         },
322                         is_final_ufcs: matches!(expr.kind, ExprKind::Call(..)),
323                         target_mut,
324                     },
325                     data,
326                 ));
327             },
328             (
329                 Some((
330                     State::DerefedBorrow {
331                         count,
332                         required_precedence,
333                         msg,
334                     },
335                     data,
336                 )),
337                 RefOp::AddrOf,
338             ) if count != 0 => {
339                 self.state = Some((
340                     State::DerefedBorrow {
341                         count: count - 1,
342                         required_precedence,
343                         msg,
344                     },
345                     data,
346                 ));
347             },
348
349             (Some((state, data)), _) => report(cx, expr, state, data),
350         }
351     }
352
353     fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
354         if let PatKind::Binding(BindingAnnotation::Ref, id, name, _) = pat.kind {
355             if let Some(opt_prev_pat) = self.ref_locals.get_mut(&id) {
356                 // This binding id has been seen before. Add this pattern to the list of changes.
357                 if let Some(prev_pat) = opt_prev_pat {
358                     if pat.span.from_expansion() {
359                         // Doesn't match the context of the previous pattern. Can't lint here.
360                         *opt_prev_pat = None;
361                     } else {
362                         prev_pat.spans.push(pat.span);
363                         prev_pat.replacements.push((
364                             pat.span,
365                             snippet_with_context(cx, name.span, pat.span.ctxt(), "..", &mut prev_pat.app)
366                                 .0
367                                 .into(),
368                         ));
369                     }
370                 }
371                 return;
372             }
373
374             if_chain! {
375                 if !pat.span.from_expansion();
376                 if let ty::Ref(_, tam, _) = *cx.typeck_results().pat_ty(pat).kind();
377                 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
378                 if let ty::Ref(_, _, Mutability::Not) = *tam.kind();
379                 then {
380                     let mut app = Applicability::MachineApplicable;
381                     let snip = snippet_with_context(cx, name.span, pat.span.ctxt(), "..", &mut app).0;
382                     self.current_body = self.current_body.or(cx.enclosing_body);
383                     self.ref_locals.insert(
384                         id,
385                         Some(RefPat {
386                             always_deref: true,
387                             spans: vec![pat.span],
388                             app,
389                             replacements: vec![(pat.span, snip.into())],
390                         }),
391                     );
392                 }
393             }
394         }
395     }
396
397     fn check_body_post(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
398         if Some(body.id()) == self.current_body {
399             for pat in self.ref_locals.drain(..).filter_map(|(_, x)| x) {
400                 let replacements = pat.replacements;
401                 let app = pat.app;
402                 span_lint_and_then(
403                     cx,
404                     if pat.always_deref {
405                         NEEDLESS_BORROW
406                     } else {
407                         REF_BINDING_TO_REFERENCE
408                     },
409                     pat.spans,
410                     "this pattern creates a reference to a reference",
411                     |diag| {
412                         diag.multipart_suggestion("try this", replacements, app);
413                     },
414                 );
415             }
416             self.current_body = None;
417         }
418     }
419 }
420
421 fn try_parse_ref_op<'tcx>(
422     tcx: TyCtxt<'tcx>,
423     typeck: &'tcx TypeckResults<'_>,
424     expr: &'tcx Expr<'_>,
425 ) -> Option<(RefOp, &'tcx Expr<'tcx>)> {
426     let (def_id, arg) = match expr.kind {
427         ExprKind::MethodCall(_, [arg], _) => (typeck.type_dependent_def_id(expr.hir_id)?, arg),
428         ExprKind::Call(
429             Expr {
430                 kind: ExprKind::Path(path),
431                 hir_id,
432                 ..
433             },
434             [arg],
435         ) => (typeck.qpath_res(path, *hir_id).opt_def_id()?, arg),
436         ExprKind::Unary(UnOp::Deref, sub_expr) if !typeck.expr_ty(sub_expr).is_unsafe_ptr() => {
437             return Some((RefOp::Deref, sub_expr));
438         },
439         ExprKind::AddrOf(BorrowKind::Ref, _, sub_expr) => return Some((RefOp::AddrOf, sub_expr)),
440         _ => return None,
441     };
442     if tcx.is_diagnostic_item(sym::deref_method, def_id) {
443         Some((RefOp::Method(Mutability::Not), arg))
444     } else if tcx.trait_of_item(def_id)? == tcx.lang_items().deref_mut_trait()? {
445         Some((RefOp::Method(Mutability::Mut), arg))
446     } else {
447         None
448     }
449 }
450
451 // Checks whether the type for a deref call actually changed the type, not just the mutability of
452 // the reference.
453 fn deref_method_same_type<'tcx>(result_ty: Ty<'tcx>, arg_ty: Ty<'tcx>) -> bool {
454     match (result_ty.kind(), arg_ty.kind()) {
455         (ty::Ref(_, result_ty, _), ty::Ref(_, arg_ty, _)) => result_ty == arg_ty,
456
457         // The result type for a deref method is always a reference
458         // Not matching the previous pattern means the argument type is not a reference
459         // This means that the type did change
460         _ => false,
461     }
462 }
463
464 // Checks whether the parent node is a suitable context for switching from a deref method to the
465 // deref operator.
466 fn is_linted_explicit_deref_position(parent: Option<Node<'_>>, child_id: HirId, child_span: Span) -> bool {
467     let parent = match parent {
468         Some(Node::Expr(e)) if e.span.ctxt() == child_span.ctxt() => e,
469         _ => return true,
470     };
471     match parent.kind {
472         // Leave deref calls in the middle of a method chain.
473         // e.g. x.deref().foo()
474         ExprKind::MethodCall(_, [self_arg, ..], _) if self_arg.hir_id == child_id => false,
475
476         // Leave deref calls resulting in a called function
477         // e.g. (x.deref())()
478         ExprKind::Call(func_expr, _) if func_expr.hir_id == child_id => false,
479
480         // Makes an ugly suggestion
481         // e.g. *x.deref() => *&*x
482         ExprKind::Unary(UnOp::Deref, _)
483         // Postfix expressions would require parens
484         | ExprKind::Match(_, _, MatchSource::TryDesugar | MatchSource::AwaitDesugar)
485         | ExprKind::Field(..)
486         | ExprKind::Index(..)
487         | ExprKind::Err => false,
488
489         ExprKind::Box(..)
490         | ExprKind::ConstBlock(..)
491         | ExprKind::Array(_)
492         | ExprKind::Call(..)
493         | ExprKind::MethodCall(..)
494         | ExprKind::Tup(..)
495         | ExprKind::Binary(..)
496         | ExprKind::Unary(..)
497         | ExprKind::Lit(..)
498         | ExprKind::Cast(..)
499         | ExprKind::Type(..)
500         | ExprKind::DropTemps(..)
501         | ExprKind::If(..)
502         | ExprKind::Loop(..)
503         | ExprKind::Match(..)
504         | ExprKind::Let(..)
505         | ExprKind::Closure(..)
506         | ExprKind::Block(..)
507         | ExprKind::Assign(..)
508         | ExprKind::AssignOp(..)
509         | ExprKind::Path(..)
510         | ExprKind::AddrOf(..)
511         | ExprKind::Break(..)
512         | ExprKind::Continue(..)
513         | ExprKind::Ret(..)
514         | ExprKind::InlineAsm(..)
515         | ExprKind::Struct(..)
516         | ExprKind::Repeat(..)
517         | ExprKind::Yield(..) => true,
518     }
519 }
520
521 /// Checks if the given expression is in a position which can be auto-reborrowed.
522 /// Note: This is only correct assuming auto-deref is already occurring.
523 fn is_auto_reborrow_position(parent: Option<Node<'_>>) -> bool {
524     match parent {
525         Some(Node::Expr(parent)) => matches!(parent.kind, ExprKind::MethodCall(..) | ExprKind::Call(..)),
526         Some(Node::Local(_)) => true,
527         _ => false,
528     }
529 }
530
531 /// Checks if the given expression is a position which can auto-borrow.
532 fn is_auto_borrow_position(parent: Option<Node<'_>>, child_id: HirId) -> bool {
533     if let Some(Node::Expr(parent)) = parent {
534         match parent.kind {
535             // ExprKind::MethodCall(_, [self_arg, ..], _) => self_arg.hir_id == child_id,
536             ExprKind::Field(..) => true,
537             ExprKind::Call(f, _) => f.hir_id == child_id,
538             _ => false,
539         }
540     } else {
541         false
542     }
543 }
544
545 /// Adjustments are sometimes made in the parent block rather than the expression itself.
546 fn find_adjustments<'tcx>(
547     tcx: TyCtxt<'tcx>,
548     typeck: &'tcx TypeckResults<'tcx>,
549     expr: &'tcx Expr<'tcx>,
550 ) -> &'tcx [Adjustment<'tcx>] {
551     let map = tcx.hir();
552     let mut iter = map.parent_iter(expr.hir_id);
553     let mut prev = expr;
554
555     loop {
556         match typeck.expr_adjustments(prev) {
557             [] => (),
558             a => break a,
559         };
560
561         match iter.next().map(|(_, x)| x) {
562             Some(Node::Block(_)) => {
563                 if let Some((_, Node::Expr(e))) = iter.next() {
564                     prev = e;
565                 } else {
566                     // This shouldn't happen. Blocks are always contained in an expression.
567                     break &[];
568                 }
569             },
570             Some(Node::Expr(&Expr {
571                 kind: ExprKind::Break(Destination { target_id: Ok(id), .. }, _),
572                 ..
573             })) => {
574                 if let Some(Node::Expr(e)) = map.find(id) {
575                     prev = e;
576                     iter = map.parent_iter(id);
577                 } else {
578                     // This shouldn't happen. The destination should exist.
579                     break &[];
580                 }
581             },
582             _ => break &[],
583         }
584     }
585 }
586
587 #[expect(clippy::needless_pass_by_value)]
588 fn report<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>, state: State, data: StateData) {
589     match state {
590         State::DerefMethod {
591             ty_changed_count,
592             is_final_ufcs,
593             target_mut,
594         } => {
595             let mut app = Applicability::MachineApplicable;
596             let (expr_str, expr_is_macro_call) = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app);
597             let ty = cx.typeck_results().expr_ty(expr);
598             let (_, ref_count) = peel_mid_ty_refs(ty);
599             let deref_str = if ty_changed_count >= ref_count && ref_count != 0 {
600                 // a deref call changing &T -> &U requires two deref operators the first time
601                 // this occurs. One to remove the reference, a second to call the deref impl.
602                 "*".repeat(ty_changed_count + 1)
603             } else {
604                 "*".repeat(ty_changed_count)
605             };
606             let addr_of_str = if ty_changed_count < ref_count {
607                 // Check if a reborrow from &mut T -> &T is required.
608                 if target_mut == Mutability::Not && matches!(ty.kind(), ty::Ref(_, _, Mutability::Mut)) {
609                     "&*"
610                 } else {
611                     ""
612                 }
613             } else if target_mut == Mutability::Mut {
614                 "&mut "
615             } else {
616                 "&"
617             };
618
619             let expr_str = if !expr_is_macro_call && is_final_ufcs && expr.precedence().order() < PREC_PREFIX {
620                 format!("({})", expr_str)
621             } else {
622                 expr_str.into_owned()
623             };
624
625             span_lint_and_sugg(
626                 cx,
627                 EXPLICIT_DEREF_METHODS,
628                 data.span,
629                 match target_mut {
630                     Mutability::Not => "explicit `deref` method call",
631                     Mutability::Mut => "explicit `deref_mut` method call",
632                 },
633                 "try this",
634                 format!("{}{}{}", addr_of_str, deref_str, expr_str),
635                 app,
636             );
637         },
638         State::DerefedBorrow {
639             required_precedence,
640             msg,
641             ..
642         } => {
643             let mut app = Applicability::MachineApplicable;
644             let snip = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app).0;
645             span_lint_and_sugg(
646                 cx,
647                 NEEDLESS_BORROW,
648                 data.span,
649                 msg,
650                 "change this to",
651                 if required_precedence > expr.precedence().order() && !has_enclosing_paren(&snip) {
652                     format!("({})", snip)
653                 } else {
654                     snip.into()
655                 },
656                 app,
657             );
658         },
659     }
660 }
661
662 impl Dereferencing {
663     fn check_local_usage<'tcx>(&mut self, cx: &LateContext<'tcx>, e: &Expr<'tcx>, local: HirId) {
664         if let Some(outer_pat) = self.ref_locals.get_mut(&local) {
665             if let Some(pat) = outer_pat {
666                 // Check for auto-deref
667                 if !matches!(
668                     cx.typeck_results().expr_adjustments(e),
669                     [
670                         Adjustment {
671                             kind: Adjust::Deref(_),
672                             ..
673                         },
674                         Adjustment {
675                             kind: Adjust::Deref(_),
676                             ..
677                         },
678                         ..
679                     ]
680                 ) {
681                     match get_parent_expr(cx, e) {
682                         // Field accesses are the same no matter the number of references.
683                         Some(Expr {
684                             kind: ExprKind::Field(..),
685                             ..
686                         }) => (),
687                         Some(&Expr {
688                             span,
689                             kind: ExprKind::Unary(UnOp::Deref, _),
690                             ..
691                         }) if !span.from_expansion() => {
692                             // Remove explicit deref.
693                             let snip = snippet_with_context(cx, e.span, span.ctxt(), "..", &mut pat.app).0;
694                             pat.replacements.push((span, snip.into()));
695                         },
696                         Some(parent) if !parent.span.from_expansion() => {
697                             // Double reference might be needed at this point.
698                             if parent.precedence().order() == PREC_POSTFIX {
699                                 // Parentheses would be needed here, don't lint.
700                                 *outer_pat = None;
701                             } else {
702                                 pat.always_deref = false;
703                                 let snip = snippet_with_context(cx, e.span, parent.span.ctxt(), "..", &mut pat.app).0;
704                                 pat.replacements.push((e.span, format!("&{}", snip)));
705                             }
706                         },
707                         _ if !e.span.from_expansion() => {
708                             // Double reference might be needed at this point.
709                             pat.always_deref = false;
710                             let snip = snippet_with_applicability(cx, e.span, "..", &mut pat.app);
711                             pat.replacements.push((e.span, format!("&{}", snip)));
712                         },
713                         // Edge case for macros. The span of the identifier will usually match the context of the
714                         // binding, but not if the identifier was created in a macro. e.g. `concat_idents` and proc
715                         // macros
716                         _ => *outer_pat = None,
717                     }
718                 }
719             }
720         }
721     }
722 }