]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/dereference.rs
Auto merge of #9487 - kraktus:question_mark, r=Jarcho
[rust.git] / clippy_lints / src / dereference.rs
1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_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::{expr_sig, is_copy, peel_mid_ty_refs, ty_sig, variant_of_res};
5 use clippy_utils::{
6     fn_def_id, get_parent_expr, get_parent_expr_for_hir, is_lint_allowed, meets_msrv, msrvs, path_to_local,
7     walk_to_expr_usage,
8 };
9 use rustc_ast::util::parser::{PREC_POSTFIX, PREC_PREFIX};
10 use rustc_data_structures::fx::FxIndexMap;
11 use rustc_errors::Applicability;
12 use rustc_hir::intravisit::{walk_ty, Visitor};
13 use rustc_hir::{
14     self as hir, def_id::DefId, BindingAnnotation, Body, BodyId, BorrowKind, Closure, Expr, ExprKind, FnRetTy,
15     GenericArg, HirId, ImplItem, ImplItemKind, Item, ItemKind, Local, MatchSource, Mutability, Node, Pat, PatKind,
16     Path, QPath, TraitItem, TraitItemKind, TyKind, UnOp,
17 };
18 use rustc_index::bit_set::BitSet;
19 use rustc_infer::infer::TyCtxtInferExt;
20 use rustc_lint::{LateContext, LateLintPass};
21 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
22 use rustc_middle::ty::{
23     self, subst::Subst, Binder, BoundVariableKind, EarlyBinder, FnSig, GenericArgKind, List, ParamTy, PredicateKind,
24     ProjectionPredicate, Ty, TyCtxt, TypeVisitable, TypeckResults,
25 };
26 use rustc_semver::RustcVersion;
27 use rustc_session::{declare_tool_lint, impl_lint_pass};
28 use rustc_span::{symbol::sym, Span, Symbol, DUMMY_SP};
29 use rustc_trait_selection::infer::InferCtxtExt as _;
30 use rustc_trait_selection::traits::{query::evaluate_obligation::InferCtxtExt as _, Obligation, ObligationCause};
31 use std::collections::VecDeque;
32
33 declare_clippy_lint! {
34     /// ### What it does
35     /// Checks for explicit `deref()` or `deref_mut()` method calls.
36     ///
37     /// ### Why is this bad?
38     /// Dereferencing by `&*x` or `&mut *x` is clearer and more concise,
39     /// when not part of a method chain.
40     ///
41     /// ### Example
42     /// ```rust
43     /// use std::ops::Deref;
44     /// let a: &mut String = &mut String::from("foo");
45     /// let b: &str = a.deref();
46     /// ```
47     ///
48     /// Use instead:
49     /// ```rust
50     /// let a: &mut String = &mut String::from("foo");
51     /// let b = &*a;
52     /// ```
53     ///
54     /// This lint excludes:
55     /// ```rust,ignore
56     /// let _ = d.unwrap().deref();
57     /// ```
58     #[clippy::version = "1.44.0"]
59     pub EXPLICIT_DEREF_METHODS,
60     pedantic,
61     "Explicit use of deref or deref_mut method while not in a method chain."
62 }
63
64 declare_clippy_lint! {
65     /// ### What it does
66     /// Checks for address of operations (`&`) that are going to
67     /// be dereferenced immediately by the compiler.
68     ///
69     /// ### Why is this bad?
70     /// Suggests that the receiver of the expression borrows
71     /// the expression.
72     ///
73     /// ### Example
74     /// ```rust
75     /// fn fun(_a: &i32) {}
76     ///
77     /// let x: &i32 = &&&&&&5;
78     /// fun(&x);
79     /// ```
80     ///
81     /// Use instead:
82     /// ```rust
83     /// # fn fun(_a: &i32) {}
84     /// let x: &i32 = &5;
85     /// fun(x);
86     /// ```
87     #[clippy::version = "pre 1.29.0"]
88     pub NEEDLESS_BORROW,
89     style,
90     "taking a reference that is going to be automatically dereferenced"
91 }
92
93 declare_clippy_lint! {
94     /// ### What it does
95     /// Checks for `ref` bindings which create a reference to a reference.
96     ///
97     /// ### Why is this bad?
98     /// The address-of operator at the use site is clearer about the need for a reference.
99     ///
100     /// ### Example
101     /// ```rust
102     /// let x = Some("");
103     /// if let Some(ref x) = x {
104     ///     // use `x` here
105     /// }
106     /// ```
107     ///
108     /// Use instead:
109     /// ```rust
110     /// let x = Some("");
111     /// if let Some(x) = x {
112     ///     // use `&x` here
113     /// }
114     /// ```
115     #[clippy::version = "1.54.0"]
116     pub REF_BINDING_TO_REFERENCE,
117     pedantic,
118     "`ref` binding to a reference"
119 }
120
121 declare_clippy_lint! {
122     /// ### What it does
123     /// Checks for dereferencing expressions which would be covered by auto-deref.
124     ///
125     /// ### Why is this bad?
126     /// This unnecessarily complicates the code.
127     ///
128     /// ### Example
129     /// ```rust
130     /// let x = String::new();
131     /// let y: &str = &*x;
132     /// ```
133     /// Use instead:
134     /// ```rust
135     /// let x = String::new();
136     /// let y: &str = &x;
137     /// ```
138     #[clippy::version = "1.64.0"]
139     pub EXPLICIT_AUTO_DEREF,
140     complexity,
141     "dereferencing when the compiler would automatically dereference"
142 }
143
144 impl_lint_pass!(Dereferencing => [
145     EXPLICIT_DEREF_METHODS,
146     NEEDLESS_BORROW,
147     REF_BINDING_TO_REFERENCE,
148     EXPLICIT_AUTO_DEREF,
149 ]);
150
151 #[derive(Default)]
152 pub struct Dereferencing {
153     state: Option<(State, StateData)>,
154
155     // While parsing a `deref` method call in ufcs form, the path to the function is itself an
156     // expression. This is to store the id of that expression so it can be skipped when
157     // `check_expr` is called for it.
158     skip_expr: Option<HirId>,
159
160     /// The body the first local was found in. Used to emit lints when the traversal of the body has
161     /// been finished. Note we can't lint at the end of every body as they can be nested within each
162     /// other.
163     current_body: Option<BodyId>,
164
165     /// The list of locals currently being checked by the lint.
166     /// If the value is `None`, then the binding has been seen as a ref pattern, but is not linted.
167     /// This is needed for or patterns where one of the branches can be linted, but another can not
168     /// be.
169     ///
170     /// e.g. `m!(x) | Foo::Bar(ref x)`
171     ref_locals: FxIndexMap<HirId, Option<RefPat>>,
172
173     // `IntoIterator` for arrays requires Rust 1.53.
174     msrv: Option<RustcVersion>,
175 }
176
177 impl Dereferencing {
178     #[must_use]
179     pub fn new(msrv: Option<RustcVersion>) -> Self {
180         Self {
181             msrv,
182             ..Dereferencing::default()
183         }
184     }
185 }
186
187 struct StateData {
188     /// Span of the top level expression
189     span: Span,
190     hir_id: HirId,
191     position: Position,
192 }
193
194 struct DerefedBorrow {
195     count: usize,
196     msg: &'static str,
197     snip_expr: Option<HirId>,
198 }
199
200 enum State {
201     // Any number of deref method calls.
202     DerefMethod {
203         // The number of calls in a sequence which changed the referenced type
204         ty_changed_count: usize,
205         is_final_ufcs: bool,
206         /// The required mutability
207         target_mut: Mutability,
208     },
209     DerefedBorrow(DerefedBorrow),
210     ExplicitDeref {
211         mutability: Option<Mutability>,
212     },
213     ExplicitDerefField {
214         name: Symbol,
215     },
216     Reborrow {
217         mutability: Mutability,
218     },
219     Borrow {
220         mutability: Mutability,
221     },
222 }
223
224 // A reference operation considered by this lint pass
225 enum RefOp {
226     Method(Mutability),
227     Deref,
228     AddrOf(Mutability),
229 }
230
231 struct RefPat {
232     /// Whether every usage of the binding is dereferenced.
233     always_deref: bool,
234     /// The spans of all the ref bindings for this local.
235     spans: Vec<Span>,
236     /// The applicability of this suggestion.
237     app: Applicability,
238     /// All the replacements which need to be made.
239     replacements: Vec<(Span, String)>,
240     /// The [`HirId`] that the lint should be emitted at.
241     hir_id: HirId,
242 }
243
244 impl<'tcx> LateLintPass<'tcx> for Dereferencing {
245     #[expect(clippy::too_many_lines)]
246     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
247         // Skip path expressions from deref calls. e.g. `Deref::deref(e)`
248         if Some(expr.hir_id) == self.skip_expr.take() {
249             return;
250         }
251
252         if let Some(local) = path_to_local(expr) {
253             self.check_local_usage(cx, expr, local);
254         }
255
256         // Stop processing sub expressions when a macro call is seen
257         if expr.span.from_expansion() {
258             if let Some((state, data)) = self.state.take() {
259                 report(cx, expr, state, data);
260             }
261             return;
262         }
263
264         let typeck = cx.typeck_results();
265         let (kind, sub_expr) = if let Some(x) = try_parse_ref_op(cx.tcx, typeck, expr) {
266             x
267         } else {
268             // The whole chain of reference operations has been seen
269             if let Some((state, data)) = self.state.take() {
270                 report(cx, expr, state, data);
271             }
272             return;
273         };
274
275         match (self.state.take(), kind) {
276             (None, kind) => {
277                 let expr_ty = typeck.expr_ty(expr);
278                 let (position, adjustments) = walk_parents(cx, expr, self.msrv);
279
280                 match kind {
281                     RefOp::Deref => {
282                         if let Position::FieldAccess(name) = position
283                             && !ty_contains_field(typeck.expr_ty(sub_expr), name)
284                         {
285                             self.state = Some((
286                                 State::ExplicitDerefField { name },
287                                 StateData { span: expr.span, hir_id: expr.hir_id, position },
288                             ));
289                         } else if position.is_deref_stable() {
290                             self.state = Some((
291                                 State::ExplicitDeref { mutability: None },
292                                 StateData { span: expr.span, hir_id: expr.hir_id, position },
293                             ));
294                         }
295                     }
296                     RefOp::Method(target_mut)
297                         if !is_lint_allowed(cx, EXPLICIT_DEREF_METHODS, expr.hir_id)
298                             && position.lint_explicit_deref() =>
299                     {
300                         let ty_changed_count = usize::from(!deref_method_same_type(expr_ty, typeck.expr_ty(sub_expr)));
301                         self.state = Some((
302                             State::DerefMethod {
303                                 ty_changed_count,
304                                 is_final_ufcs: matches!(expr.kind, ExprKind::Call(..)),
305                                 target_mut,
306                             },
307                             StateData {
308                                 span: expr.span,
309                                 hir_id: expr.hir_id,
310                                 position
311                             },
312                         ));
313                     },
314                     RefOp::AddrOf(mutability) => {
315                         // Find the number of times the borrow is auto-derefed.
316                         let mut iter = adjustments.iter();
317                         let mut deref_count = 0usize;
318                         let next_adjust = loop {
319                             match iter.next() {
320                                 Some(adjust) => {
321                                     if !matches!(adjust.kind, Adjust::Deref(_)) {
322                                         break Some(adjust);
323                                     } else if !adjust.target.is_ref() {
324                                         deref_count += 1;
325                                         break iter.next();
326                                     }
327                                     deref_count += 1;
328                                 },
329                                 None => break None,
330                             };
331                         };
332
333                         // Determine the required number of references before any can be removed. In all cases the
334                         // reference made by the current expression will be removed. After that there are four cases to
335                         // handle.
336                         //
337                         // 1. Auto-borrow will trigger in the current position, so no further references are required.
338                         // 2. Auto-deref ends at a reference, or the underlying type, so one extra needs to be left to
339                         //    handle the automatically inserted re-borrow.
340                         // 3. Auto-deref hits a user-defined `Deref` impl, so at least one reference needs to exist to
341                         //    start auto-deref.
342                         // 4. If the chain of non-user-defined derefs ends with a mutable re-borrow, and re-borrow
343                         //    adjustments will not be inserted automatically, then leave one further reference to avoid
344                         //    moving a mutable borrow.
345                         //    e.g.
346                         //        fn foo<T>(x: &mut Option<&mut T>, y: &mut T) {
347                         //            let x = match x {
348                         //                // Removing the borrow will cause `x` to be moved
349                         //                Some(x) => &mut *x,
350                         //                None => y
351                         //            };
352                         //        }
353                         let deref_msg =
354                             "this expression creates a reference which is immediately dereferenced by the compiler";
355                         let borrow_msg = "this expression borrows a value the compiler would automatically borrow";
356                         let impl_msg = "the borrowed expression implements the required traits";
357
358                         let (required_refs, msg, snip_expr) = if position.can_auto_borrow() {
359                             (1, if deref_count == 1 { borrow_msg } else { deref_msg }, None)
360                         } else if let Position::ImplArg(hir_id) = position {
361                             (0, impl_msg, Some(hir_id))
362                         } else if let Some(&Adjust::Borrow(AutoBorrow::Ref(_, mutability))) =
363                             next_adjust.map(|a| &a.kind)
364                         {
365                             if matches!(mutability, AutoBorrowMutability::Mut { .. }) && !position.is_reborrow_stable()
366                             {
367                                 (3, deref_msg, None)
368                             } else {
369                                 (2, deref_msg, None)
370                             }
371                         } else {
372                             (2, deref_msg, None)
373                         };
374
375                         if deref_count >= required_refs {
376                             self.state = Some((
377                                 State::DerefedBorrow(DerefedBorrow {
378                                     // One of the required refs is for the current borrow expression, the remaining ones
379                                     // can't be removed without breaking the code. See earlier comment.
380                                     count: deref_count - required_refs,
381                                     msg,
382                                     snip_expr,
383                                 }),
384                                 StateData { span: expr.span, hir_id: expr.hir_id, position },
385                             ));
386                         } else if position.is_deref_stable()
387                             // Auto-deref doesn't combine with other adjustments
388                             && next_adjust.map_or(true, |a| matches!(a.kind, Adjust::Deref(_) | Adjust::Borrow(_)))
389                             && iter.all(|a| matches!(a.kind, Adjust::Deref(_) | Adjust::Borrow(_)))
390                         {
391                             self.state = Some((
392                                 State::Borrow { mutability },
393                                 StateData {
394                                     span: expr.span,
395                                     hir_id: expr.hir_id,
396                                     position
397                                 },
398                             ));
399                         }
400                     },
401                     RefOp::Method(..) => (),
402                 }
403             },
404             (
405                 Some((
406                     State::DerefMethod {
407                         target_mut,
408                         ty_changed_count,
409                         ..
410                     },
411                     data,
412                 )),
413                 RefOp::Method(_),
414             ) => {
415                 self.state = Some((
416                     State::DerefMethod {
417                         ty_changed_count: if deref_method_same_type(typeck.expr_ty(expr), typeck.expr_ty(sub_expr)) {
418                             ty_changed_count
419                         } else {
420                             ty_changed_count + 1
421                         },
422                         is_final_ufcs: matches!(expr.kind, ExprKind::Call(..)),
423                         target_mut,
424                     },
425                     data,
426                 ));
427             },
428             (Some((State::DerefedBorrow(state), data)), RefOp::AddrOf(_)) if state.count != 0 => {
429                 self.state = Some((
430                     State::DerefedBorrow(DerefedBorrow {
431                         count: state.count - 1,
432                         ..state
433                     }),
434                     data,
435                 ));
436             },
437             (Some((State::DerefedBorrow(state), data)), RefOp::AddrOf(mutability)) => {
438                 let position = data.position;
439                 report(cx, expr, State::DerefedBorrow(state), data);
440                 if position.is_deref_stable() {
441                     self.state = Some((
442                         State::Borrow { mutability },
443                         StateData {
444                             span: expr.span,
445                             hir_id: expr.hir_id,
446                             position,
447                         },
448                     ));
449                 }
450             },
451             (Some((State::DerefedBorrow(state), data)), RefOp::Deref) => {
452                 let position = data.position;
453                 report(cx, expr, State::DerefedBorrow(state), data);
454                 if let Position::FieldAccess(name) = position
455                     && !ty_contains_field(typeck.expr_ty(sub_expr), name)
456                 {
457                     self.state = Some((
458                         State::ExplicitDerefField { name },
459                         StateData { span: expr.span, hir_id: expr.hir_id, position },
460                     ));
461                 } else if position.is_deref_stable() {
462                     self.state = Some((
463                         State::ExplicitDeref { mutability: None },
464                         StateData { span: expr.span, hir_id: expr.hir_id, position },
465                     ));
466                 }
467             },
468
469             (Some((State::Borrow { mutability }, data)), RefOp::Deref) => {
470                 if typeck.expr_ty(sub_expr).is_ref() {
471                     self.state = Some((State::Reborrow { mutability }, data));
472                 } else {
473                     self.state = Some((
474                         State::ExplicitDeref {
475                             mutability: Some(mutability),
476                         },
477                         data,
478                     ));
479                 }
480             },
481             (Some((State::Reborrow { mutability }, data)), RefOp::Deref) => {
482                 self.state = Some((
483                     State::ExplicitDeref {
484                         mutability: Some(mutability),
485                     },
486                     data,
487                 ));
488             },
489             (state @ Some((State::ExplicitDeref { .. }, _)), RefOp::Deref) => {
490                 self.state = state;
491             },
492             (Some((State::ExplicitDerefField { name }, data)), RefOp::Deref)
493                 if !ty_contains_field(typeck.expr_ty(sub_expr), name) =>
494             {
495                 self.state = Some((State::ExplicitDerefField { name }, data));
496             },
497
498             (Some((state, data)), _) => report(cx, expr, state, data),
499         }
500     }
501
502     fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
503         if let PatKind::Binding(BindingAnnotation::REF, id, name, _) = pat.kind {
504             if let Some(opt_prev_pat) = self.ref_locals.get_mut(&id) {
505                 // This binding id has been seen before. Add this pattern to the list of changes.
506                 if let Some(prev_pat) = opt_prev_pat {
507                     if pat.span.from_expansion() {
508                         // Doesn't match the context of the previous pattern. Can't lint here.
509                         *opt_prev_pat = None;
510                     } else {
511                         prev_pat.spans.push(pat.span);
512                         prev_pat.replacements.push((
513                             pat.span,
514                             snippet_with_context(cx, name.span, pat.span.ctxt(), "..", &mut prev_pat.app)
515                                 .0
516                                 .into(),
517                         ));
518                     }
519                 }
520                 return;
521             }
522
523             if_chain! {
524                 if !pat.span.from_expansion();
525                 if let ty::Ref(_, tam, _) = *cx.typeck_results().pat_ty(pat).kind();
526                 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
527                 if let ty::Ref(_, _, Mutability::Not) = *tam.kind();
528                 then {
529                     let mut app = Applicability::MachineApplicable;
530                     let snip = snippet_with_context(cx, name.span, pat.span.ctxt(), "..", &mut app).0;
531                     self.current_body = self.current_body.or(cx.enclosing_body);
532                     self.ref_locals.insert(
533                         id,
534                         Some(RefPat {
535                             always_deref: true,
536                             spans: vec![pat.span],
537                             app,
538                             replacements: vec![(pat.span, snip.into())],
539                             hir_id: pat.hir_id,
540                         }),
541                     );
542                 }
543             }
544         }
545     }
546
547     fn check_body_post(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
548         if Some(body.id()) == self.current_body {
549             for pat in self.ref_locals.drain(..).filter_map(|(_, x)| x) {
550                 let replacements = pat.replacements;
551                 let app = pat.app;
552                 let lint = if pat.always_deref {
553                     NEEDLESS_BORROW
554                 } else {
555                     REF_BINDING_TO_REFERENCE
556                 };
557                 span_lint_hir_and_then(
558                     cx,
559                     lint,
560                     pat.hir_id,
561                     pat.spans,
562                     "this pattern creates a reference to a reference",
563                     |diag| {
564                         diag.multipart_suggestion("try this", replacements, app);
565                     },
566                 );
567             }
568             self.current_body = None;
569         }
570     }
571
572     extract_msrv_attr!(LateContext);
573 }
574
575 fn try_parse_ref_op<'tcx>(
576     tcx: TyCtxt<'tcx>,
577     typeck: &'tcx TypeckResults<'_>,
578     expr: &'tcx Expr<'_>,
579 ) -> Option<(RefOp, &'tcx Expr<'tcx>)> {
580     let (def_id, arg) = match expr.kind {
581         ExprKind::MethodCall(_, arg, [], _) => (typeck.type_dependent_def_id(expr.hir_id)?, arg),
582         ExprKind::Call(
583             Expr {
584                 kind: ExprKind::Path(path),
585                 hir_id,
586                 ..
587             },
588             [arg],
589         ) => (typeck.qpath_res(path, *hir_id).opt_def_id()?, arg),
590         ExprKind::Unary(UnOp::Deref, sub_expr) if !typeck.expr_ty(sub_expr).is_unsafe_ptr() => {
591             return Some((RefOp::Deref, sub_expr));
592         },
593         ExprKind::AddrOf(BorrowKind::Ref, mutability, sub_expr) => return Some((RefOp::AddrOf(mutability), sub_expr)),
594         _ => return None,
595     };
596     if tcx.is_diagnostic_item(sym::deref_method, def_id) {
597         Some((RefOp::Method(Mutability::Not), arg))
598     } else if tcx.trait_of_item(def_id)? == tcx.lang_items().deref_mut_trait()? {
599         Some((RefOp::Method(Mutability::Mut), arg))
600     } else {
601         None
602     }
603 }
604
605 // Checks whether the type for a deref call actually changed the type, not just the mutability of
606 // the reference.
607 fn deref_method_same_type<'tcx>(result_ty: Ty<'tcx>, arg_ty: Ty<'tcx>) -> bool {
608     match (result_ty.kind(), arg_ty.kind()) {
609         (ty::Ref(_, result_ty, _), ty::Ref(_, arg_ty, _)) => result_ty == arg_ty,
610
611         // The result type for a deref method is always a reference
612         // Not matching the previous pattern means the argument type is not a reference
613         // This means that the type did change
614         _ => false,
615     }
616 }
617
618 /// The position of an expression relative to it's parent.
619 #[derive(Clone, Copy)]
620 enum Position {
621     MethodReceiver,
622     /// The method is defined on a reference type. e.g. `impl Foo for &T`
623     MethodReceiverRefImpl,
624     Callee,
625     ImplArg(HirId),
626     FieldAccess(Symbol),
627     Postfix,
628     Deref,
629     /// Any other location which will trigger auto-deref to a specific time.
630     /// Contains the precedence of the parent expression and whether the target type is sized.
631     DerefStable(i8, bool),
632     /// Any other location which will trigger auto-reborrowing.
633     /// Contains the precedence of the parent expression.
634     ReborrowStable(i8),
635     /// Contains the precedence of the parent expression.
636     Other(i8),
637 }
638 impl Position {
639     fn is_deref_stable(self) -> bool {
640         matches!(self, Self::DerefStable(..))
641     }
642
643     fn is_reborrow_stable(self) -> bool {
644         matches!(self, Self::DerefStable(..) | Self::ReborrowStable(_))
645     }
646
647     fn can_auto_borrow(self) -> bool {
648         matches!(self, Self::MethodReceiver | Self::FieldAccess(_) | Self::Callee)
649     }
650
651     fn lint_explicit_deref(self) -> bool {
652         matches!(self, Self::Other(_) | Self::DerefStable(..) | Self::ReborrowStable(_))
653     }
654
655     fn precedence(self) -> i8 {
656         match self {
657             Self::MethodReceiver
658             | Self::MethodReceiverRefImpl
659             | Self::Callee
660             | Self::FieldAccess(_)
661             | Self::Postfix => PREC_POSTFIX,
662             Self::ImplArg(_) | Self::Deref => PREC_PREFIX,
663             Self::DerefStable(p, _) | Self::ReborrowStable(p) | Self::Other(p) => p,
664         }
665     }
666 }
667
668 /// Walks up the parent expressions attempting to determine both how stable the auto-deref result
669 /// is, and which adjustments will be applied to it. Note this will not consider auto-borrow
670 /// locations as those follow different rules.
671 #[expect(clippy::too_many_lines)]
672 fn walk_parents<'tcx>(
673     cx: &LateContext<'tcx>,
674     e: &'tcx Expr<'_>,
675     msrv: Option<RustcVersion>,
676 ) -> (Position, &'tcx [Adjustment<'tcx>]) {
677     let mut adjustments = [].as_slice();
678     let mut precedence = 0i8;
679     let ctxt = e.span.ctxt();
680     let position = walk_to_expr_usage(cx, e, &mut |parent, child_id| {
681         // LocalTableInContext returns the wrong lifetime, so go use `expr_adjustments` instead.
682         if adjustments.is_empty() && let Node::Expr(e) = cx.tcx.hir().get(child_id) {
683             adjustments = cx.typeck_results().expr_adjustments(e);
684         }
685         match parent {
686             Node::Local(Local { ty: Some(ty), span, .. }) if span.ctxt() == ctxt => {
687                 Some(binding_ty_auto_deref_stability(cx, ty, precedence, List::empty()))
688             },
689             Node::Item(&Item {
690                 kind: ItemKind::Static(..) | ItemKind::Const(..),
691                 def_id,
692                 span,
693                 ..
694             })
695             | Node::TraitItem(&TraitItem {
696                 kind: TraitItemKind::Const(..),
697                 def_id,
698                 span,
699                 ..
700             })
701             | Node::ImplItem(&ImplItem {
702                 kind: ImplItemKind::Const(..),
703                 def_id,
704                 span,
705                 ..
706             }) if span.ctxt() == ctxt => {
707                 let ty = cx.tcx.type_of(def_id);
708                 Some(ty_auto_deref_stability(cx, ty, precedence).position_for_result(cx))
709             },
710
711             Node::Item(&Item {
712                 kind: ItemKind::Fn(..),
713                 def_id,
714                 span,
715                 ..
716             })
717             | Node::TraitItem(&TraitItem {
718                 kind: TraitItemKind::Fn(..),
719                 def_id,
720                 span,
721                 ..
722             })
723             | Node::ImplItem(&ImplItem {
724                 kind: ImplItemKind::Fn(..),
725                 def_id,
726                 span,
727                 ..
728             }) if span.ctxt() == ctxt => {
729                 let output = cx
730                     .tcx
731                     .erase_late_bound_regions(cx.tcx.fn_sig(def_id.to_def_id()).output());
732                 Some(ty_auto_deref_stability(cx, output, precedence).position_for_result(cx))
733             },
734
735             Node::ExprField(field) if field.span.ctxt() == ctxt => match get_parent_expr_for_hir(cx, field.hir_id) {
736                 Some(Expr {
737                     hir_id,
738                     kind: ExprKind::Struct(path, ..),
739                     ..
740                 }) => variant_of_res(cx, cx.qpath_res(path, *hir_id))
741                     .and_then(|variant| variant.fields.iter().find(|f| f.name == field.ident.name))
742                     .map(|field_def| {
743                         ty_auto_deref_stability(cx, cx.tcx.type_of(field_def.did), precedence).position_for_arg()
744                     }),
745                 _ => None,
746             },
747
748             Node::Expr(parent) if parent.span.ctxt() == ctxt => match parent.kind {
749                 ExprKind::Ret(_) => {
750                     let owner_id = cx.tcx.hir().body_owner(cx.enclosing_body.unwrap());
751                     Some(
752                         if let Node::Expr(
753                             closure_expr @ Expr {
754                                 kind: ExprKind::Closure(closure),
755                                 ..
756                             },
757                         ) = cx.tcx.hir().get(owner_id)
758                         {
759                             closure_result_position(cx, closure, cx.typeck_results().expr_ty(closure_expr), precedence)
760                         } else {
761                             let output = cx
762                                 .tcx
763                                 .erase_late_bound_regions(cx.tcx.fn_sig(cx.tcx.hir().local_def_id(owner_id)).output());
764                             ty_auto_deref_stability(cx, output, precedence).position_for_result(cx)
765                         },
766                     )
767                 },
768                 ExprKind::Closure(closure) => Some(closure_result_position(
769                     cx,
770                     closure,
771                     cx.typeck_results().expr_ty(parent),
772                     precedence,
773                 )),
774                 ExprKind::Call(func, _) if func.hir_id == child_id => {
775                     (child_id == e.hir_id).then_some(Position::Callee)
776                 },
777                 ExprKind::Call(func, args) => args
778                     .iter()
779                     .position(|arg| arg.hir_id == child_id)
780                     .zip(expr_sig(cx, func))
781                     .and_then(|(i, sig)| {
782                         sig.input_with_hir(i).map(|(hir_ty, ty)| match hir_ty {
783                             // Type inference for closures can depend on how they're called. Only go by the explicit
784                             // types here.
785                             Some(hir_ty) => binding_ty_auto_deref_stability(cx, hir_ty, precedence, ty.bound_vars()),
786                             None => {
787                                 if let ty::Param(param_ty) = ty.skip_binder().kind() {
788                                     needless_borrow_impl_arg_position(cx, parent, i, *param_ty, e, precedence, msrv)
789                                 } else {
790                                     ty_auto_deref_stability(cx, cx.tcx.erase_late_bound_regions(ty), precedence)
791                                         .position_for_arg()
792                                 }
793                             },
794                         })
795                     }),
796                 ExprKind::MethodCall(_, receiver, args, _) => {
797                     let id = cx.typeck_results().type_dependent_def_id(parent.hir_id).unwrap();
798                     if receiver.hir_id == child_id {
799                         // Check for calls to trait methods where the trait is implemented on a reference.
800                         // Two cases need to be handled:
801                         // * `self` methods on `&T` will never have auto-borrow
802                         // * `&self` methods on `&T` can have auto-borrow, but `&self` methods on `T` will take
803                         //   priority.
804                         if e.hir_id != child_id {
805                             return Some(Position::ReborrowStable(precedence))
806                         } else if let Some(trait_id) = cx.tcx.trait_of_item(id)
807                             && let arg_ty = cx.tcx.erase_regions(cx.typeck_results().expr_ty_adjusted(e))
808                             && let ty::Ref(_, sub_ty, _) = *arg_ty.kind()
809                             && let subs = match cx
810                                 .typeck_results()
811                                 .node_substs_opt(parent.hir_id)
812                                 .and_then(|subs| subs.get(1..))
813                             {
814                                 Some(subs) => cx.tcx.mk_substs(subs.iter().copied()),
815                                 None => cx.tcx.mk_substs(std::iter::empty::<ty::subst::GenericArg<'_>>()),
816                             } && let impl_ty = if cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref() {
817                                 // Trait methods taking `&self`
818                                 sub_ty
819                             } else {
820                                 // Trait methods taking `self`
821                                 arg_ty
822                             } && impl_ty.is_ref()
823                             && cx.tcx.infer_ctxt().enter(|infcx|
824                                 infcx
825                                     .type_implements_trait(trait_id, impl_ty, subs, cx.param_env)
826                                     .must_apply_modulo_regions()
827                             )
828                         {
829                             return Some(Position::MethodReceiverRefImpl)
830                         }
831                         return Some(Position::MethodReceiver);
832                     }
833                     args.iter().position(|arg| arg.hir_id == child_id).map(|i| {
834                         let ty = cx.tcx.fn_sig(id).skip_binder().inputs()[i + 1];
835                         if let ty::Param(param_ty) = ty.kind() {
836                             needless_borrow_impl_arg_position(cx, parent, i + 1, *param_ty, e, precedence, msrv)
837                         } else {
838                             ty_auto_deref_stability(
839                                 cx,
840                                 cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).input(i + 1)),
841                                 precedence,
842                             )
843                             .position_for_arg()
844                         }
845                     })
846                 },
847                 ExprKind::Field(child, name) if child.hir_id == e.hir_id => Some(Position::FieldAccess(name.name)),
848                 ExprKind::Unary(UnOp::Deref, child) if child.hir_id == e.hir_id => Some(Position::Deref),
849                 ExprKind::Match(child, _, MatchSource::TryDesugar | MatchSource::AwaitDesugar)
850                 | ExprKind::Index(child, _)
851                     if child.hir_id == e.hir_id =>
852                 {
853                     Some(Position::Postfix)
854                 },
855                 _ if child_id == e.hir_id => {
856                     precedence = parent.precedence().order();
857                     None
858                 },
859                 _ => None,
860             },
861             _ => None,
862         }
863     })
864     .unwrap_or(Position::Other(precedence));
865     (position, adjustments)
866 }
867
868 fn closure_result_position<'tcx>(
869     cx: &LateContext<'tcx>,
870     closure: &'tcx Closure<'_>,
871     ty: Ty<'tcx>,
872     precedence: i8,
873 ) -> Position {
874     match closure.fn_decl.output {
875         FnRetTy::Return(hir_ty) => {
876             if let Some(sig) = ty_sig(cx, ty)
877                 && let Some(output) = sig.output()
878             {
879                 binding_ty_auto_deref_stability(cx, hir_ty, precedence, output.bound_vars())
880             } else {
881                 Position::Other(precedence)
882             }
883         },
884         FnRetTy::DefaultReturn(_) => Position::Other(precedence),
885     }
886 }
887
888 // Checks the stability of auto-deref when assigned to a binding with the given explicit type.
889 //
890 // e.g.
891 // let x = Box::new(Box::new(0u32));
892 // let y1: &Box<_> = x.deref();
893 // let y2: &Box<_> = &x;
894 //
895 // Here `y1` and `y2` would resolve to different types, so the type `&Box<_>` is not stable when
896 // switching to auto-dereferencing.
897 fn binding_ty_auto_deref_stability<'tcx>(
898     cx: &LateContext<'tcx>,
899     ty: &'tcx hir::Ty<'_>,
900     precedence: i8,
901     binder_args: &'tcx List<BoundVariableKind>,
902 ) -> Position {
903     let TyKind::Rptr(_, ty) = &ty.kind else {
904         return Position::Other(precedence);
905     };
906     let mut ty = ty;
907
908     loop {
909         break match ty.ty.kind {
910             TyKind::Rptr(_, ref ref_ty) => {
911                 ty = ref_ty;
912                 continue;
913             },
914             TyKind::Path(
915                 QPath::TypeRelative(_, path)
916                 | QPath::Resolved(
917                     _,
918                     Path {
919                         segments: [.., path], ..
920                     },
921                 ),
922             ) => {
923                 if let Some(args) = path.args
924                     && args.args.iter().any(|arg| match arg {
925                         GenericArg::Infer(_) => true,
926                         GenericArg::Type(ty) => ty_contains_infer(ty),
927                         _ => false,
928                     })
929                 {
930                     Position::ReborrowStable(precedence)
931                 } else {
932                     Position::DerefStable(
933                         precedence,
934                         cx.tcx
935                             .erase_late_bound_regions(Binder::bind_with_vars(
936                                 cx.typeck_results().node_type(ty.ty.hir_id),
937                                 binder_args,
938                             ))
939                             .is_sized(cx.tcx.at(DUMMY_SP), cx.param_env.without_caller_bounds()),
940                     )
941                 }
942             },
943             TyKind::Slice(_) => Position::DerefStable(precedence, false),
944             TyKind::Array(..) | TyKind::Ptr(_) | TyKind::BareFn(_) => Position::DerefStable(precedence, true),
945             TyKind::Never
946             | TyKind::Tup(_)
947             | TyKind::Path(_) => Position::DerefStable(
948                 precedence,
949                 cx.tcx
950                     .erase_late_bound_regions(Binder::bind_with_vars(
951                         cx.typeck_results().node_type(ty.ty.hir_id),
952                         binder_args,
953                     ))
954                     .is_sized(cx.tcx.at(DUMMY_SP), cx.param_env.without_caller_bounds()),
955             ),
956             TyKind::OpaqueDef(..) | TyKind::Infer | TyKind::Typeof(..) | TyKind::TraitObject(..) | TyKind::Err => {
957                 Position::ReborrowStable(precedence)
958             },
959         };
960     }
961 }
962
963 // Checks whether a type is inferred at some point.
964 // e.g. `_`, `Box<_>`, `[_]`
965 fn ty_contains_infer(ty: &hir::Ty<'_>) -> bool {
966     struct V(bool);
967     impl Visitor<'_> for V {
968         fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
969             if self.0
970                 || matches!(
971                     ty.kind,
972                     TyKind::OpaqueDef(..) | TyKind::Infer | TyKind::Typeof(_) | TyKind::Err
973                 )
974             {
975                 self.0 = true;
976             } else {
977                 walk_ty(self, ty);
978             }
979         }
980
981         fn visit_generic_arg(&mut self, arg: &GenericArg<'_>) {
982             if self.0 || matches!(arg, GenericArg::Infer(_)) {
983                 self.0 = true;
984             } else if let GenericArg::Type(ty) = arg {
985                 self.visit_ty(ty);
986             }
987         }
988     }
989     let mut v = V(false);
990     v.visit_ty(ty);
991     v.0
992 }
993
994 // Checks whether:
995 // * child is an expression of the form `&e` in an argument position requiring an `impl Trait`
996 // * `e`'s type implements `Trait` and is copyable
997 // If the conditions are met, returns `Some(Position::ImplArg(..))`; otherwise, returns `None`.
998 //   The "is copyable" condition is to avoid the case where removing the `&` means `e` would have to
999 // be moved, but it cannot be.
1000 fn needless_borrow_impl_arg_position<'tcx>(
1001     cx: &LateContext<'tcx>,
1002     parent: &Expr<'tcx>,
1003     arg_index: usize,
1004     param_ty: ParamTy,
1005     mut expr: &Expr<'tcx>,
1006     precedence: i8,
1007     msrv: Option<RustcVersion>,
1008 ) -> Position {
1009     let destruct_trait_def_id = cx.tcx.lang_items().destruct_trait();
1010     let sized_trait_def_id = cx.tcx.lang_items().sized_trait();
1011
1012     let Some(callee_def_id) = fn_def_id(cx, parent) else { return Position::Other(precedence) };
1013     let fn_sig = cx.tcx.fn_sig(callee_def_id).skip_binder();
1014     let substs_with_expr_ty = cx
1015         .typeck_results()
1016         .node_substs(if let ExprKind::Call(callee, _) = parent.kind {
1017             callee.hir_id
1018         } else {
1019             parent.hir_id
1020         });
1021
1022     let predicates = cx.tcx.param_env(callee_def_id).caller_bounds();
1023     let projection_predicates = predicates
1024         .iter()
1025         .filter_map(|predicate| {
1026             if let PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
1027                 Some(projection_predicate)
1028             } else {
1029                 None
1030             }
1031         })
1032         .collect::<Vec<_>>();
1033
1034     let mut trait_with_ref_mut_self_method = false;
1035
1036     // If no traits were found, or only the `Destruct`, `Sized`, or `Any` traits were found, return.
1037     if predicates
1038         .iter()
1039         .filter_map(|predicate| {
1040             if let PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder()
1041                 && trait_predicate.trait_ref.self_ty() == param_ty.to_ty(cx.tcx)
1042             {
1043                 Some(trait_predicate.trait_ref.def_id)
1044             } else {
1045                 None
1046             }
1047         })
1048         .inspect(|trait_def_id| {
1049             trait_with_ref_mut_self_method |= has_ref_mut_self_method(cx, *trait_def_id);
1050         })
1051         .all(|trait_def_id| {
1052             Some(trait_def_id) == destruct_trait_def_id
1053                 || Some(trait_def_id) == sized_trait_def_id
1054                 || cx.tcx.is_diagnostic_item(sym::Any, trait_def_id)
1055         })
1056     {
1057         return Position::Other(precedence);
1058     }
1059
1060     // `substs_with_referent_ty` can be constructed outside of `check_referent` because the same
1061     // elements are modified each time `check_referent` is called.
1062     let mut substs_with_referent_ty = substs_with_expr_ty.to_vec();
1063
1064     let mut check_referent = |referent| {
1065         let referent_ty = cx.typeck_results().expr_ty(referent);
1066
1067         if !is_copy(cx, referent_ty) {
1068             return false;
1069         }
1070
1071         // https://github.com/rust-lang/rust-clippy/pull/9136#pullrequestreview-1037379321
1072         if trait_with_ref_mut_self_method && !matches!(referent_ty.kind(), ty::Ref(_, _, Mutability::Mut)) {
1073             return false;
1074         }
1075
1076         if !replace_types(
1077             cx,
1078             param_ty,
1079             referent_ty,
1080             fn_sig,
1081             arg_index,
1082             &projection_predicates,
1083             &mut substs_with_referent_ty,
1084         ) {
1085             return false;
1086         }
1087
1088         predicates.iter().all(|predicate| {
1089             if let PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder()
1090                 && cx.tcx.is_diagnostic_item(sym::IntoIterator, trait_predicate.trait_ref.def_id)
1091                 && let ty::Param(param_ty) = trait_predicate.self_ty().kind()
1092                 && let GenericArgKind::Type(ty) = substs_with_referent_ty[param_ty.index as usize].unpack()
1093                 && ty.is_array()
1094                 && !meets_msrv(msrv, msrvs::ARRAY_INTO_ITERATOR)
1095             {
1096                 return false;
1097             }
1098
1099             let predicate = EarlyBinder(predicate).subst(cx.tcx, &substs_with_referent_ty);
1100             let obligation = Obligation::new(ObligationCause::dummy(), cx.param_env, predicate);
1101             cx.tcx
1102                 .infer_ctxt()
1103                 .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
1104         })
1105     };
1106
1107     let mut needless_borrow = false;
1108     while let ExprKind::AddrOf(_, _, referent) = expr.kind {
1109         if !check_referent(referent) {
1110             break;
1111         }
1112         expr = referent;
1113         needless_borrow = true;
1114     }
1115
1116     if needless_borrow {
1117         Position::ImplArg(expr.hir_id)
1118     } else {
1119         Position::Other(precedence)
1120     }
1121 }
1122
1123 fn has_ref_mut_self_method(cx: &LateContext<'_>, trait_def_id: DefId) -> bool {
1124     cx.tcx
1125         .associated_items(trait_def_id)
1126         .in_definition_order()
1127         .any(|assoc_item| {
1128             if assoc_item.fn_has_self_parameter {
1129                 let self_ty = cx.tcx.fn_sig(assoc_item.def_id).skip_binder().inputs()[0];
1130                 matches!(self_ty.kind(), ty::Ref(_, _, Mutability::Mut))
1131             } else {
1132                 false
1133             }
1134         })
1135 }
1136
1137 // Iteratively replaces `param_ty` with `new_ty` in `substs`, and similarly for each resulting
1138 // projected type that is a type parameter. Returns `false` if replacing the types would have an
1139 // effect on the function signature beyond substituting `new_ty` for `param_ty`.
1140 // See: https://github.com/rust-lang/rust-clippy/pull/9136#discussion_r927212757
1141 fn replace_types<'tcx>(
1142     cx: &LateContext<'tcx>,
1143     param_ty: ParamTy,
1144     new_ty: Ty<'tcx>,
1145     fn_sig: FnSig<'tcx>,
1146     arg_index: usize,
1147     projection_predicates: &[ProjectionPredicate<'tcx>],
1148     substs: &mut [ty::GenericArg<'tcx>],
1149 ) -> bool {
1150     let mut replaced = BitSet::new_empty(substs.len());
1151
1152     let mut deque = VecDeque::with_capacity(substs.len());
1153     deque.push_back((param_ty, new_ty));
1154
1155     while let Some((param_ty, new_ty)) = deque.pop_front() {
1156         // If `replaced.is_empty()`, then `param_ty` and `new_ty` are those initially passed in.
1157         if !fn_sig
1158             .inputs_and_output
1159             .iter()
1160             .enumerate()
1161             .all(|(i, ty)| (replaced.is_empty() && i == arg_index) || !ty.contains(param_ty.to_ty(cx.tcx)))
1162         {
1163             return false;
1164         }
1165
1166         substs[param_ty.index as usize] = ty::GenericArg::from(new_ty);
1167
1168         // The `replaced.insert(...)` check provides some protection against infinite loops.
1169         if replaced.insert(param_ty.index) {
1170             for projection_predicate in projection_predicates {
1171                 if projection_predicate.projection_ty.self_ty() == param_ty.to_ty(cx.tcx)
1172                     && let Some(term_ty) = projection_predicate.term.ty()
1173                     && let ty::Param(term_param_ty) = term_ty.kind()
1174                 {
1175                     let item_def_id = projection_predicate.projection_ty.item_def_id;
1176                     let assoc_item = cx.tcx.associated_item(item_def_id);
1177                     let projection = cx.tcx
1178                         .mk_projection(assoc_item.def_id, cx.tcx.mk_substs_trait(new_ty, &[]));
1179
1180                     if let Ok(projected_ty) = cx.tcx.try_normalize_erasing_regions(cx.param_env, projection)
1181                         && substs[term_param_ty.index as usize] != ty::GenericArg::from(projected_ty)
1182                     {
1183                         deque.push_back((*term_param_ty, projected_ty));
1184                     }
1185                 }
1186             }
1187         }
1188     }
1189
1190     true
1191 }
1192
1193 struct TyPosition<'tcx> {
1194     position: Position,
1195     ty: Option<Ty<'tcx>>,
1196 }
1197 impl From<Position> for TyPosition<'_> {
1198     fn from(position: Position) -> Self {
1199         Self { position, ty: None }
1200     }
1201 }
1202 impl<'tcx> TyPosition<'tcx> {
1203     fn new_deref_stable_for_result(precedence: i8, ty: Ty<'tcx>) -> Self {
1204         Self {
1205             position: Position::ReborrowStable(precedence),
1206             ty: Some(ty),
1207         }
1208     }
1209     fn position_for_result(self, cx: &LateContext<'tcx>) -> Position {
1210         match (self.position, self.ty) {
1211             (Position::ReborrowStable(precedence), Some(ty)) => {
1212                 Position::DerefStable(precedence, ty.is_sized(cx.tcx.at(DUMMY_SP), cx.param_env))
1213             },
1214             (position, _) => position,
1215         }
1216     }
1217     fn position_for_arg(self) -> Position {
1218         self.position
1219     }
1220 }
1221
1222 // Checks whether a type is stable when switching to auto dereferencing,
1223 fn ty_auto_deref_stability<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, precedence: i8) -> TyPosition<'tcx> {
1224     let ty::Ref(_, mut ty, _) = *ty.kind() else {
1225         return Position::Other(precedence).into();
1226     };
1227
1228     loop {
1229         break match *ty.kind() {
1230             ty::Ref(_, ref_ty, _) => {
1231                 ty = ref_ty;
1232                 continue;
1233             },
1234             ty::Param(_) => TyPosition::new_deref_stable_for_result(precedence, ty),
1235             ty::Infer(_) | ty::Error(_) | ty::Bound(..) | ty::Opaque(..) | ty::Placeholder(_) | ty::Dynamic(..) => {
1236                 Position::ReborrowStable(precedence).into()
1237             },
1238             ty::Adt(..) if ty.has_placeholders() || ty.has_opaque_types() => {
1239                 Position::ReborrowStable(precedence).into()
1240             },
1241             ty::Adt(_, substs) if substs.has_param_types_or_consts() => {
1242                 TyPosition::new_deref_stable_for_result(precedence, ty)
1243             },
1244             ty::Bool
1245             | ty::Char
1246             | ty::Int(_)
1247             | ty::Uint(_)
1248             | ty::Array(..)
1249             | ty::Float(_)
1250             | ty::RawPtr(..)
1251             | ty::FnPtr(_) => Position::DerefStable(precedence, true).into(),
1252             ty::Str | ty::Slice(..) => Position::DerefStable(precedence, false).into(),
1253             ty::Adt(..)
1254             | ty::Foreign(_)
1255             | ty::FnDef(..)
1256             | ty::Generator(..)
1257             | ty::GeneratorWitness(..)
1258             | ty::Closure(..)
1259             | ty::Never
1260             | ty::Tuple(_)
1261             | ty::Projection(_) => Position::DerefStable(
1262                 precedence,
1263                 ty.is_sized(cx.tcx.at(DUMMY_SP), cx.param_env.without_caller_bounds()),
1264             )
1265             .into(),
1266         };
1267     }
1268 }
1269
1270 fn ty_contains_field(ty: Ty<'_>, name: Symbol) -> bool {
1271     if let ty::Adt(adt, _) = *ty.kind() {
1272         adt.is_struct() && adt.all_fields().any(|f| f.name == name)
1273     } else {
1274         false
1275     }
1276 }
1277
1278 #[expect(clippy::needless_pass_by_value, clippy::too_many_lines)]
1279 fn report<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, state: State, data: StateData) {
1280     match state {
1281         State::DerefMethod {
1282             ty_changed_count,
1283             is_final_ufcs,
1284             target_mut,
1285         } => {
1286             let mut app = Applicability::MachineApplicable;
1287             let (expr_str, expr_is_macro_call) = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app);
1288             let ty = cx.typeck_results().expr_ty(expr);
1289             let (_, ref_count) = peel_mid_ty_refs(ty);
1290             let deref_str = if ty_changed_count >= ref_count && ref_count != 0 {
1291                 // a deref call changing &T -> &U requires two deref operators the first time
1292                 // this occurs. One to remove the reference, a second to call the deref impl.
1293                 "*".repeat(ty_changed_count + 1)
1294             } else {
1295                 "*".repeat(ty_changed_count)
1296             };
1297             let addr_of_str = if ty_changed_count < ref_count {
1298                 // Check if a reborrow from &mut T -> &T is required.
1299                 if target_mut == Mutability::Not && matches!(ty.kind(), ty::Ref(_, _, Mutability::Mut)) {
1300                     "&*"
1301                 } else {
1302                     ""
1303                 }
1304             } else if target_mut == Mutability::Mut {
1305                 "&mut "
1306             } else {
1307                 "&"
1308             };
1309
1310             let expr_str = if !expr_is_macro_call && is_final_ufcs && expr.precedence().order() < PREC_PREFIX {
1311                 format!("({expr_str})")
1312             } else {
1313                 expr_str.into_owned()
1314             };
1315
1316             span_lint_and_sugg(
1317                 cx,
1318                 EXPLICIT_DEREF_METHODS,
1319                 data.span,
1320                 match target_mut {
1321                     Mutability::Not => "explicit `deref` method call",
1322                     Mutability::Mut => "explicit `deref_mut` method call",
1323                 },
1324                 "try this",
1325                 format!("{addr_of_str}{deref_str}{expr_str}"),
1326                 app,
1327             );
1328         },
1329         State::DerefedBorrow(state) => {
1330             let mut app = Applicability::MachineApplicable;
1331             let snip_expr = state.snip_expr.map_or(expr, |hir_id| cx.tcx.hir().expect_expr(hir_id));
1332             let (snip, snip_is_macro) = snippet_with_context(cx, snip_expr.span, data.span.ctxt(), "..", &mut app);
1333             span_lint_hir_and_then(cx, NEEDLESS_BORROW, data.hir_id, data.span, state.msg, |diag| {
1334                 let calls_field = matches!(expr.kind, ExprKind::Field(..)) && matches!(data.position, Position::Callee);
1335                 let sugg = if !snip_is_macro
1336                     && !has_enclosing_paren(&snip)
1337                     && (expr.precedence().order() < data.position.precedence() || calls_field)
1338                 {
1339                     format!("({snip})")
1340                 } else {
1341                     snip.into()
1342                 };
1343                 diag.span_suggestion(data.span, "change this to", sugg, app);
1344             });
1345         },
1346         State::ExplicitDeref { mutability } => {
1347             if matches!(
1348                 expr.kind,
1349                 ExprKind::Block(..)
1350                     | ExprKind::ConstBlock(_)
1351                     | ExprKind::If(..)
1352                     | ExprKind::Loop(..)
1353                     | ExprKind::Match(..)
1354             ) && matches!(data.position, Position::DerefStable(_, true))
1355             {
1356                 // Rustc bug: auto deref doesn't work on block expression when targeting sized types.
1357                 return;
1358             }
1359
1360             let (prefix, precedence) = if let Some(mutability) = mutability
1361                 && !cx.typeck_results().expr_ty(expr).is_ref()
1362             {
1363                 let prefix = match mutability {
1364                     Mutability::Not => "&",
1365                     Mutability::Mut => "&mut ",
1366                 };
1367                 (prefix, 0)
1368             } else {
1369                 ("", data.position.precedence())
1370             };
1371             span_lint_hir_and_then(
1372                 cx,
1373                 EXPLICIT_AUTO_DEREF,
1374                 data.hir_id,
1375                 data.span,
1376                 "deref which would be done by auto-deref",
1377                 |diag| {
1378                     let mut app = Applicability::MachineApplicable;
1379                     let (snip, snip_is_macro) = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app);
1380                     let sugg =
1381                         if !snip_is_macro && expr.precedence().order() < precedence && !has_enclosing_paren(&snip) {
1382                             format!("{prefix}({snip})")
1383                         } else {
1384                             format!("{prefix}{snip}")
1385                         };
1386                     diag.span_suggestion(data.span, "try this", sugg, app);
1387                 },
1388             );
1389         },
1390         State::ExplicitDerefField { .. } => {
1391             if matches!(
1392                 expr.kind,
1393                 ExprKind::Block(..)
1394                     | ExprKind::ConstBlock(_)
1395                     | ExprKind::If(..)
1396                     | ExprKind::Loop(..)
1397                     | ExprKind::Match(..)
1398             ) && matches!(data.position, Position::DerefStable(_, true))
1399             {
1400                 // Rustc bug: auto deref doesn't work on block expression when targeting sized types.
1401                 return;
1402             }
1403
1404             span_lint_hir_and_then(
1405                 cx,
1406                 EXPLICIT_AUTO_DEREF,
1407                 data.hir_id,
1408                 data.span,
1409                 "deref which would be done by auto-deref",
1410                 |diag| {
1411                     let mut app = Applicability::MachineApplicable;
1412                     let snip = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app).0;
1413                     diag.span_suggestion(data.span, "try this", snip.into_owned(), app);
1414                 },
1415             );
1416         },
1417         State::Borrow { .. } | State::Reborrow { .. } => (),
1418     }
1419 }
1420
1421 impl Dereferencing {
1422     fn check_local_usage<'tcx>(&mut self, cx: &LateContext<'tcx>, e: &Expr<'tcx>, local: HirId) {
1423         if let Some(outer_pat) = self.ref_locals.get_mut(&local) {
1424             if let Some(pat) = outer_pat {
1425                 // Check for auto-deref
1426                 if !matches!(
1427                     cx.typeck_results().expr_adjustments(e),
1428                     [
1429                         Adjustment {
1430                             kind: Adjust::Deref(_),
1431                             ..
1432                         },
1433                         Adjustment {
1434                             kind: Adjust::Deref(_),
1435                             ..
1436                         },
1437                         ..
1438                     ]
1439                 ) {
1440                     match get_parent_expr(cx, e) {
1441                         // Field accesses are the same no matter the number of references.
1442                         Some(Expr {
1443                             kind: ExprKind::Field(..),
1444                             ..
1445                         }) => (),
1446                         Some(&Expr {
1447                             span,
1448                             kind: ExprKind::Unary(UnOp::Deref, _),
1449                             ..
1450                         }) if !span.from_expansion() => {
1451                             // Remove explicit deref.
1452                             let snip = snippet_with_context(cx, e.span, span.ctxt(), "..", &mut pat.app).0;
1453                             pat.replacements.push((span, snip.into()));
1454                         },
1455                         Some(parent) if !parent.span.from_expansion() => {
1456                             // Double reference might be needed at this point.
1457                             if parent.precedence().order() == PREC_POSTFIX {
1458                                 // Parentheses would be needed here, don't lint.
1459                                 *outer_pat = None;
1460                             } else {
1461                                 pat.always_deref = false;
1462                                 let snip = snippet_with_context(cx, e.span, parent.span.ctxt(), "..", &mut pat.app).0;
1463                                 pat.replacements.push((e.span, format!("&{snip}")));
1464                             }
1465                         },
1466                         _ if !e.span.from_expansion() => {
1467                             // Double reference might be needed at this point.
1468                             pat.always_deref = false;
1469                             let snip = snippet_with_applicability(cx, e.span, "..", &mut pat.app);
1470                             pat.replacements.push((e.span, format!("&{snip}")));
1471                         },
1472                         // Edge case for macros. The span of the identifier will usually match the context of the
1473                         // binding, but not if the identifier was created in a macro. e.g. `concat_idents` and proc
1474                         // macros
1475                         _ => *outer_pat = None,
1476                     }
1477                 }
1478             }
1479         }
1480     }
1481 }