rustc_hir_analysis/
autoderef.rs

1use rustc_hir::limit::Limit;
2use rustc_infer::infer::InferCtxt;
3use rustc_infer::traits::PredicateObligations;
4use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
5use rustc_span::def_id::{LOCAL_CRATE, LocalDefId};
6use rustc_span::{ErrorGuaranteed, Span};
7use rustc_trait_selection::traits::ObligationCtxt;
8use tracing::{debug, instrument};
9
10use crate::errors::AutoDerefReachedRecursionLimit;
11use crate::traits;
12use crate::traits::query::evaluate_obligation::InferCtxtExt;
13
14#[derive(Copy, Clone, Debug)]
15pub enum AutoderefKind {
16    /// A true pointer type, such as `&T` and `*mut T`.
17    Builtin,
18    /// A type which must dispatch to a `Deref` implementation.
19    Overloaded,
20}
21struct AutoderefSnapshot<'tcx> {
22    at_start: bool,
23    reached_recursion_limit: bool,
24    steps: Vec<(Ty<'tcx>, AutoderefKind)>,
25    cur_ty: Ty<'tcx>,
26    obligations: PredicateObligations<'tcx>,
27}
28
29/// Recursively dereference a type, considering both built-in
30/// dereferences (`*`) and the `Deref` trait.
31/// Although called `Autoderef` it can be configured to use the
32/// `Receiver` trait instead of the `Deref` trait.
33pub struct Autoderef<'a, 'tcx> {
34    // Meta infos:
35    infcx: &'a InferCtxt<'tcx>,
36    span: Span,
37    body_id: LocalDefId,
38    param_env: ty::ParamEnv<'tcx>,
39
40    // Current state:
41    state: AutoderefSnapshot<'tcx>,
42
43    // Configurations:
44    include_raw_pointers: bool,
45    use_receiver_trait: bool,
46    silence_errors: bool,
47}
48
49impl<'a, 'tcx> Iterator for Autoderef<'a, 'tcx> {
50    type Item = (Ty<'tcx>, usize);
51
52    fn next(&mut self) -> Option<Self::Item> {
53        let tcx = self.infcx.tcx;
54
55        debug!("autoderef: steps={:?}, cur_ty={:?}", self.state.steps, self.state.cur_ty);
56        if self.state.at_start {
57            self.state.at_start = false;
58            debug!("autoderef stage #0 is {:?}", self.state.cur_ty);
59            return Some((self.state.cur_ty, 0));
60        }
61
62        // If we have reached the recursion limit, error gracefully.
63        if !tcx.recursion_limit().value_within_limit(self.state.steps.len()) {
64            if !self.silence_errors {
65                report_autoderef_recursion_limit_error(tcx, self.span, self.state.cur_ty);
66            }
67            self.state.reached_recursion_limit = true;
68            return None;
69        }
70
71        // We want to support method and function calls for `impl Deref<Target = ..>`.
72        //
73        // To do so we don't eagerly bail if the current type is the hidden type of an
74        // opaque type and instead return `None` in `fn overloaded_deref_ty` if the
75        // opaque does not have a `Deref` item-bound.
76        if let &ty::Infer(ty::TyVar(vid)) = self.state.cur_ty.kind()
77            && !self.infcx.has_opaques_with_sub_unified_hidden_type(vid)
78        {
79            return None;
80        }
81
82        // Otherwise, deref if type is derefable:
83        // NOTE: in the case of self.use_receiver_trait = true, you might think it would
84        // be better to skip this clause and use the Overloaded case only, since &T
85        // and &mut T implement Receiver. But built-in derefs apply equally to Receiver
86        // and Deref, and this has benefits for const and the emitted MIR.
87        let (kind, new_ty) =
88            if let Some(ty) = self.state.cur_ty.builtin_deref(self.include_raw_pointers) {
89                debug_assert_eq!(ty, self.infcx.resolve_vars_if_possible(ty));
90                // NOTE: we may still need to normalize the built-in deref in case
91                // we have some type like `&<Ty as Trait>::Assoc`, since users of
92                // autoderef expect this type to have been structurally normalized.
93                if self.infcx.next_trait_solver()
94                    && let ty::Alias(..) = ty.kind()
95                {
96                    let (normalized_ty, obligations) = self.structurally_normalize_ty(ty)?;
97                    self.state.obligations.extend(obligations);
98                    (AutoderefKind::Builtin, normalized_ty)
99                } else {
100                    (AutoderefKind::Builtin, ty)
101                }
102            } else if let Some(ty) = self.overloaded_deref_ty(self.state.cur_ty) {
103                // The overloaded deref check already normalizes the pointee type.
104                (AutoderefKind::Overloaded, ty)
105            } else {
106                return None;
107            };
108
109        self.state.steps.push((self.state.cur_ty, kind));
110        debug!(
111            "autoderef stage #{:?} is {:?} from {:?}",
112            self.step_count(),
113            new_ty,
114            (self.state.cur_ty, kind)
115        );
116        self.state.cur_ty = new_ty;
117
118        Some((self.state.cur_ty, self.step_count()))
119    }
120}
121
122impl<'a, 'tcx> Autoderef<'a, 'tcx> {
123    pub fn new(
124        infcx: &'a InferCtxt<'tcx>,
125        param_env: ty::ParamEnv<'tcx>,
126        body_def_id: LocalDefId,
127        span: Span,
128        base_ty: Ty<'tcx>,
129    ) -> Self {
130        Autoderef {
131            infcx,
132            span,
133            body_id: body_def_id,
134            param_env,
135            state: AutoderefSnapshot {
136                steps: vec![],
137                cur_ty: infcx.resolve_vars_if_possible(base_ty),
138                obligations: PredicateObligations::new(),
139                at_start: true,
140                reached_recursion_limit: false,
141            },
142            include_raw_pointers: false,
143            use_receiver_trait: false,
144            silence_errors: false,
145        }
146    }
147
148    fn overloaded_deref_ty(&mut self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
149        debug!("overloaded_deref_ty({:?})", ty);
150        let tcx = self.infcx.tcx;
151
152        if ty.references_error() {
153            return None;
154        }
155
156        // <ty as Deref>, or whatever the equivalent trait is that we've been asked to walk.
157        let (trait_def_id, trait_target_def_id) = if self.use_receiver_trait {
158            (tcx.lang_items().receiver_trait()?, tcx.lang_items().receiver_target()?)
159        } else {
160            (tcx.lang_items().deref_trait()?, tcx.lang_items().deref_target()?)
161        };
162        let trait_ref = ty::TraitRef::new(tcx, trait_def_id, [ty]);
163        let cause = traits::ObligationCause::misc(self.span, self.body_id);
164        let obligation = traits::Obligation::new(
165            tcx,
166            cause.clone(),
167            self.param_env,
168            ty::Binder::dummy(trait_ref),
169        );
170        // We detect whether the self type implements `Deref` before trying to
171        // structurally normalize. We use `predicate_may_hold_opaque_types_jank`
172        // to support not-yet-defined opaque types. It will succeed for `impl Deref`
173        // but fail for `impl OtherTrait`.
174        if !self.infcx.predicate_may_hold_opaque_types_jank(&obligation) {
175            debug!("overloaded_deref_ty: cannot match obligation");
176            return None;
177        }
178
179        let (normalized_ty, obligations) =
180            self.structurally_normalize_ty(Ty::new_projection(tcx, trait_target_def_id, [ty]))?;
181        debug!("overloaded_deref_ty({:?}) = ({:?}, {:?})", ty, normalized_ty, obligations);
182        self.state.obligations.extend(obligations);
183
184        Some(self.infcx.resolve_vars_if_possible(normalized_ty))
185    }
186
187    #[instrument(level = "debug", skip(self), ret)]
188    pub fn structurally_normalize_ty(
189        &self,
190        ty: Ty<'tcx>,
191    ) -> Option<(Ty<'tcx>, PredicateObligations<'tcx>)> {
192        let ocx = ObligationCtxt::new(self.infcx);
193        let Ok(normalized_ty) = ocx.structurally_normalize_ty(
194            &traits::ObligationCause::misc(self.span, self.body_id),
195            self.param_env,
196            ty,
197        ) else {
198            // We shouldn't have errors here in the old solver, except for
199            // evaluate/fulfill mismatches, but that's not a reason for an ICE.
200            return None;
201        };
202        let errors = ocx.select_where_possible();
203        if !errors.is_empty() {
204            if self.infcx.next_trait_solver() {
205                unreachable!();
206            }
207            // We shouldn't have errors here in the old solver, except for
208            // evaluate/fulfill mismatches, but that's not a reason for an ICE.
209            debug!(?errors, "encountered errors while fulfilling");
210            return None;
211        }
212
213        Some((normalized_ty, ocx.into_pending_obligations()))
214    }
215
216    /// Returns the final type we ended up with, which may be an unresolved
217    /// inference variable.
218    pub fn final_ty(&self) -> Ty<'tcx> {
219        self.state.cur_ty
220    }
221
222    pub fn step_count(&self) -> usize {
223        self.state.steps.len()
224    }
225
226    pub fn into_obligations(self) -> PredicateObligations<'tcx> {
227        self.state.obligations
228    }
229
230    pub fn current_obligations(&self) -> PredicateObligations<'tcx> {
231        self.state.obligations.clone()
232    }
233
234    pub fn steps(&self) -> &[(Ty<'tcx>, AutoderefKind)] {
235        &self.state.steps
236    }
237
238    pub fn span(&self) -> Span {
239        self.span
240    }
241
242    pub fn reached_recursion_limit(&self) -> bool {
243        self.state.reached_recursion_limit
244    }
245
246    /// also dereference through raw pointer types
247    /// e.g., assuming ptr_to_Foo is the type `*const Foo`
248    /// fcx.autoderef(span, ptr_to_Foo)  => [*const Foo]
249    /// fcx.autoderef(span, ptr_to_Foo).include_raw_ptrs() => [*const Foo, Foo]
250    pub fn include_raw_pointers(mut self) -> Self {
251        self.include_raw_pointers = true;
252        self
253    }
254
255    /// Use `core::ops::Receiver` and `core::ops::Receiver::Target` as
256    /// the trait and associated type to iterate, instead of
257    /// `core::ops::Deref` and `core::ops::Deref::Target`
258    pub fn use_receiver_trait(mut self) -> Self {
259        self.use_receiver_trait = true;
260        self
261    }
262
263    pub fn silence_errors(mut self) -> Self {
264        self.silence_errors = true;
265        self
266    }
267}
268
269pub fn report_autoderef_recursion_limit_error<'tcx>(
270    tcx: TyCtxt<'tcx>,
271    span: Span,
272    ty: Ty<'tcx>,
273) -> ErrorGuaranteed {
274    // We've reached the recursion limit, error gracefully.
275    let suggested_limit = match tcx.recursion_limit() {
276        Limit(0) => Limit(2),
277        limit => limit * 2,
278    };
279    tcx.dcx().emit_err(AutoDerefReachedRecursionLimit {
280        span,
281        ty,
282        suggested_limit,
283        crate_name: tcx.crate_name(LOCAL_CRATE),
284    })
285}