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