]>
Commit | Line | Data |
---|---|---|
ba9703b0 XL |
1 | //! Code for projecting associated types out of trait references. |
2 | ||
ba9703b0 XL |
3 | use super::specialization_graph; |
4 | use super::translate_substs; | |
5 | use super::util; | |
6 | use super::MismatchedProjectionTypes; | |
7 | use super::Obligation; | |
8 | use super::ObligationCause; | |
9 | use super::PredicateObligation; | |
10 | use super::Selection; | |
11 | use super::SelectionContext; | |
12 | use super::SelectionError; | |
f9f354fc | 13 | use super::{ |
487cf647 FG |
14 | ImplSourceClosureData, ImplSourceFnPointerData, ImplSourceFutureData, ImplSourceGeneratorData, |
15 | ImplSourceUserDefinedData, | |
f9f354fc | 16 | }; |
f035d41b | 17 | use super::{Normalized, NormalizedTy, ProjectionCacheEntry, ProjectionCacheKey}; |
ba9703b0 XL |
18 | |
19 | use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; | |
20 | use crate::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime}; | |
2b03887a | 21 | use crate::traits::error_reporting::TypeErrCtxtExt as _; |
04454e1e | 22 | use crate::traits::query::evaluate_obligation::InferCtxtExt as _; |
5099ac24 | 23 | use crate::traits::select::ProjectionMatchesProjection; |
3c0e092e | 24 | use rustc_data_structures::sso::SsoHashSet; |
f9f354fc | 25 | use rustc_data_structures::stack::ensure_sufficient_stack; |
5e7ed085 | 26 | use rustc_errors::ErrorGuaranteed; |
5099ac24 | 27 | use rustc_hir::def::DefKind; |
3dfed10e | 28 | use rustc_hir::lang_items::LangItem; |
487cf647 | 29 | use rustc_infer::infer::at::At; |
f035d41b | 30 | use rustc_infer::infer::resolve::OpportunisticRegionResolver; |
487cf647 | 31 | use rustc_infer::traits::ImplSourceBuiltinData; |
5e7ed085 | 32 | use rustc_middle::traits::select::OverflowError; |
064997fb | 33 | use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; |
9ffffee4 | 34 | use rustc_middle::ty::visit::{MaxUniverse, TypeVisitable, TypeVisitableExt}; |
f2b60f7d | 35 | use rustc_middle::ty::DefIdTree; |
064997fb | 36 | use rustc_middle::ty::{self, Term, ToPredicate, Ty, TyCtxt}; |
f035d41b | 37 | use rustc_span::symbol::sym; |
ba9703b0 | 38 | |
136023e0 XL |
39 | use std::collections::BTreeMap; |
40 | ||
ba9703b0 XL |
41 | pub use rustc_middle::traits::Reveal; |
42 | ||
43 | pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>; | |
44 | ||
45 | pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>; | |
46 | ||
9c376795 | 47 | pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::AliasTy<'tcx>>; |
ba9703b0 | 48 | |
f9652781 XL |
49 | pub(super) struct InProgress; |
50 | ||
487cf647 FG |
51 | pub trait NormalizeExt<'tcx> { |
52 | /// Normalize a value using the `AssocTypeNormalizer`. | |
53 | /// | |
54 | /// This normalization should be used when the type contains inference variables or the | |
55 | /// projection may be fallible. | |
9ffffee4 | 56 | fn normalize<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> InferOk<'tcx, T>; |
487cf647 FG |
57 | } |
58 | ||
59 | impl<'tcx> NormalizeExt<'tcx> for At<'_, 'tcx> { | |
9ffffee4 | 60 | fn normalize<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> InferOk<'tcx, T> { |
487cf647 FG |
61 | let mut selcx = SelectionContext::new(self.infcx); |
62 | let Normalized { value, obligations } = | |
63 | normalize_with_depth(&mut selcx, self.param_env, self.cause.clone(), 0, value); | |
64 | InferOk { value, obligations } | |
65 | } | |
66 | } | |
67 | ||
ba9703b0 XL |
68 | /// When attempting to resolve `<T as TraitRef>::Name` ... |
69 | #[derive(Debug)] | |
5099ac24 | 70 | pub enum ProjectionError<'tcx> { |
ba9703b0 XL |
71 | /// ...we found multiple sources of information and couldn't resolve the ambiguity. |
72 | TooManyCandidates, | |
73 | ||
74 | /// ...an error occurred matching `T : TraitRef` | |
75 | TraitSelectionError(SelectionError<'tcx>), | |
76 | } | |
77 | ||
78 | #[derive(PartialEq, Eq, Debug)] | |
5099ac24 | 79 | enum ProjectionCandidate<'tcx> { |
29967ef6 | 80 | /// From a where-clause in the env or object type |
ba9703b0 XL |
81 | ParamEnv(ty::PolyProjectionPredicate<'tcx>), |
82 | ||
2b03887a FG |
83 | /// From the definition of `Trait` when you have something like |
84 | /// `<<A as Trait>::B as Trait2>::C`. | |
ba9703b0 XL |
85 | TraitDef(ty::PolyProjectionPredicate<'tcx>), |
86 | ||
29967ef6 XL |
87 | /// Bounds specified on an object type |
88 | Object(ty::PolyProjectionPredicate<'tcx>), | |
89 | ||
94222f64 | 90 | /// From an "impl" (or a "pseudo-impl" returned by select) |
ba9703b0 | 91 | Select(Selection<'tcx>), |
f2b60f7d | 92 | |
9ffffee4 | 93 | ImplTraitInTrait(ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>), |
ba9703b0 XL |
94 | } |
95 | ||
5099ac24 | 96 | enum ProjectionCandidateSet<'tcx> { |
ba9703b0 | 97 | None, |
5099ac24 | 98 | Single(ProjectionCandidate<'tcx>), |
ba9703b0 XL |
99 | Ambiguous, |
100 | Error(SelectionError<'tcx>), | |
101 | } | |
102 | ||
5099ac24 | 103 | impl<'tcx> ProjectionCandidateSet<'tcx> { |
ba9703b0 | 104 | fn mark_ambiguous(&mut self) { |
5099ac24 | 105 | *self = ProjectionCandidateSet::Ambiguous; |
ba9703b0 XL |
106 | } |
107 | ||
108 | fn mark_error(&mut self, err: SelectionError<'tcx>) { | |
5099ac24 | 109 | *self = ProjectionCandidateSet::Error(err); |
ba9703b0 XL |
110 | } |
111 | ||
112 | // Returns true if the push was successful, or false if the candidate | |
113 | // was discarded -- this could be because of ambiguity, or because | |
114 | // a higher-priority candidate is already there. | |
5099ac24 FG |
115 | fn push_candidate(&mut self, candidate: ProjectionCandidate<'tcx>) -> bool { |
116 | use self::ProjectionCandidate::*; | |
117 | use self::ProjectionCandidateSet::*; | |
ba9703b0 XL |
118 | |
119 | // This wacky variable is just used to try and | |
120 | // make code readable and avoid confusing paths. | |
121 | // It is assigned a "value" of `()` only on those | |
122 | // paths in which we wish to convert `*self` to | |
123 | // ambiguous (and return false, because the candidate | |
124 | // was not used). On other paths, it is not assigned, | |
125 | // and hence if those paths *could* reach the code that | |
126 | // comes after the match, this fn would not compile. | |
127 | let convert_to_ambiguous; | |
128 | ||
129 | match self { | |
130 | None => { | |
131 | *self = Single(candidate); | |
132 | return true; | |
133 | } | |
134 | ||
135 | Single(current) => { | |
136 | // Duplicates can happen inside ParamEnv. In the case, we | |
137 | // perform a lazy deduplication. | |
138 | if current == &candidate { | |
139 | return false; | |
140 | } | |
141 | ||
142 | // Prefer where-clauses. As in select, if there are multiple | |
9c376795 | 143 | // candidates, we prefer where-clause candidates over impls. This |
ba9703b0 XL |
144 | // may seem a bit surprising, since impls are the source of |
145 | // "truth" in some sense, but in fact some of the impls that SEEM | |
146 | // applicable are not, because of nested obligations. Where | |
147 | // clauses are the safer choice. See the comment on | |
148 | // `select::SelectionCandidate` and #21974 for more details. | |
149 | match (current, candidate) { | |
150 | (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (), | |
151 | (ParamEnv(..), _) => return false, | |
152 | (_, ParamEnv(..)) => unreachable!(), | |
153 | (_, _) => convert_to_ambiguous = (), | |
154 | } | |
155 | } | |
156 | ||
157 | Ambiguous | Error(..) => { | |
158 | return false; | |
159 | } | |
160 | } | |
161 | ||
162 | // We only ever get here when we moved from a single candidate | |
163 | // to ambiguous. | |
164 | let () = convert_to_ambiguous; | |
165 | *self = Ambiguous; | |
166 | false | |
167 | } | |
168 | } | |
169 | ||
923072b8 FG |
170 | /// States returned from `poly_project_and_unify_type`. Takes the place |
171 | /// of the old return type, which was: | |
172 | /// ```ignore (not-rust) | |
5e7ed085 FG |
173 | /// Result< |
174 | /// Result<Option<Vec<PredicateObligation<'tcx>>>, InProgress>, | |
175 | /// MismatchedProjectionTypes<'tcx>, | |
176 | /// > | |
923072b8 | 177 | /// ``` |
5e7ed085 | 178 | pub(super) enum ProjectAndUnifyResult<'tcx> { |
923072b8 FG |
179 | /// The projection bound holds subject to the given obligations. If the |
180 | /// projection cannot be normalized because the required trait bound does | |
181 | /// not hold, this is returned, with `obligations` being a predicate that | |
182 | /// cannot be proven. | |
5e7ed085 | 183 | Holds(Vec<PredicateObligation<'tcx>>), |
923072b8 FG |
184 | /// The projection cannot be normalized due to ambiguity. Resolving some |
185 | /// inference variables in the projection may fix this. | |
5e7ed085 | 186 | FailedNormalization, |
923072b8 FG |
187 | /// The project cannot be normalized because `poly_project_and_unify_type` |
188 | /// is called recursively while normalizing the same projection. | |
5e7ed085 | 189 | Recursive, |
923072b8 FG |
190 | // the projection can be normalized, but is not equal to the expected type. |
191 | // Returns the type error that arose from the mismatch. | |
5e7ed085 FG |
192 | MismatchedProjectionTypes(MismatchedProjectionTypes<'tcx>), |
193 | } | |
194 | ||
ba9703b0 | 195 | /// Evaluates constraints of the form: |
04454e1e FG |
196 | /// ```ignore (not-rust) |
197 | /// for<...> <T as Trait>::U == V | |
198 | /// ``` | |
ba9703b0 XL |
199 | /// If successful, this may result in additional obligations. Also returns |
200 | /// the projection cache key used to track these additional obligations. | |
29967ef6 | 201 | #[instrument(level = "debug", skip(selcx))] |
f9652781 | 202 | pub(super) fn poly_project_and_unify_type<'cx, 'tcx>( |
ba9703b0 XL |
203 | selcx: &mut SelectionContext<'cx, 'tcx>, |
204 | obligation: &PolyProjectionObligation<'tcx>, | |
5e7ed085 | 205 | ) -> ProjectAndUnifyResult<'tcx> { |
487cf647 | 206 | let infcx = selcx.infcx; |
5e7ed085 FG |
207 | let r = infcx.commit_if_ok(|_snapshot| { |
208 | let old_universe = infcx.universe(); | |
29967ef6 | 209 | let placeholder_predicate = |
9ffffee4 | 210 | infcx.instantiate_binder_with_placeholders(obligation.predicate); |
5e7ed085 | 211 | let new_universe = infcx.universe(); |
ba9703b0 | 212 | |
487cf647 | 213 | let placeholder_obligation = obligation.with(infcx.tcx, placeholder_predicate); |
5e7ed085 FG |
214 | match project_and_unify_type(selcx, &placeholder_obligation) { |
215 | ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e), | |
216 | ProjectAndUnifyResult::Holds(obligations) | |
217 | if old_universe != new_universe | |
218 | && selcx.tcx().features().generic_associated_types_extended => | |
219 | { | |
220 | // If the `generic_associated_types_extended` feature is active, then we ignore any | |
221 | // obligations references lifetimes from any universe greater than or equal to the | |
222 | // universe just created. Otherwise, we can end up with something like `for<'a> I: 'a`, | |
223 | // which isn't quite what we want. Ideally, we want either an implied | |
224 | // `for<'a where I: 'a> I: 'a` or we want to "lazily" check these hold when we | |
225 | // substitute concrete regions. There is design work to be done here; until then, | |
226 | // however, this allows experimenting potential GAT features without running into | |
227 | // well-formedness issues. | |
228 | let new_obligations = obligations | |
229 | .into_iter() | |
230 | .filter(|obligation| { | |
231 | let mut visitor = MaxUniverse::new(); | |
232 | obligation.predicate.visit_with(&mut visitor); | |
233 | visitor.max_universe() < new_universe | |
234 | }) | |
235 | .collect(); | |
236 | Ok(ProjectAndUnifyResult::Holds(new_obligations)) | |
237 | } | |
238 | other => Ok(other), | |
239 | } | |
240 | }); | |
241 | ||
242 | match r { | |
243 | Ok(inner) => inner, | |
244 | Err(err) => ProjectAndUnifyResult::MismatchedProjectionTypes(err), | |
245 | } | |
ba9703b0 XL |
246 | } |
247 | ||
248 | /// Evaluates constraints of the form: | |
04454e1e FG |
249 | /// ```ignore (not-rust) |
250 | /// <T as Trait>::U == V | |
251 | /// ``` | |
ba9703b0 | 252 | /// If successful, this may result in additional obligations. |
f9652781 XL |
253 | /// |
254 | /// See [poly_project_and_unify_type] for an explanation of the return value. | |
f2b60f7d | 255 | #[instrument(level = "debug", skip(selcx))] |
ba9703b0 XL |
256 | fn project_and_unify_type<'cx, 'tcx>( |
257 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
258 | obligation: &ProjectionObligation<'tcx>, | |
5e7ed085 | 259 | ) -> ProjectAndUnifyResult<'tcx> { |
ba9703b0 | 260 | let mut obligations = vec![]; |
5099ac24 | 261 | |
487cf647 | 262 | let infcx = selcx.infcx; |
5099ac24 | 263 | let normalized = match opt_normalize_projection_type( |
ba9703b0 XL |
264 | selcx, |
265 | obligation.param_env, | |
266 | obligation.predicate.projection_ty, | |
267 | obligation.cause.clone(), | |
268 | obligation.recursion_depth, | |
269 | &mut obligations, | |
270 | ) { | |
f9652781 | 271 | Ok(Some(n)) => n, |
5e7ed085 FG |
272 | Ok(None) => return ProjectAndUnifyResult::FailedNormalization, |
273 | Err(InProgress) => return ProjectAndUnifyResult::Recursive, | |
ba9703b0 | 274 | }; |
5099ac24 | 275 | debug!(?normalized, ?obligations, "project_and_unify_type result"); |
5e7ed085 | 276 | let actual = obligation.predicate.term; |
9c376795 | 277 | // For an example where this is necessary see tests/ui/impl-trait/nested-return-type2.rs |
064997fb FG |
278 | // This allows users to omit re-mentioning all bounds on an associated type and just use an |
279 | // `impl Trait` for the assoc type to add more bounds. | |
5e7ed085 | 280 | let InferOk { value: actual, obligations: new } = |
487cf647 | 281 | selcx.infcx.replace_opaque_types_with_inference_vars( |
5e7ed085 FG |
282 | actual, |
283 | obligation.cause.body_id, | |
284 | obligation.cause.span, | |
285 | obligation.param_env, | |
286 | ); | |
287 | obligations.extend(new); | |
288 | ||
9ffffee4 FG |
289 | match infcx |
290 | .at(&obligation.cause, obligation.param_env) | |
291 | // This is needed to support nested opaque types like `impl Fn() -> impl Trait` | |
292 | .define_opaque_types(true) | |
293 | .eq(normalized, actual) | |
294 | { | |
ba9703b0 XL |
295 | Ok(InferOk { obligations: inferred_obligations, value: () }) => { |
296 | obligations.extend(inferred_obligations); | |
5e7ed085 | 297 | ProjectAndUnifyResult::Holds(obligations) |
ba9703b0 XL |
298 | } |
299 | Err(err) => { | |
5e7ed085 FG |
300 | debug!("equating types encountered error {:?}", err); |
301 | ProjectAndUnifyResult::MismatchedProjectionTypes(MismatchedProjectionTypes { err }) | |
ba9703b0 XL |
302 | } |
303 | } | |
304 | } | |
305 | ||
ba9703b0 | 306 | /// As `normalize`, but with a custom depth. |
487cf647 | 307 | pub(crate) fn normalize_with_depth<'a, 'b, 'tcx, T>( |
ba9703b0 XL |
308 | selcx: &'a mut SelectionContext<'b, 'tcx>, |
309 | param_env: ty::ParamEnv<'tcx>, | |
310 | cause: ObligationCause<'tcx>, | |
311 | depth: usize, | |
fc512014 | 312 | value: T, |
ba9703b0 XL |
313 | ) -> Normalized<'tcx, T> |
314 | where | |
9ffffee4 | 315 | T: TypeFoldable<TyCtxt<'tcx>>, |
ba9703b0 XL |
316 | { |
317 | let mut obligations = Vec::new(); | |
318 | let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations); | |
319 | Normalized { value, obligations } | |
320 | } | |
321 | ||
136023e0 | 322 | #[instrument(level = "info", skip(selcx, param_env, cause, obligations))] |
487cf647 | 323 | pub(crate) fn normalize_with_depth_to<'a, 'b, 'tcx, T>( |
ba9703b0 XL |
324 | selcx: &'a mut SelectionContext<'b, 'tcx>, |
325 | param_env: ty::ParamEnv<'tcx>, | |
326 | cause: ObligationCause<'tcx>, | |
327 | depth: usize, | |
fc512014 | 328 | value: T, |
ba9703b0 XL |
329 | obligations: &mut Vec<PredicateObligation<'tcx>>, |
330 | ) -> T | |
331 | where | |
9ffffee4 | 332 | T: TypeFoldable<TyCtxt<'tcx>>, |
ba9703b0 | 333 | { |
136023e0 | 334 | debug!(obligations.len = obligations.len()); |
ba9703b0 | 335 | let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations); |
f9f354fc | 336 | let result = ensure_sufficient_stack(|| normalizer.fold(value)); |
29967ef6 XL |
337 | debug!(?result, obligations.len = normalizer.obligations.len()); |
338 | debug!(?normalizer.obligations,); | |
ba9703b0 XL |
339 | result |
340 | } | |
341 | ||
5e7ed085 | 342 | #[instrument(level = "info", skip(selcx, param_env, cause, obligations))] |
487cf647 | 343 | pub(crate) fn try_normalize_with_depth_to<'a, 'b, 'tcx, T>( |
5e7ed085 FG |
344 | selcx: &'a mut SelectionContext<'b, 'tcx>, |
345 | param_env: ty::ParamEnv<'tcx>, | |
346 | cause: ObligationCause<'tcx>, | |
347 | depth: usize, | |
348 | value: T, | |
349 | obligations: &mut Vec<PredicateObligation<'tcx>>, | |
350 | ) -> T | |
351 | where | |
9ffffee4 | 352 | T: TypeFoldable<TyCtxt<'tcx>>, |
5e7ed085 FG |
353 | { |
354 | debug!(obligations.len = obligations.len()); | |
355 | let mut normalizer = AssocTypeNormalizer::new_without_eager_inference_replacement( | |
356 | selcx, | |
357 | param_env, | |
358 | cause, | |
359 | depth, | |
360 | obligations, | |
361 | ); | |
362 | let result = ensure_sufficient_stack(|| normalizer.fold(value)); | |
363 | debug!(?result, obligations.len = normalizer.obligations.len()); | |
364 | debug!(?normalizer.obligations,); | |
365 | result | |
366 | } | |
367 | ||
9ffffee4 FG |
368 | pub(crate) fn needs_normalization<'tcx, T: TypeVisitable<TyCtxt<'tcx>>>( |
369 | value: &T, | |
370 | reveal: Reveal, | |
371 | ) -> bool { | |
136023e0 XL |
372 | match reveal { |
373 | Reveal::UserFacing => value | |
374 | .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION), | |
375 | Reveal::All => value.has_type_flags( | |
376 | ty::TypeFlags::HAS_TY_PROJECTION | |
377 | | ty::TypeFlags::HAS_TY_OPAQUE | |
378 | | ty::TypeFlags::HAS_CT_PROJECTION, | |
379 | ), | |
380 | } | |
381 | } | |
382 | ||
ba9703b0 XL |
383 | struct AssocTypeNormalizer<'a, 'b, 'tcx> { |
384 | selcx: &'a mut SelectionContext<'b, 'tcx>, | |
385 | param_env: ty::ParamEnv<'tcx>, | |
386 | cause: ObligationCause<'tcx>, | |
387 | obligations: &'a mut Vec<PredicateObligation<'tcx>>, | |
388 | depth: usize, | |
136023e0 | 389 | universes: Vec<Option<ty::UniverseIndex>>, |
5e7ed085 FG |
390 | /// If true, when a projection is unable to be completed, an inference |
391 | /// variable will be created and an obligation registered to project to that | |
392 | /// inference variable. Also, constants will be eagerly evaluated. | |
393 | eager_inference_replacement: bool, | |
ba9703b0 XL |
394 | } |
395 | ||
396 | impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> { | |
397 | fn new( | |
398 | selcx: &'a mut SelectionContext<'b, 'tcx>, | |
399 | param_env: ty::ParamEnv<'tcx>, | |
400 | cause: ObligationCause<'tcx>, | |
401 | depth: usize, | |
402 | obligations: &'a mut Vec<PredicateObligation<'tcx>>, | |
403 | ) -> AssocTypeNormalizer<'a, 'b, 'tcx> { | |
5e7ed085 FG |
404 | AssocTypeNormalizer { |
405 | selcx, | |
406 | param_env, | |
407 | cause, | |
408 | obligations, | |
409 | depth, | |
410 | universes: vec![], | |
411 | eager_inference_replacement: true, | |
412 | } | |
413 | } | |
414 | ||
415 | fn new_without_eager_inference_replacement( | |
416 | selcx: &'a mut SelectionContext<'b, 'tcx>, | |
417 | param_env: ty::ParamEnv<'tcx>, | |
418 | cause: ObligationCause<'tcx>, | |
419 | depth: usize, | |
420 | obligations: &'a mut Vec<PredicateObligation<'tcx>>, | |
421 | ) -> AssocTypeNormalizer<'a, 'b, 'tcx> { | |
422 | AssocTypeNormalizer { | |
423 | selcx, | |
424 | param_env, | |
425 | cause, | |
426 | obligations, | |
427 | depth, | |
428 | universes: vec![], | |
429 | eager_inference_replacement: false, | |
430 | } | |
ba9703b0 XL |
431 | } |
432 | ||
9ffffee4 | 433 | fn fold<T: TypeFoldable<TyCtxt<'tcx>>>(&mut self, value: T) -> T { |
487cf647 | 434 | let value = self.selcx.infcx.resolve_vars_if_possible(value); |
136023e0 XL |
435 | debug!(?value); |
436 | ||
437 | assert!( | |
438 | !value.has_escaping_bound_vars(), | |
439 | "Normalizing {:?} without wrapping in a `Binder`", | |
440 | value | |
441 | ); | |
ba9703b0 | 442 | |
136023e0 XL |
443 | if !needs_normalization(&value, self.param_env.reveal()) { |
444 | value | |
445 | } else { | |
446 | value.fold_with(self) | |
447 | } | |
ba9703b0 XL |
448 | } |
449 | } | |
450 | ||
9ffffee4 FG |
451 | impl<'a, 'b, 'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTypeNormalizer<'a, 'b, 'tcx> { |
452 | fn interner(&self) -> TyCtxt<'tcx> { | |
ba9703b0 XL |
453 | self.selcx.tcx() |
454 | } | |
455 | ||
9ffffee4 | 456 | fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>( |
136023e0 XL |
457 | &mut self, |
458 | t: ty::Binder<'tcx, T>, | |
459 | ) -> ty::Binder<'tcx, T> { | |
460 | self.universes.push(None); | |
461 | let t = t.super_fold_with(self); | |
462 | self.universes.pop(); | |
463 | t | |
464 | } | |
465 | ||
ba9703b0 | 466 | fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { |
136023e0 | 467 | if !needs_normalization(&ty, self.param_env.reveal()) { |
ba9703b0 XL |
468 | return ty; |
469 | } | |
94222f64 XL |
470 | |
471 | // We try to be a little clever here as a performance optimization in | |
472 | // cases where there are nested projections under binders. | |
473 | // For example: | |
474 | // ``` | |
475 | // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>) | |
476 | // ``` | |
477 | // We normalize the substs on the projection before the projecting, but | |
478 | // if we're naive, we'll | |
479 | // replace bound vars on inner, project inner, replace placeholders on inner, | |
480 | // replace bound vars on outer, project outer, replace placeholders on outer | |
ba9703b0 | 481 | // |
94222f64 XL |
482 | // However, if we're a bit more clever, we can replace the bound vars |
483 | // on the entire type before normalizing nested projections, meaning we | |
484 | // replace bound vars on outer, project inner, | |
485 | // project outer, replace placeholders on outer | |
ba9703b0 | 486 | // |
94222f64 XL |
487 | // This is possible because the inner `'a` will already be a placeholder |
488 | // when we need to normalize the inner projection | |
ba9703b0 | 489 | // |
94222f64 XL |
490 | // On the other hand, this does add a bit of complexity, since we only |
491 | // replace bound vars if the current type is a `Projection` and we need | |
492 | // to make sure we don't forget to fold the substs regardless. | |
ba9703b0 | 493 | |
1b1a35ee | 494 | match *ty.kind() { |
94222f64 XL |
495 | // This is really important. While we *can* handle this, this has |
496 | // severe performance implications for large opaque types with | |
497 | // late-bound regions. See `issue-88862` benchmark. | |
9c376795 FG |
498 | ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) |
499 | if !substs.has_escaping_bound_vars() => | |
500 | { | |
5099ac24 | 501 | // Only normalize `impl Trait` outside of type inference, usually in codegen. |
f035d41b | 502 | match self.param_env.reveal() { |
94222f64 | 503 | Reveal::UserFacing => ty.super_fold_with(self), |
ba9703b0 XL |
504 | |
505 | Reveal::All => { | |
9ffffee4 | 506 | let recursion_limit = self.interner().recursion_limit(); |
f9f354fc | 507 | if !recursion_limit.value_within_limit(self.depth) { |
487cf647 FG |
508 | self.selcx.infcx.err_ctxt().report_overflow_error( |
509 | &ty, | |
510 | self.cause.span, | |
511 | true, | |
512 | |_| {}, | |
ba9703b0 | 513 | ); |
ba9703b0 XL |
514 | } |
515 | ||
923072b8 | 516 | let substs = substs.fold_with(self); |
9ffffee4 FG |
517 | let generic_ty = self.interner().type_of(def_id); |
518 | let concrete_ty = generic_ty.subst(self.interner(), substs); | |
ba9703b0 XL |
519 | self.depth += 1; |
520 | let folded_ty = self.fold_ty(concrete_ty); | |
521 | self.depth -= 1; | |
522 | folded_ty | |
523 | } | |
524 | } | |
525 | } | |
526 | ||
9c376795 | 527 | ty::Alias(ty::Projection, data) if !data.has_escaping_bound_vars() => { |
94222f64 XL |
528 | // This branch is *mostly* just an optimization: when we don't |
529 | // have escaping bound vars, we don't need to replace them with | |
530 | // placeholders (see branch below). *Also*, we know that we can | |
531 | // register an obligation to *later* project, since we know | |
532 | // there won't be bound vars there. | |
923072b8 | 533 | let data = data.fold_with(self); |
5e7ed085 FG |
534 | let normalized_ty = if self.eager_inference_replacement { |
535 | normalize_projection_type( | |
536 | self.selcx, | |
537 | self.param_env, | |
538 | data, | |
539 | self.cause.clone(), | |
540 | self.depth, | |
541 | &mut self.obligations, | |
542 | ) | |
543 | } else { | |
544 | opt_normalize_projection_type( | |
545 | self.selcx, | |
546 | self.param_env, | |
547 | data, | |
548 | self.cause.clone(), | |
549 | self.depth, | |
550 | &mut self.obligations, | |
551 | ) | |
552 | .ok() | |
553 | .flatten() | |
f2b60f7d | 554 | .unwrap_or_else(|| ty.super_fold_with(self).into()) |
5e7ed085 | 555 | }; |
ba9703b0 | 556 | debug!( |
29967ef6 XL |
557 | ?self.depth, |
558 | ?ty, | |
559 | ?normalized_ty, | |
560 | obligations.len = ?self.obligations.len(), | |
561 | "AssocTypeNormalizer: normalized type" | |
ba9703b0 | 562 | ); |
5099ac24 | 563 | normalized_ty.ty().unwrap() |
ba9703b0 XL |
564 | } |
565 | ||
9c376795 | 566 | ty::Alias(ty::Projection, data) => { |
94222f64 XL |
567 | // If there are escaping bound vars, we temporarily replace the |
568 | // bound vars with placeholders. Note though, that in the case | |
569 | // that we still can't project for whatever reason (e.g. self | |
570 | // type isn't known enough), we *can't* register an obligation | |
571 | // and return an inference variable (since then that obligation | |
572 | // would have bound vars and that's a can of worms). Instead, | |
573 | // we just give up and fall back to pretending like we never tried! | |
574 | // | |
575 | // Note: this isn't necessarily the final approach here; we may | |
576 | // want to figure out how to register obligations with escaping vars | |
577 | // or handle this some other way. | |
136023e0 | 578 | |
487cf647 | 579 | let infcx = self.selcx.infcx; |
136023e0 XL |
580 | let (data, mapped_regions, mapped_types, mapped_consts) = |
581 | BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data); | |
923072b8 | 582 | let data = data.fold_with(self); |
136023e0 XL |
583 | let normalized_ty = opt_normalize_projection_type( |
584 | self.selcx, | |
585 | self.param_env, | |
586 | data, | |
587 | self.cause.clone(), | |
588 | self.depth, | |
589 | &mut self.obligations, | |
590 | ) | |
591 | .ok() | |
592 | .flatten() | |
5099ac24 | 593 | .map(|term| term.ty().unwrap()) |
94222f64 XL |
594 | .map(|normalized_ty| { |
595 | PlaceholderReplacer::replace_placeholders( | |
596 | infcx, | |
597 | mapped_regions, | |
598 | mapped_types, | |
599 | mapped_consts, | |
600 | &self.universes, | |
601 | normalized_ty, | |
602 | ) | |
603 | }) | |
604 | .unwrap_or_else(|| ty.super_fold_with(self)); | |
605 | ||
136023e0 XL |
606 | debug!( |
607 | ?self.depth, | |
608 | ?ty, | |
609 | ?normalized_ty, | |
610 | obligations.len = ?self.obligations.len(), | |
611 | "AssocTypeNormalizer: normalized type" | |
612 | ); | |
613 | normalized_ty | |
614 | } | |
615 | ||
94222f64 | 616 | _ => ty.super_fold_with(self), |
ba9703b0 XL |
617 | } |
618 | } | |
619 | ||
923072b8 | 620 | #[instrument(skip(self), level = "debug")] |
5099ac24 | 621 | fn fold_const(&mut self, constant: ty::Const<'tcx>) -> ty::Const<'tcx> { |
f2b60f7d | 622 | let tcx = self.selcx.tcx(); |
487cf647 | 623 | if tcx.lazy_normalization() || !needs_normalization(&constant, self.param_env.reveal()) { |
f9f354fc XL |
624 | constant |
625 | } else { | |
626 | let constant = constant.super_fold_with(self); | |
f2b60f7d FG |
627 | debug!(?constant, ?self.param_env); |
628 | with_replaced_escaping_bound_vars( | |
487cf647 | 629 | self.selcx.infcx, |
f2b60f7d FG |
630 | &mut self.universes, |
631 | constant, | |
632 | |constant| constant.eval(tcx, self.param_env), | |
633 | ) | |
634 | } | |
635 | } | |
636 | ||
637 | #[inline] | |
638 | fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> { | |
639 | if p.allow_normalization() && needs_normalization(&p, self.param_env.reveal()) { | |
640 | p.super_fold_with(self) | |
641 | } else { | |
642 | p | |
f9f354fc | 643 | } |
ba9703b0 XL |
644 | } |
645 | } | |
646 | ||
136023e0 | 647 | pub struct BoundVarReplacer<'me, 'tcx> { |
2b03887a | 648 | infcx: &'me InferCtxt<'tcx>, |
136023e0 XL |
649 | // These three maps track the bound variable that were replaced by placeholders. It might be |
650 | // nice to remove these since we already have the `kind` in the placeholder; we really just need | |
651 | // the `var` (but we *could* bring that into scope if we were to track them as we pass them). | |
652 | mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>, | |
653 | mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>, | |
654 | mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>, | |
655 | // The current depth relative to *this* folding, *not* the entire normalization. In other words, | |
656 | // the depth of binders we've passed here. | |
657 | current_index: ty::DebruijnIndex, | |
658 | // The `UniverseIndex` of the binding levels above us. These are optional, since we are lazy: | |
659 | // we don't actually create a universe until we see a bound var we have to replace. | |
660 | universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>, | |
661 | } | |
662 | ||
f2b60f7d FG |
663 | /// Executes `f` on `value` after replacing all escaping bound variables with placeholders |
664 | /// and then replaces these placeholders with the original bound variables in the result. | |
665 | /// | |
666 | /// In most places, bound variables should be replaced right when entering a binder, making | |
667 | /// this function unnecessary. However, normalization currently does not do that, so we have | |
668 | /// to do this lazily. | |
669 | /// | |
670 | /// You should not add any additional uses of this function, at least not without first | |
671 | /// discussing it with t-types. | |
672 | /// | |
673 | /// FIXME(@lcnr): We may even consider experimenting with eagerly replacing bound vars during | |
674 | /// normalization as well, at which point this function will be unnecessary and can be removed. | |
9ffffee4 FG |
675 | pub fn with_replaced_escaping_bound_vars< |
676 | 'a, | |
677 | 'tcx, | |
678 | T: TypeFoldable<TyCtxt<'tcx>>, | |
679 | R: TypeFoldable<TyCtxt<'tcx>>, | |
680 | >( | |
2b03887a | 681 | infcx: &'a InferCtxt<'tcx>, |
f2b60f7d FG |
682 | universe_indices: &'a mut Vec<Option<ty::UniverseIndex>>, |
683 | value: T, | |
684 | f: impl FnOnce(T) -> R, | |
685 | ) -> R { | |
686 | if value.has_escaping_bound_vars() { | |
687 | let (value, mapped_regions, mapped_types, mapped_consts) = | |
688 | BoundVarReplacer::replace_bound_vars(infcx, universe_indices, value); | |
689 | let result = f(value); | |
690 | PlaceholderReplacer::replace_placeholders( | |
691 | infcx, | |
692 | mapped_regions, | |
693 | mapped_types, | |
694 | mapped_consts, | |
695 | universe_indices, | |
696 | result, | |
697 | ) | |
698 | } else { | |
699 | f(value) | |
700 | } | |
701 | } | |
702 | ||
136023e0 XL |
703 | impl<'me, 'tcx> BoundVarReplacer<'me, 'tcx> { |
704 | /// Returns `Some` if we *were* able to replace bound vars. If there are any bound vars that | |
705 | /// use a binding level above `universe_indices.len()`, we fail. | |
9ffffee4 | 706 | pub fn replace_bound_vars<T: TypeFoldable<TyCtxt<'tcx>>>( |
2b03887a | 707 | infcx: &'me InferCtxt<'tcx>, |
136023e0 XL |
708 | universe_indices: &'me mut Vec<Option<ty::UniverseIndex>>, |
709 | value: T, | |
710 | ) -> ( | |
711 | T, | |
712 | BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>, | |
713 | BTreeMap<ty::PlaceholderType, ty::BoundTy>, | |
714 | BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>, | |
715 | ) { | |
716 | let mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion> = BTreeMap::new(); | |
717 | let mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy> = BTreeMap::new(); | |
718 | let mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar> = BTreeMap::new(); | |
719 | ||
720 | let mut replacer = BoundVarReplacer { | |
721 | infcx, | |
722 | mapped_regions, | |
723 | mapped_types, | |
724 | mapped_consts, | |
725 | current_index: ty::INNERMOST, | |
726 | universe_indices, | |
727 | }; | |
728 | ||
923072b8 | 729 | let value = value.fold_with(&mut replacer); |
136023e0 XL |
730 | |
731 | (value, replacer.mapped_regions, replacer.mapped_types, replacer.mapped_consts) | |
732 | } | |
733 | ||
734 | fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex { | |
735 | let infcx = self.infcx; | |
736 | let index = | |
c295e0f8 | 737 | self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1; |
136023e0 XL |
738 | let universe = self.universe_indices[index].unwrap_or_else(|| { |
739 | for i in self.universe_indices.iter_mut().take(index + 1) { | |
740 | *i = i.or_else(|| Some(infcx.create_next_universe())) | |
741 | } | |
742 | self.universe_indices[index].unwrap() | |
743 | }); | |
744 | universe | |
745 | } | |
746 | } | |
747 | ||
9ffffee4 FG |
748 | impl<'tcx> TypeFolder<TyCtxt<'tcx>> for BoundVarReplacer<'_, 'tcx> { |
749 | fn interner(&self) -> TyCtxt<'tcx> { | |
136023e0 XL |
750 | self.infcx.tcx |
751 | } | |
752 | ||
9ffffee4 | 753 | fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>( |
136023e0 XL |
754 | &mut self, |
755 | t: ty::Binder<'tcx, T>, | |
756 | ) -> ty::Binder<'tcx, T> { | |
757 | self.current_index.shift_in(1); | |
758 | let t = t.super_fold_with(self); | |
759 | self.current_index.shift_out(1); | |
760 | t | |
761 | } | |
762 | ||
763 | fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { | |
764 | match *r { | |
765 | ty::ReLateBound(debruijn, _) | |
766 | if debruijn.as_usize() + 1 | |
767 | > self.current_index.as_usize() + self.universe_indices.len() => | |
768 | { | |
769 | bug!("Bound vars outside of `self.universe_indices`"); | |
770 | } | |
771 | ty::ReLateBound(debruijn, br) if debruijn >= self.current_index => { | |
772 | let universe = self.universe_for(debruijn); | |
773 | let p = ty::PlaceholderRegion { universe, name: br.kind }; | |
c295e0f8 | 774 | self.mapped_regions.insert(p, br); |
9ffffee4 | 775 | self.infcx.tcx.mk_re_placeholder(p) |
136023e0 XL |
776 | } |
777 | _ => r, | |
778 | } | |
779 | } | |
780 | ||
781 | fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { | |
782 | match *t.kind() { | |
783 | ty::Bound(debruijn, _) | |
784 | if debruijn.as_usize() + 1 | |
785 | > self.current_index.as_usize() + self.universe_indices.len() => | |
786 | { | |
787 | bug!("Bound vars outside of `self.universe_indices`"); | |
788 | } | |
789 | ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => { | |
790 | let universe = self.universe_for(debruijn); | |
9ffffee4 | 791 | let p = ty::PlaceholderType { universe, name: bound_ty.kind }; |
c295e0f8 | 792 | self.mapped_types.insert(p, bound_ty); |
9ffffee4 | 793 | self.infcx.tcx.mk_placeholder(p) |
136023e0 XL |
794 | } |
795 | _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self), | |
796 | _ => t, | |
797 | } | |
798 | } | |
799 | ||
5099ac24 | 800 | fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> { |
923072b8 | 801 | match ct.kind() { |
5099ac24 | 802 | ty::ConstKind::Bound(debruijn, _) |
136023e0 XL |
803 | if debruijn.as_usize() + 1 |
804 | > self.current_index.as_usize() + self.universe_indices.len() => | |
805 | { | |
806 | bug!("Bound vars outside of `self.universe_indices`"); | |
807 | } | |
5099ac24 | 808 | ty::ConstKind::Bound(debruijn, bound_const) if debruijn >= self.current_index => { |
136023e0 | 809 | let universe = self.universe_for(debruijn); |
064997fb | 810 | let p = ty::PlaceholderConst { universe, name: bound_const }; |
c295e0f8 | 811 | self.mapped_consts.insert(p, bound_const); |
487cf647 | 812 | self.infcx.tcx.mk_const(p, ct.ty()) |
136023e0 | 813 | } |
064997fb | 814 | _ => ct.super_fold_with(self), |
136023e0 XL |
815 | } |
816 | } | |
064997fb FG |
817 | |
818 | fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> { | |
819 | if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p } | |
820 | } | |
136023e0 XL |
821 | } |
822 | ||
487cf647 | 823 | /// The inverse of [`BoundVarReplacer`]: replaces placeholders with the bound vars from which they came. |
136023e0 | 824 | pub struct PlaceholderReplacer<'me, 'tcx> { |
2b03887a | 825 | infcx: &'me InferCtxt<'tcx>, |
136023e0 XL |
826 | mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>, |
827 | mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>, | |
828 | mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>, | |
923072b8 | 829 | universe_indices: &'me [Option<ty::UniverseIndex>], |
136023e0 XL |
830 | current_index: ty::DebruijnIndex, |
831 | } | |
832 | ||
833 | impl<'me, 'tcx> PlaceholderReplacer<'me, 'tcx> { | |
9ffffee4 | 834 | pub fn replace_placeholders<T: TypeFoldable<TyCtxt<'tcx>>>( |
2b03887a | 835 | infcx: &'me InferCtxt<'tcx>, |
136023e0 XL |
836 | mapped_regions: BTreeMap<ty::PlaceholderRegion, ty::BoundRegion>, |
837 | mapped_types: BTreeMap<ty::PlaceholderType, ty::BoundTy>, | |
838 | mapped_consts: BTreeMap<ty::PlaceholderConst<'tcx>, ty::BoundVar>, | |
923072b8 | 839 | universe_indices: &'me [Option<ty::UniverseIndex>], |
136023e0 XL |
840 | value: T, |
841 | ) -> T { | |
842 | let mut replacer = PlaceholderReplacer { | |
843 | infcx, | |
844 | mapped_regions, | |
845 | mapped_types, | |
846 | mapped_consts, | |
847 | universe_indices, | |
848 | current_index: ty::INNERMOST, | |
849 | }; | |
923072b8 | 850 | value.fold_with(&mut replacer) |
136023e0 XL |
851 | } |
852 | } | |
853 | ||
9ffffee4 FG |
854 | impl<'tcx> TypeFolder<TyCtxt<'tcx>> for PlaceholderReplacer<'_, 'tcx> { |
855 | fn interner(&self) -> TyCtxt<'tcx> { | |
136023e0 XL |
856 | self.infcx.tcx |
857 | } | |
858 | ||
9ffffee4 | 859 | fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>( |
136023e0 XL |
860 | &mut self, |
861 | t: ty::Binder<'tcx, T>, | |
862 | ) -> ty::Binder<'tcx, T> { | |
863 | if !t.has_placeholders() && !t.has_infer_regions() { | |
864 | return t; | |
865 | } | |
866 | self.current_index.shift_in(1); | |
867 | let t = t.super_fold_with(self); | |
868 | self.current_index.shift_out(1); | |
869 | t | |
870 | } | |
871 | ||
872 | fn fold_region(&mut self, r0: ty::Region<'tcx>) -> ty::Region<'tcx> { | |
5099ac24 | 873 | let r1 = match *r0 { |
136023e0 XL |
874 | ty::ReVar(_) => self |
875 | .infcx | |
876 | .inner | |
877 | .borrow_mut() | |
878 | .unwrap_region_constraints() | |
879 | .opportunistic_resolve_region(self.infcx.tcx, r0), | |
880 | _ => r0, | |
881 | }; | |
882 | ||
883 | let r2 = match *r1 { | |
884 | ty::RePlaceholder(p) => { | |
885 | let replace_var = self.mapped_regions.get(&p); | |
886 | match replace_var { | |
887 | Some(replace_var) => { | |
888 | let index = self | |
889 | .universe_indices | |
890 | .iter() | |
891 | .position(|u| matches!(u, Some(pu) if *pu == p.universe)) | |
892 | .unwrap_or_else(|| bug!("Unexpected placeholder universe.")); | |
893 | let db = ty::DebruijnIndex::from_usize( | |
894 | self.universe_indices.len() - index + self.current_index.as_usize() - 1, | |
895 | ); | |
9ffffee4 | 896 | self.interner().mk_re_late_bound(db, *replace_var) |
136023e0 XL |
897 | } |
898 | None => r1, | |
899 | } | |
900 | } | |
901 | _ => r1, | |
902 | }; | |
903 | ||
904 | debug!(?r0, ?r1, ?r2, "fold_region"); | |
905 | ||
906 | r2 | |
907 | } | |
908 | ||
909 | fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { | |
910 | match *ty.kind() { | |
911 | ty::Placeholder(p) => { | |
912 | let replace_var = self.mapped_types.get(&p); | |
913 | match replace_var { | |
914 | Some(replace_var) => { | |
915 | let index = self | |
916 | .universe_indices | |
917 | .iter() | |
918 | .position(|u| matches!(u, Some(pu) if *pu == p.universe)) | |
919 | .unwrap_or_else(|| bug!("Unexpected placeholder universe.")); | |
920 | let db = ty::DebruijnIndex::from_usize( | |
921 | self.universe_indices.len() - index + self.current_index.as_usize() - 1, | |
922 | ); | |
9ffffee4 | 923 | self.interner().mk_bound(db, *replace_var) |
136023e0 XL |
924 | } |
925 | None => ty, | |
926 | } | |
927 | } | |
928 | ||
929 | _ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self), | |
930 | _ => ty, | |
931 | } | |
932 | } | |
933 | ||
5099ac24 | 934 | fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> { |
923072b8 | 935 | if let ty::ConstKind::Placeholder(p) = ct.kind() { |
136023e0 XL |
936 | let replace_var = self.mapped_consts.get(&p); |
937 | match replace_var { | |
938 | Some(replace_var) => { | |
939 | let index = self | |
940 | .universe_indices | |
941 | .iter() | |
942 | .position(|u| matches!(u, Some(pu) if *pu == p.universe)) | |
943 | .unwrap_or_else(|| bug!("Unexpected placeholder universe.")); | |
944 | let db = ty::DebruijnIndex::from_usize( | |
945 | self.universe_indices.len() - index + self.current_index.as_usize() - 1, | |
946 | ); | |
9ffffee4 | 947 | self.interner().mk_const(ty::ConstKind::Bound(db, *replace_var), ct.ty()) |
136023e0 XL |
948 | } |
949 | None => ct, | |
950 | } | |
951 | } else { | |
952 | ct.super_fold_with(self) | |
953 | } | |
954 | } | |
955 | } | |
956 | ||
ba9703b0 XL |
957 | /// The guts of `normalize`: normalize a specific projection like `<T |
958 | /// as Trait>::Item`. The result is always a type (and possibly | |
959 | /// additional obligations). If ambiguity arises, which implies that | |
960 | /// there are unresolved type variables in the projection, we will | |
961 | /// substitute a fresh type variable `$X` and generate a new | |
962 | /// obligation `<T as Trait>::Item == $X` for later. | |
963 | pub fn normalize_projection_type<'a, 'b, 'tcx>( | |
964 | selcx: &'a mut SelectionContext<'b, 'tcx>, | |
965 | param_env: ty::ParamEnv<'tcx>, | |
9c376795 | 966 | projection_ty: ty::AliasTy<'tcx>, |
ba9703b0 XL |
967 | cause: ObligationCause<'tcx>, |
968 | depth: usize, | |
969 | obligations: &mut Vec<PredicateObligation<'tcx>>, | |
5099ac24 | 970 | ) -> Term<'tcx> { |
ba9703b0 XL |
971 | opt_normalize_projection_type( |
972 | selcx, | |
973 | param_env, | |
974 | projection_ty, | |
975 | cause.clone(), | |
976 | depth, | |
977 | obligations, | |
978 | ) | |
f9652781 XL |
979 | .ok() |
980 | .flatten() | |
ba9703b0 XL |
981 | .unwrap_or_else(move || { |
982 | // if we bottom out in ambiguity, create a type variable | |
983 | // and a deferred predicate to resolve this when more type | |
984 | // information is available. | |
985 | ||
487cf647 | 986 | selcx.infcx.infer_projection(param_env, projection_ty, cause, depth + 1, obligations).into() |
ba9703b0 XL |
987 | }) |
988 | } | |
989 | ||
990 | /// The guts of `normalize`: normalize a specific projection like `<T | |
991 | /// as Trait>::Item`. The result is always a type (and possibly | |
992 | /// additional obligations). Returns `None` in the case of ambiguity, | |
993 | /// which indicates that there are unbound type variables. | |
994 | /// | |
995 | /// This function used to return `Option<NormalizedTy<'tcx>>`, which contains a | |
996 | /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very | |
997 | /// often immediately appended to another obligations vector. So now this | |
998 | /// function takes an obligations vector and appends to it directly, which is | |
999 | /// slightly uglier but avoids the need for an extra short-lived allocation. | |
29967ef6 | 1000 | #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))] |
ba9703b0 XL |
1001 | fn opt_normalize_projection_type<'a, 'b, 'tcx>( |
1002 | selcx: &'a mut SelectionContext<'b, 'tcx>, | |
1003 | param_env: ty::ParamEnv<'tcx>, | |
9c376795 | 1004 | projection_ty: ty::AliasTy<'tcx>, |
ba9703b0 XL |
1005 | cause: ObligationCause<'tcx>, |
1006 | depth: usize, | |
1007 | obligations: &mut Vec<PredicateObligation<'tcx>>, | |
5099ac24 | 1008 | ) -> Result<Option<Term<'tcx>>, InProgress> { |
487cf647 | 1009 | let infcx = selcx.infcx; |
94222f64 XL |
1010 | // Don't use the projection cache in intercrate mode - |
1011 | // the `infcx` may be re-used between intercrate in non-intercrate | |
1012 | // mode, which could lead to using incorrect cache results. | |
1013 | let use_cache = !selcx.is_intercrate(); | |
ba9703b0 | 1014 | |
fc512014 | 1015 | let projection_ty = infcx.resolve_vars_if_possible(projection_ty); |
ba9703b0 XL |
1016 | let cache_key = ProjectionCacheKey::new(projection_ty); |
1017 | ||
ba9703b0 XL |
1018 | // FIXME(#20304) For now, I am caching here, which is good, but it |
1019 | // means we don't capture the type variables that are created in | |
1020 | // the case of ambiguity. Which means we may create a large stream | |
1021 | // of such variables. OTOH, if we move the caching up a level, we | |
1022 | // would not benefit from caching when proving `T: Trait<U=Foo>` | |
1023 | // bounds. It might be the case that we want two distinct caches, | |
1024 | // or else another kind of cache entry. | |
1025 | ||
94222f64 XL |
1026 | let cache_result = if use_cache { |
1027 | infcx.inner.borrow_mut().projection_cache().try_start(cache_key) | |
1028 | } else { | |
1029 | Ok(()) | |
1030 | }; | |
ba9703b0 | 1031 | match cache_result { |
136023e0 | 1032 | Ok(()) => debug!("no cache"), |
ba9703b0 XL |
1033 | Err(ProjectionCacheEntry::Ambiguous) => { |
1034 | // If we found ambiguity the last time, that means we will continue | |
1035 | // to do so until some type in the key changes (and we know it | |
1036 | // hasn't, because we just fully resolved it). | |
29967ef6 | 1037 | debug!("found cache entry: ambiguous"); |
f9652781 | 1038 | return Ok(None); |
ba9703b0 XL |
1039 | } |
1040 | Err(ProjectionCacheEntry::InProgress) => { | |
ba9703b0 | 1041 | // Under lazy normalization, this can arise when |
9c376795 | 1042 | // bootstrapping. That is, imagine an environment with a |
ba9703b0 XL |
1043 | // where-clause like `A::B == u32`. Now, if we are asked |
1044 | // to normalize `A::B`, we will want to check the | |
1045 | // where-clauses in scope. So we will try to unify `A::B` | |
1046 | // with `A::B`, which can trigger a recursive | |
f9652781 | 1047 | // normalization. |
ba9703b0 | 1048 | |
29967ef6 | 1049 | debug!("found cache entry: in-progress"); |
ba9703b0 | 1050 | |
b9856134 XL |
1051 | // Cache that normalizing this projection resulted in a cycle. This |
1052 | // should ensure that, unless this happens within a snapshot that's | |
1053 | // rolled back, fulfillment or evaluation will notice the cycle. | |
1054 | ||
94222f64 XL |
1055 | if use_cache { |
1056 | infcx.inner.borrow_mut().projection_cache().recur(cache_key); | |
1057 | } | |
b9856134 XL |
1058 | return Err(InProgress); |
1059 | } | |
1060 | Err(ProjectionCacheEntry::Recur) => { | |
136023e0 | 1061 | debug!("recur cache"); |
f9652781 | 1062 | return Err(InProgress); |
ba9703b0 | 1063 | } |
a2a8927a | 1064 | Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => { |
ba9703b0 XL |
1065 | // This is the hottest path in this function. |
1066 | // | |
1067 | // If we find the value in the cache, then return it along | |
1068 | // with the obligations that went along with it. Note | |
1069 | // that, when using a fulfillment context, these | |
1070 | // obligations could in principle be ignored: they have | |
1071 | // already been registered when the cache entry was | |
1072 | // created (and hence the new ones will quickly be | |
1073 | // discarded as duplicated). But when doing trait | |
1074 | // evaluation this is not the case, and dropping the trait | |
1075 | // evaluations can causes ICEs (e.g., #43132). | |
29967ef6 | 1076 | debug!(?ty, "found normalized ty"); |
17df50a5 | 1077 | obligations.extend(ty.obligations); |
f9652781 | 1078 | return Ok(Some(ty.value)); |
ba9703b0 XL |
1079 | } |
1080 | Err(ProjectionCacheEntry::Error) => { | |
29967ef6 | 1081 | debug!("opt_normalize_projection_type: found error"); |
ba9703b0 XL |
1082 | let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth); |
1083 | obligations.extend(result.obligations); | |
5099ac24 | 1084 | return Ok(Some(result.value.into())); |
ba9703b0 XL |
1085 | } |
1086 | } | |
1087 | ||
487cf647 FG |
1088 | let obligation = |
1089 | Obligation::with_depth(selcx.tcx(), cause.clone(), depth, param_env, projection_ty); | |
94222f64 | 1090 | |
5099ac24 FG |
1091 | match project(selcx, &obligation) { |
1092 | Ok(Projected::Progress(Progress { | |
1093 | term: projected_term, | |
ba9703b0 XL |
1094 | obligations: mut projected_obligations, |
1095 | })) => { | |
1096 | // if projection succeeded, then what we get out of this | |
1097 | // is also non-normalized (consider: it was derived from | |
1098 | // an impl, where-clause etc) and hence we must | |
1099 | // re-normalize it | |
1100 | ||
487cf647 | 1101 | let projected_term = selcx.infcx.resolve_vars_if_possible(projected_term); |
ba9703b0 | 1102 | |
5099ac24 | 1103 | let mut result = if projected_term.has_projections() { |
ba9703b0 XL |
1104 | let mut normalizer = AssocTypeNormalizer::new( |
1105 | selcx, | |
1106 | param_env, | |
1107 | cause, | |
1108 | depth + 1, | |
1109 | &mut projected_obligations, | |
1110 | ); | |
5099ac24 | 1111 | let normalized_ty = normalizer.fold(projected_term); |
ba9703b0 XL |
1112 | |
1113 | Normalized { value: normalized_ty, obligations: projected_obligations } | |
1114 | } else { | |
5099ac24 | 1115 | Normalized { value: projected_term, obligations: projected_obligations } |
ba9703b0 XL |
1116 | }; |
1117 | ||
3c0e092e | 1118 | let mut deduped: SsoHashSet<_> = Default::default(); |
94222f64 | 1119 | result.obligations.drain_filter(|projected_obligation| { |
3c0e092e XL |
1120 | if !deduped.insert(projected_obligation.clone()) { |
1121 | return true; | |
1122 | } | |
a2a8927a | 1123 | false |
94222f64 XL |
1124 | }); |
1125 | ||
1126 | if use_cache { | |
5099ac24 | 1127 | infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone()); |
94222f64 | 1128 | } |
ba9703b0 | 1129 | obligations.extend(result.obligations); |
f9652781 | 1130 | Ok(Some(result.value)) |
ba9703b0 | 1131 | } |
5099ac24 | 1132 | Ok(Projected::NoProgress(projected_ty)) => { |
ba9703b0 | 1133 | let result = Normalized { value: projected_ty, obligations: vec![] }; |
94222f64 | 1134 | if use_cache { |
5099ac24 | 1135 | infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone()); |
94222f64 | 1136 | } |
ba9703b0 | 1137 | // No need to extend `obligations`. |
f9652781 | 1138 | Ok(Some(result.value)) |
ba9703b0 | 1139 | } |
5099ac24 | 1140 | Err(ProjectionError::TooManyCandidates) => { |
29967ef6 | 1141 | debug!("opt_normalize_projection_type: too many candidates"); |
94222f64 XL |
1142 | if use_cache { |
1143 | infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key); | |
1144 | } | |
f9652781 | 1145 | Ok(None) |
ba9703b0 | 1146 | } |
5099ac24 | 1147 | Err(ProjectionError::TraitSelectionError(_)) => { |
ba9703b0 XL |
1148 | debug!("opt_normalize_projection_type: ERROR"); |
1149 | // if we got an error processing the `T as Trait` part, | |
1150 | // just return `ty::err` but add the obligation `T : | |
1151 | // Trait`, which when processed will cause the error to be | |
1152 | // reported later | |
1153 | ||
94222f64 XL |
1154 | if use_cache { |
1155 | infcx.inner.borrow_mut().projection_cache().error(cache_key); | |
1156 | } | |
ba9703b0 XL |
1157 | let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth); |
1158 | obligations.extend(result.obligations); | |
5099ac24 | 1159 | Ok(Some(result.value.into())) |
ba9703b0 XL |
1160 | } |
1161 | } | |
1162 | } | |
1163 | ||
ba9703b0 XL |
1164 | /// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not |
1165 | /// hold. In various error cases, we cannot generate a valid | |
1166 | /// normalized projection. Therefore, we create an inference variable | |
1167 | /// return an associated obligation that, when fulfilled, will lead to | |
1168 | /// an error. | |
1169 | /// | |
1170 | /// Note that we used to return `Error` here, but that was quite | |
1171 | /// dubious -- the premise was that an error would *eventually* be | |
1172 | /// reported, when the obligation was processed. But in general once | |
94222f64 | 1173 | /// you see an `Error` you are supposed to be able to assume that an |
ba9703b0 XL |
1174 | /// error *has been* reported, so that you can take whatever heuristic |
1175 | /// paths you want to take. To make things worse, it was possible for | |
1176 | /// cycles to arise, where you basically had a setup like `<MyType<$0> | |
1177 | /// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as | |
9ffffee4 | 1178 | /// Trait>::Foo>` to `[type error]` would lead to an obligation of |
ba9703b0 XL |
1179 | /// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report |
1180 | /// an error for this obligation, but we legitimately should not, | |
1181 | /// because it contains `[type error]`. Yuck! (See issue #29857 for | |
1182 | /// one case where this arose.) | |
1183 | fn normalize_to_error<'a, 'tcx>( | |
1184 | selcx: &mut SelectionContext<'a, 'tcx>, | |
1185 | param_env: ty::ParamEnv<'tcx>, | |
9c376795 | 1186 | projection_ty: ty::AliasTy<'tcx>, |
ba9703b0 XL |
1187 | cause: ObligationCause<'tcx>, |
1188 | depth: usize, | |
1189 | ) -> NormalizedTy<'tcx> { | |
c295e0f8 | 1190 | let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx())); |
ba9703b0 XL |
1191 | let trait_obligation = Obligation { |
1192 | cause, | |
1193 | recursion_depth: depth, | |
1194 | param_env, | |
f9f354fc | 1195 | predicate: trait_ref.without_const().to_predicate(selcx.tcx()), |
ba9703b0 | 1196 | }; |
487cf647 | 1197 | let tcx = selcx.infcx.tcx; |
487cf647 | 1198 | let new_value = selcx.infcx.next_ty_var(TypeVariableOrigin { |
ba9703b0 | 1199 | kind: TypeVariableOriginKind::NormalizeProjectionType, |
9c376795 | 1200 | span: tcx.def_span(projection_ty.def_id), |
ba9703b0 XL |
1201 | }); |
1202 | Normalized { value: new_value, obligations: vec![trait_obligation] } | |
1203 | } | |
1204 | ||
5099ac24 | 1205 | enum Projected<'tcx> { |
ba9703b0 | 1206 | Progress(Progress<'tcx>), |
5099ac24 | 1207 | NoProgress(ty::Term<'tcx>), |
ba9703b0 XL |
1208 | } |
1209 | ||
1210 | struct Progress<'tcx> { | |
5099ac24 | 1211 | term: ty::Term<'tcx>, |
ba9703b0 XL |
1212 | obligations: Vec<PredicateObligation<'tcx>>, |
1213 | } | |
1214 | ||
1215 | impl<'tcx> Progress<'tcx> { | |
9ffffee4 FG |
1216 | fn error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self { |
1217 | Progress { term: tcx.ty_error(guar).into(), obligations: vec![] } | |
ba9703b0 XL |
1218 | } |
1219 | ||
1220 | fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx>>) -> Self { | |
ba9703b0 XL |
1221 | self.obligations.append(&mut obligations); |
1222 | self | |
1223 | } | |
1224 | } | |
1225 | ||
1226 | /// Computes the result of a projection type (if we can). | |
1227 | /// | |
1228 | /// IMPORTANT: | |
1229 | /// - `obligation` must be fully normalized | |
f2b60f7d | 1230 | #[instrument(level = "info", skip(selcx))] |
5099ac24 | 1231 | fn project<'cx, 'tcx>( |
ba9703b0 XL |
1232 | selcx: &mut SelectionContext<'cx, 'tcx>, |
1233 | obligation: &ProjectionTyObligation<'tcx>, | |
5099ac24 | 1234 | ) -> Result<Projected<'tcx>, ProjectionError<'tcx>> { |
136023e0 | 1235 | if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) { |
fc512014 XL |
1236 | // This should really be an immediate error, but some existing code |
1237 | // relies on being able to recover from this. | |
5e7ed085 FG |
1238 | return Err(ProjectionError::TraitSelectionError(SelectionError::Overflow( |
1239 | OverflowError::Canonical, | |
1240 | ))); | |
ba9703b0 XL |
1241 | } |
1242 | ||
9ffffee4 FG |
1243 | if let Err(guar) = obligation.predicate.error_reported() { |
1244 | return Ok(Projected::Progress(Progress::error(selcx.tcx(), guar))); | |
ba9703b0 XL |
1245 | } |
1246 | ||
5099ac24 | 1247 | let mut candidates = ProjectionCandidateSet::None; |
ba9703b0 | 1248 | |
f2b60f7d FG |
1249 | assemble_candidate_for_impl_trait_in_trait(selcx, obligation, &mut candidates); |
1250 | ||
ba9703b0 XL |
1251 | // Make sure that the following procedures are kept in order. ParamEnv |
1252 | // needs to be first because it has highest priority, and Select checks | |
1253 | // the return value of push_candidate which assumes it's ran at last. | |
6a06907d | 1254 | assemble_candidates_from_param_env(selcx, obligation, &mut candidates); |
ba9703b0 | 1255 | |
6a06907d | 1256 | assemble_candidates_from_trait_def(selcx, obligation, &mut candidates); |
ba9703b0 | 1257 | |
6a06907d | 1258 | assemble_candidates_from_object_ty(selcx, obligation, &mut candidates); |
29967ef6 | 1259 | |
5099ac24 | 1260 | if let ProjectionCandidateSet::Single(ProjectionCandidate::Object(_)) = candidates { |
29967ef6 XL |
1261 | // Avoid normalization cycle from selection (see |
1262 | // `assemble_candidates_from_object_ty`). | |
1263 | // FIXME(lazy_normalization): Lazy normalization should save us from | |
6a06907d | 1264 | // having to special case this. |
29967ef6 | 1265 | } else { |
6a06907d | 1266 | assemble_candidates_from_impls(selcx, obligation, &mut candidates); |
29967ef6 | 1267 | }; |
ba9703b0 XL |
1268 | |
1269 | match candidates { | |
5099ac24 FG |
1270 | ProjectionCandidateSet::Single(candidate) => { |
1271 | Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate))) | |
29967ef6 | 1272 | } |
5099ac24 FG |
1273 | ProjectionCandidateSet::None => Ok(Projected::NoProgress( |
1274 | // FIXME(associated_const_generics): this may need to change in the future? | |
1275 | // need to investigate whether or not this is fine. | |
ba9703b0 XL |
1276 | selcx |
1277 | .tcx() | |
9c376795 | 1278 | .mk_projection(obligation.predicate.def_id, obligation.predicate.substs) |
5099ac24 | 1279 | .into(), |
ba9703b0 XL |
1280 | )), |
1281 | // Error occurred while trying to processing impls. | |
5099ac24 | 1282 | ProjectionCandidateSet::Error(e) => Err(ProjectionError::TraitSelectionError(e)), |
ba9703b0 XL |
1283 | // Inherent ambiguity that prevents us from even enumerating the |
1284 | // candidates. | |
5099ac24 | 1285 | ProjectionCandidateSet::Ambiguous => Err(ProjectionError::TooManyCandidates), |
ba9703b0 XL |
1286 | } |
1287 | } | |
1288 | ||
f2b60f7d FG |
1289 | /// If the predicate's item is an `ImplTraitPlaceholder`, we do a select on the |
1290 | /// corresponding trait ref. If this yields an `impl`, then we're able to project | |
1291 | /// to a concrete type, since we have an `impl`'s method to provide the RPITIT. | |
1292 | fn assemble_candidate_for_impl_trait_in_trait<'cx, 'tcx>( | |
1293 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1294 | obligation: &ProjectionTyObligation<'tcx>, | |
1295 | candidate_set: &mut ProjectionCandidateSet<'tcx>, | |
1296 | ) { | |
1297 | let tcx = selcx.tcx(); | |
9c376795 FG |
1298 | if tcx.def_kind(obligation.predicate.def_id) == DefKind::ImplTraitPlaceholder { |
1299 | let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.def_id); | |
2b03887a | 1300 | |
f2b60f7d FG |
1301 | let trait_def_id = tcx.parent(trait_fn_def_id); |
1302 | let trait_substs = | |
1303 | obligation.predicate.substs.truncate_to(tcx, tcx.generics_of(trait_def_id)); | |
1304 | // FIXME(named-returns): Binders | |
9c376795 | 1305 | let trait_predicate = ty::Binder::dummy(tcx.mk_trait_ref(trait_def_id, trait_substs)); |
f2b60f7d | 1306 | |
487cf647 FG |
1307 | let _ = selcx.infcx.commit_if_ok(|_| { |
1308 | match selcx.select(&obligation.with(tcx, trait_predicate)) { | |
f2b60f7d | 1309 | Ok(Some(super::ImplSource::UserDefined(data))) => { |
9ffffee4 | 1310 | candidate_set.push_candidate(ProjectionCandidate::ImplTraitInTrait(data)); |
f2b60f7d FG |
1311 | Ok(()) |
1312 | } | |
1313 | Ok(None) => { | |
1314 | candidate_set.mark_ambiguous(); | |
9ffffee4 | 1315 | Err(()) |
f2b60f7d FG |
1316 | } |
1317 | Ok(Some(_)) => { | |
1318 | // Don't know enough about the impl to provide a useful signature | |
9ffffee4 | 1319 | Err(()) |
f2b60f7d FG |
1320 | } |
1321 | Err(e) => { | |
1322 | debug!(error = ?e, "selection error"); | |
1323 | candidate_set.mark_error(e); | |
9ffffee4 | 1324 | Err(()) |
f2b60f7d | 1325 | } |
487cf647 FG |
1326 | } |
1327 | }); | |
f2b60f7d FG |
1328 | } |
1329 | } | |
1330 | ||
ba9703b0 XL |
1331 | /// The first thing we have to do is scan through the parameter |
1332 | /// environment to see whether there are any projection predicates | |
1333 | /// there that can answer this question. | |
1334 | fn assemble_candidates_from_param_env<'cx, 'tcx>( | |
1335 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1336 | obligation: &ProjectionTyObligation<'tcx>, | |
5099ac24 | 1337 | candidate_set: &mut ProjectionCandidateSet<'tcx>, |
ba9703b0 | 1338 | ) { |
ba9703b0 XL |
1339 | assemble_candidates_from_predicates( |
1340 | selcx, | |
1341 | obligation, | |
ba9703b0 | 1342 | candidate_set, |
5099ac24 | 1343 | ProjectionCandidate::ParamEnv, |
f035d41b | 1344 | obligation.param_env.caller_bounds().iter(), |
29967ef6 | 1345 | false, |
ba9703b0 XL |
1346 | ); |
1347 | } | |
1348 | ||
2b03887a | 1349 | /// In the case of a nested projection like `<<A as Foo>::FooT as Bar>::BarT`, we may find |
ba9703b0 XL |
1350 | /// that the definition of `Foo` has some clues: |
1351 | /// | |
04454e1e | 1352 | /// ```ignore (illustrative) |
ba9703b0 XL |
1353 | /// trait Foo { |
1354 | /// type FooT : Bar<BarT=i32> | |
1355 | /// } | |
1356 | /// ``` | |
1357 | /// | |
1358 | /// Here, for example, we could conclude that the result is `i32`. | |
1359 | fn assemble_candidates_from_trait_def<'cx, 'tcx>( | |
1360 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1361 | obligation: &ProjectionTyObligation<'tcx>, | |
5099ac24 | 1362 | candidate_set: &mut ProjectionCandidateSet<'tcx>, |
ba9703b0 XL |
1363 | ) { |
1364 | debug!("assemble_candidates_from_trait_def(..)"); | |
1365 | ||
1366 | let tcx = selcx.tcx(); | |
1367 | // Check whether the self-type is itself a projection. | |
f035d41b | 1368 | // If so, extract what we know from the trait and try to come up with a good answer. |
6a06907d | 1369 | let bounds = match *obligation.predicate.self_ty().kind() { |
9c376795 | 1370 | ty::Alias(_, ref data) => tcx.item_bounds(data.def_id).subst(tcx, data.substs), |
ba9703b0 XL |
1371 | ty::Infer(ty::TyVar(_)) => { |
1372 | // If the self-type is an inference variable, then it MAY wind up | |
1373 | // being a projected type, so induce an ambiguity. | |
1374 | candidate_set.mark_ambiguous(); | |
1375 | return; | |
1376 | } | |
1377 | _ => return, | |
1378 | }; | |
1379 | ||
ba9703b0 XL |
1380 | assemble_candidates_from_predicates( |
1381 | selcx, | |
1382 | obligation, | |
ba9703b0 | 1383 | candidate_set, |
5099ac24 | 1384 | ProjectionCandidate::TraitDef, |
f035d41b | 1385 | bounds.iter(), |
29967ef6 | 1386 | true, |
5099ac24 | 1387 | ); |
ba9703b0 XL |
1388 | } |
1389 | ||
29967ef6 XL |
1390 | /// In the case of a trait object like |
1391 | /// `<dyn Iterator<Item = ()> as Iterator>::Item` we can use the existential | |
1392 | /// predicate in the trait object. | |
1393 | /// | |
1394 | /// We don't go through the select candidate for these bounds to avoid cycles: | |
1395 | /// In the above case, `dyn Iterator<Item = ()>: Iterator` would create a | |
1396 | /// nested obligation of `<dyn Iterator<Item = ()> as Iterator>::Item: Sized`, | |
1397 | /// this then has to be normalized without having to prove | |
1398 | /// `dyn Iterator<Item = ()>: Iterator` again. | |
1399 | fn assemble_candidates_from_object_ty<'cx, 'tcx>( | |
1400 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1401 | obligation: &ProjectionTyObligation<'tcx>, | |
5099ac24 | 1402 | candidate_set: &mut ProjectionCandidateSet<'tcx>, |
29967ef6 XL |
1403 | ) { |
1404 | debug!("assemble_candidates_from_object_ty(..)"); | |
1405 | ||
1406 | let tcx = selcx.tcx(); | |
1407 | ||
6a06907d | 1408 | let self_ty = obligation.predicate.self_ty(); |
487cf647 | 1409 | let object_ty = selcx.infcx.shallow_resolve(self_ty); |
29967ef6 XL |
1410 | let data = match object_ty.kind() { |
1411 | ty::Dynamic(data, ..) => data, | |
1412 | ty::Infer(ty::TyVar(_)) => { | |
1413 | // If the self-type is an inference variable, then it MAY wind up | |
1414 | // being an object type, so induce an ambiguity. | |
1415 | candidate_set.mark_ambiguous(); | |
1416 | return; | |
1417 | } | |
1418 | _ => return, | |
1419 | }; | |
1420 | let env_predicates = data | |
1421 | .projection_bounds() | |
9c376795 | 1422 | .filter(|bound| bound.item_def_id() == obligation.predicate.def_id) |
29967ef6 XL |
1423 | .map(|p| p.with_self_ty(tcx, object_ty).to_predicate(tcx)); |
1424 | ||
1425 | assemble_candidates_from_predicates( | |
1426 | selcx, | |
1427 | obligation, | |
29967ef6 | 1428 | candidate_set, |
5099ac24 | 1429 | ProjectionCandidate::Object, |
29967ef6 XL |
1430 | env_predicates, |
1431 | false, | |
1432 | ); | |
1433 | } | |
1434 | ||
f2b60f7d | 1435 | #[instrument( |
5099ac24 FG |
1436 | level = "debug", |
1437 | skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates) | |
1438 | )] | |
ba9703b0 XL |
1439 | fn assemble_candidates_from_predicates<'cx, 'tcx>( |
1440 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1441 | obligation: &ProjectionTyObligation<'tcx>, | |
5099ac24 FG |
1442 | candidate_set: &mut ProjectionCandidateSet<'tcx>, |
1443 | ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>, | |
ba9703b0 | 1444 | env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>, |
29967ef6 | 1445 | potentially_unnormalized_candidates: bool, |
ba9703b0 | 1446 | ) { |
487cf647 | 1447 | let infcx = selcx.infcx; |
ba9703b0 | 1448 | for predicate in env_predicates { |
5869c6ff | 1449 | let bound_predicate = predicate.kind(); |
487cf647 FG |
1450 | if let ty::PredicateKind::Clause(ty::Clause::Projection(data)) = |
1451 | predicate.kind().skip_binder() | |
1452 | { | |
29967ef6 | 1453 | let data = bound_predicate.rebind(data); |
9c376795 | 1454 | if data.projection_def_id() != obligation.predicate.def_id { |
5099ac24 FG |
1455 | continue; |
1456 | } | |
ba9703b0 | 1457 | |
5099ac24 FG |
1458 | let is_match = infcx.probe(|_| { |
1459 | selcx.match_projection_projections( | |
1460 | obligation, | |
1461 | data, | |
1462 | potentially_unnormalized_candidates, | |
1463 | ) | |
1464 | }); | |
29967ef6 | 1465 | |
5099ac24 FG |
1466 | match is_match { |
1467 | ProjectionMatchesProjection::Yes => { | |
1468 | candidate_set.push_candidate(ctor(data)); | |
1469 | ||
1470 | if potentially_unnormalized_candidates | |
2b03887a | 1471 | && !obligation.predicate.has_non_region_infer() |
5099ac24 FG |
1472 | { |
1473 | // HACK: Pick the first trait def candidate for a fully | |
1474 | // inferred predicate. This is to allow duplicates that | |
1475 | // differ only in normalization. | |
1476 | return; | |
1477 | } | |
1478 | } | |
1479 | ProjectionMatchesProjection::Ambiguous => { | |
1480 | candidate_set.mark_ambiguous(); | |
29967ef6 | 1481 | } |
5099ac24 | 1482 | ProjectionMatchesProjection::No => {} |
ba9703b0 XL |
1483 | } |
1484 | } | |
1485 | } | |
1486 | } | |
1487 | ||
f2b60f7d | 1488 | #[instrument(level = "debug", skip(selcx, obligation, candidate_set))] |
ba9703b0 XL |
1489 | fn assemble_candidates_from_impls<'cx, 'tcx>( |
1490 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1491 | obligation: &ProjectionTyObligation<'tcx>, | |
5099ac24 | 1492 | candidate_set: &mut ProjectionCandidateSet<'tcx>, |
ba9703b0 | 1493 | ) { |
f2b60f7d | 1494 | // Can't assemble candidate from impl for RPITIT |
9c376795 | 1495 | if selcx.tcx().def_kind(obligation.predicate.def_id) == DefKind::ImplTraitPlaceholder { |
f2b60f7d FG |
1496 | return; |
1497 | } | |
1498 | ||
ba9703b0 XL |
1499 | // If we are resolving `<T as TraitRef<...>>::Item == Type`, |
1500 | // start out by selecting the predicate `T as TraitRef<...>`: | |
c295e0f8 | 1501 | let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx())); |
487cf647 FG |
1502 | let trait_obligation = obligation.with(selcx.tcx(), poly_trait_ref); |
1503 | let _ = selcx.infcx.commit_if_ok(|_| { | |
f035d41b XL |
1504 | let impl_source = match selcx.select(&trait_obligation) { |
1505 | Ok(Some(impl_source)) => impl_source, | |
ba9703b0 XL |
1506 | Ok(None) => { |
1507 | candidate_set.mark_ambiguous(); | |
1508 | return Err(()); | |
1509 | } | |
1510 | Err(e) => { | |
29967ef6 | 1511 | debug!(error = ?e, "selection error"); |
ba9703b0 XL |
1512 | candidate_set.mark_error(e); |
1513 | return Err(()); | |
1514 | } | |
1515 | }; | |
1516 | ||
f035d41b | 1517 | let eligible = match &impl_source { |
1b1a35ee XL |
1518 | super::ImplSource::Closure(_) |
1519 | | super::ImplSource::Generator(_) | |
487cf647 | 1520 | | super::ImplSource::Future(_) |
1b1a35ee | 1521 | | super::ImplSource::FnPointer(_) |
5099ac24 | 1522 | | super::ImplSource::TraitAlias(_) => true, |
1b1a35ee | 1523 | super::ImplSource::UserDefined(impl_data) => { |
ba9703b0 XL |
1524 | // We have to be careful when projecting out of an |
1525 | // impl because of specialization. If we are not in | |
1526 | // codegen (i.e., projection mode is not "any"), and the | |
1527 | // impl's type is declared as default, then we disable | |
1528 | // projection (even if the trait ref is fully | |
1529 | // monomorphic). In the case where trait ref is not | |
1530 | // fully monomorphic (i.e., includes type parameters), | |
1531 | // this is because those type parameters may | |
1532 | // ultimately be bound to types from other crates that | |
1533 | // may have specialized impls we can't see. In the | |
1534 | // case where the trait ref IS fully monomorphic, this | |
1535 | // is a policy decision that we made in the RFC in | |
1536 | // order to preserve flexibility for the crate that | |
1537 | // defined the specializable impl to specialize later | |
1538 | // for existing types. | |
1539 | // | |
1540 | // In either case, we handle this by not adding a | |
1541 | // candidate for an impl if it contains a `default` | |
1542 | // type. | |
1543 | // | |
1544 | // NOTE: This should be kept in sync with the similar code in | |
fc512014 | 1545 | // `rustc_ty_utils::instance::resolve_associated_item()`. |
ba9703b0 | 1546 | let node_item = |
9c376795 | 1547 | specialization_graph::assoc_def(selcx.tcx(), impl_data.impl_def_id, obligation.predicate.def_id) |
5e7ed085 | 1548 | .map_err(|ErrorGuaranteed { .. }| ())?; |
ba9703b0 XL |
1549 | |
1550 | if node_item.is_final() { | |
1551 | // Non-specializable items are always projectable. | |
1552 | true | |
1553 | } else { | |
1554 | // Only reveal a specializable default if we're past type-checking | |
1555 | // and the obligation is monomorphic, otherwise passes such as | |
1556 | // transmute checking and polymorphic MIR optimizations could | |
1557 | // get a result which isn't correct for all monomorphizations. | |
f035d41b | 1558 | if obligation.param_env.reveal() == Reveal::All { |
ba9703b0 XL |
1559 | // NOTE(eddyb) inference variables can resolve to parameters, so |
1560 | // assume `poly_trait_ref` isn't monomorphic, if it contains any. | |
487cf647 | 1561 | let poly_trait_ref = selcx.infcx.resolve_vars_if_possible(poly_trait_ref); |
ba9703b0 XL |
1562 | !poly_trait_ref.still_further_specializable() |
1563 | } else { | |
1564 | debug!( | |
29967ef6 XL |
1565 | assoc_ty = ?selcx.tcx().def_path_str(node_item.item.def_id), |
1566 | ?obligation.predicate, | |
1567 | "assemble_candidates_from_impls: not eligible due to default", | |
ba9703b0 XL |
1568 | ); |
1569 | false | |
1570 | } | |
1571 | } | |
1572 | } | |
487cf647 FG |
1573 | super::ImplSource::Builtin(..) => { |
1574 | // While a builtin impl may be known to exist, the associated type may not yet | |
1575 | // be known. Any type with multiple potential associated types is therefore | |
1576 | // not eligible. | |
1577 | let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty()); | |
1578 | ||
1579 | let lang_items = selcx.tcx().lang_items(); | |
1580 | if lang_items.discriminant_kind_trait() == Some(poly_trait_ref.def_id()) { | |
1581 | match self_ty.kind() { | |
1582 | ty::Bool | |
1583 | | ty::Char | |
1584 | | ty::Int(_) | |
1585 | | ty::Uint(_) | |
1586 | | ty::Float(_) | |
1587 | | ty::Adt(..) | |
1588 | | ty::Foreign(_) | |
1589 | | ty::Str | |
1590 | | ty::Array(..) | |
1591 | | ty::Slice(_) | |
1592 | | ty::RawPtr(..) | |
1593 | | ty::Ref(..) | |
1594 | | ty::FnDef(..) | |
1595 | | ty::FnPtr(..) | |
1596 | | ty::Dynamic(..) | |
1597 | | ty::Closure(..) | |
1598 | | ty::Generator(..) | |
1599 | | ty::GeneratorWitness(..) | |
9ffffee4 | 1600 | | ty::GeneratorWitnessMIR(..) |
487cf647 FG |
1601 | | ty::Never |
1602 | | ty::Tuple(..) | |
1603 | // Integers and floats always have `u8` as their discriminant. | |
1604 | | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true, | |
1605 | ||
1606 | // type parameters, opaques, and unnormalized projections have pointer | |
1607 | // metadata if they're known (e.g. by the param_env) to be sized | |
1608 | ty::Param(_) | |
9c376795 | 1609 | | ty::Alias(..) |
487cf647 FG |
1610 | | ty::Bound(..) |
1611 | | ty::Placeholder(..) | |
1612 | | ty::Infer(..) | |
1613 | | ty::Error(_) => false, | |
5e7ed085 | 1614 | } |
487cf647 FG |
1615 | } else if lang_items.pointee_trait() == Some(poly_trait_ref.def_id()) { |
1616 | let tail = selcx.tcx().struct_tail_with_normalize( | |
1617 | self_ty, | |
1618 | |ty| { | |
1619 | // We throw away any obligations we get from this, since we normalize | |
1620 | // and confirm these obligations once again during confirmation | |
1621 | normalize_with_depth( | |
1622 | selcx, | |
1623 | obligation.param_env, | |
1624 | obligation.cause.clone(), | |
1625 | obligation.recursion_depth + 1, | |
1626 | ty, | |
1627 | ) | |
1628 | .value | |
1629 | }, | |
1630 | || {}, | |
1631 | ); | |
5e7ed085 | 1632 | |
487cf647 FG |
1633 | match tail.kind() { |
1634 | ty::Bool | |
1635 | | ty::Char | |
1636 | | ty::Int(_) | |
1637 | | ty::Uint(_) | |
1638 | | ty::Float(_) | |
1639 | | ty::Str | |
1640 | | ty::Array(..) | |
1641 | | ty::Slice(_) | |
1642 | | ty::RawPtr(..) | |
1643 | | ty::Ref(..) | |
1644 | | ty::FnDef(..) | |
1645 | | ty::FnPtr(..) | |
1646 | | ty::Dynamic(..) | |
1647 | | ty::Closure(..) | |
1648 | | ty::Generator(..) | |
1649 | | ty::GeneratorWitness(..) | |
9ffffee4 | 1650 | | ty::GeneratorWitnessMIR(..) |
487cf647 FG |
1651 | | ty::Never |
1652 | // Extern types have unit metadata, according to RFC 2850 | |
1653 | | ty::Foreign(_) | |
1654 | // If returned by `struct_tail_without_normalization` this is a unit struct | |
1655 | // without any fields, or not a struct, and therefore is Sized. | |
1656 | | ty::Adt(..) | |
1657 | // If returned by `struct_tail_without_normalization` this is the empty tuple. | |
1658 | | ty::Tuple(..) | |
1659 | // Integers and floats are always Sized, and so have unit type metadata. | |
1660 | | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) => true, | |
1661 | ||
1662 | // type parameters, opaques, and unnormalized projections have pointer | |
1663 | // metadata if they're known (e.g. by the param_env) to be sized | |
9c376795 | 1664 | ty::Param(_) | ty::Alias(..) |
487cf647 FG |
1665 | if selcx.infcx.predicate_must_hold_modulo_regions( |
1666 | &obligation.with( | |
1667 | selcx.tcx(), | |
1668 | ty::Binder::dummy( | |
1669 | selcx.tcx().at(obligation.cause.span()).mk_trait_ref(LangItem::Sized, [self_ty]), | |
1670 | ) | |
1671 | .without_const(), | |
1672 | ), | |
1673 | ) => | |
1674 | { | |
1675 | true | |
1676 | } | |
1677 | ||
1678 | // FIXME(compiler-errors): are Bound and Placeholder types ever known sized? | |
1679 | ty::Param(_) | |
9c376795 | 1680 | | ty::Alias(..) |
487cf647 FG |
1681 | | ty::Bound(..) |
1682 | | ty::Placeholder(..) | |
1683 | | ty::Infer(..) | |
1684 | | ty::Error(_) => { | |
1685 | if tail.has_infer_types() { | |
1686 | candidate_set.mark_ambiguous(); | |
1687 | } | |
1688 | false | |
5099ac24 | 1689 | } |
5e7ed085 | 1690 | } |
487cf647 FG |
1691 | } else { |
1692 | bug!("unexpected builtin trait with associated type: {poly_trait_ref:?}") | |
6a06907d XL |
1693 | } |
1694 | } | |
1b1a35ee | 1695 | super::ImplSource::Param(..) => { |
ba9703b0 XL |
1696 | // This case tell us nothing about the value of an |
1697 | // associated type. Consider: | |
1698 | // | |
1699 | // ``` | |
1700 | // trait SomeTrait { type Foo; } | |
1701 | // fn foo<T:SomeTrait>(...) { } | |
1702 | // ``` | |
1703 | // | |
1704 | // If the user writes `<T as SomeTrait>::Foo`, then the `T | |
1705 | // : SomeTrait` binding does not help us decide what the | |
1706 | // type `Foo` is (at least, not more specifically than | |
1707 | // what we already knew). | |
1708 | // | |
1709 | // But wait, you say! What about an example like this: | |
1710 | // | |
1711 | // ``` | |
1712 | // fn bar<T:SomeTrait<Foo=usize>>(...) { ... } | |
1713 | // ``` | |
1714 | // | |
5e7ed085 | 1715 | // Doesn't the `T : SomeTrait<Foo=usize>` predicate help |
ba9703b0 XL |
1716 | // resolve `T::Foo`? And of course it does, but in fact |
1717 | // that single predicate is desugared into two predicates | |
1718 | // in the compiler: a trait predicate (`T : SomeTrait`) and a | |
1719 | // projection. And the projection where clause is handled | |
1720 | // in `assemble_candidates_from_param_env`. | |
1721 | false | |
1722 | } | |
29967ef6 XL |
1723 | super::ImplSource::Object(_) => { |
1724 | // Handled by the `Object` projection candidate. See | |
1725 | // `assemble_candidates_from_object_ty` for an explanation of | |
1726 | // why we special case object types. | |
1727 | false | |
1728 | } | |
94222f64 | 1729 | super::ImplSource::AutoImpl(..) |
c295e0f8 | 1730 | | super::ImplSource::TraitUpcasting(_) |
2b03887a | 1731 | | super::ImplSource::ConstDestruct(_) => { |
ba9703b0 | 1732 | // These traits have no associated types. |
f9652781 | 1733 | selcx.tcx().sess.delay_span_bug( |
ba9703b0 | 1734 | obligation.cause.span, |
f9652781 | 1735 | &format!("Cannot project an associated type from `{:?}`", impl_source), |
ba9703b0 | 1736 | ); |
f9652781 | 1737 | return Err(()); |
ba9703b0 XL |
1738 | } |
1739 | }; | |
1740 | ||
1741 | if eligible { | |
5099ac24 | 1742 | if candidate_set.push_candidate(ProjectionCandidate::Select(impl_source)) { |
ba9703b0 XL |
1743 | Ok(()) |
1744 | } else { | |
1745 | Err(()) | |
1746 | } | |
1747 | } else { | |
1748 | Err(()) | |
1749 | } | |
1750 | }); | |
1751 | } | |
1752 | ||
1753 | fn confirm_candidate<'cx, 'tcx>( | |
1754 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1755 | obligation: &ProjectionTyObligation<'tcx>, | |
5099ac24 | 1756 | candidate: ProjectionCandidate<'tcx>, |
ba9703b0 | 1757 | ) -> Progress<'tcx> { |
29967ef6 | 1758 | debug!(?obligation, ?candidate, "confirm_candidate"); |
f035d41b | 1759 | let mut progress = match candidate { |
5099ac24 FG |
1760 | ProjectionCandidate::ParamEnv(poly_projection) |
1761 | | ProjectionCandidate::Object(poly_projection) => { | |
29967ef6 XL |
1762 | confirm_param_env_candidate(selcx, obligation, poly_projection, false) |
1763 | } | |
1764 | ||
5099ac24 | 1765 | ProjectionCandidate::TraitDef(poly_projection) => { |
29967ef6 | 1766 | confirm_param_env_candidate(selcx, obligation, poly_projection, true) |
ba9703b0 XL |
1767 | } |
1768 | ||
5099ac24 | 1769 | ProjectionCandidate::Select(impl_source) => { |
29967ef6 | 1770 | confirm_select_candidate(selcx, obligation, impl_source) |
ba9703b0 | 1771 | } |
9ffffee4 | 1772 | ProjectionCandidate::ImplTraitInTrait(data) => { |
f2b60f7d FG |
1773 | confirm_impl_trait_in_trait_candidate(selcx, obligation, data) |
1774 | } | |
f035d41b | 1775 | }; |
5099ac24 | 1776 | |
f035d41b XL |
1777 | // When checking for cycle during evaluation, we compare predicates with |
1778 | // "syntactic" equality. Since normalization generally introduces a type | |
1779 | // with new region variables, we need to resolve them to existing variables | |
1780 | // when possible for this to work. See `auto-trait-projection-recursion.rs` | |
1781 | // for a case where this matters. | |
5099ac24 | 1782 | if progress.term.has_infer_regions() { |
487cf647 | 1783 | progress.term = progress.term.fold_with(&mut OpportunisticRegionResolver::new(selcx.infcx)); |
ba9703b0 | 1784 | } |
f035d41b | 1785 | progress |
ba9703b0 XL |
1786 | } |
1787 | ||
1788 | fn confirm_select_candidate<'cx, 'tcx>( | |
1789 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1790 | obligation: &ProjectionTyObligation<'tcx>, | |
f035d41b | 1791 | impl_source: Selection<'tcx>, |
ba9703b0 | 1792 | ) -> Progress<'tcx> { |
f035d41b | 1793 | match impl_source { |
1b1a35ee XL |
1794 | super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data), |
1795 | super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data), | |
487cf647 | 1796 | super::ImplSource::Future(data) => confirm_future_candidate(selcx, obligation, data), |
1b1a35ee XL |
1797 | super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data), |
1798 | super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data), | |
487cf647 | 1799 | super::ImplSource::Builtin(data) => confirm_builtin_candidate(selcx, obligation, data), |
29967ef6 XL |
1800 | super::ImplSource::Object(_) |
1801 | | super::ImplSource::AutoImpl(..) | |
1b1a35ee | 1802 | | super::ImplSource::Param(..) |
94222f64 | 1803 | | super::ImplSource::TraitUpcasting(_) |
c295e0f8 | 1804 | | super::ImplSource::TraitAlias(..) |
2b03887a | 1805 | | super::ImplSource::ConstDestruct(_) => { |
29967ef6 | 1806 | // we don't create Select candidates with this kind of resolution |
ba9703b0 XL |
1807 | span_bug!( |
1808 | obligation.cause.span, | |
1809 | "Cannot project an associated type from `{:?}`", | |
f035d41b | 1810 | impl_source |
ba9703b0 XL |
1811 | ) |
1812 | } | |
1813 | } | |
1814 | } | |
1815 | ||
ba9703b0 XL |
1816 | fn confirm_generator_candidate<'cx, 'tcx>( |
1817 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1818 | obligation: &ProjectionTyObligation<'tcx>, | |
f035d41b | 1819 | impl_source: ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, |
ba9703b0 | 1820 | ) -> Progress<'tcx> { |
f035d41b | 1821 | let gen_sig = impl_source.substs.as_generator().poly_sig(); |
ba9703b0 XL |
1822 | let Normalized { value: gen_sig, obligations } = normalize_with_depth( |
1823 | selcx, | |
1824 | obligation.param_env, | |
1825 | obligation.cause.clone(), | |
1826 | obligation.recursion_depth + 1, | |
fc512014 | 1827 | gen_sig, |
ba9703b0 XL |
1828 | ); |
1829 | ||
29967ef6 | 1830 | debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate"); |
ba9703b0 XL |
1831 | |
1832 | let tcx = selcx.tcx(); | |
1833 | ||
3dfed10e | 1834 | let gen_def_id = tcx.require_lang_item(LangItem::Generator, None); |
ba9703b0 XL |
1835 | |
1836 | let predicate = super::util::generator_trait_ref_and_outputs( | |
1837 | tcx, | |
1838 | gen_def_id, | |
1839 | obligation.predicate.self_ty(), | |
1840 | gen_sig, | |
1841 | ) | |
1842 | .map_bound(|(trait_ref, yield_ty, return_ty)| { | |
9c376795 | 1843 | let name = tcx.associated_item(obligation.predicate.def_id).name; |
ba9703b0 XL |
1844 | let ty = if name == sym::Return { |
1845 | return_ty | |
1846 | } else if name == sym::Yield { | |
1847 | yield_ty | |
1848 | } else { | |
1849 | bug!() | |
1850 | }; | |
1851 | ||
1852 | ty::ProjectionPredicate { | |
9c376795 | 1853 | projection_ty: tcx.mk_alias_ty(obligation.predicate.def_id, trait_ref.substs), |
5099ac24 | 1854 | term: ty.into(), |
ba9703b0 XL |
1855 | } |
1856 | }); | |
1857 | ||
29967ef6 | 1858 | confirm_param_env_candidate(selcx, obligation, predicate, false) |
f035d41b | 1859 | .with_addl_obligations(impl_source.nested) |
ba9703b0 XL |
1860 | .with_addl_obligations(obligations) |
1861 | } | |
1862 | ||
487cf647 | 1863 | fn confirm_future_candidate<'cx, 'tcx>( |
f9f354fc XL |
1864 | selcx: &mut SelectionContext<'cx, 'tcx>, |
1865 | obligation: &ProjectionTyObligation<'tcx>, | |
487cf647 | 1866 | impl_source: ImplSourceFutureData<'tcx, PredicateObligation<'tcx>>, |
f9f354fc | 1867 | ) -> Progress<'tcx> { |
487cf647 FG |
1868 | let gen_sig = impl_source.substs.as_generator().poly_sig(); |
1869 | let Normalized { value: gen_sig, obligations } = normalize_with_depth( | |
1870 | selcx, | |
1871 | obligation.param_env, | |
1872 | obligation.cause.clone(), | |
1873 | obligation.recursion_depth + 1, | |
1874 | gen_sig, | |
1875 | ); | |
f9f354fc | 1876 | |
487cf647 | 1877 | debug!(?obligation, ?gen_sig, ?obligations, "confirm_future_candidate"); |
f9f354fc | 1878 | |
487cf647 FG |
1879 | let tcx = selcx.tcx(); |
1880 | let fut_def_id = tcx.require_lang_item(LangItem::Future, None); | |
f9f354fc | 1881 | |
487cf647 FG |
1882 | let predicate = super::util::future_trait_ref_and_outputs( |
1883 | tcx, | |
1884 | fut_def_id, | |
1885 | obligation.predicate.self_ty(), | |
1886 | gen_sig, | |
1887 | ) | |
1888 | .map_bound(|(trait_ref, return_ty)| { | |
9c376795 | 1889 | debug_assert_eq!(tcx.associated_item(obligation.predicate.def_id).name, sym::Output); |
f9f354fc | 1890 | |
487cf647 | 1891 | ty::ProjectionPredicate { |
9c376795 | 1892 | projection_ty: tcx.mk_alias_ty(obligation.predicate.def_id, trait_ref.substs), |
487cf647 FG |
1893 | term: return_ty.into(), |
1894 | } | |
1895 | }); | |
1896 | ||
1897 | confirm_param_env_candidate(selcx, obligation, predicate, false) | |
1898 | .with_addl_obligations(impl_source.nested) | |
1899 | .with_addl_obligations(obligations) | |
f9f354fc XL |
1900 | } |
1901 | ||
487cf647 | 1902 | fn confirm_builtin_candidate<'cx, 'tcx>( |
6a06907d XL |
1903 | selcx: &mut SelectionContext<'cx, 'tcx>, |
1904 | obligation: &ProjectionTyObligation<'tcx>, | |
487cf647 | 1905 | data: ImplSourceBuiltinData<PredicateObligation<'tcx>>, |
6a06907d XL |
1906 | ) -> Progress<'tcx> { |
1907 | let tcx = selcx.tcx(); | |
487cf647 | 1908 | let self_ty = obligation.predicate.self_ty(); |
9ffffee4 | 1909 | let substs = tcx.mk_substs(&[self_ty.into()]); |
487cf647 | 1910 | let lang_items = tcx.lang_items(); |
9c376795 | 1911 | let item_def_id = obligation.predicate.def_id; |
487cf647 FG |
1912 | let trait_def_id = tcx.trait_of_item(item_def_id).unwrap(); |
1913 | let (term, obligations) = if lang_items.discriminant_kind_trait() == Some(trait_def_id) { | |
1914 | let discriminant_def_id = tcx.require_lang_item(LangItem::Discriminant, None); | |
1915 | assert_eq!(discriminant_def_id, item_def_id); | |
1916 | ||
1917 | (self_ty.discriminant_ty(tcx).into(), Vec::new()) | |
1918 | } else if lang_items.pointee_trait() == Some(trait_def_id) { | |
1919 | let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, None); | |
1920 | assert_eq!(metadata_def_id, item_def_id); | |
1921 | ||
1922 | let mut obligations = Vec::new(); | |
1923 | let (metadata_ty, check_is_sized) = self_ty.ptr_metadata_ty(tcx, |ty| { | |
1924 | normalize_with_depth_to( | |
1925 | selcx, | |
1926 | obligation.param_env, | |
1927 | obligation.cause.clone(), | |
1928 | obligation.recursion_depth + 1, | |
1929 | ty, | |
1930 | &mut obligations, | |
1931 | ) | |
1932 | }); | |
1933 | if check_is_sized { | |
1934 | let sized_predicate = ty::Binder::dummy( | |
1935 | tcx.at(obligation.cause.span()).mk_trait_ref(LangItem::Sized, [self_ty]), | |
1936 | ) | |
1937 | .without_const(); | |
1938 | obligations.push(obligation.with(tcx, sized_predicate)); | |
1939 | } | |
1940 | (metadata_ty.into(), obligations) | |
1941 | } else { | |
1942 | bug!("unexpected builtin trait with associated type: {:?}", obligation.predicate); | |
6a06907d XL |
1943 | }; |
1944 | ||
487cf647 | 1945 | let predicate = |
9c376795 | 1946 | ty::ProjectionPredicate { projection_ty: tcx.mk_alias_ty(item_def_id, substs), term }; |
487cf647 | 1947 | |
136023e0 | 1948 | confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false) |
5099ac24 | 1949 | .with_addl_obligations(obligations) |
487cf647 | 1950 | .with_addl_obligations(data.nested) |
6a06907d XL |
1951 | } |
1952 | ||
ba9703b0 XL |
1953 | fn confirm_fn_pointer_candidate<'cx, 'tcx>( |
1954 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1955 | obligation: &ProjectionTyObligation<'tcx>, | |
f035d41b | 1956 | fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, |
ba9703b0 | 1957 | ) -> Progress<'tcx> { |
487cf647 | 1958 | let fn_type = selcx.infcx.shallow_resolve(fn_pointer_impl_source.fn_ty); |
ba9703b0 XL |
1959 | let sig = fn_type.fn_sig(selcx.tcx()); |
1960 | let Normalized { value: sig, obligations } = normalize_with_depth( | |
1961 | selcx, | |
1962 | obligation.param_env, | |
1963 | obligation.cause.clone(), | |
1964 | obligation.recursion_depth + 1, | |
fc512014 | 1965 | sig, |
ba9703b0 XL |
1966 | ); |
1967 | ||
1968 | confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes) | |
f035d41b | 1969 | .with_addl_obligations(fn_pointer_impl_source.nested) |
ba9703b0 XL |
1970 | .with_addl_obligations(obligations) |
1971 | } | |
1972 | ||
1973 | fn confirm_closure_candidate<'cx, 'tcx>( | |
1974 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1975 | obligation: &ProjectionTyObligation<'tcx>, | |
f035d41b | 1976 | impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, |
ba9703b0 | 1977 | ) -> Progress<'tcx> { |
f035d41b | 1978 | let closure_sig = impl_source.substs.as_closure().sig(); |
ba9703b0 XL |
1979 | let Normalized { value: closure_sig, obligations } = normalize_with_depth( |
1980 | selcx, | |
1981 | obligation.param_env, | |
1982 | obligation.cause.clone(), | |
1983 | obligation.recursion_depth + 1, | |
fc512014 | 1984 | closure_sig, |
ba9703b0 XL |
1985 | ); |
1986 | ||
29967ef6 | 1987 | debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate"); |
ba9703b0 XL |
1988 | |
1989 | confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No) | |
f035d41b | 1990 | .with_addl_obligations(impl_source.nested) |
ba9703b0 XL |
1991 | .with_addl_obligations(obligations) |
1992 | } | |
1993 | ||
1994 | fn confirm_callable_candidate<'cx, 'tcx>( | |
1995 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
1996 | obligation: &ProjectionTyObligation<'tcx>, | |
1997 | fn_sig: ty::PolyFnSig<'tcx>, | |
1998 | flag: util::TupleArgumentsFlag, | |
1999 | ) -> Progress<'tcx> { | |
2000 | let tcx = selcx.tcx(); | |
2001 | ||
29967ef6 | 2002 | debug!(?obligation, ?fn_sig, "confirm_callable_candidate"); |
ba9703b0 | 2003 | |
3dfed10e XL |
2004 | let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None); |
2005 | let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None); | |
ba9703b0 XL |
2006 | |
2007 | let predicate = super::util::closure_trait_ref_and_return_type( | |
2008 | tcx, | |
2009 | fn_once_def_id, | |
2010 | obligation.predicate.self_ty(), | |
2011 | fn_sig, | |
2012 | flag, | |
2013 | ) | |
2014 | .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate { | |
9c376795 | 2015 | projection_ty: tcx.mk_alias_ty(fn_once_output_def_id, trait_ref.substs), |
5099ac24 | 2016 | term: ret_type.into(), |
ba9703b0 XL |
2017 | }); |
2018 | ||
3c0e092e | 2019 | confirm_param_env_candidate(selcx, obligation, predicate, true) |
ba9703b0 XL |
2020 | } |
2021 | ||
2022 | fn confirm_param_env_candidate<'cx, 'tcx>( | |
2023 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
2024 | obligation: &ProjectionTyObligation<'tcx>, | |
2025 | poly_cache_entry: ty::PolyProjectionPredicate<'tcx>, | |
29967ef6 | 2026 | potentially_unnormalized_candidate: bool, |
ba9703b0 | 2027 | ) -> Progress<'tcx> { |
487cf647 | 2028 | let infcx = selcx.infcx; |
ba9703b0 XL |
2029 | let cause = &obligation.cause; |
2030 | let param_env = obligation.param_env; | |
2031 | ||
9ffffee4 | 2032 | let cache_entry = infcx.instantiate_binder_with_fresh_vars( |
ba9703b0 XL |
2033 | cause.span, |
2034 | LateBoundRegionConversionTime::HigherRankedType, | |
fc512014 | 2035 | poly_cache_entry, |
ba9703b0 XL |
2036 | ); |
2037 | ||
6a06907d | 2038 | let cache_projection = cache_entry.projection_ty; |
29967ef6 | 2039 | let mut nested_obligations = Vec::new(); |
3c0e092e XL |
2040 | let obligation_projection = obligation.predicate; |
2041 | let obligation_projection = ensure_sufficient_stack(|| { | |
2042 | normalize_with_depth_to( | |
2043 | selcx, | |
2044 | obligation.param_env, | |
2045 | obligation.cause.clone(), | |
2046 | obligation.recursion_depth + 1, | |
2047 | obligation_projection, | |
2048 | &mut nested_obligations, | |
2049 | ) | |
2050 | }); | |
6a06907d | 2051 | let cache_projection = if potentially_unnormalized_candidate { |
29967ef6 XL |
2052 | ensure_sufficient_stack(|| { |
2053 | normalize_with_depth_to( | |
2054 | selcx, | |
2055 | obligation.param_env, | |
2056 | obligation.cause.clone(), | |
2057 | obligation.recursion_depth + 1, | |
6a06907d | 2058 | cache_projection, |
29967ef6 XL |
2059 | &mut nested_obligations, |
2060 | ) | |
2061 | }) | |
2062 | } else { | |
6a06907d | 2063 | cache_projection |
29967ef6 XL |
2064 | }; |
2065 | ||
3c0e092e XL |
2066 | debug!(?cache_projection, ?obligation_projection); |
2067 | ||
6a06907d | 2068 | match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) { |
29967ef6 XL |
2069 | Ok(InferOk { value: _, obligations }) => { |
2070 | nested_obligations.extend(obligations); | |
2071 | assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations); | |
5099ac24 FG |
2072 | // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take |
2073 | // a term instead. | |
2074 | Progress { term: cache_entry.term, obligations: nested_obligations } | |
29967ef6 | 2075 | } |
ba9703b0 XL |
2076 | Err(e) => { |
2077 | let msg = format!( | |
2078 | "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}", | |
2079 | obligation, poly_cache_entry, e, | |
2080 | ); | |
2081 | debug!("confirm_param_env_candidate: {}", msg); | |
f035d41b | 2082 | let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg); |
5099ac24 | 2083 | Progress { term: err.into(), obligations: vec![] } |
ba9703b0 XL |
2084 | } |
2085 | } | |
2086 | } | |
2087 | ||
2088 | fn confirm_impl_candidate<'cx, 'tcx>( | |
2089 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
2090 | obligation: &ProjectionTyObligation<'tcx>, | |
f035d41b | 2091 | impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>, |
ba9703b0 XL |
2092 | ) -> Progress<'tcx> { |
2093 | let tcx = selcx.tcx(); | |
2094 | ||
29967ef6 | 2095 | let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source; |
9c376795 | 2096 | let assoc_item_id = obligation.predicate.def_id; |
ba9703b0 XL |
2097 | let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap(); |
2098 | ||
2099 | let param_env = obligation.param_env; | |
9ffffee4 FG |
2100 | let assoc_ty = match specialization_graph::assoc_def(tcx, impl_def_id, assoc_item_id) { |
2101 | Ok(assoc_ty) => assoc_ty, | |
2102 | Err(guar) => return Progress::error(tcx, guar), | |
ba9703b0 XL |
2103 | }; |
2104 | ||
064997fb | 2105 | if !assoc_ty.item.defaultness(tcx).has_value() { |
ba9703b0 XL |
2106 | // This means that the impl is missing a definition for the |
2107 | // associated type. This error will be reported by the type | |
2108 | // checker method `check_impl_items_against_trait`, so here we | |
2109 | // just return Error. | |
2110 | debug!( | |
2111 | "confirm_impl_candidate: no associated type {:?} for {:?}", | |
5099ac24 | 2112 | assoc_ty.item.name, obligation.predicate |
ba9703b0 | 2113 | ); |
9ffffee4 | 2114 | return Progress { term: tcx.ty_error_misc().into(), obligations: nested }; |
ba9703b0 | 2115 | } |
f035d41b XL |
2116 | // If we're trying to normalize `<Vec<u32> as X>::A<S>` using |
2117 | //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then: | |
2118 | // | |
2119 | // * `obligation.predicate.substs` is `[Vec<u32>, S]` | |
2120 | // * `substs` is `[u32]` | |
2121 | // * `substs` ends up as `[u32, S]` | |
ba9703b0 XL |
2122 | let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs); |
2123 | let substs = | |
487cf647 | 2124 | translate_substs(selcx.infcx, param_env, impl_def_id, substs, assoc_ty.defining_node); |
9ffffee4 | 2125 | let ty = tcx.type_of(assoc_ty.item.def_id); |
5099ac24 | 2126 | let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst); |
064997fb | 2127 | let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const { |
5099ac24 FG |
2128 | let identity_substs = |
2129 | crate::traits::InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id); | |
2130 | let did = ty::WithOptConstParam::unknown(assoc_ty.item.def_id); | |
2b03887a | 2131 | let kind = ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs)); |
487cf647 | 2132 | ty.map_bound(|ty| tcx.mk_const(kind, ty).into()) |
5099ac24 | 2133 | } else { |
064997fb | 2134 | ty.map_bound(|ty| ty.into()) |
5099ac24 | 2135 | }; |
9ffffee4 | 2136 | if !check_substs_compatible(tcx, assoc_ty.item, substs) { |
f035d41b | 2137 | let err = tcx.ty_error_with_message( |
29967ef6 | 2138 | obligation.cause.span, |
2b03887a | 2139 | "impl item and trait item have different parameters", |
f035d41b | 2140 | ); |
5099ac24 | 2141 | Progress { term: err.into(), obligations: nested } |
ba9703b0 | 2142 | } else { |
29967ef6 | 2143 | assoc_ty_own_obligations(selcx, obligation, &mut nested); |
064997fb | 2144 | Progress { term: term.subst(tcx, substs), obligations: nested } |
ba9703b0 XL |
2145 | } |
2146 | } | |
2147 | ||
2b03887a FG |
2148 | // Verify that the trait item and its implementation have compatible substs lists |
2149 | fn check_substs_compatible<'tcx>( | |
2150 | tcx: TyCtxt<'tcx>, | |
9ffffee4 | 2151 | assoc_item: ty::AssocItem, |
2b03887a FG |
2152 | substs: ty::SubstsRef<'tcx>, |
2153 | ) -> bool { | |
2154 | fn check_substs_compatible_inner<'tcx>( | |
2155 | tcx: TyCtxt<'tcx>, | |
2156 | generics: &'tcx ty::Generics, | |
2157 | args: &'tcx [ty::GenericArg<'tcx>], | |
2158 | ) -> bool { | |
2159 | if generics.count() != args.len() { | |
2160 | return false; | |
2161 | } | |
2162 | ||
2163 | let (parent_args, own_args) = args.split_at(generics.parent_count); | |
2164 | ||
2165 | if let Some(parent) = generics.parent | |
2166 | && let parent_generics = tcx.generics_of(parent) | |
2167 | && !check_substs_compatible_inner(tcx, parent_generics, parent_args) { | |
2168 | return false; | |
2169 | } | |
2170 | ||
2171 | for (param, arg) in std::iter::zip(&generics.params, own_args) { | |
2172 | match (¶m.kind, arg.unpack()) { | |
2173 | (ty::GenericParamDefKind::Type { .. }, ty::GenericArgKind::Type(_)) | |
2174 | | (ty::GenericParamDefKind::Lifetime, ty::GenericArgKind::Lifetime(_)) | |
2175 | | (ty::GenericParamDefKind::Const { .. }, ty::GenericArgKind::Const(_)) => {} | |
2176 | _ => return false, | |
2177 | } | |
2178 | } | |
2179 | ||
2180 | true | |
2181 | } | |
2182 | ||
487cf647 FG |
2183 | let generics = tcx.generics_of(assoc_item.def_id); |
2184 | // Chop off any additional substs (RPITIT) substs | |
2185 | let substs = &substs[0..generics.count().min(substs.len())]; | |
2186 | check_substs_compatible_inner(tcx, generics, substs) | |
2b03887a FG |
2187 | } |
2188 | ||
f2b60f7d FG |
2189 | fn confirm_impl_trait_in_trait_candidate<'tcx>( |
2190 | selcx: &mut SelectionContext<'_, 'tcx>, | |
2191 | obligation: &ProjectionTyObligation<'tcx>, | |
2192 | data: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>, | |
2193 | ) -> Progress<'tcx> { | |
2194 | let tcx = selcx.tcx(); | |
2195 | let mut obligations = data.nested; | |
2196 | ||
9c376795 | 2197 | let trait_fn_def_id = tcx.impl_trait_in_trait_parent(obligation.predicate.def_id); |
9ffffee4 FG |
2198 | let leaf_def = match specialization_graph::assoc_def(tcx, data.impl_def_id, trait_fn_def_id) { |
2199 | Ok(assoc_ty) => assoc_ty, | |
2200 | Err(guar) => return Progress::error(tcx, guar), | |
f2b60f7d | 2201 | }; |
9ffffee4 FG |
2202 | // We don't support specialization for RPITITs anyways... yet. |
2203 | if !leaf_def.is_final() { | |
2204 | return Progress { term: tcx.ty_error_misc().into(), obligations }; | |
f2b60f7d FG |
2205 | } |
2206 | ||
2b03887a FG |
2207 | // Use the default `impl Trait` for the trait, e.g., for a default trait body |
2208 | if leaf_def.item.container == ty::AssocItemContainer::TraitContainer { | |
2209 | return Progress { | |
9c376795 | 2210 | term: tcx.mk_opaque(obligation.predicate.def_id, obligation.predicate.substs).into(), |
2b03887a FG |
2211 | obligations, |
2212 | }; | |
2213 | } | |
2214 | ||
2b03887a FG |
2215 | // Rebase from {trait}::{fn}::{opaque} to {impl}::{fn}::{opaque}, |
2216 | // since `data.substs` are the impl substs. | |
2217 | let impl_fn_substs = | |
2218 | obligation.predicate.substs.rebase_onto(tcx, tcx.parent(trait_fn_def_id), data.substs); | |
487cf647 FG |
2219 | let impl_fn_substs = translate_substs( |
2220 | selcx.infcx, | |
2221 | obligation.param_env, | |
2222 | data.impl_def_id, | |
2223 | impl_fn_substs, | |
2224 | leaf_def.defining_node, | |
2225 | ); | |
2226 | ||
9ffffee4 | 2227 | if !check_substs_compatible(tcx, leaf_def.item, impl_fn_substs) { |
487cf647 FG |
2228 | let err = tcx.ty_error_with_message( |
2229 | obligation.cause.span, | |
2230 | "impl method and trait method have different parameters", | |
2231 | ); | |
2232 | return Progress { term: err.into(), obligations }; | |
2233 | } | |
2234 | ||
2235 | let impl_fn_def_id = leaf_def.item.def_id; | |
f2b60f7d FG |
2236 | |
2237 | let cause = ObligationCause::new( | |
2238 | obligation.cause.span, | |
2239 | obligation.cause.body_id, | |
2240 | super::ItemObligation(impl_fn_def_id), | |
2241 | ); | |
2242 | let predicates = normalize_with_depth_to( | |
2243 | selcx, | |
2244 | obligation.param_env, | |
2245 | cause.clone(), | |
2246 | obligation.recursion_depth + 1, | |
2247 | tcx.predicates_of(impl_fn_def_id).instantiate(tcx, impl_fn_substs), | |
2248 | &mut obligations, | |
2249 | ); | |
9c376795 FG |
2250 | obligations.extend(predicates.into_iter().map(|(pred, span)| { |
2251 | Obligation::with_depth( | |
2252 | tcx, | |
2253 | ObligationCause::new( | |
2254 | obligation.cause.span, | |
2255 | obligation.cause.body_id, | |
2256 | if span.is_dummy() { | |
2257 | super::ItemObligation(impl_fn_def_id) | |
2258 | } else { | |
2259 | super::BindingObligation(impl_fn_def_id, span) | |
2260 | }, | |
2261 | ), | |
2262 | obligation.recursion_depth + 1, | |
2263 | obligation.param_env, | |
2264 | pred, | |
2265 | ) | |
2266 | })); | |
f2b60f7d | 2267 | |
487cf647 | 2268 | let ty = normalize_with_depth_to( |
f2b60f7d FG |
2269 | selcx, |
2270 | obligation.param_env, | |
2271 | cause.clone(), | |
487cf647 | 2272 | obligation.recursion_depth + 1, |
9c376795 | 2273 | tcx.bound_return_position_impl_trait_in_trait_tys(impl_fn_def_id) |
f2b60f7d | 2274 | .map_bound(|tys| { |
9ffffee4 | 2275 | tys.map_or_else(|guar| tcx.ty_error(guar), |tys| tys[&obligation.predicate.def_id]) |
f2b60f7d FG |
2276 | }) |
2277 | .subst(tcx, impl_fn_substs), | |
2278 | &mut obligations, | |
2279 | ); | |
2280 | ||
2281 | Progress { term: ty.into(), obligations } | |
2282 | } | |
2283 | ||
29967ef6 XL |
2284 | // Get obligations corresponding to the predicates from the where-clause of the |
2285 | // associated type itself. | |
29967ef6 XL |
2286 | fn assoc_ty_own_obligations<'cx, 'tcx>( |
2287 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
2288 | obligation: &ProjectionTyObligation<'tcx>, | |
2289 | nested: &mut Vec<PredicateObligation<'tcx>>, | |
2290 | ) { | |
2291 | let tcx = selcx.tcx(); | |
9c376795 FG |
2292 | let predicates = tcx |
2293 | .predicates_of(obligation.predicate.def_id) | |
487cf647 | 2294 | .instantiate_own(tcx, obligation.predicate.substs); |
9c376795 | 2295 | for (predicate, span) in predicates { |
29967ef6 XL |
2296 | let normalized = normalize_with_depth_to( |
2297 | selcx, | |
2298 | obligation.param_env, | |
2299 | obligation.cause.clone(), | |
2300 | obligation.recursion_depth + 1, | |
fc512014 | 2301 | predicate, |
29967ef6 XL |
2302 | nested, |
2303 | ); | |
487cf647 FG |
2304 | |
2305 | let nested_cause = if matches!( | |
2306 | obligation.cause.code(), | |
2307 | super::CompareImplItemObligation { .. } | |
2308 | | super::CheckAssociatedTypeBounds { .. } | |
2309 | | super::AscribeUserTypeProvePredicate(..) | |
2310 | ) { | |
2311 | obligation.cause.clone() | |
2312 | } else if span.is_dummy() { | |
2313 | ObligationCause::new( | |
2314 | obligation.cause.span, | |
2315 | obligation.cause.body_id, | |
9c376795 | 2316 | super::ItemObligation(obligation.predicate.def_id), |
487cf647 FG |
2317 | ) |
2318 | } else { | |
2319 | ObligationCause::new( | |
2320 | obligation.cause.span, | |
2321 | obligation.cause.body_id, | |
9c376795 | 2322 | super::BindingObligation(obligation.predicate.def_id, span), |
487cf647 FG |
2323 | ) |
2324 | }; | |
29967ef6 | 2325 | nested.push(Obligation::with_depth( |
487cf647 FG |
2326 | tcx, |
2327 | nested_cause, | |
29967ef6 XL |
2328 | obligation.recursion_depth + 1, |
2329 | obligation.param_env, | |
2330 | normalized, | |
2331 | )); | |
2332 | } | |
2333 | } | |
2334 | ||
923072b8 | 2335 | pub(crate) trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized { |
ba9703b0 XL |
2336 | fn from_poly_projection_predicate( |
2337 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
f9f354fc | 2338 | predicate: ty::PolyProjectionPredicate<'tcx>, |
ba9703b0 XL |
2339 | ) -> Option<Self>; |
2340 | } | |
2341 | ||
a2a8927a | 2342 | impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> { |
ba9703b0 XL |
2343 | fn from_poly_projection_predicate( |
2344 | selcx: &mut SelectionContext<'cx, 'tcx>, | |
f9f354fc | 2345 | predicate: ty::PolyProjectionPredicate<'tcx>, |
ba9703b0 | 2346 | ) -> Option<Self> { |
487cf647 | 2347 | let infcx = selcx.infcx; |
ba9703b0 XL |
2348 | // We don't do cross-snapshot caching of obligations with escaping regions, |
2349 | // so there's no cache key to use | |
2350 | predicate.no_bound_vars().map(|predicate| { | |
2351 | ProjectionCacheKey::new( | |
2352 | // We don't attempt to match up with a specific type-variable state | |
2353 | // from a specific call to `opt_normalize_projection_type` - if | |
2354 | // there's no precise match, the original cache entry is "stranded" | |
2355 | // anyway. | |
fc512014 | 2356 | infcx.resolve_vars_if_possible(predicate.projection_ty), |
ba9703b0 XL |
2357 | ) |
2358 | }) | |
2359 | } | |
2360 | } |