rustc_trait_selection/traits/select/mod.rs
1//! Candidate selection. See the [rustc dev guide] for more information on how this works.
2//!
3//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection
4
5use std::assert_matches::assert_matches;
6use std::cell::{Cell, RefCell};
7use std::cmp;
8use std::fmt::{self, Display};
9use std::ops::ControlFlow;
10
11use hir::def::DefKind;
12use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
13use rustc_data_structures::stack::ensure_sufficient_stack;
14use rustc_errors::{Diag, EmissionGuarantee};
15use rustc_hir as hir;
16use rustc_hir::LangItem;
17use rustc_hir::def_id::DefId;
18use rustc_infer::infer::BoundRegionConversionTime::{self, HigherRankedType};
19use rustc_infer::infer::DefineOpaqueTypes;
20use rustc_infer::infer::at::ToTrace;
21use rustc_infer::infer::relate::TypeRelation;
22use rustc_infer::traits::{PredicateObligations, TraitObligation};
23use rustc_macros::{TypeFoldable, TypeVisitable};
24use rustc_middle::bug;
25use rustc_middle::dep_graph::{DepNodeIndex, dep_kinds};
26pub use rustc_middle::traits::select::*;
27use rustc_middle::ty::abstract_const::NotConstEvaluatable;
28use rustc_middle::ty::error::TypeErrorToStringExt;
29use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths};
30use rustc_middle::ty::{
31 self, DeepRejectCtxt, GenericArgsRef, PolyProjectionPredicate, SizedTraitKind, Ty, TyCtxt,
32 TypeFoldable, TypeVisitableExt, TypingMode, Upcast, elaborate, may_use_unstable_feature,
33};
34use rustc_span::{Symbol, sym};
35use tracing::{debug, instrument, trace};
36
37use self::EvaluationResult::*;
38use self::SelectionCandidate::*;
39use super::coherence::{self, Conflict};
40use super::project::ProjectionTermObligation;
41use super::util::closure_trait_ref_and_return_type;
42use super::{
43 ImplDerivedCause, Normalized, Obligation, ObligationCause, ObligationCauseCode,
44 PolyTraitObligation, PredicateObligation, Selection, SelectionError, SelectionResult,
45 TraitQueryMode, const_evaluatable, project, util, wf,
46};
47use crate::error_reporting::InferCtxtErrorExt;
48use crate::infer::{InferCtxt, InferOk, TypeFreshener};
49use crate::solve::InferCtxtSelectExt as _;
50use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to};
51use crate::traits::project::{ProjectAndUnifyResult, ProjectionCacheKeyExt};
52use crate::traits::{EvaluateConstErr, ProjectionCacheKey, effects, sizedness_fast_path};
53
54mod _match;
55mod candidate_assembly;
56mod confirmation;
57
58#[derive(Clone, Debug, Eq, PartialEq, Hash)]
59pub enum IntercrateAmbiguityCause<'tcx> {
60 DownstreamCrate { trait_ref: ty::TraitRef<'tcx>, self_ty: Option<Ty<'tcx>> },
61 UpstreamCrateUpdate { trait_ref: ty::TraitRef<'tcx>, self_ty: Option<Ty<'tcx>> },
62 ReservationImpl { message: Symbol },
63}
64
65impl<'tcx> IntercrateAmbiguityCause<'tcx> {
66 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
67 /// See #23980 for details.
68 pub fn add_intercrate_ambiguity_hint<G: EmissionGuarantee>(&self, err: &mut Diag<'_, G>) {
69 err.note(self.intercrate_ambiguity_hint());
70 }
71
72 pub fn intercrate_ambiguity_hint(&self) -> String {
73 with_no_trimmed_paths!(match self {
74 IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty } => {
75 format!(
76 "downstream crates may implement trait `{trait_desc}`{self_desc}",
77 trait_desc = trait_ref.print_trait_sugared(),
78 self_desc = if let Some(self_ty) = self_ty {
79 format!(" for type `{self_ty}`")
80 } else {
81 String::new()
82 }
83 )
84 }
85 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty } => {
86 format!(
87 "upstream crates may add a new impl of trait `{trait_desc}`{self_desc} \
88 in future versions",
89 trait_desc = trait_ref.print_trait_sugared(),
90 self_desc = if let Some(self_ty) = self_ty {
91 format!(" for type `{self_ty}`")
92 } else {
93 String::new()
94 }
95 )
96 }
97 IntercrateAmbiguityCause::ReservationImpl { message } => message.to_string(),
98 })
99 }
100}
101
102pub struct SelectionContext<'cx, 'tcx> {
103 pub infcx: &'cx InferCtxt<'tcx>,
104
105 /// Freshener used specifically for entries on the obligation
106 /// stack. This ensures that all entries on the stack at one time
107 /// will have the same set of placeholder entries, which is
108 /// important for checking for trait bounds that recursively
109 /// require themselves.
110 freshener: TypeFreshener<'cx, 'tcx>,
111
112 /// If `intercrate` is set, we remember predicates which were
113 /// considered ambiguous because of impls potentially added in other crates.
114 /// This is used in coherence to give improved diagnostics.
115 /// We don't do his until we detect a coherence error because it can
116 /// lead to false overflow results (#47139) and because always
117 /// computing it may negatively impact performance.
118 intercrate_ambiguity_causes: Option<FxIndexSet<IntercrateAmbiguityCause<'tcx>>>,
119
120 /// The mode that trait queries run in, which informs our error handling
121 /// policy. In essence, canonicalized queries need their errors propagated
122 /// rather than immediately reported because we do not have accurate spans.
123 query_mode: TraitQueryMode,
124}
125
126// A stack that walks back up the stack frame.
127struct TraitObligationStack<'prev, 'tcx> {
128 obligation: &'prev PolyTraitObligation<'tcx>,
129
130 /// The trait predicate from `obligation` but "freshened" with the
131 /// selection-context's freshener. Used to check for recursion.
132 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
133
134 /// Starts out equal to `depth` -- if, during evaluation, we
135 /// encounter a cycle, then we will set this flag to the minimum
136 /// depth of that cycle for all participants in the cycle. These
137 /// participants will then forego caching their results. This is
138 /// not the most efficient solution, but it addresses #60010. The
139 /// problem we are trying to prevent:
140 ///
141 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
142 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
143 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
144 ///
145 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
146 /// is `EvaluatedToOk`; this is because they were only considered
147 /// ok on the premise that if `A: AutoTrait` held, but we indeed
148 /// encountered a problem (later on) with `A: AutoTrait`. So we
149 /// currently set a flag on the stack node for `B: AutoTrait` (as
150 /// well as the second instance of `A: AutoTrait`) to suppress
151 /// caching.
152 ///
153 /// This is a simple, targeted fix. A more-performant fix requires
154 /// deeper changes, but would permit more caching: we could
155 /// basically defer caching until we have fully evaluated the
156 /// tree, and then cache the entire tree at once. In any case, the
157 /// performance impact here shouldn't be so horrible: every time
158 /// this is hit, we do cache at least one trait, so we only
159 /// evaluate each member of a cycle up to N times, where N is the
160 /// length of the cycle. This means the performance impact is
161 /// bounded and we shouldn't have any terrible worst-cases.
162 reached_depth: Cell<usize>,
163
164 previous: TraitObligationStackList<'prev, 'tcx>,
165
166 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
167 depth: usize,
168
169 /// The depth-first number of this node in the search graph -- a
170 /// pre-order index. Basically, a freshly incremented counter.
171 dfn: usize,
172}
173
174struct SelectionCandidateSet<'tcx> {
175 /// A list of candidates that definitely apply to the current
176 /// obligation (meaning: types unify).
177 vec: Vec<SelectionCandidate<'tcx>>,
178
179 /// If `true`, then there were candidates that might or might
180 /// not have applied, but we couldn't tell. This occurs when some
181 /// of the input types are type variables, in which case there are
182 /// various "builtin" rules that might or might not trigger.
183 ambiguous: bool,
184}
185
186#[derive(PartialEq, Eq, Debug, Clone)]
187struct EvaluatedCandidate<'tcx> {
188 candidate: SelectionCandidate<'tcx>,
189 evaluation: EvaluationResult,
190}
191
192impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
193 pub fn new(infcx: &'cx InferCtxt<'tcx>) -> SelectionContext<'cx, 'tcx> {
194 SelectionContext {
195 infcx,
196 freshener: infcx.freshener(),
197 intercrate_ambiguity_causes: None,
198 query_mode: TraitQueryMode::Standard,
199 }
200 }
201
202 pub fn with_query_mode(
203 infcx: &'cx InferCtxt<'tcx>,
204 query_mode: TraitQueryMode,
205 ) -> SelectionContext<'cx, 'tcx> {
206 debug!(?query_mode, "with_query_mode");
207 SelectionContext { query_mode, ..SelectionContext::new(infcx) }
208 }
209
210 /// Enables tracking of intercrate ambiguity causes. See
211 /// the documentation of [`Self::intercrate_ambiguity_causes`] for more.
212 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
213 assert_matches!(self.infcx.typing_mode(), TypingMode::Coherence);
214 assert!(self.intercrate_ambiguity_causes.is_none());
215 self.intercrate_ambiguity_causes = Some(FxIndexSet::default());
216 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
217 }
218
219 /// Gets the intercrate ambiguity causes collected since tracking
220 /// was enabled and disables tracking at the same time. If
221 /// tracking is not enabled, just returns an empty vector.
222 pub fn take_intercrate_ambiguity_causes(
223 &mut self,
224 ) -> FxIndexSet<IntercrateAmbiguityCause<'tcx>> {
225 assert_matches!(self.infcx.typing_mode(), TypingMode::Coherence);
226 self.intercrate_ambiguity_causes.take().unwrap_or_default()
227 }
228
229 pub fn tcx(&self) -> TyCtxt<'tcx> {
230 self.infcx.tcx
231 }
232
233 ///////////////////////////////////////////////////////////////////////////
234 // Selection
235 //
236 // The selection phase tries to identify *how* an obligation will
237 // be resolved. For example, it will identify which impl or
238 // parameter bound is to be used. The process can be inconclusive
239 // if the self type in the obligation is not fully inferred. Selection
240 // can result in an error in one of two ways:
241 //
242 // 1. If no applicable impl or parameter bound can be found.
243 // 2. If the output type parameters in the obligation do not match
244 // those specified by the impl/bound. For example, if the obligation
245 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
246 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
247
248 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
249 /// type environment by performing unification.
250 #[instrument(level = "debug", skip(self), ret)]
251 pub fn poly_select(
252 &mut self,
253 obligation: &PolyTraitObligation<'tcx>,
254 ) -> SelectionResult<'tcx, Selection<'tcx>> {
255 assert!(!self.infcx.next_trait_solver());
256
257 let candidate = match self.select_from_obligation(obligation) {
258 Err(SelectionError::Overflow(OverflowError::Canonical)) => {
259 // In standard mode, overflow must have been caught and reported
260 // earlier.
261 assert!(self.query_mode == TraitQueryMode::Canonical);
262 return Err(SelectionError::Overflow(OverflowError::Canonical));
263 }
264 Err(e) => {
265 return Err(e);
266 }
267 Ok(None) => {
268 return Ok(None);
269 }
270 Ok(Some(candidate)) => candidate,
271 };
272
273 match self.confirm_candidate(obligation, candidate) {
274 Err(SelectionError::Overflow(OverflowError::Canonical)) => {
275 assert!(self.query_mode == TraitQueryMode::Canonical);
276 Err(SelectionError::Overflow(OverflowError::Canonical))
277 }
278 Err(e) => Err(e),
279 Ok(candidate) => Ok(Some(candidate)),
280 }
281 }
282
283 pub fn select(
284 &mut self,
285 obligation: &TraitObligation<'tcx>,
286 ) -> SelectionResult<'tcx, Selection<'tcx>> {
287 if self.infcx.next_trait_solver() {
288 return self.infcx.select_in_new_trait_solver(obligation);
289 }
290
291 self.poly_select(&Obligation {
292 cause: obligation.cause.clone(),
293 param_env: obligation.param_env,
294 predicate: ty::Binder::dummy(obligation.predicate),
295 recursion_depth: obligation.recursion_depth,
296 })
297 }
298
299 fn select_from_obligation(
300 &mut self,
301 obligation: &PolyTraitObligation<'tcx>,
302 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
303 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
304
305 let pec = &ProvisionalEvaluationCache::default();
306 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
307
308 self.candidate_from_obligation(&stack)
309 }
310
311 #[instrument(level = "debug", skip(self), ret)]
312 fn candidate_from_obligation<'o>(
313 &mut self,
314 stack: &TraitObligationStack<'o, 'tcx>,
315 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
316 debug_assert!(!self.infcx.next_trait_solver());
317 // Watch out for overflow. This intentionally bypasses (and does
318 // not update) the cache.
319 self.check_recursion_limit(stack.obligation, stack.obligation)?;
320
321 // Check the cache. Note that we freshen the trait-ref
322 // separately rather than using `stack.fresh_trait_ref` --
323 // this is because we want the unbound variables to be
324 // replaced with fresh types starting from index 0.
325 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate);
326 debug!(?cache_fresh_trait_pred);
327 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
328
329 if let Some(c) =
330 self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
331 {
332 debug!("CACHE HIT");
333 return c;
334 }
335
336 // If no match, compute result and insert into cache.
337 //
338 // FIXME(nikomatsakis) -- this cache is not taking into
339 // account cycles that may have occurred in forming the
340 // candidate. I don't know of any specific problems that
341 // result but it seems awfully suspicious.
342 let (candidate, dep_node) =
343 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
344
345 debug!("CACHE MISS");
346 self.insert_candidate_cache(
347 stack.obligation.param_env,
348 cache_fresh_trait_pred,
349 dep_node,
350 candidate.clone(),
351 );
352 candidate
353 }
354
355 fn candidate_from_obligation_no_cache<'o>(
356 &mut self,
357 stack: &TraitObligationStack<'o, 'tcx>,
358 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
359 if let Err(conflict) = self.is_knowable(stack) {
360 debug!("coherence stage: not knowable");
361 if self.intercrate_ambiguity_causes.is_some() {
362 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
363 // Heuristics: show the diagnostics when there are no candidates in crate.
364 if let Ok(candidate_set) = self.assemble_candidates(stack) {
365 let mut no_candidates_apply = true;
366
367 for c in candidate_set.vec.iter() {
368 if self.evaluate_candidate(stack, c)?.may_apply() {
369 no_candidates_apply = false;
370 break;
371 }
372 }
373
374 if !candidate_set.ambiguous && no_candidates_apply {
375 let trait_ref = self.infcx.resolve_vars_if_possible(
376 stack.obligation.predicate.skip_binder().trait_ref,
377 );
378 if !trait_ref.references_error() {
379 let self_ty = trait_ref.self_ty();
380 let self_ty = self_ty.has_concrete_skeleton().then(|| self_ty);
381 let cause = if let Conflict::Upstream = conflict {
382 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty }
383 } else {
384 IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty }
385 };
386 debug!(?cause, "evaluate_stack: pushing cause");
387 self.intercrate_ambiguity_causes.as_mut().unwrap().insert(cause);
388 }
389 }
390 }
391 }
392 return Ok(None);
393 }
394
395 let candidate_set = self.assemble_candidates(stack)?;
396
397 if candidate_set.ambiguous {
398 debug!("candidate set contains ambig");
399 return Ok(None);
400 }
401
402 let candidates = candidate_set.vec;
403
404 debug!(?stack, ?candidates, "assembled {} candidates", candidates.len());
405
406 // At this point, we know that each of the entries in the
407 // candidate set is *individually* applicable. Now we have to
408 // figure out if they contain mutual incompatibilities. This
409 // frequently arises if we have an unconstrained input type --
410 // for example, we are looking for `$0: Eq` where `$0` is some
411 // unconstrained type variable. In that case, we'll get a
412 // candidate which assumes $0 == int, one that assumes `$0 ==
413 // usize`, etc. This spells an ambiguity.
414
415 let mut candidates = self.filter_impls(candidates, stack.obligation);
416
417 // If there is more than one candidate, first winnow them down
418 // by considering extra conditions (nested obligations and so
419 // forth). We don't winnow if there is exactly one
420 // candidate. This is a relatively minor distinction but it
421 // can lead to better inference and error-reporting. An
422 // example would be if there was an impl:
423 //
424 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
425 //
426 // and we were to see some code `foo.push_clone()` where `boo`
427 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
428 // we were to winnow, we'd wind up with zero candidates.
429 // Instead, we select the right impl now but report "`Bar` does
430 // not implement `Clone`".
431 if candidates.len() == 1 {
432 return self.filter_reservation_impls(candidates.pop().unwrap());
433 }
434
435 // Winnow, but record the exact outcome of evaluation, which
436 // is needed for specialization. Propagate overflow if it occurs.
437 let candidates = candidates
438 .into_iter()
439 .map(|c| match self.evaluate_candidate(stack, &c) {
440 Ok(eval) if eval.may_apply() => {
441 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
442 }
443 Ok(_) => Ok(None),
444 Err(OverflowError::Canonical) => {
445 Err(SelectionError::Overflow(OverflowError::Canonical))
446 }
447 Err(OverflowError::Error(e)) => {
448 Err(SelectionError::Overflow(OverflowError::Error(e)))
449 }
450 })
451 .flat_map(Result::transpose)
452 .collect::<Result<Vec<_>, _>>()?;
453
454 debug!(?stack, ?candidates, "{} potentially applicable candidates", candidates.len());
455 // If there are *NO* candidates, then there are no impls --
456 // that we know of, anyway. Note that in the case where there
457 // are unbound type variables within the obligation, it might
458 // be the case that you could still satisfy the obligation
459 // from another crate by instantiating the type variables with
460 // a type from another crate that does have an impl. This case
461 // is checked for in `evaluate_stack` (and hence users
462 // who might care about this case, like coherence, should use
463 // that function).
464 if candidates.is_empty() {
465 // If there's an error type, 'downgrade' our result from
466 // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
467 // emitting additional spurious errors, since we're guaranteed
468 // to have emitted at least one.
469 if stack.obligation.predicate.references_error() {
470 debug!(?stack.obligation.predicate, "found error type in predicate, treating as ambiguous");
471 Ok(None)
472 } else {
473 Err(SelectionError::Unimplemented)
474 }
475 } else {
476 let has_non_region_infer = stack.obligation.predicate.has_non_region_infer();
477 if let Some(candidate) = self.winnow_candidates(has_non_region_infer, candidates) {
478 self.filter_reservation_impls(candidate)
479 } else {
480 Ok(None)
481 }
482 }
483 }
484
485 ///////////////////////////////////////////////////////////////////////////
486 // EVALUATION
487 //
488 // Tests whether an obligation can be selected or whether an impl
489 // can be applied to particular types. It skips the "confirmation"
490 // step and hence completely ignores output type parameters.
491 //
492 // The result is "true" if the obligation *may* hold and "false" if
493 // we can be sure it does not.
494
495 /// Evaluates whether the obligation `obligation` can be satisfied
496 /// and returns an `EvaluationResult`. This is meant for the
497 /// *initial* call.
498 ///
499 /// Do not use this directly, use `infcx.evaluate_obligation` instead.
500 pub fn evaluate_root_obligation(
501 &mut self,
502 obligation: &PredicateObligation<'tcx>,
503 ) -> Result<EvaluationResult, OverflowError> {
504 debug_assert!(!self.infcx.next_trait_solver());
505 self.evaluation_probe(|this| {
506 let goal =
507 this.infcx.resolve_vars_if_possible((obligation.predicate, obligation.param_env));
508 let mut result = this.evaluate_predicate_recursively(
509 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
510 obligation.clone(),
511 )?;
512 // If the predicate has done any inference, then downgrade the
513 // result to ambiguous.
514 if this.infcx.resolve_vars_if_possible(goal) != goal {
515 result = result.max(EvaluatedToAmbig);
516 }
517 Ok(result)
518 })
519 }
520
521 /// Computes the evaluation result of `op`, discarding any constraints.
522 ///
523 /// This also runs for leak check to allow higher ranked region errors to impact
524 /// selection. By default it checks for leaks from all universes created inside of
525 /// `op`, but this can be overwritten if necessary.
526 fn evaluation_probe(
527 &mut self,
528 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
529 ) -> Result<EvaluationResult, OverflowError> {
530 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
531 let outer_universe = self.infcx.universe();
532 let result = op(self)?;
533
534 match self.infcx.leak_check(outer_universe, Some(snapshot)) {
535 Ok(()) => {}
536 Err(_) => return Ok(EvaluatedToErr),
537 }
538
539 if self.infcx.opaque_types_added_in_snapshot(snapshot) {
540 return Ok(result.max(EvaluatedToOkModuloOpaqueTypes));
541 }
542
543 if self.infcx.region_constraints_added_in_snapshot(snapshot) {
544 Ok(result.max(EvaluatedToOkModuloRegions))
545 } else {
546 Ok(result)
547 }
548 })
549 }
550
551 /// Evaluates the predicates in `predicates` recursively. This may
552 /// guide inference. If this is not desired, run it inside of a
553 /// is run within an inference probe.
554 /// `probe`.
555 #[instrument(skip(self, stack), level = "debug")]
556 fn evaluate_predicates_recursively<'o, I>(
557 &mut self,
558 stack: TraitObligationStackList<'o, 'tcx>,
559 predicates: I,
560 ) -> Result<EvaluationResult, OverflowError>
561 where
562 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
563 {
564 let mut result = EvaluatedToOk;
565 for mut obligation in predicates {
566 obligation.set_depth_from_parent(stack.depth());
567 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
568 if let EvaluatedToErr = eval {
569 // fast-path - EvaluatedToErr is the top of the lattice,
570 // so we don't need to look on the other predicates.
571 return Ok(EvaluatedToErr);
572 } else {
573 result = cmp::max(result, eval);
574 }
575 }
576 Ok(result)
577 }
578
579 #[instrument(
580 level = "debug",
581 skip(self, previous_stack),
582 fields(previous_stack = ?previous_stack.head())
583 ret,
584 )]
585 fn evaluate_predicate_recursively<'o>(
586 &mut self,
587 previous_stack: TraitObligationStackList<'o, 'tcx>,
588 obligation: PredicateObligation<'tcx>,
589 ) -> Result<EvaluationResult, OverflowError> {
590 debug_assert!(!self.infcx.next_trait_solver());
591 // `previous_stack` stores a `PolyTraitObligation`, while `obligation` is
592 // a `PredicateObligation`. These are distinct types, so we can't
593 // use any `Option` combinator method that would force them to be
594 // the same.
595 match previous_stack.head() {
596 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
597 None => self.check_recursion_limit(&obligation, &obligation)?,
598 }
599
600 if sizedness_fast_path(self.tcx(), obligation.predicate, obligation.param_env) {
601 return Ok(EvaluatedToOk);
602 }
603
604 ensure_sufficient_stack(|| {
605 let bound_predicate = obligation.predicate.kind();
606 match bound_predicate.skip_binder() {
607 ty::PredicateKind::Clause(ty::ClauseKind::Trait(t)) => {
608 let t = bound_predicate.rebind(t);
609 debug_assert!(!t.has_escaping_bound_vars());
610 let obligation = obligation.with(self.tcx(), t);
611 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
612 }
613
614 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(data)) => {
615 self.infcx.enter_forall(bound_predicate.rebind(data), |data| {
616 match effects::evaluate_host_effect_obligation(
617 self,
618 &obligation.with(self.tcx(), data),
619 ) {
620 Ok(nested) => {
621 self.evaluate_predicates_recursively(previous_stack, nested)
622 }
623 Err(effects::EvaluationFailure::Ambiguous) => Ok(EvaluatedToAmbig),
624 Err(effects::EvaluationFailure::NoSolution) => Ok(EvaluatedToErr),
625 }
626 })
627 }
628
629 ty::PredicateKind::Subtype(p) => {
630 let p = bound_predicate.rebind(p);
631 // Does this code ever run?
632 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
633 Ok(Ok(InferOk { obligations, .. })) => {
634 self.evaluate_predicates_recursively(previous_stack, obligations)
635 }
636 Ok(Err(_)) => Ok(EvaluatedToErr),
637 Err(..) => Ok(EvaluatedToAmbig),
638 }
639 }
640
641 ty::PredicateKind::Coerce(p) => {
642 let p = bound_predicate.rebind(p);
643 // Does this code ever run?
644 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
645 Ok(Ok(InferOk { obligations, .. })) => {
646 self.evaluate_predicates_recursively(previous_stack, obligations)
647 }
648 Ok(Err(_)) => Ok(EvaluatedToErr),
649 Err(..) => Ok(EvaluatedToAmbig),
650 }
651 }
652
653 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
654 if term.is_trivially_wf(self.tcx()) {
655 return Ok(EvaluatedToOk);
656 }
657
658 // So, there is a bit going on here. First, `WellFormed` predicates
659 // are coinductive, like trait predicates with auto traits.
660 // This means that we need to detect if we have recursively
661 // evaluated `WellFormed(X)`. Otherwise, we would run into
662 // a "natural" overflow error.
663 //
664 // Now, the next question is whether we need to do anything
665 // special with caching. Considering the following tree:
666 // - `WF(Foo<T>)`
667 // - `Bar<T>: Send`
668 // - `WF(Foo<T>)`
669 // - `Foo<T>: Trait`
670 // In this case, the innermost `WF(Foo<T>)` should return
671 // `EvaluatedToOk`, since it's coinductive. Then if
672 // `Bar<T>: Send` is resolved to `EvaluatedToOk`, it can be
673 // inserted into a cache (because without thinking about `WF`
674 // goals, it isn't in a cycle). If `Foo<T>: Trait` later doesn't
675 // hold, then `Bar<T>: Send` shouldn't hold. Therefore, we
676 // *do* need to keep track of coinductive cycles.
677
678 let cache = previous_stack.cache;
679 let dfn = cache.next_dfn();
680
681 for stack_term in previous_stack.cache.wf_args.borrow().iter().rev() {
682 if stack_term.0 != term {
683 continue;
684 }
685 debug!("WellFormed({:?}) on stack", term);
686 if let Some(stack) = previous_stack.head {
687 // Okay, let's imagine we have two different stacks:
688 // `T: NonAutoTrait -> WF(T) -> T: NonAutoTrait`
689 // `WF(T) -> T: NonAutoTrait -> WF(T)`
690 // Because of this, we need to check that all
691 // predicates between the WF goals are coinductive.
692 // Otherwise, we can say that `T: NonAutoTrait` is
693 // true.
694 // Let's imagine we have a predicate stack like
695 // `Foo: Bar -> WF(T) -> T: NonAutoTrait -> T: Auto`
696 // depth ^1 ^2 ^3
697 // and the current predicate is `WF(T)`. `wf_args`
698 // would contain `(T, 1)`. We want to check all
699 // trait predicates greater than `1`. The previous
700 // stack would be `T: Auto`.
701 let cycle = stack.iter().take_while(|s| s.depth > stack_term.1);
702 let tcx = self.tcx();
703 let cycle = cycle.map(|stack| stack.obligation.predicate.upcast(tcx));
704 if self.coinductive_match(cycle) {
705 stack.update_reached_depth(stack_term.1);
706 return Ok(EvaluatedToOk);
707 } else {
708 return Ok(EvaluatedToAmbigStackDependent);
709 }
710 }
711 return Ok(EvaluatedToOk);
712 }
713
714 match wf::obligations(
715 self.infcx,
716 obligation.param_env,
717 obligation.cause.body_id,
718 obligation.recursion_depth + 1,
719 term,
720 obligation.cause.span,
721 ) {
722 Some(obligations) => {
723 cache.wf_args.borrow_mut().push((term, previous_stack.depth()));
724 let result =
725 self.evaluate_predicates_recursively(previous_stack, obligations);
726 cache.wf_args.borrow_mut().pop();
727
728 let result = result?;
729
730 if !result.must_apply_modulo_regions() {
731 cache.on_failure(dfn);
732 }
733
734 cache.on_completion(dfn);
735
736 Ok(result)
737 }
738 None => Ok(EvaluatedToAmbig),
739 }
740 }
741
742 ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(pred)) => {
743 // A global type with no free lifetimes or generic parameters
744 // outlives anything.
745 if pred.0.has_free_regions()
746 || pred.0.has_bound_regions()
747 || pred.0.has_non_region_infer()
748 || pred.0.has_non_region_infer()
749 {
750 Ok(EvaluatedToOkModuloRegions)
751 } else {
752 Ok(EvaluatedToOk)
753 }
754 }
755
756 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..)) => {
757 // We do not consider region relationships when evaluating trait matches.
758 Ok(EvaluatedToOkModuloRegions)
759 }
760
761 ty::PredicateKind::DynCompatible(trait_def_id) => {
762 if self.tcx().is_dyn_compatible(trait_def_id) {
763 Ok(EvaluatedToOk)
764 } else {
765 Ok(EvaluatedToErr)
766 }
767 }
768
769 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
770 let data = bound_predicate.rebind(data);
771 let project_obligation = obligation.with(self.tcx(), data);
772 match project::poly_project_and_unify_term(self, &project_obligation) {
773 ProjectAndUnifyResult::Holds(mut subobligations) => {
774 'compute_res: {
775 // If we've previously marked this projection as 'complete', then
776 // use the final cached result (either `EvaluatedToOk` or
777 // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
778 // sub-obligations.
779 if let Some(key) =
780 ProjectionCacheKey::from_poly_projection_obligation(
781 self,
782 &project_obligation,
783 )
784 && let Some(cached_res) = self
785 .infcx
786 .inner
787 .borrow_mut()
788 .projection_cache()
789 .is_complete(key)
790 {
791 break 'compute_res Ok(cached_res);
792 }
793
794 // Need to explicitly set the depth of nested goals here as
795 // projection obligations can cycle by themselves and in
796 // `evaluate_predicates_recursively` we only add the depth
797 // for parent trait goals because only these get added to the
798 // `TraitObligationStackList`.
799 for subobligation in subobligations.iter_mut() {
800 subobligation.set_depth_from_parent(obligation.recursion_depth);
801 }
802 let res = self.evaluate_predicates_recursively(
803 previous_stack,
804 subobligations,
805 );
806 if let Ok(eval_rslt) = res
807 && (eval_rslt == EvaluatedToOk
808 || eval_rslt == EvaluatedToOkModuloRegions)
809 && let Some(key) =
810 ProjectionCacheKey::from_poly_projection_obligation(
811 self,
812 &project_obligation,
813 )
814 {
815 // If the result is something that we can cache, then mark this
816 // entry as 'complete'. This will allow us to skip evaluating the
817 // subobligations at all the next time we evaluate the projection
818 // predicate.
819 self.infcx
820 .inner
821 .borrow_mut()
822 .projection_cache()
823 .complete(key, eval_rslt);
824 }
825 res
826 }
827 }
828 ProjectAndUnifyResult::FailedNormalization => Ok(EvaluatedToAmbig),
829 ProjectAndUnifyResult::Recursive => Ok(EvaluatedToAmbigStackDependent),
830 ProjectAndUnifyResult::MismatchedProjectionTypes(_) => Ok(EvaluatedToErr),
831 }
832 }
833
834 ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(symbol)) => {
835 if may_use_unstable_feature(self.infcx, obligation.param_env, symbol) {
836 Ok(EvaluatedToOk)
837 } else {
838 Ok(EvaluatedToAmbig)
839 }
840 }
841
842 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(uv)) => {
843 match const_evaluatable::is_const_evaluatable(
844 self.infcx,
845 uv,
846 obligation.param_env,
847 obligation.cause.span,
848 ) {
849 Ok(()) => Ok(EvaluatedToOk),
850 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
851 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
852 Err(_) => Ok(EvaluatedToErr),
853 }
854 }
855
856 ty::PredicateKind::ConstEquate(c1, c2) => {
857 let tcx = self.tcx();
858 assert!(
859 tcx.features().generic_const_exprs(),
860 "`ConstEquate` without a feature gate: {c1:?} {c2:?}",
861 );
862
863 {
864 let c1 = tcx.expand_abstract_consts(c1);
865 let c2 = tcx.expand_abstract_consts(c2);
866 debug!(
867 "evaluate_predicate_recursively: equating consts:\nc1= {:?}\nc2= {:?}",
868 c1, c2
869 );
870
871 use rustc_hir::def::DefKind;
872 match (c1.kind(), c2.kind()) {
873 (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b))
874 if a.def == b.def && tcx.def_kind(a.def) == DefKind::AssocConst =>
875 {
876 if let Ok(InferOk { obligations, value: () }) = self
877 .infcx
878 .at(&obligation.cause, obligation.param_env)
879 // Can define opaque types as this is only reachable with
880 // `generic_const_exprs`
881 .eq(
882 DefineOpaqueTypes::Yes,
883 ty::AliasTerm::from(a),
884 ty::AliasTerm::from(b),
885 )
886 {
887 return self.evaluate_predicates_recursively(
888 previous_stack,
889 obligations,
890 );
891 }
892 }
893 (_, ty::ConstKind::Unevaluated(_))
894 | (ty::ConstKind::Unevaluated(_), _) => (),
895 (_, _) => {
896 if let Ok(InferOk { obligations, value: () }) = self
897 .infcx
898 .at(&obligation.cause, obligation.param_env)
899 // Can define opaque types as this is only reachable with
900 // `generic_const_exprs`
901 .eq(DefineOpaqueTypes::Yes, c1, c2)
902 {
903 return self.evaluate_predicates_recursively(
904 previous_stack,
905 obligations,
906 );
907 }
908 }
909 }
910 }
911
912 let evaluate = |c: ty::Const<'tcx>| {
913 if let ty::ConstKind::Unevaluated(_) = c.kind() {
914 match crate::traits::try_evaluate_const(
915 self.infcx,
916 c,
917 obligation.param_env,
918 ) {
919 Ok(val) => Ok(val),
920 Err(e) => Err(e),
921 }
922 } else {
923 Ok(c)
924 }
925 };
926
927 match (evaluate(c1), evaluate(c2)) {
928 (Ok(c1), Ok(c2)) => {
929 match self.infcx.at(&obligation.cause, obligation.param_env).eq(
930 // Can define opaque types as this is only reachable with
931 // `generic_const_exprs`
932 DefineOpaqueTypes::Yes,
933 c1,
934 c2,
935 ) {
936 Ok(inf_ok) => self.evaluate_predicates_recursively(
937 previous_stack,
938 inf_ok.into_obligations(),
939 ),
940 Err(_) => Ok(EvaluatedToErr),
941 }
942 }
943 (Err(EvaluateConstErr::InvalidConstParamTy(..)), _)
944 | (_, Err(EvaluateConstErr::InvalidConstParamTy(..))) => Ok(EvaluatedToErr),
945 (Err(EvaluateConstErr::EvaluationFailure(..)), _)
946 | (_, Err(EvaluateConstErr::EvaluationFailure(..))) => Ok(EvaluatedToErr),
947 (Err(EvaluateConstErr::HasGenericsOrInfers), _)
948 | (_, Err(EvaluateConstErr::HasGenericsOrInfers)) => {
949 if c1.has_non_region_infer() || c2.has_non_region_infer() {
950 Ok(EvaluatedToAmbig)
951 } else {
952 // Two different constants using generic parameters ~> error.
953 Ok(EvaluatedToErr)
954 }
955 }
956 }
957 }
958 ty::PredicateKind::NormalizesTo(..) => {
959 bug!("NormalizesTo is only used by the new solver")
960 }
961 ty::PredicateKind::AliasRelate(..) => {
962 bug!("AliasRelate is only used by the new solver")
963 }
964 ty::PredicateKind::Ambiguous => Ok(EvaluatedToAmbig),
965 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
966 let ct = self.infcx.shallow_resolve_const(ct);
967 let ct_ty = match ct.kind() {
968 ty::ConstKind::Infer(_) => {
969 return Ok(EvaluatedToAmbig);
970 }
971 ty::ConstKind::Error(_) => return Ok(EvaluatedToOk),
972 ty::ConstKind::Value(cv) => cv.ty,
973 ty::ConstKind::Unevaluated(uv) => {
974 self.tcx().type_of(uv.def).instantiate(self.tcx(), uv.args)
975 }
976 // FIXME(generic_const_exprs): See comment in `fulfill.rs`
977 ty::ConstKind::Expr(_) => return Ok(EvaluatedToOk),
978 ty::ConstKind::Placeholder(_) => {
979 bug!("placeholder const {:?} in old solver", ct)
980 }
981 ty::ConstKind::Bound(_, _) => bug!("escaping bound vars in {:?}", ct),
982 ty::ConstKind::Param(param_ct) => {
983 param_ct.find_const_ty_from_env(obligation.param_env)
984 }
985 };
986
987 match self.infcx.at(&obligation.cause, obligation.param_env).eq(
988 // Only really exercised by generic_const_exprs
989 DefineOpaqueTypes::Yes,
990 ct_ty,
991 ty,
992 ) {
993 Ok(inf_ok) => self.evaluate_predicates_recursively(
994 previous_stack,
995 inf_ok.into_obligations(),
996 ),
997 Err(_) => Ok(EvaluatedToErr),
998 }
999 }
1000 }
1001 })
1002 }
1003
1004 #[instrument(skip(self, previous_stack), level = "debug", ret)]
1005 fn evaluate_trait_predicate_recursively<'o>(
1006 &mut self,
1007 previous_stack: TraitObligationStackList<'o, 'tcx>,
1008 mut obligation: PolyTraitObligation<'tcx>,
1009 ) -> Result<EvaluationResult, OverflowError> {
1010 if !matches!(self.infcx.typing_mode(), TypingMode::Coherence)
1011 && obligation.is_global()
1012 && obligation.param_env.caller_bounds().iter().all(|bound| bound.has_param())
1013 {
1014 // If a param env has no global bounds, global obligations do not
1015 // depend on its particular value in order to work, so we can clear
1016 // out the param env and get better caching.
1017 debug!("in global");
1018 obligation.param_env = ty::ParamEnv::empty();
1019 }
1020
1021 let stack = self.push_stack(previous_stack, &obligation);
1022 let fresh_trait_pred = stack.fresh_trait_pred;
1023 let param_env = obligation.param_env;
1024
1025 debug!(?fresh_trait_pred);
1026
1027 // If a trait predicate is in the (local or global) evaluation cache,
1028 // then we know it holds without cycles.
1029 if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
1030 debug!("CACHE HIT");
1031 return Ok(result);
1032 }
1033
1034 if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
1035 debug!("PROVISIONAL CACHE HIT");
1036 stack.update_reached_depth(result.reached_depth);
1037 return Ok(result.result);
1038 }
1039
1040 // Check if this is a match for something already on the
1041 // stack. If so, we don't want to insert the result into the
1042 // main cache (it is cycle dependent) nor the provisional
1043 // cache (which is meant for things that have completed but
1044 // for a "backedge" -- this result *is* the backedge).
1045 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
1046 return Ok(cycle_result);
1047 }
1048
1049 let (result, dep_node) = self.in_task(|this| {
1050 let mut result = this.evaluate_stack(&stack)?;
1051
1052 // fix issue #103563, we don't normalize
1053 // nested obligations which produced by `TraitDef` candidate
1054 // (i.e. using bounds on assoc items as assumptions).
1055 // because we don't have enough information to
1056 // normalize these obligations before evaluating.
1057 // so we will try to normalize the obligation and evaluate again.
1058 // we will replace it with new solver in the future.
1059 if EvaluationResult::EvaluatedToErr == result
1060 && fresh_trait_pred.has_aliases()
1061 && fresh_trait_pred.is_global()
1062 {
1063 let mut nested_obligations = PredicateObligations::new();
1064 let predicate = normalize_with_depth_to(
1065 this,
1066 param_env,
1067 obligation.cause.clone(),
1068 obligation.recursion_depth + 1,
1069 obligation.predicate,
1070 &mut nested_obligations,
1071 );
1072 if predicate != obligation.predicate {
1073 let mut nested_result = EvaluationResult::EvaluatedToOk;
1074 for obligation in nested_obligations {
1075 nested_result = cmp::max(
1076 this.evaluate_predicate_recursively(previous_stack, obligation)?,
1077 nested_result,
1078 );
1079 }
1080
1081 if nested_result.must_apply_modulo_regions() {
1082 let obligation = obligation.with(this.tcx(), predicate);
1083 result = cmp::max(
1084 nested_result,
1085 this.evaluate_trait_predicate_recursively(previous_stack, obligation)?,
1086 );
1087 }
1088 }
1089 }
1090
1091 Ok::<_, OverflowError>(result)
1092 });
1093
1094 let result = result?;
1095
1096 if !result.must_apply_modulo_regions() {
1097 stack.cache().on_failure(stack.dfn);
1098 }
1099
1100 let reached_depth = stack.reached_depth.get();
1101 if reached_depth >= stack.depth {
1102 debug!("CACHE MISS");
1103 self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
1104 stack.cache().on_completion(stack.dfn);
1105 } else {
1106 debug!("PROVISIONAL");
1107 debug!(
1108 "caching provisionally because {:?} \
1109 is a cycle participant (at depth {}, reached depth {})",
1110 fresh_trait_pred, stack.depth, reached_depth,
1111 );
1112
1113 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_pred, result);
1114 }
1115
1116 Ok(result)
1117 }
1118
1119 /// If there is any previous entry on the stack that precisely
1120 /// matches this obligation, then we can assume that the
1121 /// obligation is satisfied for now (still all other conditions
1122 /// must be met of course). One obvious case this comes up is
1123 /// marker traits like `Send`. Think of a linked list:
1124 ///
1125 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
1126 ///
1127 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
1128 /// `Option<Box<List<T>>>` is `Send`, and in turn
1129 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
1130 /// `Send`.
1131 ///
1132 /// Note that we do this comparison using the `fresh_trait_ref`
1133 /// fields. Because these have all been freshened using
1134 /// `self.freshener`, we can be sure that (a) this will not
1135 /// affect the inferencer state and (b) that if we see two
1136 /// fresh regions with the same index, they refer to the same
1137 /// unbound type variable.
1138 fn check_evaluation_cycle(
1139 &mut self,
1140 stack: &TraitObligationStack<'_, 'tcx>,
1141 ) -> Option<EvaluationResult> {
1142 if let Some(cycle_depth) = stack
1143 .iter()
1144 .skip(1) // Skip top-most frame.
1145 .find(|prev| {
1146 stack.obligation.param_env == prev.obligation.param_env
1147 && stack.fresh_trait_pred == prev.fresh_trait_pred
1148 })
1149 .map(|stack| stack.depth)
1150 {
1151 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
1152
1153 // If we have a stack like `A B C D E A`, where the top of
1154 // the stack is the final `A`, then this will iterate over
1155 // `A, E, D, C, B` -- i.e., all the participants apart
1156 // from the cycle head. We mark them as participating in a
1157 // cycle. This suppresses caching for those nodes. See
1158 // `in_cycle` field for more details.
1159 stack.update_reached_depth(cycle_depth);
1160
1161 // Subtle: when checking for a coinductive cycle, we do
1162 // not compare using the "freshened trait refs" (which
1163 // have erased regions) but rather the fully explicit
1164 // trait refs. This is important because it's only a cycle
1165 // if the regions match exactly.
1166 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
1167 let tcx = self.tcx();
1168 let cycle = cycle.map(|stack| stack.obligation.predicate.upcast(tcx));
1169 if self.coinductive_match(cycle) {
1170 debug!("evaluate_stack --> recursive, coinductive");
1171 Some(EvaluatedToOk)
1172 } else {
1173 debug!("evaluate_stack --> recursive, inductive");
1174 Some(EvaluatedToAmbigStackDependent)
1175 }
1176 } else {
1177 None
1178 }
1179 }
1180
1181 fn evaluate_stack<'o>(
1182 &mut self,
1183 stack: &TraitObligationStack<'o, 'tcx>,
1184 ) -> Result<EvaluationResult, OverflowError> {
1185 debug_assert!(!self.infcx.next_trait_solver());
1186 // In intercrate mode, whenever any of the generics are unbound,
1187 // there can always be an impl. Even if there are no impls in
1188 // this crate, perhaps the type would be unified with
1189 // something from another crate that does provide an impl.
1190 //
1191 // In intra mode, we must still be conservative. The reason is
1192 // that we want to avoid cycles. Imagine an impl like:
1193 //
1194 // impl<T:Eq> Eq for Vec<T>
1195 //
1196 // and a trait reference like `$0 : Eq` where `$0` is an
1197 // unbound variable. When we evaluate this trait-reference, we
1198 // will unify `$0` with `Vec<$1>` (for some fresh variable
1199 // `$1`), on the condition that `$1 : Eq`. We will then wind
1200 // up with many candidates (since that are other `Eq` impls
1201 // that apply) and try to winnow things down. This results in
1202 // a recursive evaluation that `$1 : Eq` -- as you can
1203 // imagine, this is just where we started. To avoid that, we
1204 // check for unbound variables and return an ambiguous (hence possible)
1205 // match if we've seen this trait before.
1206 //
1207 // This suffices to allow chains like `FnMut` implemented in
1208 // terms of `Fn` etc, but we could probably make this more
1209 // precise still.
1210 let unbound_input_types =
1211 stack.fresh_trait_pred.skip_binder().trait_ref.args.types().any(|ty| ty.is_fresh());
1212
1213 if unbound_input_types
1214 && stack.iter().skip(1).any(|prev| {
1215 stack.obligation.param_env == prev.obligation.param_env
1216 && self.match_fresh_trait_refs(stack.fresh_trait_pred, prev.fresh_trait_pred)
1217 })
1218 {
1219 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
1220 return Ok(EvaluatedToAmbigStackDependent);
1221 }
1222
1223 match self.candidate_from_obligation(stack) {
1224 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1225 Ok(None) => Ok(EvaluatedToAmbig),
1226 Err(SelectionError::Overflow(OverflowError::Canonical)) => {
1227 Err(OverflowError::Canonical)
1228 }
1229 Err(..) => Ok(EvaluatedToErr),
1230 }
1231 }
1232
1233 /// For defaulted traits, we use a co-inductive strategy to solve, so
1234 /// that recursion is ok. This routine returns `true` if the top of the
1235 /// stack (`cycle[0]`):
1236 ///
1237 /// - is a coinductive trait: an auto-trait or `Sized`,
1238 /// - it also appears in the backtrace at some position `X`,
1239 /// - all the predicates at positions `X..` between `X` and the top are
1240 /// also coinductive traits.
1241 pub(crate) fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
1242 where
1243 I: Iterator<Item = ty::Predicate<'tcx>>,
1244 {
1245 cycle.all(|p| match p.kind().skip_binder() {
1246 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
1247 self.infcx.tcx.trait_is_coinductive(data.def_id())
1248 }
1249 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => {
1250 // FIXME(generic_const_exprs): GCE needs well-formedness predicates to be
1251 // coinductive, but GCE is on the way out anyways, so this should eventually
1252 // be replaced with `false`.
1253 self.infcx.tcx.features().generic_const_exprs()
1254 }
1255 _ => false,
1256 })
1257 }
1258
1259 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
1260 /// obligations are met. Returns whether `candidate` remains viable after this further
1261 /// scrutiny.
1262 #[instrument(
1263 level = "debug",
1264 skip(self, stack),
1265 fields(depth = stack.obligation.recursion_depth),
1266 ret
1267 )]
1268 fn evaluate_candidate<'o>(
1269 &mut self,
1270 stack: &TraitObligationStack<'o, 'tcx>,
1271 candidate: &SelectionCandidate<'tcx>,
1272 ) -> Result<EvaluationResult, OverflowError> {
1273 let mut result = self.evaluation_probe(|this| {
1274 match this.confirm_candidate(stack.obligation, candidate.clone()) {
1275 Ok(selection) => {
1276 debug!(?selection);
1277 this.evaluate_predicates_recursively(
1278 stack.list(),
1279 selection.nested_obligations().into_iter(),
1280 )
1281 }
1282 Err(..) => Ok(EvaluatedToErr),
1283 }
1284 })?;
1285
1286 // If we erased any lifetimes, then we want to use
1287 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
1288 // as your final result. The result will be cached using
1289 // the freshened trait predicate as a key, so we need
1290 // our result to be correct by *any* choice of original lifetimes,
1291 // not just the lifetime choice for this particular (non-erased)
1292 // predicate.
1293 // See issue #80691
1294 if stack.fresh_trait_pred.has_erased_regions() {
1295 result = result.max(EvaluatedToOkModuloRegions);
1296 }
1297
1298 Ok(result)
1299 }
1300
1301 fn check_evaluation_cache(
1302 &self,
1303 param_env: ty::ParamEnv<'tcx>,
1304 trait_pred: ty::PolyTraitPredicate<'tcx>,
1305 ) -> Option<EvaluationResult> {
1306 let infcx = self.infcx;
1307 let tcx = infcx.tcx;
1308 if self.can_use_global_caches(param_env, trait_pred) {
1309 let key = (infcx.typing_env(param_env), trait_pred);
1310 if let Some(res) = tcx.evaluation_cache.get(&key, tcx) {
1311 Some(res)
1312 } else {
1313 debug_assert_eq!(infcx.evaluation_cache.get(&(param_env, trait_pred), tcx), None);
1314 None
1315 }
1316 } else {
1317 self.infcx.evaluation_cache.get(&(param_env, trait_pred), tcx)
1318 }
1319 }
1320
1321 fn insert_evaluation_cache(
1322 &mut self,
1323 param_env: ty::ParamEnv<'tcx>,
1324 trait_pred: ty::PolyTraitPredicate<'tcx>,
1325 dep_node: DepNodeIndex,
1326 result: EvaluationResult,
1327 ) {
1328 // Avoid caching results that depend on more than just the trait-ref
1329 // - the stack can create recursion.
1330 if result.is_stack_dependent() {
1331 return;
1332 }
1333
1334 let infcx = self.infcx;
1335 let tcx = infcx.tcx;
1336 if self.can_use_global_caches(param_env, trait_pred) {
1337 debug!(?trait_pred, ?result, "insert_evaluation_cache global");
1338 // This may overwrite the cache with the same value
1339 tcx.evaluation_cache.insert(
1340 (infcx.typing_env(param_env), trait_pred),
1341 dep_node,
1342 result,
1343 );
1344 return;
1345 } else {
1346 debug!(?trait_pred, ?result, "insert_evaluation_cache local");
1347 self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1348 }
1349 }
1350
1351 fn check_recursion_depth<T>(
1352 &self,
1353 depth: usize,
1354 error_obligation: &Obligation<'tcx, T>,
1355 ) -> Result<(), OverflowError>
1356 where
1357 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + Clone,
1358 {
1359 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1360 match self.query_mode {
1361 TraitQueryMode::Standard => {
1362 if let Some(e) = self.infcx.tainted_by_errors() {
1363 return Err(OverflowError::Error(e));
1364 }
1365 self.infcx.err_ctxt().report_overflow_obligation(error_obligation, true);
1366 }
1367 TraitQueryMode::Canonical => {
1368 return Err(OverflowError::Canonical);
1369 }
1370 }
1371 }
1372 Ok(())
1373 }
1374
1375 /// Checks that the recursion limit has not been exceeded.
1376 ///
1377 /// The weird return type of this function allows it to be used with the `try` (`?`)
1378 /// operator within certain functions.
1379 #[inline(always)]
1380 fn check_recursion_limit<T: Display + TypeFoldable<TyCtxt<'tcx>>, V>(
1381 &self,
1382 obligation: &Obligation<'tcx, T>,
1383 error_obligation: &Obligation<'tcx, V>,
1384 ) -> Result<(), OverflowError>
1385 where
1386 V: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + Clone,
1387 {
1388 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1389 }
1390
1391 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1392 where
1393 OP: FnOnce(&mut Self) -> R,
1394 {
1395 self.tcx().dep_graph.with_anon_task(self.tcx(), dep_kinds::TraitSelect, || op(self))
1396 }
1397
1398 /// filter_impls filters candidates that have a positive impl for a negative
1399 /// goal and a negative impl for a positive goal
1400 #[instrument(level = "debug", skip(self, candidates))]
1401 fn filter_impls(
1402 &mut self,
1403 candidates: Vec<SelectionCandidate<'tcx>>,
1404 obligation: &PolyTraitObligation<'tcx>,
1405 ) -> Vec<SelectionCandidate<'tcx>> {
1406 trace!("{candidates:#?}");
1407 let tcx = self.tcx();
1408 let mut result = Vec::with_capacity(candidates.len());
1409
1410 for candidate in candidates {
1411 if let ImplCandidate(def_id) = candidate {
1412 match (tcx.impl_polarity(def_id), obligation.polarity()) {
1413 (ty::ImplPolarity::Reservation, _)
1414 | (ty::ImplPolarity::Positive, ty::PredicatePolarity::Positive)
1415 | (ty::ImplPolarity::Negative, ty::PredicatePolarity::Negative) => {
1416 result.push(candidate);
1417 }
1418 _ => {}
1419 }
1420 } else {
1421 result.push(candidate);
1422 }
1423 }
1424
1425 trace!("{result:#?}");
1426 result
1427 }
1428
1429 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1430 #[instrument(level = "debug", skip(self))]
1431 fn filter_reservation_impls(
1432 &mut self,
1433 candidate: SelectionCandidate<'tcx>,
1434 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1435 let tcx = self.tcx();
1436 // Treat reservation impls as ambiguity.
1437 if let ImplCandidate(def_id) = candidate
1438 && let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id)
1439 {
1440 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1441 let message =
1442 tcx.get_attr(def_id, sym::rustc_reservation_impl).and_then(|a| a.value_str());
1443 if let Some(message) = message {
1444 debug!(
1445 "filter_reservation_impls: \
1446 reservation impl ambiguity on {:?}",
1447 def_id
1448 );
1449 intercrate_ambiguity_clauses
1450 .insert(IntercrateAmbiguityCause::ReservationImpl { message });
1451 }
1452 }
1453 return Ok(None);
1454 }
1455 Ok(Some(candidate))
1456 }
1457
1458 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Result<(), Conflict> {
1459 let obligation = &stack.obligation;
1460 match self.infcx.typing_mode() {
1461 TypingMode::Coherence => {}
1462 TypingMode::Analysis { .. }
1463 | TypingMode::Borrowck { .. }
1464 | TypingMode::PostBorrowckAnalysis { .. }
1465 | TypingMode::PostAnalysis => return Ok(()),
1466 }
1467
1468 debug!("is_knowable()");
1469
1470 let predicate = self.infcx.resolve_vars_if_possible(obligation.predicate);
1471
1472 // Okay to skip binder because of the nature of the
1473 // trait-ref-is-knowable check, which does not care about
1474 // bound regions.
1475 let trait_ref = predicate.skip_binder().trait_ref;
1476
1477 coherence::trait_ref_is_knowable(self.infcx, trait_ref, |ty| Ok::<_, !>(ty)).into_ok()
1478 }
1479
1480 /// Returns `true` if the global caches can be used.
1481 fn can_use_global_caches(
1482 &self,
1483 param_env: ty::ParamEnv<'tcx>,
1484 pred: ty::PolyTraitPredicate<'tcx>,
1485 ) -> bool {
1486 // If there are any inference variables in the `ParamEnv`, then we
1487 // always use a cache local to this particular scope. Otherwise, we
1488 // switch to a global cache.
1489 if param_env.has_infer() || pred.has_infer() {
1490 return false;
1491 }
1492
1493 match self.infcx.typing_mode() {
1494 // Avoid using the global cache during coherence and just rely
1495 // on the local cache. It is really just a simplification to
1496 // avoid us having to fear that coherence results "pollute"
1497 // the master cache. Since coherence executes pretty quickly,
1498 // it's not worth going to more trouble to increase the
1499 // hit-rate, I don't think.
1500 TypingMode::Coherence => false,
1501 // Avoid using the global cache when we're defining opaque types
1502 // as their hidden type may impact the result of candidate selection.
1503 //
1504 // HACK: This is still theoretically unsound. Goals can indirectly rely
1505 // on opaques in the defining scope, and it's easier to do so with TAIT.
1506 // However, if we disqualify *all* goals from being cached, perf suffers.
1507 // This is likely fixed by better caching in general in the new solver.
1508 // See: <https://github.com/rust-lang/rust/issues/132064>.
1509 TypingMode::Analysis {
1510 defining_opaque_types_and_generators: defining_opaque_types,
1511 }
1512 | TypingMode::Borrowck { defining_opaque_types } => {
1513 defining_opaque_types.is_empty()
1514 || (!pred.has_opaque_types() && !pred.has_coroutines())
1515 }
1516 // The hidden types of `defined_opaque_types` is not local to the current
1517 // inference context, so we can freely move this to the global cache.
1518 TypingMode::PostBorrowckAnalysis { .. } => true,
1519 // The global cache is only used if there are no opaque types in
1520 // the defining scope or we're outside of analysis.
1521 //
1522 // FIXME(#132279): This is still incorrect as we treat opaque types
1523 // and default associated items differently between these two modes.
1524 TypingMode::PostAnalysis => true,
1525 }
1526 }
1527
1528 fn check_candidate_cache(
1529 &mut self,
1530 param_env: ty::ParamEnv<'tcx>,
1531 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1532 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1533 let infcx = self.infcx;
1534 let tcx = infcx.tcx;
1535 let pred = cache_fresh_trait_pred.skip_binder();
1536
1537 if self.can_use_global_caches(param_env, cache_fresh_trait_pred) {
1538 if let Some(res) = tcx.selection_cache.get(&(infcx.typing_env(param_env), pred), tcx) {
1539 return Some(res);
1540 } else if cfg!(debug_assertions) {
1541 match infcx.selection_cache.get(&(param_env, pred), tcx) {
1542 None | Some(Err(SelectionError::Overflow(OverflowError::Canonical))) => {}
1543 res => bug!("unexpected local cache result: {res:?}"),
1544 }
1545 }
1546 }
1547
1548 // Subtle: we need to check the local cache even if we're able to use the
1549 // global cache as we don't cache overflow in the global cache but need to
1550 // cache it as otherwise rustdoc hangs when compiling diesel.
1551 infcx.selection_cache.get(&(param_env, pred), tcx)
1552 }
1553
1554 /// Determines whether can we safely cache the result
1555 /// of selecting an obligation. This is almost always `true`,
1556 /// except when dealing with certain `ParamCandidate`s.
1557 ///
1558 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1559 /// since it was usually produced directly from a `DefId`. However,
1560 /// certain cases (currently only librustdoc's blanket impl finder),
1561 /// a `ParamEnv` may be explicitly constructed with inference types.
1562 /// When this is the case, we do *not* want to cache the resulting selection
1563 /// candidate. This is due to the fact that it might not always be possible
1564 /// to equate the obligation's trait ref and the candidate's trait ref,
1565 /// if more constraints end up getting added to an inference variable.
1566 ///
1567 /// Because of this, we always want to re-run the full selection
1568 /// process for our obligation the next time we see it, since
1569 /// we might end up picking a different `SelectionCandidate` (or none at all).
1570 fn can_cache_candidate(
1571 &self,
1572 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1573 ) -> bool {
1574 match result {
1575 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.has_infer(),
1576 _ => true,
1577 }
1578 }
1579
1580 #[instrument(skip(self, param_env, cache_fresh_trait_pred, dep_node), level = "debug")]
1581 fn insert_candidate_cache(
1582 &mut self,
1583 param_env: ty::ParamEnv<'tcx>,
1584 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1585 dep_node: DepNodeIndex,
1586 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1587 ) {
1588 let infcx = self.infcx;
1589 let tcx = infcx.tcx;
1590 let pred = cache_fresh_trait_pred.skip_binder();
1591
1592 if !self.can_cache_candidate(&candidate) {
1593 debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1594 return;
1595 }
1596
1597 if self.can_use_global_caches(param_env, cache_fresh_trait_pred) {
1598 if let Err(SelectionError::Overflow(OverflowError::Canonical)) = candidate {
1599 // Don't cache overflow globally; we only produce this in certain modes.
1600 } else {
1601 debug!(?pred, ?candidate, "insert_candidate_cache global");
1602 debug_assert!(!candidate.has_infer());
1603
1604 // This may overwrite the cache with the same value.
1605 tcx.selection_cache.insert(
1606 (infcx.typing_env(param_env), pred),
1607 dep_node,
1608 candidate,
1609 );
1610 return;
1611 }
1612 }
1613
1614 debug!(?pred, ?candidate, "insert_candidate_cache local");
1615 self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1616 }
1617
1618 /// Looks at the item bounds of the projection or opaque type.
1619 /// If this is a nested rigid projection, such as
1620 /// `<<T as Tr1>::Assoc as Tr2>::Assoc`, consider the item bounds
1621 /// on both `Tr1::Assoc` and `Tr2::Assoc`, since we may encounter
1622 /// relative bounds on both via the `associated_type_bounds` feature.
1623 pub(super) fn for_each_item_bound<T>(
1624 &mut self,
1625 mut self_ty: Ty<'tcx>,
1626 mut for_each: impl FnMut(&mut Self, ty::Clause<'tcx>, usize) -> ControlFlow<T, ()>,
1627 on_ambiguity: impl FnOnce(),
1628 ) -> ControlFlow<T, ()> {
1629 let mut idx = 0;
1630 let mut in_parent_alias_type = false;
1631
1632 loop {
1633 let (kind, alias_ty) = match *self_ty.kind() {
1634 ty::Alias(kind @ (ty::Projection | ty::Opaque), alias_ty) => (kind, alias_ty),
1635 ty::Infer(ty::TyVar(_)) => {
1636 on_ambiguity();
1637 return ControlFlow::Continue(());
1638 }
1639 _ => return ControlFlow::Continue(()),
1640 };
1641
1642 // HACK: On subsequent recursions, we only care about bounds that don't
1643 // share the same type as `self_ty`. This is because for truly rigid
1644 // projections, we will never be able to equate, e.g. `<T as Tr>::A`
1645 // with `<<T as Tr>::A as Tr>::A`.
1646 let relevant_bounds = if in_parent_alias_type {
1647 self.tcx().item_non_self_bounds(alias_ty.def_id)
1648 } else {
1649 self.tcx().item_self_bounds(alias_ty.def_id)
1650 };
1651
1652 for bound in relevant_bounds.instantiate(self.tcx(), alias_ty.args) {
1653 for_each(self, bound, idx)?;
1654 idx += 1;
1655 }
1656
1657 if kind == ty::Projection {
1658 self_ty = alias_ty.self_ty();
1659 } else {
1660 return ControlFlow::Continue(());
1661 }
1662
1663 in_parent_alias_type = true;
1664 }
1665 }
1666
1667 /// Equates the trait in `obligation` with trait bound. If the two traits
1668 /// can be equated and the normalized trait bound doesn't contain inference
1669 /// variables or placeholders, the normalized bound is returned.
1670 fn match_normalize_trait_ref(
1671 &mut self,
1672 obligation: &PolyTraitObligation<'tcx>,
1673 placeholder_trait_ref: ty::TraitRef<'tcx>,
1674 trait_bound: ty::PolyTraitRef<'tcx>,
1675 ) -> Result<Option<ty::TraitRef<'tcx>>, ()> {
1676 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1677 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1678 // Avoid unnecessary normalization
1679 return Err(());
1680 }
1681
1682 let drcx = DeepRejectCtxt::relate_rigid_rigid(self.infcx.tcx);
1683 let obligation_args = obligation.predicate.skip_binder().trait_ref.args;
1684 if !drcx.args_may_unify(obligation_args, trait_bound.skip_binder().args) {
1685 return Err(());
1686 }
1687
1688 let trait_bound = self.infcx.instantiate_binder_with_fresh_vars(
1689 obligation.cause.span,
1690 HigherRankedType,
1691 trait_bound,
1692 );
1693 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1694 normalize_with_depth(
1695 self,
1696 obligation.param_env,
1697 obligation.cause.clone(),
1698 obligation.recursion_depth + 1,
1699 trait_bound,
1700 )
1701 });
1702 self.infcx
1703 .at(&obligation.cause, obligation.param_env)
1704 .eq(DefineOpaqueTypes::No, placeholder_trait_ref, trait_bound)
1705 .map(|InferOk { obligations: _, value: () }| {
1706 // This method is called within a probe, so we can't have
1707 // inference variables and placeholders escape.
1708 if !trait_bound.has_infer() && !trait_bound.has_placeholders() {
1709 Some(trait_bound)
1710 } else {
1711 None
1712 }
1713 })
1714 .map_err(|_| ())
1715 }
1716
1717 fn where_clause_may_apply<'o>(
1718 &mut self,
1719 stack: &TraitObligationStack<'o, 'tcx>,
1720 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1721 ) -> Result<EvaluationResult, OverflowError> {
1722 self.evaluation_probe(|this| {
1723 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1724 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1725 Err(()) => Ok(EvaluatedToErr),
1726 }
1727 })
1728 }
1729
1730 /// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
1731 /// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
1732 /// and applying this env_predicate constrains any of the obligation's GAT parameters.
1733 ///
1734 /// This behavior is a somewhat of a hack to prevent over-constraining inference variables
1735 /// in cases like #91762.
1736 pub(super) fn match_projection_projections(
1737 &mut self,
1738 obligation: &ProjectionTermObligation<'tcx>,
1739 env_predicate: PolyProjectionPredicate<'tcx>,
1740 potentially_unnormalized_candidates: bool,
1741 ) -> ProjectionMatchesProjection {
1742 debug_assert_eq!(obligation.predicate.def_id, env_predicate.item_def_id());
1743
1744 let mut nested_obligations = PredicateObligations::new();
1745 let infer_predicate = self.infcx.instantiate_binder_with_fresh_vars(
1746 obligation.cause.span,
1747 BoundRegionConversionTime::HigherRankedType,
1748 env_predicate,
1749 );
1750 let infer_projection = if potentially_unnormalized_candidates {
1751 ensure_sufficient_stack(|| {
1752 normalize_with_depth_to(
1753 self,
1754 obligation.param_env,
1755 obligation.cause.clone(),
1756 obligation.recursion_depth + 1,
1757 infer_predicate.projection_term,
1758 &mut nested_obligations,
1759 )
1760 })
1761 } else {
1762 infer_predicate.projection_term
1763 };
1764
1765 let is_match = self
1766 .infcx
1767 .at(&obligation.cause, obligation.param_env)
1768 .eq(DefineOpaqueTypes::No, obligation.predicate, infer_projection)
1769 .is_ok_and(|InferOk { obligations, value: () }| {
1770 self.evaluate_predicates_recursively(
1771 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1772 nested_obligations.into_iter().chain(obligations),
1773 )
1774 .is_ok_and(|res| res.may_apply())
1775 });
1776
1777 if is_match {
1778 let generics = self.tcx().generics_of(obligation.predicate.def_id);
1779 // FIXME(generic_associated_types): Addresses aggressive inference in #92917.
1780 // If this type is a GAT, and of the GAT args resolve to something new,
1781 // that means that we must have newly inferred something about the GAT.
1782 // We should give up in that case.
1783 //
1784 // This only detects one layer of inference, which is probably not what we actually
1785 // want, but fixing it causes some ambiguity:
1786 // <https://github.com/rust-lang/rust/issues/125196>.
1787 if !generics.is_own_empty()
1788 && obligation.predicate.args[generics.parent_count..].iter().any(|&p| {
1789 p.has_non_region_infer()
1790 && match p.kind() {
1791 ty::GenericArgKind::Const(ct) => {
1792 self.infcx.shallow_resolve_const(ct) != ct
1793 }
1794 ty::GenericArgKind::Type(ty) => self.infcx.shallow_resolve(ty) != ty,
1795 ty::GenericArgKind::Lifetime(_) => false,
1796 }
1797 })
1798 {
1799 ProjectionMatchesProjection::Ambiguous
1800 } else {
1801 ProjectionMatchesProjection::Yes
1802 }
1803 } else {
1804 ProjectionMatchesProjection::No
1805 }
1806 }
1807}
1808
1809/// ## Winnowing
1810///
1811/// Winnowing is the process of attempting to resolve ambiguity by
1812/// probing further. During the winnowing process, we unify all
1813/// type variables and then we also attempt to evaluate recursive
1814/// bounds to see if they are satisfied.
1815impl<'tcx> SelectionContext<'_, 'tcx> {
1816 /// If there are multiple ways to prove a trait goal, we make some
1817 /// *fairly arbitrary* choices about which candidate is actually used.
1818 ///
1819 /// For more details, look at the implementation of this method :)
1820 #[instrument(level = "debug", skip(self), ret)]
1821 fn winnow_candidates(
1822 &mut self,
1823 has_non_region_infer: bool,
1824 mut candidates: Vec<EvaluatedCandidate<'tcx>>,
1825 ) -> Option<SelectionCandidate<'tcx>> {
1826 if candidates.len() == 1 {
1827 return Some(candidates.pop().unwrap().candidate);
1828 }
1829
1830 // We prefer `Sized` candidates over everything.
1831 let mut sized_candidates =
1832 candidates.iter().filter(|c| matches!(c.candidate, SizedCandidate));
1833 if let Some(sized_candidate) = sized_candidates.next() {
1834 // There should only ever be a single sized candidate
1835 // as they would otherwise overlap.
1836 debug_assert_eq!(sized_candidates.next(), None);
1837 // Only prefer the built-in `Sized` candidate if its nested goals are certain.
1838 // Otherwise, we may encounter failure later on if inference causes this candidate
1839 // to not hold, but a where clause would've applied instead.
1840 if sized_candidate.evaluation.must_apply_modulo_regions() {
1841 return Some(sized_candidate.candidate.clone());
1842 } else {
1843 return None;
1844 }
1845 }
1846
1847 // Before we consider where-bounds, we have to deduplicate them here and also
1848 // drop where-bounds in case the same where-bound exists without bound vars.
1849 // This is necessary as elaborating super-trait bounds may result in duplicates.
1850 'search_victim: loop {
1851 for (i, this) in candidates.iter().enumerate() {
1852 let ParamCandidate(this) = this.candidate else { continue };
1853 for (j, other) in candidates.iter().enumerate() {
1854 if i == j {
1855 continue;
1856 }
1857
1858 let ParamCandidate(other) = other.candidate else { continue };
1859 if this == other {
1860 candidates.remove(j);
1861 continue 'search_victim;
1862 }
1863
1864 if this.skip_binder().trait_ref == other.skip_binder().trait_ref
1865 && this.skip_binder().polarity == other.skip_binder().polarity
1866 && !this.skip_binder().trait_ref.has_escaping_bound_vars()
1867 {
1868 candidates.remove(j);
1869 continue 'search_victim;
1870 }
1871 }
1872 }
1873
1874 break;
1875 }
1876
1877 // The next highest priority is for non-global where-bounds. However, while we don't
1878 // prefer global where-clauses here, we do bail with ambiguity when encountering both
1879 // a global and a non-global where-clause.
1880 //
1881 // Our handling of where-bounds is generally fairly messy but necessary for backwards
1882 // compatibility, see #50825 for why we need to handle global where-bounds like this.
1883 let is_global = |c: ty::PolyTraitPredicate<'tcx>| c.is_global() && !c.has_bound_vars();
1884 let param_candidates = candidates
1885 .iter()
1886 .filter_map(|c| if let ParamCandidate(p) = c.candidate { Some(p) } else { None });
1887 let mut has_global_bounds = false;
1888 let mut param_candidate = None;
1889 for c in param_candidates {
1890 if is_global(c) {
1891 has_global_bounds = true;
1892 } else if param_candidate.replace(c).is_some() {
1893 // Ambiguity, two potentially different where-clauses
1894 return None;
1895 }
1896 }
1897 if let Some(predicate) = param_candidate {
1898 // Ambiguity, a global and a non-global where-bound.
1899 if has_global_bounds {
1900 return None;
1901 } else {
1902 return Some(ParamCandidate(predicate));
1903 }
1904 }
1905
1906 // Prefer alias-bounds over blanket impls for rigid associated types. This is
1907 // fairly arbitrary but once again necessary for backwards compatibility.
1908 // If there are multiple applicable candidates which don't affect type inference,
1909 // choose the one with the lowest index.
1910 let alias_bound = candidates
1911 .iter()
1912 .filter_map(|c| if let ProjectionCandidate(i) = c.candidate { Some(i) } else { None })
1913 .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) });
1914 match alias_bound {
1915 Some(Some(index)) => return Some(ProjectionCandidate(index)),
1916 Some(None) => {}
1917 None => return None,
1918 }
1919
1920 // Need to prioritize builtin trait object impls as `<dyn Any as Any>::type_id`
1921 // should use the vtable method and not the method provided by the user-defined
1922 // impl `impl<T: ?Sized> Any for T { .. }`. This really shouldn't exist but is
1923 // necessary due to #57893. We again arbitrarily prefer the applicable candidate
1924 // with the lowest index.
1925 //
1926 // We do not want to use these impls to guide inference in case a user-written impl
1927 // may also apply.
1928 let object_bound = candidates
1929 .iter()
1930 .filter_map(|c| if let ObjectCandidate(i) = c.candidate { Some(i) } else { None })
1931 .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) });
1932 match object_bound {
1933 Some(Some(index)) => {
1934 return if has_non_region_infer
1935 && candidates.iter().any(|c| matches!(c.candidate, ImplCandidate(_)))
1936 {
1937 None
1938 } else {
1939 Some(ObjectCandidate(index))
1940 };
1941 }
1942 Some(None) => {}
1943 None => return None,
1944 }
1945 // Same for upcasting.
1946 let upcast_bound = candidates
1947 .iter()
1948 .filter_map(|c| {
1949 if let TraitUpcastingUnsizeCandidate(i) = c.candidate { Some(i) } else { None }
1950 })
1951 .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) });
1952 match upcast_bound {
1953 Some(Some(index)) => return Some(TraitUpcastingUnsizeCandidate(index)),
1954 Some(None) => {}
1955 None => return None,
1956 }
1957
1958 // Finally, handle overlapping user-written impls.
1959 let impls = candidates.iter().filter_map(|c| {
1960 if let ImplCandidate(def_id) = c.candidate {
1961 Some((def_id, c.evaluation))
1962 } else {
1963 None
1964 }
1965 });
1966 let mut impl_candidate = None;
1967 for c in impls {
1968 if let Some(prev) = impl_candidate.replace(c) {
1969 if self.prefer_lhs_over_victim(has_non_region_infer, c, prev.0) {
1970 // Ok, prefer `c` over the previous entry
1971 } else if self.prefer_lhs_over_victim(has_non_region_infer, prev, c.0) {
1972 // Ok, keep `prev` instead of the new entry
1973 impl_candidate = Some(prev);
1974 } else {
1975 // Ambiguity, two potentially different where-clauses
1976 return None;
1977 }
1978 }
1979 }
1980 if let Some((def_id, _evaluation)) = impl_candidate {
1981 // Don't use impl candidates which overlap with other candidates.
1982 // This should pretty much only ever happen with malformed impls.
1983 if candidates.iter().all(|c| match c.candidate {
1984 SizedCandidate
1985 | BuiltinCandidate
1986 | TransmutabilityCandidate
1987 | AutoImplCandidate
1988 | ClosureCandidate { .. }
1989 | AsyncClosureCandidate
1990 | AsyncFnKindHelperCandidate
1991 | CoroutineCandidate
1992 | FutureCandidate
1993 | IteratorCandidate
1994 | AsyncIteratorCandidate
1995 | FnPointerCandidate
1996 | TraitAliasCandidate
1997 | TraitUpcastingUnsizeCandidate(_)
1998 | BuiltinObjectCandidate
1999 | BuiltinUnsizeCandidate
2000 | BikeshedGuaranteedNoDropCandidate => false,
2001 // Non-global param candidates have already been handled, global
2002 // where-bounds get ignored.
2003 ParamCandidate(_) | ImplCandidate(_) => true,
2004 ProjectionCandidate(_) | ObjectCandidate(_) => unreachable!(),
2005 }) {
2006 return Some(ImplCandidate(def_id));
2007 } else {
2008 return None;
2009 }
2010 }
2011
2012 if candidates.len() == 1 {
2013 Some(candidates.pop().unwrap().candidate)
2014 } else {
2015 // Also try ignoring all global where-bounds and check whether we end
2016 // with a unique candidate in this case.
2017 let mut not_a_global_where_bound = candidates
2018 .into_iter()
2019 .filter(|c| !matches!(c.candidate, ParamCandidate(p) if is_global(p)));
2020 not_a_global_where_bound
2021 .next()
2022 .map(|c| c.candidate)
2023 .filter(|_| not_a_global_where_bound.next().is_none())
2024 }
2025 }
2026
2027 fn prefer_lhs_over_victim(
2028 &self,
2029 has_non_region_infer: bool,
2030 (lhs, lhs_evaluation): (DefId, EvaluationResult),
2031 victim: DefId,
2032 ) -> bool {
2033 let tcx = self.tcx();
2034 // See if we can toss out `victim` based on specialization.
2035 //
2036 // While this requires us to know *for sure* that the `lhs` impl applies
2037 // we still use modulo regions here. This is fine as specialization currently
2038 // assumes that specializing impls have to be always applicable, meaning that
2039 // the only allowed region constraints may be constraints also present on the default impl.
2040 if lhs_evaluation.must_apply_modulo_regions() {
2041 if tcx.specializes((lhs, victim)) {
2042 return true;
2043 }
2044 }
2045
2046 match tcx.impls_are_allowed_to_overlap(lhs, victim) {
2047 // For candidates which already reference errors it doesn't really
2048 // matter what we do 🤷
2049 Some(ty::ImplOverlapKind::Permitted { marker: false }) => {
2050 lhs_evaluation.must_apply_considering_regions()
2051 }
2052 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
2053 // Subtle: If the predicate we are evaluating has inference
2054 // variables, do *not* allow discarding candidates due to
2055 // marker trait impls.
2056 //
2057 // Without this restriction, we could end up accidentally
2058 // constraining inference variables based on an arbitrarily
2059 // chosen trait impl.
2060 //
2061 // Imagine we have the following code:
2062 //
2063 // ```rust
2064 // #[marker] trait MyTrait {}
2065 // impl MyTrait for u8 {}
2066 // impl MyTrait for bool {}
2067 // ```
2068 //
2069 // And we are evaluating the predicate `<_#0t as MyTrait>`.
2070 //
2071 // During selection, we will end up with one candidate for each
2072 // impl of `MyTrait`. If we were to discard one impl in favor
2073 // of the other, we would be left with one candidate, causing
2074 // us to "successfully" select the predicate, unifying
2075 // _#0t with (for example) `u8`.
2076 //
2077 // However, we have no reason to believe that this unification
2078 // is correct - we've essentially just picked an arbitrary
2079 // *possibility* for _#0t, and required that this be the *only*
2080 // possibility.
2081 //
2082 // Eventually, we will either:
2083 // 1) Unify all inference variables in the predicate through
2084 // some other means (e.g. type-checking of a function). We will
2085 // then be in a position to drop marker trait candidates
2086 // without constraining inference variables (since there are
2087 // none left to constrain)
2088 // 2) Be left with some unconstrained inference variables. We
2089 // will then correctly report an inference error, since the
2090 // existence of multiple marker trait impls tells us nothing
2091 // about which one should actually apply.
2092 !has_non_region_infer && lhs_evaluation.must_apply_considering_regions()
2093 }
2094 None => false,
2095 }
2096 }
2097}
2098
2099impl<'tcx> SelectionContext<'_, 'tcx> {
2100 fn sizedness_conditions(
2101 &mut self,
2102 self_ty: Ty<'tcx>,
2103 sizedness: SizedTraitKind,
2104 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
2105 match self_ty.kind() {
2106 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2107 | ty::Uint(_)
2108 | ty::Int(_)
2109 | ty::Bool
2110 | ty::Float(_)
2111 | ty::FnDef(..)
2112 | ty::FnPtr(..)
2113 | ty::RawPtr(..)
2114 | ty::Char
2115 | ty::Ref(..)
2116 | ty::Coroutine(..)
2117 | ty::CoroutineWitness(..)
2118 | ty::Array(..)
2119 | ty::Closure(..)
2120 | ty::CoroutineClosure(..)
2121 | ty::Never
2122 | ty::Error(_) => ty::Binder::dummy(vec![]),
2123
2124 ty::Str | ty::Slice(_) | ty::Dynamic(..) => match sizedness {
2125 SizedTraitKind::Sized => unreachable!("tried to assemble `Sized` for unsized type"),
2126 SizedTraitKind::MetaSized => ty::Binder::dummy(vec![]),
2127 },
2128
2129 ty::Foreign(..) => unreachable!("tried to assemble `Sized` for unsized type"),
2130
2131 ty::Tuple(tys) => {
2132 ty::Binder::dummy(tys.last().map_or_else(Vec::new, |&last| vec![last]))
2133 }
2134
2135 ty::Pat(ty, _) => ty::Binder::dummy(vec![*ty]),
2136
2137 ty::Adt(def, args) => {
2138 if let Some(crit) = def.sizedness_constraint(self.tcx(), sizedness) {
2139 ty::Binder::dummy(vec![crit.instantiate(self.tcx(), args)])
2140 } else {
2141 ty::Binder::dummy(vec![])
2142 }
2143 }
2144
2145 ty::UnsafeBinder(binder_ty) => binder_ty.map_bound(|ty| vec![ty]),
2146
2147 ty::Alias(..)
2148 | ty::Param(_)
2149 | ty::Placeholder(..)
2150 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
2151 | ty::Bound(..) => {
2152 bug!("asked to assemble `Sized` of unexpected type: {:?}", self_ty);
2153 }
2154 }
2155 }
2156
2157 fn copy_clone_conditions(&mut self, self_ty: Ty<'tcx>) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
2158 match *self_ty.kind() {
2159 ty::FnDef(..) | ty::FnPtr(..) | ty::Error(_) => ty::Binder::dummy(vec![]),
2160
2161 ty::Uint(_)
2162 | ty::Int(_)
2163 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2164 | ty::Bool
2165 | ty::Float(_)
2166 | ty::Char
2167 | ty::RawPtr(..)
2168 | ty::Never
2169 | ty::Ref(_, _, hir::Mutability::Not)
2170 | ty::Array(..) => {
2171 unreachable!("tried to assemble `Sized` for type with libcore-provided impl")
2172 }
2173
2174 // FIXME(unsafe_binder): Should we conditionally
2175 // (i.e. universally) implement copy/clone?
2176 ty::UnsafeBinder(_) => unreachable!("tried to assemble `Sized` for unsafe binder"),
2177
2178 ty::Tuple(tys) => {
2179 // (*) binder moved here
2180 ty::Binder::dummy(tys.iter().collect())
2181 }
2182
2183 ty::Pat(ty, _) => {
2184 // (*) binder moved here
2185 ty::Binder::dummy(vec![ty])
2186 }
2187
2188 ty::Coroutine(def_id, args) => match self.tcx().coroutine_movability(def_id) {
2189 hir::Movability::Static => {
2190 unreachable!("tried to assemble `Clone` for static coroutine")
2191 }
2192 hir::Movability::Movable => {
2193 if self.tcx().features().coroutine_clone() {
2194 ty::Binder::dummy(vec![
2195 args.as_coroutine().tupled_upvars_ty(),
2196 Ty::new_coroutine_witness_for_coroutine(self.tcx(), def_id, args),
2197 ])
2198 } else {
2199 unreachable!(
2200 "tried to assemble `Clone` for coroutine without enabled feature"
2201 )
2202 }
2203 }
2204 },
2205
2206 ty::CoroutineWitness(def_id, args) => self
2207 .infcx
2208 .tcx
2209 .coroutine_hidden_types(def_id)
2210 .instantiate(self.infcx.tcx, args)
2211 .map_bound(|witness| witness.types.to_vec()),
2212
2213 ty::Closure(_, args) => ty::Binder::dummy(args.as_closure().upvar_tys().to_vec()),
2214
2215 ty::CoroutineClosure(_, args) => {
2216 ty::Binder::dummy(args.as_coroutine_closure().upvar_tys().to_vec())
2217 }
2218
2219 ty::Foreign(..)
2220 | ty::Str
2221 | ty::Slice(_)
2222 | ty::Dynamic(..)
2223 | ty::Adt(..)
2224 | ty::Alias(..)
2225 | ty::Param(..)
2226 | ty::Placeholder(..)
2227 | ty::Bound(..)
2228 | ty::Ref(_, _, ty::Mutability::Mut)
2229 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2230 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
2231 }
2232 }
2233 }
2234
2235 fn coroutine_is_gen(&mut self, self_ty: Ty<'tcx>) -> bool {
2236 matches!(*self_ty.kind(), ty::Coroutine(did, ..)
2237 if self.tcx().coroutine_is_gen(did))
2238 }
2239
2240 /// For default impls, we need to break apart a type into its
2241 /// "constituent types" -- meaning, the types that it contains.
2242 ///
2243 /// Here are some (simple) examples:
2244 ///
2245 /// ```ignore (illustrative)
2246 /// (i32, u32) -> [i32, u32]
2247 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2248 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2249 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2250 /// ```
2251 #[instrument(level = "debug", skip(self), ret)]
2252 fn constituent_types_for_auto_trait(
2253 &self,
2254 t: Ty<'tcx>,
2255 ) -> Result<ty::Binder<'tcx, AutoImplConstituents<'tcx>>, SelectionError<'tcx>> {
2256 Ok(match *t.kind() {
2257 ty::Uint(_)
2258 | ty::Int(_)
2259 | ty::Bool
2260 | ty::Float(_)
2261 | ty::FnDef(..)
2262 | ty::FnPtr(..)
2263 | ty::Error(_)
2264 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2265 | ty::Never
2266 | ty::Char => {
2267 ty::Binder::dummy(AutoImplConstituents { types: vec![], assumptions: vec![] })
2268 }
2269
2270 // This branch is only for `experimental_default_bounds`.
2271 // Other foreign types were rejected earlier in
2272 // `assemble_candidates_from_auto_impls`.
2273 ty::Foreign(..) => {
2274 ty::Binder::dummy(AutoImplConstituents { types: vec![], assumptions: vec![] })
2275 }
2276
2277 ty::UnsafeBinder(ty) => {
2278 ty.map_bound(|ty| AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2279 }
2280
2281 // Treat this like `struct str([u8]);`
2282 ty::Str => ty::Binder::dummy(AutoImplConstituents {
2283 types: vec![Ty::new_slice(self.tcx(), self.tcx().types.u8)],
2284 assumptions: vec![],
2285 }),
2286
2287 ty::Placeholder(..)
2288 | ty::Dynamic(..)
2289 | ty::Param(..)
2290 | ty::Alias(ty::Projection | ty::Inherent | ty::Free, ..)
2291 | ty::Bound(..)
2292 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2293 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2294 }
2295
2296 ty::RawPtr(element_ty, _) | ty::Ref(_, element_ty, _) => {
2297 ty::Binder::dummy(AutoImplConstituents {
2298 types: vec![element_ty],
2299 assumptions: vec![],
2300 })
2301 }
2302
2303 ty::Pat(ty, _) | ty::Array(ty, _) | ty::Slice(ty) => {
2304 ty::Binder::dummy(AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2305 }
2306
2307 ty::Tuple(tys) => {
2308 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2309 ty::Binder::dummy(AutoImplConstituents {
2310 types: tys.iter().collect(),
2311 assumptions: vec![],
2312 })
2313 }
2314
2315 ty::Closure(_, args) => {
2316 let ty = self.infcx.shallow_resolve(args.as_closure().tupled_upvars_ty());
2317 ty::Binder::dummy(AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2318 }
2319
2320 ty::CoroutineClosure(_, args) => {
2321 let ty = self.infcx.shallow_resolve(args.as_coroutine_closure().tupled_upvars_ty());
2322 ty::Binder::dummy(AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2323 }
2324
2325 ty::Coroutine(def_id, args) => {
2326 let ty = self.infcx.shallow_resolve(args.as_coroutine().tupled_upvars_ty());
2327 let tcx = self.tcx();
2328 let witness = Ty::new_coroutine_witness_for_coroutine(tcx, def_id, args);
2329 ty::Binder::dummy(AutoImplConstituents {
2330 types: vec![ty, witness],
2331 assumptions: vec![],
2332 })
2333 }
2334
2335 ty::CoroutineWitness(def_id, args) => self
2336 .infcx
2337 .tcx
2338 .coroutine_hidden_types(def_id)
2339 .instantiate(self.infcx.tcx, args)
2340 .map_bound(|witness| AutoImplConstituents {
2341 types: witness.types.to_vec(),
2342 assumptions: witness.assumptions.to_vec(),
2343 }),
2344
2345 // For `PhantomData<T>`, we pass `T`.
2346 ty::Adt(def, args) if def.is_phantom_data() => {
2347 ty::Binder::dummy(AutoImplConstituents {
2348 types: args.types().collect(),
2349 assumptions: vec![],
2350 })
2351 }
2352
2353 ty::Adt(def, args) => ty::Binder::dummy(AutoImplConstituents {
2354 types: def.all_fields().map(|f| f.ty(self.tcx(), args)).collect(),
2355 assumptions: vec![],
2356 }),
2357
2358 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
2359 if self.infcx.can_define_opaque_ty(def_id) {
2360 unreachable!()
2361 } else {
2362 // We can resolve the `impl Trait` to its concrete type,
2363 // which enforces a DAG between the functions requiring
2364 // the auto trait bounds in question.
2365 match self.tcx().type_of_opaque(def_id) {
2366 Ok(ty) => ty::Binder::dummy(AutoImplConstituents {
2367 types: vec![ty.instantiate(self.tcx(), args)],
2368 assumptions: vec![],
2369 }),
2370 Err(_) => {
2371 return Err(SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id));
2372 }
2373 }
2374 }
2375 }
2376 })
2377 }
2378
2379 fn collect_predicates_for_types(
2380 &mut self,
2381 param_env: ty::ParamEnv<'tcx>,
2382 cause: ObligationCause<'tcx>,
2383 recursion_depth: usize,
2384 trait_def_id: DefId,
2385 types: Vec<Ty<'tcx>>,
2386 ) -> PredicateObligations<'tcx> {
2387 // Because the types were potentially derived from
2388 // higher-ranked obligations they may reference late-bound
2389 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2390 // yield a type like `for<'a> &'a i32`. In general, we
2391 // maintain the invariant that we never manipulate bound
2392 // regions, so we have to process these bound regions somehow.
2393 //
2394 // The strategy is to:
2395 //
2396 // 1. Instantiate those regions to placeholder regions (e.g.,
2397 // `for<'a> &'a i32` becomes `&0 i32`.
2398 // 2. Produce something like `&'0 i32 : Copy`
2399 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
2400
2401 types
2402 .into_iter()
2403 .flat_map(|placeholder_ty| {
2404 let Normalized { value: normalized_ty, mut obligations } =
2405 ensure_sufficient_stack(|| {
2406 normalize_with_depth(
2407 self,
2408 param_env,
2409 cause.clone(),
2410 recursion_depth,
2411 placeholder_ty,
2412 )
2413 });
2414
2415 let tcx = self.tcx();
2416 let trait_ref = if tcx.generics_of(trait_def_id).own_params.len() == 1 {
2417 ty::TraitRef::new(tcx, trait_def_id, [normalized_ty])
2418 } else {
2419 // If this is an ill-formed auto/built-in trait, then synthesize
2420 // new error args for the missing generics.
2421 let err_args = ty::GenericArgs::extend_with_error(
2422 tcx,
2423 trait_def_id,
2424 &[normalized_ty.into()],
2425 );
2426 ty::TraitRef::new_from_args(tcx, trait_def_id, err_args)
2427 };
2428
2429 let obligation = Obligation::new(self.tcx(), cause.clone(), param_env, trait_ref);
2430 obligations.push(obligation);
2431 obligations
2432 })
2433 .collect()
2434 }
2435
2436 ///////////////////////////////////////////////////////////////////////////
2437 // Matching
2438 //
2439 // Matching is a common path used for both evaluation and
2440 // confirmation. It basically unifies types that appear in impls
2441 // and traits. This does affect the surrounding environment;
2442 // therefore, when used during evaluation, match routines must be
2443 // run inside of a `probe()` so that their side-effects are
2444 // contained.
2445
2446 fn rematch_impl(
2447 &mut self,
2448 impl_def_id: DefId,
2449 obligation: &PolyTraitObligation<'tcx>,
2450 ) -> Normalized<'tcx, GenericArgsRef<'tcx>> {
2451 let impl_trait_header = self.tcx().impl_trait_header(impl_def_id).unwrap();
2452 match self.match_impl(impl_def_id, impl_trait_header, obligation) {
2453 Ok(args) => args,
2454 Err(()) => {
2455 let predicate = self.infcx.resolve_vars_if_possible(obligation.predicate);
2456 bug!("impl {impl_def_id:?} was matchable against {predicate:?} but now is not")
2457 }
2458 }
2459 }
2460
2461 #[instrument(level = "debug", skip(self), ret)]
2462 fn match_impl(
2463 &mut self,
2464 impl_def_id: DefId,
2465 impl_trait_header: ty::ImplTraitHeader<'tcx>,
2466 obligation: &PolyTraitObligation<'tcx>,
2467 ) -> Result<Normalized<'tcx, GenericArgsRef<'tcx>>, ()> {
2468 let placeholder_obligation =
2469 self.infcx.enter_forall_and_leak_universe(obligation.predicate);
2470 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
2471
2472 let impl_args = self.infcx.fresh_args_for_item(obligation.cause.span, impl_def_id);
2473
2474 let trait_ref = impl_trait_header.trait_ref.instantiate(self.tcx(), impl_args);
2475 debug!(?impl_trait_header);
2476
2477 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2478 ensure_sufficient_stack(|| {
2479 normalize_with_depth(
2480 self,
2481 obligation.param_env,
2482 obligation.cause.clone(),
2483 obligation.recursion_depth + 1,
2484 trait_ref,
2485 )
2486 });
2487
2488 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
2489
2490 let cause = ObligationCause::new(
2491 obligation.cause.span,
2492 obligation.cause.body_id,
2493 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2494 );
2495
2496 let InferOk { obligations, .. } = self
2497 .infcx
2498 .at(&cause, obligation.param_env)
2499 .eq(DefineOpaqueTypes::No, placeholder_obligation_trait_ref, impl_trait_ref)
2500 .map_err(|e| {
2501 debug!("match_impl: failed eq_trait_refs due to `{}`", e.to_string(self.tcx()))
2502 })?;
2503 nested_obligations.extend(obligations);
2504
2505 if impl_trait_header.polarity == ty::ImplPolarity::Reservation
2506 && !matches!(self.infcx.typing_mode(), TypingMode::Coherence)
2507 {
2508 debug!("reservation impls only apply in intercrate mode");
2509 return Err(());
2510 }
2511
2512 Ok(Normalized { value: impl_args, obligations: nested_obligations })
2513 }
2514
2515 fn match_upcast_principal(
2516 &mut self,
2517 obligation: &PolyTraitObligation<'tcx>,
2518 unnormalized_upcast_principal: ty::PolyTraitRef<'tcx>,
2519 a_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2520 b_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2521 a_region: ty::Region<'tcx>,
2522 b_region: ty::Region<'tcx>,
2523 ) -> SelectionResult<'tcx, PredicateObligations<'tcx>> {
2524 let tcx = self.tcx();
2525 let mut nested = PredicateObligations::new();
2526
2527 // We may upcast to auto traits that are either explicitly listed in
2528 // the object type's bounds, or implied by the principal trait ref's
2529 // supertraits.
2530 let a_auto_traits: FxIndexSet<DefId> = a_data
2531 .auto_traits()
2532 .chain(a_data.principal_def_id().into_iter().flat_map(|principal_def_id| {
2533 elaborate::supertrait_def_ids(tcx, principal_def_id)
2534 .filter(|def_id| tcx.trait_is_auto(*def_id))
2535 }))
2536 .collect();
2537
2538 let upcast_principal = normalize_with_depth_to(
2539 self,
2540 obligation.param_env,
2541 obligation.cause.clone(),
2542 obligation.recursion_depth + 1,
2543 unnormalized_upcast_principal,
2544 &mut nested,
2545 );
2546
2547 for bound in b_data {
2548 match bound.skip_binder() {
2549 // Check that a_ty's supertrait (upcast_principal) is compatible
2550 // with the target (b_ty).
2551 ty::ExistentialPredicate::Trait(target_principal) => {
2552 let hr_source_principal = upcast_principal.map_bound(|trait_ref| {
2553 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
2554 });
2555 let hr_target_principal = bound.rebind(target_principal);
2556
2557 nested.extend(
2558 self.infcx
2559 .enter_forall(hr_target_principal, |target_principal| {
2560 let source_principal =
2561 self.infcx.instantiate_binder_with_fresh_vars(
2562 obligation.cause.span,
2563 HigherRankedType,
2564 hr_source_principal,
2565 );
2566 self.infcx.at(&obligation.cause, obligation.param_env).eq_trace(
2567 DefineOpaqueTypes::Yes,
2568 ToTrace::to_trace(
2569 &obligation.cause,
2570 hr_target_principal,
2571 hr_source_principal,
2572 ),
2573 target_principal,
2574 source_principal,
2575 )
2576 })
2577 .map_err(|_| SelectionError::Unimplemented)?
2578 .into_obligations(),
2579 );
2580 }
2581 // Check that b_ty's projection is satisfied by exactly one of
2582 // a_ty's projections. First, we look through the list to see if
2583 // any match. If not, error. Then, if *more* than one matches, we
2584 // return ambiguity. Otherwise, if exactly one matches, equate
2585 // it with b_ty's projection.
2586 ty::ExistentialPredicate::Projection(target_projection) => {
2587 let hr_target_projection = bound.rebind(target_projection);
2588
2589 let mut matching_projections =
2590 a_data.projection_bounds().filter(|&hr_source_projection| {
2591 // Eager normalization means that we can just use can_eq
2592 // here instead of equating and processing obligations.
2593 hr_source_projection.item_def_id() == hr_target_projection.item_def_id()
2594 && self.infcx.probe(|_| {
2595 self.infcx
2596 .enter_forall(hr_target_projection, |target_projection| {
2597 let source_projection =
2598 self.infcx.instantiate_binder_with_fresh_vars(
2599 obligation.cause.span,
2600 HigherRankedType,
2601 hr_source_projection,
2602 );
2603 self.infcx
2604 .at(&obligation.cause, obligation.param_env)
2605 .eq_trace(
2606 DefineOpaqueTypes::Yes,
2607 ToTrace::to_trace(
2608 &obligation.cause,
2609 hr_target_projection,
2610 hr_source_projection,
2611 ),
2612 target_projection,
2613 source_projection,
2614 )
2615 })
2616 .is_ok()
2617 })
2618 });
2619
2620 let Some(hr_source_projection) = matching_projections.next() else {
2621 return Err(SelectionError::Unimplemented);
2622 };
2623 if matching_projections.next().is_some() {
2624 return Ok(None);
2625 }
2626 nested.extend(
2627 self.infcx
2628 .enter_forall(hr_target_projection, |target_projection| {
2629 let source_projection =
2630 self.infcx.instantiate_binder_with_fresh_vars(
2631 obligation.cause.span,
2632 HigherRankedType,
2633 hr_source_projection,
2634 );
2635 self.infcx.at(&obligation.cause, obligation.param_env).eq_trace(
2636 DefineOpaqueTypes::Yes,
2637 ToTrace::to_trace(
2638 &obligation.cause,
2639 hr_target_projection,
2640 hr_source_projection,
2641 ),
2642 target_projection,
2643 source_projection,
2644 )
2645 })
2646 .map_err(|_| SelectionError::Unimplemented)?
2647 .into_obligations(),
2648 );
2649 }
2650 // Check that b_ty's auto traits are present in a_ty's bounds.
2651 ty::ExistentialPredicate::AutoTrait(def_id) => {
2652 if !a_auto_traits.contains(&def_id) {
2653 return Err(SelectionError::Unimplemented);
2654 }
2655 }
2656 }
2657 }
2658
2659 nested.push(Obligation::with_depth(
2660 tcx,
2661 obligation.cause.clone(),
2662 obligation.recursion_depth + 1,
2663 obligation.param_env,
2664 ty::Binder::dummy(ty::OutlivesPredicate(a_region, b_region)),
2665 ));
2666
2667 Ok(Some(nested))
2668 }
2669
2670 /// Normalize `where_clause_trait_ref` and try to match it against
2671 /// `obligation`. If successful, return any predicates that
2672 /// result from the normalization.
2673 fn match_where_clause_trait_ref(
2674 &mut self,
2675 obligation: &PolyTraitObligation<'tcx>,
2676 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2677 ) -> Result<PredicateObligations<'tcx>, ()> {
2678 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2679 }
2680
2681 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2682 /// obligation is satisfied.
2683 #[instrument(skip(self), level = "debug")]
2684 fn match_poly_trait_ref(
2685 &mut self,
2686 obligation: &PolyTraitObligation<'tcx>,
2687 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2688 ) -> Result<PredicateObligations<'tcx>, ()> {
2689 let predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
2690 let trait_ref = self.infcx.instantiate_binder_with_fresh_vars(
2691 obligation.cause.span,
2692 HigherRankedType,
2693 poly_trait_ref,
2694 );
2695 self.infcx
2696 .at(&obligation.cause, obligation.param_env)
2697 .eq(DefineOpaqueTypes::No, predicate.trait_ref, trait_ref)
2698 .map(|InferOk { obligations, .. }| obligations)
2699 .map_err(|_| ())
2700 }
2701
2702 ///////////////////////////////////////////////////////////////////////////
2703 // Miscellany
2704
2705 fn match_fresh_trait_refs(
2706 &self,
2707 previous: ty::PolyTraitPredicate<'tcx>,
2708 current: ty::PolyTraitPredicate<'tcx>,
2709 ) -> bool {
2710 let mut matcher = _match::MatchAgainstFreshVars::new(self.tcx());
2711 matcher.relate(previous, current).is_ok()
2712 }
2713
2714 fn push_stack<'o>(
2715 &mut self,
2716 previous_stack: TraitObligationStackList<'o, 'tcx>,
2717 obligation: &'o PolyTraitObligation<'tcx>,
2718 ) -> TraitObligationStack<'o, 'tcx> {
2719 let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
2720
2721 let dfn = previous_stack.cache.next_dfn();
2722 let depth = previous_stack.depth() + 1;
2723 TraitObligationStack {
2724 obligation,
2725 fresh_trait_pred,
2726 reached_depth: Cell::new(depth),
2727 previous: previous_stack,
2728 dfn,
2729 depth,
2730 }
2731 }
2732
2733 #[instrument(skip(self), level = "debug")]
2734 fn closure_trait_ref_unnormalized(
2735 &mut self,
2736 self_ty: Ty<'tcx>,
2737 fn_trait_def_id: DefId,
2738 ) -> ty::PolyTraitRef<'tcx> {
2739 let ty::Closure(_, args) = *self_ty.kind() else {
2740 bug!("expected closure, found {self_ty}");
2741 };
2742 let closure_sig = args.as_closure().sig();
2743
2744 closure_trait_ref_and_return_type(
2745 self.tcx(),
2746 fn_trait_def_id,
2747 self_ty,
2748 closure_sig,
2749 util::TupleArgumentsFlag::No,
2750 )
2751 .map_bound(|(trait_ref, _)| trait_ref)
2752 }
2753
2754 /// Returns the obligations that are implied by instantiating an
2755 /// impl or trait. The obligations are instantiated and fully
2756 /// normalized. This is used when confirming an impl or default
2757 /// impl.
2758 #[instrument(level = "debug", skip(self, cause, param_env))]
2759 fn impl_or_trait_obligations(
2760 &mut self,
2761 cause: &ObligationCause<'tcx>,
2762 recursion_depth: usize,
2763 param_env: ty::ParamEnv<'tcx>,
2764 def_id: DefId, // of impl or trait
2765 args: GenericArgsRef<'tcx>, // for impl or trait
2766 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2767 ) -> PredicateObligations<'tcx> {
2768 let tcx = self.tcx();
2769
2770 // To allow for one-pass evaluation of the nested obligation,
2771 // each predicate must be preceded by the obligations required
2772 // to normalize it.
2773 // for example, if we have:
2774 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2775 // the impl will have the following predicates:
2776 // <V as Iterator>::Item = U,
2777 // U: Iterator, U: Sized,
2778 // V: Iterator, V: Sized,
2779 // <U as Iterator>::Item: Copy
2780 // When we instantiate, say, `V => IntoIter<u32>, U => $0`, the last
2781 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2782 // `$1: Copy`, so we must ensure the obligations are emitted in
2783 // that order.
2784 let predicates = tcx.predicates_of(def_id);
2785 assert_eq!(predicates.parent, None);
2786 let predicates = predicates.instantiate_own(tcx, args);
2787 let mut obligations = PredicateObligations::with_capacity(predicates.len());
2788 for (index, (predicate, span)) in predicates.into_iter().enumerate() {
2789 let cause = if tcx.is_lang_item(parent_trait_pred.def_id(), LangItem::CoerceUnsized) {
2790 cause.clone()
2791 } else {
2792 cause.clone().derived_cause(parent_trait_pred, |derived| {
2793 ObligationCauseCode::ImplDerived(Box::new(ImplDerivedCause {
2794 derived,
2795 impl_or_alias_def_id: def_id,
2796 impl_def_predicate_index: Some(index),
2797 span,
2798 }))
2799 })
2800 };
2801 let clause = normalize_with_depth_to(
2802 self,
2803 param_env,
2804 cause.clone(),
2805 recursion_depth,
2806 predicate,
2807 &mut obligations,
2808 );
2809 obligations.push(Obligation {
2810 cause,
2811 recursion_depth,
2812 param_env,
2813 predicate: clause.as_predicate(),
2814 });
2815 }
2816
2817 // Register any outlives obligations from the trait here, cc #124336.
2818 if matches!(tcx.def_kind(def_id), DefKind::Impl { of_trait: true }) {
2819 for clause in tcx.impl_super_outlives(def_id).iter_instantiated(tcx, args) {
2820 let clause = normalize_with_depth_to(
2821 self,
2822 param_env,
2823 cause.clone(),
2824 recursion_depth,
2825 clause,
2826 &mut obligations,
2827 );
2828 obligations.push(Obligation {
2829 cause: cause.clone(),
2830 recursion_depth,
2831 param_env,
2832 predicate: clause.as_predicate(),
2833 });
2834 }
2835 }
2836
2837 obligations
2838 }
2839
2840 fn should_stall_coroutine(&self, def_id: DefId) -> bool {
2841 match self.infcx.typing_mode() {
2842 TypingMode::Analysis { defining_opaque_types_and_generators: stalled_generators } => {
2843 def_id.as_local().is_some_and(|def_id| stalled_generators.contains(&def_id))
2844 }
2845 TypingMode::Coherence
2846 | TypingMode::PostAnalysis
2847 | TypingMode::Borrowck { defining_opaque_types: _ }
2848 | TypingMode::PostBorrowckAnalysis { defined_opaque_types: _ } => false,
2849 }
2850 }
2851}
2852
2853impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2854 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2855 TraitObligationStackList::with(self)
2856 }
2857
2858 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2859 self.previous.cache
2860 }
2861
2862 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2863 self.list()
2864 }
2865
2866 /// Indicates that attempting to evaluate this stack entry
2867 /// required accessing something from the stack at depth `reached_depth`.
2868 fn update_reached_depth(&self, reached_depth: usize) {
2869 assert!(
2870 self.depth >= reached_depth,
2871 "invoked `update_reached_depth` with something under this stack: \
2872 self.depth={} reached_depth={}",
2873 self.depth,
2874 reached_depth,
2875 );
2876 debug!(reached_depth, "update_reached_depth");
2877 let mut p = self;
2878 while reached_depth < p.depth {
2879 debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
2880 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2881 p = p.previous.head.unwrap();
2882 }
2883 }
2884}
2885
2886/// The "provisional evaluation cache" is used to store intermediate cache results
2887/// when solving auto traits. Auto traits are unusual in that they can support
2888/// cycles. So, for example, a "proof tree" like this would be ok:
2889///
2890/// - `Foo<T>: Send` :-
2891/// - `Bar<T>: Send` :-
2892/// - `Foo<T>: Send` -- cycle, but ok
2893/// - `Baz<T>: Send`
2894///
2895/// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2896/// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2897/// For non-auto traits, this cycle would be an error, but for auto traits (because
2898/// they are coinductive) it is considered ok.
2899///
2900/// However, there is a complication: at the point where we have
2901/// "proven" `Bar<T>: Send`, we have in fact only proven it
2902/// *provisionally*. In particular, we proved that `Bar<T>: Send`
2903/// *under the assumption* that `Foo<T>: Send`. But what if we later
2904/// find out this assumption is wrong? Specifically, we could
2905/// encounter some kind of error proving `Baz<T>: Send`. In that case,
2906/// `Bar<T>: Send` didn't turn out to be true.
2907///
2908/// In Issue #60010, we found a bug in rustc where it would cache
2909/// these intermediate results. This was fixed in #60444 by disabling
2910/// *all* caching for things involved in a cycle -- in our example,
2911/// that would mean we don't cache that `Bar<T>: Send`. But this led
2912/// to large slowdowns.
2913///
2914/// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2915/// first requires proving `Bar<T>: Send` (which is true:
2916///
2917/// - `Foo<T>: Send` :-
2918/// - `Bar<T>: Send` :-
2919/// - `Foo<T>: Send` -- cycle, but ok
2920/// - `Baz<T>: Send`
2921/// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2922/// - `*const T: Send` -- but what if we later encounter an error?
2923///
2924/// The *provisional evaluation cache* resolves this issue. It stores
2925/// cache results that we've proven but which were involved in a cycle
2926/// in some way. We track the minimal stack depth (i.e., the
2927/// farthest from the top of the stack) that we are dependent on.
2928/// The idea is that the cache results within are all valid -- so long as
2929/// none of the nodes in between the current node and the node at that minimum
2930/// depth result in an error (in which case the cached results are just thrown away).
2931///
2932/// During evaluation, we consult this provisional cache and rely on
2933/// it. Accessing a cached value is considered equivalent to accessing
2934/// a result at `reached_depth`, so it marks the *current* solution as
2935/// provisional as well. If an error is encountered, we toss out any
2936/// provisional results added from the subtree that encountered the
2937/// error. When we pop the node at `reached_depth` from the stack, we
2938/// can commit all the things that remain in the provisional cache.
2939struct ProvisionalEvaluationCache<'tcx> {
2940 /// next "depth first number" to issue -- just a counter
2941 dfn: Cell<usize>,
2942
2943 /// Map from cache key to the provisionally evaluated thing.
2944 /// The cache entries contain the result but also the DFN in which they
2945 /// were added. The DFN is used to clear out values on failure.
2946 ///
2947 /// Imagine we have a stack like:
2948 ///
2949 /// - `A B C` and we add a cache for the result of C (DFN 2)
2950 /// - Then we have a stack `A B D` where `D` has DFN 3
2951 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2952 /// - `E` generates various cache entries which have cyclic dependencies on `B`
2953 /// - `A B D E F` and so forth
2954 /// - the DFN of `F` for example would be 5
2955 /// - then we determine that `E` is in error -- we will then clear
2956 /// all cache values whose DFN is >= 4 -- in this case, that
2957 /// means the cached value for `F`.
2958 map: RefCell<FxIndexMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
2959
2960 /// The stack of terms that we assume to be well-formed because a `WF(term)` predicate
2961 /// is on the stack above (and because of wellformedness is coinductive).
2962 /// In an "ideal" world, this would share a stack with trait predicates in
2963 /// `TraitObligationStack`. However, trait predicates are *much* hotter than
2964 /// `WellFormed` predicates, and it's very likely that the additional matches
2965 /// will have a perf effect. The value here is the well-formed `GenericArg`
2966 /// and the depth of the trait predicate *above* that well-formed predicate.
2967 wf_args: RefCell<Vec<(ty::Term<'tcx>, usize)>>,
2968}
2969
2970/// A cache value for the provisional cache: contains the depth-first
2971/// number (DFN) and result.
2972#[derive(Copy, Clone, Debug)]
2973struct ProvisionalEvaluation {
2974 from_dfn: usize,
2975 reached_depth: usize,
2976 result: EvaluationResult,
2977}
2978
2979impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2980 fn default() -> Self {
2981 Self { dfn: Cell::new(0), map: Default::default(), wf_args: Default::default() }
2982 }
2983}
2984
2985impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2986 /// Get the next DFN in sequence (basically a counter).
2987 fn next_dfn(&self) -> usize {
2988 let result = self.dfn.get();
2989 self.dfn.set(result + 1);
2990 result
2991 }
2992
2993 /// Check the provisional cache for any result for
2994 /// `fresh_trait_ref`. If there is a hit, then you must consider
2995 /// it an access to the stack slots at depth
2996 /// `reached_depth` (from the returned value).
2997 fn get_provisional(
2998 &self,
2999 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
3000 ) -> Option<ProvisionalEvaluation> {
3001 debug!(
3002 ?fresh_trait_pred,
3003 "get_provisional = {:#?}",
3004 self.map.borrow().get(&fresh_trait_pred),
3005 );
3006 Some(*self.map.borrow().get(&fresh_trait_pred)?)
3007 }
3008
3009 /// Insert a provisional result into the cache. The result came
3010 /// from the node with the given DFN. It accessed a minimum depth
3011 /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
3012 /// and resulted in `result`.
3013 fn insert_provisional(
3014 &self,
3015 from_dfn: usize,
3016 reached_depth: usize,
3017 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
3018 result: EvaluationResult,
3019 ) {
3020 debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
3021
3022 let mut map = self.map.borrow_mut();
3023
3024 // Subtle: when we complete working on the DFN `from_dfn`, anything
3025 // that remains in the provisional cache must be dependent on some older
3026 // stack entry than `from_dfn`. We have to update their depth with our transitive
3027 // depth in that case or else it would be referring to some popped note.
3028 //
3029 // Example:
3030 // A (reached depth 0)
3031 // ...
3032 // B // depth 1 -- reached depth = 0
3033 // C // depth 2 -- reached depth = 1 (should be 0)
3034 // B
3035 // A // depth 0
3036 // D (reached depth 1)
3037 // C (cache -- reached depth = 2)
3038 for (_k, v) in &mut *map {
3039 if v.from_dfn >= from_dfn {
3040 v.reached_depth = reached_depth.min(v.reached_depth);
3041 }
3042 }
3043
3044 map.insert(fresh_trait_pred, ProvisionalEvaluation { from_dfn, reached_depth, result });
3045 }
3046
3047 /// Invoked when the node with dfn `dfn` does not get a successful
3048 /// result. This will clear out any provisional cache entries
3049 /// that were added since `dfn` was created. This is because the
3050 /// provisional entries are things which must assume that the
3051 /// things on the stack at the time of their creation succeeded --
3052 /// since the failing node is presently at the top of the stack,
3053 /// these provisional entries must either depend on it or some
3054 /// ancestor of it.
3055 fn on_failure(&self, dfn: usize) {
3056 debug!(?dfn, "on_failure");
3057 self.map.borrow_mut().retain(|key, eval| {
3058 if !eval.from_dfn >= dfn {
3059 debug!("on_failure: removing {:?}", key);
3060 false
3061 } else {
3062 true
3063 }
3064 });
3065 }
3066
3067 /// Invoked when the node at depth `depth` completed without
3068 /// depending on anything higher in the stack (if that completion
3069 /// was a failure, then `on_failure` should have been invoked
3070 /// already).
3071 ///
3072 /// Note that we may still have provisional cache items remaining
3073 /// in the cache when this is done. For example, if there is a
3074 /// cycle:
3075 ///
3076 /// * A depends on...
3077 /// * B depends on A
3078 /// * C depends on...
3079 /// * D depends on C
3080 /// * ...
3081 ///
3082 /// Then as we complete the C node we will have a provisional cache
3083 /// with results for A, B, C, and D. This method would clear out
3084 /// the C and D results, but leave A and B provisional.
3085 ///
3086 /// This is determined based on the DFN: we remove any provisional
3087 /// results created since `dfn` started (e.g., in our example, dfn
3088 /// would be 2, representing the C node, and hence we would
3089 /// remove the result for D, which has DFN 3, but not the results for
3090 /// A and B, which have DFNs 0 and 1 respectively).
3091 ///
3092 /// Note that we *do not* attempt to cache these cycle participants
3093 /// in the evaluation cache. Doing so would require carefully computing
3094 /// the correct `DepNode` to store in the cache entry:
3095 /// cycle participants may implicitly depend on query results
3096 /// related to other participants in the cycle, due to our logic
3097 /// which examines the evaluation stack.
3098 ///
3099 /// We used to try to perform this caching,
3100 /// but it lead to multiple incremental compilation ICEs
3101 /// (see #92987 and #96319), and was very hard to understand.
3102 /// Fortunately, removing the caching didn't seem to
3103 /// have a performance impact in practice.
3104 fn on_completion(&self, dfn: usize) {
3105 debug!(?dfn, "on_completion");
3106 self.map.borrow_mut().retain(|fresh_trait_pred, eval| {
3107 if eval.from_dfn >= dfn {
3108 debug!(?fresh_trait_pred, ?eval, "on_completion");
3109 return false;
3110 }
3111 true
3112 });
3113 }
3114}
3115
3116#[derive(Copy, Clone)]
3117struct TraitObligationStackList<'o, 'tcx> {
3118 cache: &'o ProvisionalEvaluationCache<'tcx>,
3119 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
3120}
3121
3122impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
3123 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3124 TraitObligationStackList { cache, head: None }
3125 }
3126
3127 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3128 TraitObligationStackList { cache: r.cache(), head: Some(r) }
3129 }
3130
3131 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3132 self.head
3133 }
3134
3135 fn depth(&self) -> usize {
3136 if let Some(head) = self.head { head.depth } else { 0 }
3137 }
3138}
3139
3140impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
3141 type Item = &'o TraitObligationStack<'o, 'tcx>;
3142
3143 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3144 let o = self.head?;
3145 *self = o.previous;
3146 Some(o)
3147 }
3148}
3149
3150impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
3151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3152 write!(f, "TraitObligationStack({:?})", self.obligation)
3153 }
3154}
3155
3156pub(crate) enum ProjectionMatchesProjection {
3157 Yes,
3158 Ambiguous,
3159 No,
3160}
3161
3162#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
3163pub(crate) struct AutoImplConstituents<'tcx> {
3164 pub types: Vec<Ty<'tcx>>,
3165 pub assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
3166}