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