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 Builtin,
18 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
29pub struct Autoderef<'a, 'tcx> {
34 infcx: &'a InferCtxt<'tcx>,
36 span: Span,
37 body_id: LocalDefId,
38 param_env: ty::ParamEnv<'tcx>,
39
40 state: AutoderefSnapshot<'tcx>,
42
43 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 !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 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 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 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 (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 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 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 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 debug!(?errors, "encountered errors while fulfilling");
210 return None;
211 }
212
213 Some((normalized_ty, ocx.into_pending_obligations()))
214 }
215
216 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 pub fn include_raw_pointers(mut self) -> Self {
251 self.include_raw_pointers = true;
252 self
253 }
254
255 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 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}