]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_trait_selection/src/traits/select/mod.rs
New upstream version 1.60.0+dfsg1
[rustc.git] / compiler / rustc_trait_selection / src / traits / select / mod.rs
CommitLineData
ba9703b0 1//! Candidate selection. See the [rustc dev guide] for more information on how this works.
74b04a01 2//!
ba9703b0 3//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection
74b04a01
XL
4
5use self::EvaluationResult::*;
6use self::SelectionCandidate::*;
7
8use super::coherence::{self, Conflict};
1b1a35ee 9use super::const_evaluatable;
74b04a01 10use super::project;
f035d41b 11use super::project::normalize_with_depth_to;
29967ef6 12use super::project::ProjectionTyObligation;
74b04a01
XL
13use super::util;
14use super::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
15use super::wf;
16use super::DerivedObligationCause;
c295e0f8 17use super::Normalized;
f035d41b
XL
18use super::Obligation;
19use super::ObligationCauseCode;
74b04a01
XL
20use super::Selection;
21use super::SelectionResult;
74b04a01 22use super::TraitQueryMode;
3c0e092e 23use super::{ErrorReporting, Overflow, SelectionError};
74b04a01 24use super::{ObligationCause, PredicateObligation, TraitObligation};
f035d41b
XL
25
26use crate::infer::{InferCtxt, InferOk, TypeFreshener};
ba9703b0 27use crate::traits::error_reporting::InferCtxtExt;
a2a8927a
XL
28use crate::traits::project::ProjectionCacheKeyExt;
29use crate::traits::ProjectionCacheKey;
74b04a01 30use rustc_data_structures::fx::{FxHashMap, FxHashSet};
f9f354fc
XL
31use rustc_data_structures::stack::ensure_sufficient_stack;
32use rustc_errors::ErrorReported;
74b04a01
XL
33use rustc_hir as hir;
34use rustc_hir::def_id::DefId;
6a06907d 35use rustc_infer::infer::LateBoundRegionConversionTime;
ba9703b0 36use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
f9f354fc 37use rustc_middle::mir::interpret::ErrorHandled;
c295e0f8 38use rustc_middle::thir::abstract_const::NotConstEvaluatable;
5099ac24 39use rustc_middle::ty::fast_reject::{self, SimplifyParams};
1b1a35ee 40use rustc_middle::ty::print::with_no_trimmed_paths;
ba9703b0 41use rustc_middle::ty::relate::TypeRelation;
f035d41b 42use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
29967ef6 43use rustc_middle::ty::{self, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate};
94222f64 44use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable};
74b04a01 45use rustc_span::symbol::sym;
74b04a01
XL
46
47use std::cell::{Cell, RefCell};
48use std::cmp;
49use std::fmt::{self, Display};
50use std::iter;
74b04a01 51
ba9703b0 52pub use rustc_middle::traits::select::*;
74b04a01 53
f035d41b
XL
54mod candidate_assembly;
55mod confirmation;
56
3dfed10e
XL
57#[derive(Clone, Debug)]
58pub enum IntercrateAmbiguityCause {
59 DownstreamCrate { trait_desc: String, self_desc: Option<String> },
60 UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
61 ReservationImpl { message: String },
62}
63
64impl IntercrateAmbiguityCause {
65 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
66 /// See #23980 for details.
67 pub fn add_intercrate_ambiguity_hint(&self, err: &mut rustc_errors::DiagnosticBuilder<'_>) {
68 err.note(&self.intercrate_ambiguity_hint());
69 }
70
71 pub fn intercrate_ambiguity_hint(&self) -> String {
72 match self {
5869c6ff
XL
73 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => {
74 let self_desc = if let Some(ty) = self_desc {
3dfed10e
XL
75 format!(" for type `{}`", ty)
76 } else {
77 String::new()
78 };
79 format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
80 }
5869c6ff
XL
81 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc } => {
82 let self_desc = if let Some(ty) = self_desc {
3dfed10e
XL
83 format!(" for type `{}`", ty)
84 } else {
85 String::new()
86 };
87 format!(
88 "upstream crates may add a new impl of trait `{}`{} \
89 in future versions",
90 trait_desc, self_desc
91 )
92 }
5869c6ff 93 IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(),
3dfed10e
XL
94 }
95 }
96}
97
74b04a01
XL
98pub struct SelectionContext<'cx, 'tcx> {
99 infcx: &'cx InferCtxt<'cx, 'tcx>,
100
101 /// Freshener used specifically for entries on the obligation
102 /// stack. This ensures that all entries on the stack at one time
103 /// will have the same set of placeholder entries, which is
104 /// important for checking for trait bounds that recursively
105 /// require themselves.
106 freshener: TypeFreshener<'cx, 'tcx>,
107
108 /// If `true`, indicates that the evaluation should be conservative
109 /// and consider the possibility of types outside this crate.
110 /// This comes up primarily when resolving ambiguity. Imagine
111 /// there is some trait reference `$0: Bar` where `$0` is an
112 /// inference variable. If `intercrate` is true, then we can never
113 /// say for sure that this reference is not implemented, even if
114 /// there are *no impls at all for `Bar`*, because `$0` could be
115 /// bound to some type that in a downstream crate that implements
116 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
117 /// though, we set this to false, because we are only interested
118 /// in types that the user could actually have written --- in
119 /// other words, we consider `$0: Bar` to be unimplemented if
120 /// there is no type that the user could *actually name* that
121 /// would satisfy it. This avoids crippling inference, basically.
122 intercrate: bool,
123
124 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
125
126 /// Controls whether or not to filter out negative impls when selecting.
127 /// This is used in librustdoc to distinguish between the lack of an impl
128 /// and a negative impl
129 allow_negative_impls: bool,
130
131 /// The mode that trait queries run in, which informs our error handling
132 /// policy. In essence, canonicalized queries need their errors propagated
133 /// rather than immediately reported because we do not have accurate spans.
134 query_mode: TraitQueryMode,
135}
136
74b04a01
XL
137// A stack that walks back up the stack frame.
138struct TraitObligationStack<'prev, 'tcx> {
139 obligation: &'prev TraitObligation<'tcx>,
140
a2a8927a 141 /// The trait predicate from `obligation` but "freshened" with the
74b04a01 142 /// selection-context's freshener. Used to check for recursion.
a2a8927a 143 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
74b04a01
XL
144
145 /// Starts out equal to `depth` -- if, during evaluation, we
146 /// encounter a cycle, then we will set this flag to the minimum
147 /// depth of that cycle for all participants in the cycle. These
148 /// participants will then forego caching their results. This is
149 /// not the most efficient solution, but it addresses #60010. The
150 /// problem we are trying to prevent:
151 ///
152 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
153 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
154 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
155 ///
156 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
157 /// is `EvaluatedToOk`; this is because they were only considered
158 /// ok on the premise that if `A: AutoTrait` held, but we indeed
159 /// encountered a problem (later on) with `A: AutoTrait. So we
160 /// currently set a flag on the stack node for `B: AutoTrait` (as
161 /// well as the second instance of `A: AutoTrait`) to suppress
162 /// caching.
163 ///
164 /// This is a simple, targeted fix. A more-performant fix requires
165 /// deeper changes, but would permit more caching: we could
166 /// basically defer caching until we have fully evaluated the
167 /// tree, and then cache the entire tree at once. In any case, the
168 /// performance impact here shouldn't be so horrible: every time
169 /// this is hit, we do cache at least one trait, so we only
170 /// evaluate each member of a cycle up to N times, where N is the
171 /// length of the cycle. This means the performance impact is
172 /// bounded and we shouldn't have any terrible worst-cases.
173 reached_depth: Cell<usize>,
174
175 previous: TraitObligationStackList<'prev, 'tcx>,
176
177 /// The number of parent frames plus one (thus, the topmost frame has depth 1).
178 depth: usize,
179
180 /// The depth-first number of this node in the search graph -- a
181 /// pre-order index. Basically, a freshly incremented counter.
182 dfn: usize,
183}
184
185struct SelectionCandidateSet<'tcx> {
186 // A list of candidates that definitely apply to the current
187 // obligation (meaning: types unify).
188 vec: Vec<SelectionCandidate<'tcx>>,
189
190 // If `true`, then there were candidates that might or might
191 // not have applied, but we couldn't tell. This occurs when some
192 // of the input types are type variables, in which case there are
193 // various "builtin" rules that might or might not trigger.
194 ambiguous: bool,
195}
196
197#[derive(PartialEq, Eq, Debug, Clone)]
198struct EvaluatedCandidate<'tcx> {
199 candidate: SelectionCandidate<'tcx>,
200 evaluation: EvaluationResult,
201}
202
203/// When does the builtin impl for `T: Trait` apply?
5099ac24 204#[derive(Debug)]
74b04a01
XL
205enum BuiltinImplConditions<'tcx> {
206 /// The impl is conditional on `T1, T2, ...: Trait`.
cdc7bbd5 207 Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
74b04a01
XL
208 /// There is no built-in impl. There may be some other
209 /// candidate (a where-clause or user-defined impl).
210 None,
211 /// It is unknown whether there is an impl.
212 Ambiguous,
213}
214
215impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
216 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
217 SelectionContext {
218 infcx,
136023e0 219 freshener: infcx.freshener_keep_static(),
74b04a01
XL
220 intercrate: false,
221 intercrate_ambiguity_causes: None,
222 allow_negative_impls: false,
223 query_mode: TraitQueryMode::Standard,
224 }
225 }
226
227 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
228 SelectionContext {
229 infcx,
136023e0 230 freshener: infcx.freshener_keep_static(),
74b04a01
XL
231 intercrate: true,
232 intercrate_ambiguity_causes: None,
233 allow_negative_impls: false,
234 query_mode: TraitQueryMode::Standard,
235 }
236 }
237
238 pub fn with_negative(
239 infcx: &'cx InferCtxt<'cx, 'tcx>,
240 allow_negative_impls: bool,
241 ) -> SelectionContext<'cx, 'tcx> {
29967ef6 242 debug!(?allow_negative_impls, "with_negative");
74b04a01
XL
243 SelectionContext {
244 infcx,
136023e0 245 freshener: infcx.freshener_keep_static(),
74b04a01
XL
246 intercrate: false,
247 intercrate_ambiguity_causes: None,
248 allow_negative_impls,
249 query_mode: TraitQueryMode::Standard,
250 }
251 }
252
253 pub fn with_query_mode(
254 infcx: &'cx InferCtxt<'cx, 'tcx>,
255 query_mode: TraitQueryMode,
256 ) -> SelectionContext<'cx, 'tcx> {
29967ef6 257 debug!(?query_mode, "with_query_mode");
74b04a01
XL
258 SelectionContext {
259 infcx,
136023e0 260 freshener: infcx.freshener_keep_static(),
74b04a01
XL
261 intercrate: false,
262 intercrate_ambiguity_causes: None,
263 allow_negative_impls: false,
264 query_mode,
265 }
266 }
267
268 /// Enables tracking of intercrate ambiguity causes. These are
269 /// used in coherence to give improved diagnostics. We don't do
270 /// this until we detect a coherence error because it can lead to
271 /// false overflow results (#47139) and because it costs
272 /// computation time.
273 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
274 assert!(self.intercrate);
275 assert!(self.intercrate_ambiguity_causes.is_none());
276 self.intercrate_ambiguity_causes = Some(vec![]);
277 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
278 }
279
280 /// Gets the intercrate ambiguity causes collected since tracking
281 /// was enabled and disables tracking at the same time. If
282 /// tracking is not enabled, just returns an empty vector.
283 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
284 assert!(self.intercrate);
29967ef6 285 self.intercrate_ambiguity_causes.take().unwrap_or_default()
74b04a01
XL
286 }
287
288 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
289 self.infcx
290 }
291
292 pub fn tcx(&self) -> TyCtxt<'tcx> {
293 self.infcx.tcx
294 }
295
94222f64
XL
296 pub fn is_intercrate(&self) -> bool {
297 self.intercrate
298 }
299
74b04a01
XL
300 ///////////////////////////////////////////////////////////////////////////
301 // Selection
302 //
303 // The selection phase tries to identify *how* an obligation will
304 // be resolved. For example, it will identify which impl or
305 // parameter bound is to be used. The process can be inconclusive
306 // if the self type in the obligation is not fully inferred. Selection
307 // can result in an error in one of two ways:
308 //
309 // 1. If no applicable impl or parameter bound can be found.
310 // 2. If the output type parameters in the obligation do not match
311 // those specified by the impl/bound. For example, if the obligation
312 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
313 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
314
315 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
316 /// type environment by performing unification.
29967ef6 317 #[instrument(level = "debug", skip(self))]
74b04a01
XL
318 pub fn select(
319 &mut self,
320 obligation: &TraitObligation<'tcx>,
321 ) -> SelectionResult<'tcx, Selection<'tcx>> {
3c0e092e 322 let candidate = match self.select_from_obligation(obligation) {
74b04a01
XL
323 Err(SelectionError::Overflow) => {
324 // In standard mode, overflow must have been caught and reported
325 // earlier.
326 assert!(self.query_mode == TraitQueryMode::Canonical);
327 return Err(SelectionError::Overflow);
328 }
3c0e092e
XL
329 Err(SelectionError::Ambiguous(_)) => {
330 return Ok(None);
331 }
74b04a01
XL
332 Err(e) => {
333 return Err(e);
334 }
335 Ok(None) => {
336 return Ok(None);
337 }
338 Ok(Some(candidate)) => candidate,
339 };
340
341 match self.confirm_candidate(obligation, candidate) {
342 Err(SelectionError::Overflow) => {
343 assert!(self.query_mode == TraitQueryMode::Canonical);
344 Err(SelectionError::Overflow)
345 }
346 Err(e) => Err(e),
29967ef6 347 Ok(candidate) => {
5099ac24 348 debug!(?candidate, "confirmed");
29967ef6
XL
349 Ok(Some(candidate))
350 }
74b04a01
XL
351 }
352 }
353
3c0e092e
XL
354 crate fn select_from_obligation(
355 &mut self,
356 obligation: &TraitObligation<'tcx>,
357 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
358 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
359
360 let pec = &ProvisionalEvaluationCache::default();
361 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
362
363 self.candidate_from_obligation(&stack)
364 }
365
74b04a01
XL
366 ///////////////////////////////////////////////////////////////////////////
367 // EVALUATION
368 //
369 // Tests whether an obligation can be selected or whether an impl
370 // can be applied to particular types. It skips the "confirmation"
371 // step and hence completely ignores output type parameters.
372 //
373 // The result is "true" if the obligation *may* hold and "false" if
374 // we can be sure it does not.
375
376 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
377 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
29967ef6 378 debug!(?obligation, "predicate_may_hold_fatal");
74b04a01
XL
379
380 // This fatal query is a stopgap that should only be used in standard mode,
381 // where we do not expect overflow to be propagated.
382 assert!(self.query_mode == TraitQueryMode::Standard);
383
384 self.evaluate_root_obligation(obligation)
385 .expect("Overflow should be caught earlier in standard query mode")
386 .may_apply()
387 }
388
389 /// Evaluates whether the obligation `obligation` can be satisfied
390 /// and returns an `EvaluationResult`. This is meant for the
391 /// *initial* call.
392 pub fn evaluate_root_obligation(
393 &mut self,
394 obligation: &PredicateObligation<'tcx>,
395 ) -> Result<EvaluationResult, OverflowError> {
396 self.evaluation_probe(|this| {
397 this.evaluate_predicate_recursively(
398 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
399 obligation.clone(),
400 )
401 })
402 }
403
404 fn evaluation_probe(
405 &mut self,
406 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
407 ) -> Result<EvaluationResult, OverflowError> {
408 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
409 let result = op(self)?;
f035d41b
XL
410
411 match self.infcx.leak_check(true, snapshot) {
412 Ok(()) => {}
413 Err(_) => return Ok(EvaluatedToErr),
414 }
415
74b04a01
XL
416 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
417 None => Ok(result),
418 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
419 }
420 })
421 }
422
423 /// Evaluates the predicates in `predicates` recursively. Note that
424 /// this applies projections in the predicates, and therefore
425 /// is run within an inference probe.
c295e0f8 426 #[instrument(skip(self, stack), level = "debug")]
74b04a01
XL
427 fn evaluate_predicates_recursively<'o, I>(
428 &mut self,
429 stack: TraitObligationStackList<'o, 'tcx>,
430 predicates: I,
431 ) -> Result<EvaluationResult, OverflowError>
432 where
29967ef6 433 I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
74b04a01
XL
434 {
435 let mut result = EvaluatedToOk;
436 for obligation in predicates {
437 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
74b04a01
XL
438 if let EvaluatedToErr = eval {
439 // fast-path - EvaluatedToErr is the top of the lattice,
440 // so we don't need to look on the other predicates.
441 return Ok(EvaluatedToErr);
442 } else {
443 result = cmp::max(result, eval);
444 }
445 }
446 Ok(result)
447 }
448
29967ef6
XL
449 #[instrument(
450 level = "debug",
451 skip(self, previous_stack),
452 fields(previous_stack = ?previous_stack.head())
453 )]
74b04a01
XL
454 fn evaluate_predicate_recursively<'o>(
455 &mut self,
456 previous_stack: TraitObligationStackList<'o, 'tcx>,
457 obligation: PredicateObligation<'tcx>,
458 ) -> Result<EvaluationResult, OverflowError> {
3dfed10e 459 // `previous_stack` stores a `TraitObligation`, while `obligation` is
74b04a01
XL
460 // a `PredicateObligation`. These are distinct types, so we can't
461 // use any `Option` combinator method that would force them to be
462 // the same.
463 match previous_stack.head() {
464 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
465 None => self.check_recursion_limit(&obligation, &obligation)?,
466 }
467
29967ef6 468 let result = ensure_sufficient_stack(|| {
5869c6ff 469 let bound_predicate = obligation.predicate.kind();
29967ef6 470 match bound_predicate.skip_binder() {
94222f64 471 ty::PredicateKind::Trait(t) => {
29967ef6 472 let t = bound_predicate.rebind(t);
1b1a35ee
XL
473 debug_assert!(!t.has_escaping_bound_vars());
474 let obligation = obligation.with(t);
475 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
476 }
477
5869c6ff 478 ty::PredicateKind::Subtype(p) => {
29967ef6 479 let p = bound_predicate.rebind(p);
1b1a35ee
XL
480 // Does this code ever run?
481 match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
482 Some(Ok(InferOk { mut obligations, .. })) => {
483 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
484 self.evaluate_predicates_recursively(
485 previous_stack,
486 obligations.into_iter(),
487 )
488 }
489 Some(Err(_)) => Ok(EvaluatedToErr),
490 None => Ok(EvaluatedToAmbig),
491 }
492 }
74b04a01 493
94222f64
XL
494 ty::PredicateKind::Coerce(p) => {
495 let p = bound_predicate.rebind(p);
496 // Does this code ever run?
497 match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
498 Some(Ok(InferOk { mut obligations, .. })) => {
499 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
500 self.evaluate_predicates_recursively(
501 previous_stack,
502 obligations.into_iter(),
503 )
504 }
505 Some(Err(_)) => Ok(EvaluatedToErr),
506 None => Ok(EvaluatedToAmbig),
507 }
508 }
509
5869c6ff 510 ty::PredicateKind::WellFormed(arg) => match wf::obligations(
1b1a35ee
XL
511 self.infcx,
512 obligation.param_env,
513 obligation.cause.body_id,
29967ef6 514 obligation.recursion_depth + 1,
1b1a35ee
XL
515 arg,
516 obligation.cause.span,
517 ) {
518 Some(mut obligations) => {
74b04a01 519 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
29967ef6 520 self.evaluate_predicates_recursively(previous_stack, obligations)
74b04a01 521 }
74b04a01 522 None => Ok(EvaluatedToAmbig),
1b1a35ee 523 },
74b04a01 524
136023e0 525 ty::PredicateKind::TypeOutlives(pred) => {
a2a8927a
XL
526 // A global type with no late-bound regions can only
527 // contain the "'static" lifetime (any other lifetime
528 // would either be late-bound or local), so it is guaranteed
529 // to outlive any other lifetime
5099ac24 530 if pred.0.is_global() && !pred.0.has_late_bound_regions() {
136023e0
XL
531 Ok(EvaluatedToOk)
532 } else {
533 Ok(EvaluatedToOkModuloRegions)
534 }
535 }
536
537 ty::PredicateKind::RegionOutlives(..) => {
1b1a35ee
XL
538 // We do not consider region relationships when evaluating trait matches.
539 Ok(EvaluatedToOkModuloRegions)
74b04a01 540 }
74b04a01 541
5869c6ff 542 ty::PredicateKind::ObjectSafe(trait_def_id) => {
1b1a35ee
XL
543 if self.tcx().is_object_safe(trait_def_id) {
544 Ok(EvaluatedToOk)
545 } else {
546 Ok(EvaluatedToErr)
547 }
74b04a01 548 }
74b04a01 549
5869c6ff 550 ty::PredicateKind::Projection(data) => {
29967ef6 551 let data = bound_predicate.rebind(data);
1b1a35ee
XL
552 let project_obligation = obligation.with(data);
553 match project::poly_project_and_unify_type(self, &project_obligation) {
554 Ok(Ok(Some(mut subobligations))) => {
a2a8927a
XL
555 'compute_res: {
556 // If we've previously marked this projection as 'complete', thne
557 // use the final cached result (either `EvaluatedToOk` or
558 // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
559 // sub-obligations.
560 if let Some(key) =
561 ProjectionCacheKey::from_poly_projection_predicate(self, data)
562 {
563 if let Some(cached_res) = self
564 .infcx
565 .inner
566 .borrow_mut()
567 .projection_cache()
568 .is_complete(key)
569 {
570 break 'compute_res Ok(cached_res);
571 }
572 }
573
574 self.add_depth(
575 subobligations.iter_mut(),
576 obligation.recursion_depth,
577 );
578 let res = self.evaluate_predicates_recursively(
579 previous_stack,
580 subobligations,
581 );
582 if let Ok(res) = res {
583 if res == EvaluatedToOk || res == EvaluatedToOkModuloRegions {
584 if let Some(key) =
585 ProjectionCacheKey::from_poly_projection_predicate(
586 self, data,
587 )
588 {
589 // If the result is something that we can cache, then mark this
590 // entry as 'complete'. This will allow us to skip evaluating the
591 // suboligations at all the next time we evaluate the projection
592 // predicate.
593 self.infcx
594 .inner
595 .borrow_mut()
596 .projection_cache()
597 .complete(key, res);
598 }
599 }
600 }
601 res
602 }
74b04a01 603 }
1b1a35ee 604 Ok(Ok(None)) => Ok(EvaluatedToAmbig),
29967ef6 605 Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur),
1b1a35ee 606 Err(_) => Ok(EvaluatedToErr),
74b04a01 607 }
74b04a01 608 }
74b04a01 609
5869c6ff 610 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
1b1a35ee
XL
611 match self.infcx.closure_kind(closure_substs) {
612 Some(closure_kind) => {
613 if closure_kind.extends(kind) {
614 Ok(EvaluatedToOk)
615 } else {
616 Ok(EvaluatedToErr)
617 }
74b04a01 618 }
1b1a35ee 619 None => Ok(EvaluatedToAmbig),
74b04a01 620 }
74b04a01 621 }
74b04a01 622
94222f64 623 ty::PredicateKind::ConstEvaluatable(uv) => {
1b1a35ee
XL
624 match const_evaluatable::is_const_evaluatable(
625 self.infcx,
94222f64 626 uv,
1b1a35ee
XL
627 obligation.param_env,
628 obligation.cause.span,
629 ) {
630 Ok(()) => Ok(EvaluatedToOk),
cdc7bbd5
XL
631 Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
632 Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
1b1a35ee
XL
633 Err(_) => Ok(EvaluatedToErr),
634 }
74b04a01 635 }
f9f354fc 636
5869c6ff 637 ty::PredicateKind::ConstEquate(c1, c2) => {
29967ef6 638 debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
f9f354fc 639
94222f64 640 if self.tcx().features().generic_const_exprs {
17df50a5
XL
641 // FIXME: we probably should only try to unify abstract constants
642 // if the constants depend on generic parameters.
643 //
644 // Let's just see where this breaks :shrug:
645 if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
5099ac24 646 (c1.val(), c2.val())
17df50a5 647 {
94222f64 648 if self.infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
17df50a5
XL
649 return Ok(EvaluatedToOk);
650 }
651 }
652 }
653
5099ac24
FG
654 let evaluate = |c: ty::Const<'tcx>| {
655 if let ty::ConstKind::Unevaluated(unevaluated) = c.val() {
1b1a35ee
XL
656 self.infcx
657 .const_eval_resolve(
658 obligation.param_env,
cdc7bbd5 659 unevaluated,
1b1a35ee
XL
660 Some(obligation.cause.span),
661 )
5099ac24 662 .map(|val| ty::Const::from_value(self.tcx(), val, c.ty()))
1b1a35ee
XL
663 } else {
664 Ok(c)
665 }
666 };
667
668 match (evaluate(c1), evaluate(c2)) {
669 (Ok(c1), Ok(c2)) => {
670 match self
671 .infcx()
672 .at(&obligation.cause, obligation.param_env)
673 .eq(c1, c2)
674 {
675 Ok(_) => Ok(EvaluatedToOk),
676 Err(_) => Ok(EvaluatedToErr),
677 }
678 }
679 (Err(ErrorHandled::Reported(ErrorReported)), _)
680 | (_, Err(ErrorHandled::Reported(ErrorReported))) => Ok(EvaluatedToErr),
681 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
682 span_bug!(
683 obligation.cause.span(self.tcx()),
684 "ConstEquate: const_eval_resolve returned an unexpected error"
685 )
686 }
687 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
17df50a5
XL
688 if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
689 Ok(EvaluatedToAmbig)
690 } else {
691 // Two different constants using generic parameters ~> error.
692 Ok(EvaluatedToErr)
693 }
f9f354fc 694 }
f9f354fc
XL
695 }
696 }
5869c6ff 697 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
1b1a35ee
XL
698 bug!("TypeWellFormedFromEnv is only used for chalk")
699 }
f9f354fc 700 }
29967ef6
XL
701 });
702
94222f64 703 debug!("finished: {:?} from {:?}", result, obligation);
29967ef6
XL
704
705 result
74b04a01
XL
706 }
707
c295e0f8 708 #[instrument(skip(self, previous_stack), level = "debug")]
74b04a01
XL
709 fn evaluate_trait_predicate_recursively<'o>(
710 &mut self,
711 previous_stack: TraitObligationStackList<'o, 'tcx>,
712 mut obligation: TraitObligation<'tcx>,
713 ) -> Result<EvaluationResult, OverflowError> {
74b04a01 714 if !self.intercrate
5099ac24
FG
715 && obligation.is_global()
716 && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
74b04a01
XL
717 {
718 // If a param env has no global bounds, global obligations do not
719 // depend on its particular value in order to work, so we can clear
720 // out the param env and get better caching.
c295e0f8 721 debug!("in global");
74b04a01
XL
722 obligation.param_env = obligation.param_env.without_caller_bounds();
723 }
724
725 let stack = self.push_stack(previous_stack, &obligation);
a2a8927a
XL
726 let mut fresh_trait_pred = stack.fresh_trait_pred;
727 let mut param_env = obligation.param_env;
29967ef6 728
a2a8927a
XL
729 fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| {
730 pred.remap_constness(self.tcx(), &mut param_env);
731 pred
732 });
29967ef6 733
a2a8927a
XL
734 debug!(?fresh_trait_pred);
735
736 if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
29967ef6 737 debug!(?result, "CACHE HIT");
74b04a01
XL
738 return Ok(result);
739 }
740
a2a8927a 741 if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
29967ef6 742 debug!(?result, "PROVISIONAL CACHE HIT");
17df50a5
XL
743 stack.update_reached_depth(result.reached_depth);
744 return Ok(result.result);
74b04a01
XL
745 }
746
747 // Check if this is a match for something already on the
748 // stack. If so, we don't want to insert the result into the
749 // main cache (it is cycle dependent) nor the provisional
750 // cache (which is meant for things that have completed but
751 // for a "backedge" -- this result *is* the backedge).
752 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
753 return Ok(cycle_result);
754 }
755
756 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
757 let result = result?;
758
759 if !result.must_apply_modulo_regions() {
760 stack.cache().on_failure(stack.dfn);
761 }
762
763 let reached_depth = stack.reached_depth.get();
764 if reached_depth >= stack.depth {
29967ef6 765 debug!(?result, "CACHE MISS");
a2a8927a 766 self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
74b04a01 767
5099ac24
FG
768 stack.cache().on_completion(
769 stack.dfn,
770 |fresh_trait_pred, provisional_result, provisional_dep_node| {
771 // Create a new `DepNode` that has dependencies on:
772 // * The `DepNode` for the original evaluation that resulted in a provisional cache
773 // entry being crated
774 // * The `DepNode` for the *current* evaluation, which resulted in us completing
775 // provisional caches entries and inserting them into the evaluation cache
776 //
777 // This ensures that when a query reads this entry from the evaluation cache,
778 // it will end up (transitively) dependening on all of the incr-comp dependencies
779 // created during the evaluation of this trait. For example, evaluating a trait
780 // will usually require us to invoke `type_of(field_def_id)` to determine the
781 // constituent types, and we want any queries reading from this evaluation
782 // cache entry to end up with a transitive `type_of(field_def_id`)` dependency.
783 //
784 // By using `in_task`, we're also creating an edge from the *current* query
785 // to the newly-created `combined_dep_node`. This is probably redundant,
786 // but it's better to add too many dep graph edges than to add too few
787 // dep graph edges.
788 let ((), combined_dep_node) = self.in_task(|this| {
789 this.tcx().dep_graph.read_index(provisional_dep_node);
790 this.tcx().dep_graph.read_index(dep_node);
791 });
792 self.insert_evaluation_cache(
793 param_env,
794 fresh_trait_pred,
795 combined_dep_node,
796 provisional_result.max(result),
797 );
798 },
799 );
74b04a01 800 } else {
29967ef6 801 debug!(?result, "PROVISIONAL");
74b04a01 802 debug!(
c295e0f8 803 "caching provisionally because {:?} \
74b04a01 804 is a cycle participant (at depth {}, reached depth {})",
a2a8927a 805 fresh_trait_pred, stack.depth, reached_depth,
74b04a01
XL
806 );
807
5099ac24
FG
808 stack.cache().insert_provisional(
809 stack.dfn,
810 reached_depth,
811 fresh_trait_pred,
812 result,
813 dep_node,
814 );
74b04a01
XL
815 }
816
817 Ok(result)
818 }
819
820 /// If there is any previous entry on the stack that precisely
821 /// matches this obligation, then we can assume that the
822 /// obligation is satisfied for now (still all other conditions
823 /// must be met of course). One obvious case this comes up is
824 /// marker traits like `Send`. Think of a linked list:
825 ///
826 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
827 ///
828 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
829 /// `Option<Box<List<T>>>` is `Send`, and in turn
830 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
831 /// `Send`.
832 ///
833 /// Note that we do this comparison using the `fresh_trait_ref`
834 /// fields. Because these have all been freshened using
835 /// `self.freshener`, we can be sure that (a) this will not
836 /// affect the inferencer state and (b) that if we see two
837 /// fresh regions with the same index, they refer to the same
838 /// unbound type variable.
839 fn check_evaluation_cycle(
840 &mut self,
841 stack: &TraitObligationStack<'_, 'tcx>,
842 ) -> Option<EvaluationResult> {
843 if let Some(cycle_depth) = stack
844 .iter()
845 .skip(1) // Skip top-most frame.
846 .find(|prev| {
847 stack.obligation.param_env == prev.obligation.param_env
a2a8927a 848 && stack.fresh_trait_pred == prev.fresh_trait_pred
74b04a01
XL
849 })
850 .map(|stack| stack.depth)
851 {
29967ef6 852 debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
74b04a01
XL
853
854 // If we have a stack like `A B C D E A`, where the top of
855 // the stack is the final `A`, then this will iterate over
856 // `A, E, D, C, B` -- i.e., all the participants apart
857 // from the cycle head. We mark them as participating in a
858 // cycle. This suppresses caching for those nodes. See
859 // `in_cycle` field for more details.
860 stack.update_reached_depth(cycle_depth);
861
862 // Subtle: when checking for a coinductive cycle, we do
863 // not compare using the "freshened trait refs" (which
864 // have erased regions) but rather the fully explicit
865 // trait refs. This is important because it's only a cycle
866 // if the regions match exactly.
867 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
f9f354fc 868 let tcx = self.tcx();
94222f64 869 let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
74b04a01 870 if self.coinductive_match(cycle) {
29967ef6 871 debug!("evaluate_stack --> recursive, coinductive");
74b04a01
XL
872 Some(EvaluatedToOk)
873 } else {
29967ef6 874 debug!("evaluate_stack --> recursive, inductive");
74b04a01
XL
875 Some(EvaluatedToRecur)
876 }
877 } else {
878 None
879 }
880 }
881
882 fn evaluate_stack<'o>(
883 &mut self,
884 stack: &TraitObligationStack<'o, 'tcx>,
885 ) -> Result<EvaluationResult, OverflowError> {
ba9703b0 886 // In intercrate mode, whenever any of the generics are unbound,
74b04a01
XL
887 // there can always be an impl. Even if there are no impls in
888 // this crate, perhaps the type would be unified with
889 // something from another crate that does provide an impl.
890 //
891 // In intra mode, we must still be conservative. The reason is
892 // that we want to avoid cycles. Imagine an impl like:
893 //
894 // impl<T:Eq> Eq for Vec<T>
895 //
896 // and a trait reference like `$0 : Eq` where `$0` is an
897 // unbound variable. When we evaluate this trait-reference, we
898 // will unify `$0` with `Vec<$1>` (for some fresh variable
899 // `$1`), on the condition that `$1 : Eq`. We will then wind
900 // up with many candidates (since that are other `Eq` impls
901 // that apply) and try to winnow things down. This results in
902 // a recursive evaluation that `$1 : Eq` -- as you can
903 // imagine, this is just where we started. To avoid that, we
904 // check for unbound variables and return an ambiguous (hence possible)
905 // match if we've seen this trait before.
906 //
907 // This suffices to allow chains like `FnMut` implemented in
908 // terms of `Fn` etc, but we could probably make this more
909 // precise still.
910 let unbound_input_types =
a2a8927a 911 stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh());
3c0e092e
XL
912
913 if stack.obligation.polarity() != ty::ImplPolarity::Negative {
914 // This check was an imperfect workaround for a bug in the old
915 // intercrate mode; it should be removed when that goes away.
916 if unbound_input_types && self.intercrate {
917 debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
918 // Heuristics: show the diagnostics when there are no candidates in crate.
919 if self.intercrate_ambiguity_causes.is_some() {
920 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
921 if let Ok(candidate_set) = self.assemble_candidates(stack) {
922 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
923 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
924 let self_ty = trait_ref.self_ty();
925 let cause = with_no_trimmed_paths(|| {
926 IntercrateAmbiguityCause::DownstreamCrate {
927 trait_desc: trait_ref.print_only_trait_path().to_string(),
928 self_desc: if self_ty.has_concrete_skeleton() {
929 Some(self_ty.to_string())
930 } else {
931 None
932 },
933 }
1b1a35ee
XL
934 });
935
3c0e092e
XL
936 debug!(?cause, "evaluate_stack: pushing cause");
937 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
938 }
74b04a01
XL
939 }
940 }
3c0e092e 941 return Ok(EvaluatedToAmbig);
74b04a01 942 }
74b04a01 943 }
3c0e092e 944
74b04a01
XL
945 if unbound_input_types
946 && stack.iter().skip(1).any(|prev| {
947 stack.obligation.param_env == prev.obligation.param_env
948 && self.match_fresh_trait_refs(
a2a8927a
XL
949 stack.fresh_trait_pred,
950 prev.fresh_trait_pred,
74b04a01
XL
951 prev.obligation.param_env,
952 )
953 })
954 {
29967ef6 955 debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
74b04a01
XL
956 return Ok(EvaluatedToUnknown);
957 }
958
959 match self.candidate_from_obligation(stack) {
960 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
3c0e092e 961 Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
74b04a01 962 Ok(None) => Ok(EvaluatedToAmbig),
c295e0f8
XL
963 Err(Overflow) => Err(OverflowError::Canonical),
964 Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
74b04a01
XL
965 Err(..) => Ok(EvaluatedToErr),
966 }
967 }
968
969 /// For defaulted traits, we use a co-inductive strategy to solve, so
970 /// that recursion is ok. This routine returns `true` if the top of the
971 /// stack (`cycle[0]`):
972 ///
973 /// - is a defaulted trait,
974 /// - it also appears in the backtrace at some position `X`,
975 /// - all the predicates at positions `X..` between `X` and the top are
976 /// also defaulted traits.
fc512014 977 pub fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
74b04a01
XL
978 where
979 I: Iterator<Item = ty::Predicate<'tcx>>,
980 {
74b04a01
XL
981 cycle.all(|predicate| self.coinductive_predicate(predicate))
982 }
983
984 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
5869c6ff 985 let result = match predicate.kind().skip_binder() {
94222f64 986 ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
74b04a01
XL
987 _ => false,
988 };
29967ef6 989 debug!(?predicate, ?result, "coinductive_predicate");
74b04a01
XL
990 result
991 }
992
993 /// Further evaluates `candidate` to decide whether all type parameters match and whether nested
994 /// obligations are met. Returns whether `candidate` remains viable after this further
995 /// scrutiny.
29967ef6
XL
996 #[instrument(
997 level = "debug",
998 skip(self, stack),
999 fields(depth = stack.obligation.recursion_depth)
1000 )]
74b04a01
XL
1001 fn evaluate_candidate<'o>(
1002 &mut self,
1003 stack: &TraitObligationStack<'o, 'tcx>,
1004 candidate: &SelectionCandidate<'tcx>,
1005 ) -> Result<EvaluationResult, OverflowError> {
cdc7bbd5 1006 let mut result = self.evaluation_probe(|this| {
74b04a01
XL
1007 let candidate = (*candidate).clone();
1008 match this.confirm_candidate(stack.obligation, candidate) {
29967ef6
XL
1009 Ok(selection) => {
1010 debug!(?selection);
1011 this.evaluate_predicates_recursively(
1012 stack.list(),
1013 selection.nested_obligations().into_iter(),
1014 )
1015 }
74b04a01
XL
1016 Err(..) => Ok(EvaluatedToErr),
1017 }
1018 })?;
cdc7bbd5
XL
1019
1020 // If we erased any lifetimes, then we want to use
1021 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
1022 // as your final result. The result will be cached using
1023 // the freshened trait predicate as a key, so we need
1024 // our result to be correct by *any* choice of original lifetimes,
1025 // not just the lifetime choice for this particular (non-erased)
1026 // predicate.
1027 // See issue #80691
a2a8927a 1028 if stack.fresh_trait_pred.has_erased_regions() {
cdc7bbd5
XL
1029 result = result.max(EvaluatedToOkModuloRegions);
1030 }
1031
29967ef6 1032 debug!(?result);
74b04a01
XL
1033 Ok(result)
1034 }
1035
1036 fn check_evaluation_cache(
1037 &self,
1038 param_env: ty::ParamEnv<'tcx>,
a2a8927a 1039 trait_pred: ty::PolyTraitPredicate<'tcx>,
74b04a01 1040 ) -> Option<EvaluationResult> {
94222f64
XL
1041 // Neither the global nor local cache is aware of intercrate
1042 // mode, so don't do any caching. In particular, we might
1043 // re-use the same `InferCtxt` with both an intercrate
1044 // and non-intercrate `SelectionContext`
1045 if self.intercrate {
1046 return None;
1047 }
1048
74b04a01
XL
1049 let tcx = self.tcx();
1050 if self.can_use_global_caches(param_env) {
a2a8927a 1051 if let Some(res) = tcx.evaluation_cache.get(&param_env.and(trait_pred), tcx) {
3dfed10e 1052 return Some(res);
74b04a01
XL
1053 }
1054 }
a2a8927a 1055 self.infcx.evaluation_cache.get(&param_env.and(trait_pred), tcx)
74b04a01
XL
1056 }
1057
1058 fn insert_evaluation_cache(
1059 &mut self,
1060 param_env: ty::ParamEnv<'tcx>,
a2a8927a 1061 trait_pred: ty::PolyTraitPredicate<'tcx>,
74b04a01
XL
1062 dep_node: DepNodeIndex,
1063 result: EvaluationResult,
1064 ) {
1065 // Avoid caching results that depend on more than just the trait-ref
1066 // - the stack can create recursion.
1067 if result.is_stack_dependent() {
1068 return;
1069 }
1070
94222f64
XL
1071 // Neither the global nor local cache is aware of intercrate
1072 // mode, so don't do any caching. In particular, we might
1073 // re-use the same `InferCtxt` with both an intercrate
1074 // and non-intercrate `SelectionContext`
1075 if self.intercrate {
1076 return;
1077 }
1078
74b04a01 1079 if self.can_use_global_caches(param_env) {
a2a8927a
XL
1080 if !trait_pred.needs_infer() {
1081 debug!(?trait_pred, ?result, "insert_evaluation_cache global");
74b04a01
XL
1082 // This may overwrite the cache with the same value
1083 // FIXME: Due to #50507 this overwrites the different values
1084 // This should be changed to use HashMapExt::insert_same
1085 // when that is fixed
a2a8927a 1086 self.tcx().evaluation_cache.insert(param_env.and(trait_pred), dep_node, result);
74b04a01
XL
1087 return;
1088 }
1089 }
1090
a2a8927a
XL
1091 debug!(?trait_pred, ?result, "insert_evaluation_cache");
1092 self.infcx.evaluation_cache.insert(param_env.and(trait_pred), dep_node, result);
74b04a01
XL
1093 }
1094
1095 /// For various reasons, it's possible for a subobligation
1096 /// to have a *lower* recursion_depth than the obligation used to create it.
1097 /// Projection sub-obligations may be returned from the projection cache,
1098 /// which results in obligations with an 'old' `recursion_depth`.
29967ef6
XL
1099 /// Additionally, methods like `InferCtxt.subtype_predicate` produce
1100 /// subobligations without taking in a 'parent' depth, causing the
1101 /// generated subobligations to have a `recursion_depth` of `0`.
74b04a01 1102 ///
cdc7bbd5 1103 /// To ensure that obligation_depth never decreases, we force all subobligations
74b04a01
XL
1104 /// to have at least the depth of the original obligation.
1105 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
1106 &self,
1107 it: I,
1108 min_depth: usize,
1109 ) {
1110 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1111 }
1112
c295e0f8 1113 fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
74b04a01 1114 &self,
c295e0f8
XL
1115 depth: usize,
1116 error_obligation: &Obligation<'tcx, T>,
74b04a01 1117 ) -> Result<(), OverflowError> {
c295e0f8 1118 if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
74b04a01
XL
1119 match self.query_mode {
1120 TraitQueryMode::Standard => {
c295e0f8
XL
1121 if self.infcx.is_tainted_by_errors() {
1122 return Err(OverflowError::ErrorReporting);
1123 }
1124 self.infcx.report_overflow_error(error_obligation, true);
74b04a01
XL
1125 }
1126 TraitQueryMode::Canonical => {
c295e0f8 1127 return Err(OverflowError::Canonical);
74b04a01
XL
1128 }
1129 }
1130 }
1131 Ok(())
1132 }
1133
c295e0f8
XL
1134 /// Checks that the recursion limit has not been exceeded.
1135 ///
1136 /// The weird return type of this function allows it to be used with the `try` (`?`)
1137 /// operator within certain functions.
1138 #[inline(always)]
1139 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1140 &self,
1141 obligation: &Obligation<'tcx, T>,
1142 error_obligation: &Obligation<'tcx, V>,
1143 ) -> Result<(), OverflowError> {
1144 self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1145 }
1146
74b04a01
XL
1147 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1148 where
1149 OP: FnOnce(&mut Self) -> R,
1150 {
1151 let (result, dep_node) =
cdc7bbd5 1152 self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
74b04a01
XL
1153 self.tcx().dep_graph.read_index(dep_node);
1154 (result, dep_node)
1155 }
1156
3c0e092e
XL
1157 /// filter_impls filters constant trait obligations and candidates that have a positive impl
1158 /// for a negative goal and a negative impl for a positive goal
94222f64
XL
1159 #[instrument(level = "debug", skip(self))]
1160 fn filter_impls(
74b04a01 1161 &mut self,
3c0e092e 1162 candidates: Vec<SelectionCandidate<'tcx>>,
94222f64 1163 obligation: &TraitObligation<'tcx>,
3c0e092e 1164 ) -> Vec<SelectionCandidate<'tcx>> {
94222f64 1165 let tcx = self.tcx();
3c0e092e
XL
1166 let mut result = Vec::with_capacity(candidates.len());
1167
1168 for candidate in candidates {
1169 // Respect const trait obligations
a2a8927a 1170 if obligation.is_const() {
3c0e092e
XL
1171 match candidate {
1172 // const impl
1173 ImplCandidate(def_id)
1174 if tcx.impl_constness(def_id) == hir::Constness::Const => {}
1175 // const param
5099ac24 1176 ParamCandidate(trait_pred) if trait_pred.is_const_if_const() => {}
3c0e092e
XL
1177 // auto trait impl
1178 AutoImplCandidate(..) => {}
1179 // generator, this will raise error in other places
1180 // or ignore error with const_async_blocks feature
1181 GeneratorCandidate => {}
1182 // FnDef where the function is const
1183 FnPointerCandidate { is_const: true } => {}
5099ac24 1184 ConstDropCandidate(_) => {}
3c0e092e
XL
1185 _ => {
1186 // reject all other types of candidates
1187 continue;
1188 }
94222f64
XL
1189 }
1190 }
3c0e092e
XL
1191
1192 if let ImplCandidate(def_id) = candidate {
1193 if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
1194 || obligation.polarity() == tcx.impl_polarity(def_id)
1195 || self.allow_negative_impls
1196 {
1197 result.push(candidate);
1198 }
1199 } else {
1200 result.push(candidate);
1201 }
94222f64 1202 }
3c0e092e
XL
1203
1204 result
1205 }
1206
1207 /// filter_reservation_impls filter reservation impl for any goal as ambiguous
1208 #[instrument(level = "debug", skip(self))]
1209 fn filter_reservation_impls(
1210 &mut self,
1211 candidate: SelectionCandidate<'tcx>,
1212 obligation: &TraitObligation<'tcx>,
1213 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1214 let tcx = self.tcx();
1215 // Treat reservation impls as ambiguity.
74b04a01 1216 if let ImplCandidate(def_id) = candidate {
3c0e092e
XL
1217 if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
1218 if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1219 let attrs = tcx.get_attrs(def_id);
1220 let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
1221 let value = attr.and_then(|a| a.value_str());
1222 if let Some(value) = value {
1223 debug!(
1224 "filter_reservation_impls: \
74b04a01 1225 reservation impl ambiguity on {:?}",
3c0e092e
XL
1226 def_id
1227 );
1228 intercrate_ambiguity_clauses.push(
1229 IntercrateAmbiguityCause::ReservationImpl {
1230 message: value.to_string(),
1231 },
1232 );
74b04a01 1233 }
74b04a01 1234 }
3c0e092e
XL
1235 return Ok(None);
1236 }
74b04a01
XL
1237 }
1238 Ok(Some(candidate))
1239 }
1240
74b04a01
XL
1241 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1242 debug!("is_knowable(intercrate={:?})", self.intercrate);
1243
3c0e092e 1244 if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative {
74b04a01
XL
1245 return None;
1246 }
1247
1248 let obligation = &stack.obligation;
fc512014 1249 let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
74b04a01
XL
1250
1251 // Okay to skip binder because of the nature of the
1252 // trait-ref-is-knowable check, which does not care about
1253 // bound regions.
1254 let trait_ref = predicate.skip_binder().trait_ref;
1255
1256 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
1257 }
1258
1259 /// Returns `true` if the global caches can be used.
74b04a01 1260 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
ba9703b0 1261 // If there are any inference variables in the `ParamEnv`, then we
74b04a01
XL
1262 // always use a cache local to this particular scope. Otherwise, we
1263 // switch to a global cache.
ba9703b0 1264 if param_env.needs_infer() {
74b04a01
XL
1265 return false;
1266 }
1267
1268 // Avoid using the master cache during coherence and just rely
1269 // on the local cache. This effectively disables caching
1270 // during coherence. It is really just a simplification to
1271 // avoid us having to fear that coherence results "pollute"
1272 // the master cache. Since coherence executes pretty quickly,
1273 // it's not worth going to more trouble to increase the
1274 // hit-rate, I don't think.
1275 if self.intercrate {
1276 return false;
1277 }
1278
1279 // Otherwise, we can use the global cache.
1280 true
1281 }
1282
1283 fn check_candidate_cache(
1284 &mut self,
a2a8927a 1285 mut param_env: ty::ParamEnv<'tcx>,
f9f354fc 1286 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
74b04a01 1287 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
94222f64
XL
1288 // Neither the global nor local cache is aware of intercrate
1289 // mode, so don't do any caching. In particular, we might
1290 // re-use the same `InferCtxt` with both an intercrate
1291 // and non-intercrate `SelectionContext`
1292 if self.intercrate {
1293 return None;
1294 }
74b04a01 1295 let tcx = self.tcx();
a2a8927a
XL
1296 let mut pred = cache_fresh_trait_pred.skip_binder();
1297 pred.remap_constness(tcx, &mut param_env);
1298
74b04a01 1299 if self.can_use_global_caches(param_env) {
a2a8927a 1300 if let Some(res) = tcx.selection_cache.get(&param_env.and(pred), tcx) {
3dfed10e 1301 return Some(res);
74b04a01
XL
1302 }
1303 }
a2a8927a 1304 self.infcx.selection_cache.get(&param_env.and(pred), tcx)
74b04a01
XL
1305 }
1306
1307 /// Determines whether can we safely cache the result
1308 /// of selecting an obligation. This is almost always `true`,
1309 /// except when dealing with certain `ParamCandidate`s.
1310 ///
1311 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1312 /// since it was usually produced directly from a `DefId`. However,
1313 /// certain cases (currently only librustdoc's blanket impl finder),
1314 /// a `ParamEnv` may be explicitly constructed with inference types.
1315 /// When this is the case, we do *not* want to cache the resulting selection
1316 /// candidate. This is due to the fact that it might not always be possible
1317 /// to equate the obligation's trait ref and the candidate's trait ref,
1318 /// if more constraints end up getting added to an inference variable.
1319 ///
1320 /// Because of this, we always want to re-run the full selection
1321 /// process for our obligation the next time we see it, since
1322 /// we might end up picking a different `SelectionCandidate` (or none at all).
1323 fn can_cache_candidate(
1324 &self,
1325 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1326 ) -> bool {
94222f64
XL
1327 // Neither the global nor local cache is aware of intercrate
1328 // mode, so don't do any caching. In particular, we might
1329 // re-use the same `InferCtxt` with both an intercrate
1330 // and non-intercrate `SelectionContext`
1331 if self.intercrate {
1332 return false;
1333 }
74b04a01 1334 match result {
ba9703b0 1335 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
74b04a01
XL
1336 _ => true,
1337 }
1338 }
1339
1340 fn insert_candidate_cache(
1341 &mut self,
a2a8927a 1342 mut param_env: ty::ParamEnv<'tcx>,
74b04a01
XL
1343 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1344 dep_node: DepNodeIndex,
1345 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1346 ) {
1347 let tcx = self.tcx();
a2a8927a
XL
1348 let mut pred = cache_fresh_trait_pred.skip_binder();
1349
1350 pred.remap_constness(tcx, &mut param_env);
74b04a01
XL
1351
1352 if !self.can_cache_candidate(&candidate) {
a2a8927a 1353 debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
74b04a01
XL
1354 return;
1355 }
1356
1357 if self.can_use_global_caches(param_env) {
1358 if let Err(Overflow) = candidate {
1359 // Don't cache overflow globally; we only produce this in certain modes.
a2a8927a 1360 } else if !pred.needs_infer() {
ba9703b0 1361 if !candidate.needs_infer() {
a2a8927a 1362 debug!(?pred, ?candidate, "insert_candidate_cache global");
74b04a01 1363 // This may overwrite the cache with the same value.
a2a8927a 1364 tcx.selection_cache.insert(param_env.and(pred), dep_node, candidate);
74b04a01
XL
1365 return;
1366 }
1367 }
1368 }
1369
a2a8927a
XL
1370 debug!(?pred, ?candidate, "insert_candidate_cache local");
1371 self.infcx.selection_cache.insert(param_env.and(pred), dep_node, candidate);
74b04a01
XL
1372 }
1373
29967ef6
XL
1374 /// Matches a predicate against the bounds of its self type.
1375 ///
1376 /// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
1377 /// a projection, look at the bounds of `T::Bar`, see if we can find a
1378 /// `Baz` bound. We return indexes into the list returned by
1379 /// `tcx.item_bounds` for any applicable bounds.
74b04a01
XL
1380 fn match_projection_obligation_against_definition_bounds(
1381 &mut self,
1382 obligation: &TraitObligation<'tcx>,
29967ef6 1383 ) -> smallvec::SmallVec<[usize; 2]> {
fc512014 1384 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
29967ef6 1385 let placeholder_trait_predicate =
fc512014 1386 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
74b04a01 1387 debug!(
29967ef6
XL
1388 ?placeholder_trait_predicate,
1389 "match_projection_obligation_against_definition_bounds"
74b04a01
XL
1390 );
1391
f035d41b 1392 let tcx = self.infcx.tcx;
29967ef6
XL
1393 let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
1394 ty::Projection(ref data) => (data.item_def_id, data.substs),
1395 ty::Opaque(def_id, substs) => (def_id, substs),
74b04a01
XL
1396 _ => {
1397 span_bug!(
1398 obligation.cause.span,
1399 "match_projection_obligation_against_definition_bounds() called \
1400 but self-ty is not a projection: {:?}",
1401 placeholder_trait_predicate.trait_ref.self_ty()
1402 );
1403 }
1404 };
29967ef6 1405 let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
74b04a01 1406
29967ef6
XL
1407 // The bounds returned by `item_bounds` may contain duplicates after
1408 // normalization, so try to deduplicate when possible to avoid
1409 // unnecessary ambiguity.
1410 let mut distinct_normalized_bounds = FxHashSet::default();
1411
1412 let matching_bounds = bounds
1413 .iter()
1414 .enumerate()
1415 .filter_map(|(idx, bound)| {
5869c6ff 1416 let bound_predicate = bound.kind();
94222f64 1417 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
29967ef6
XL
1418 let bound = bound_predicate.rebind(pred.trait_ref);
1419 if self.infcx.probe(|_| {
1420 match self.match_normalize_trait_ref(
1421 obligation,
1422 bound,
1423 placeholder_trait_predicate.trait_ref,
1424 ) {
1425 Ok(None) => true,
1426 Ok(Some(normalized_trait))
1427 if distinct_normalized_bounds.insert(normalized_trait) =>
1428 {
1429 true
1430 }
1431 _ => false,
1432 }
1433 }) {
1434 return Some(idx);
1435 }
f035d41b 1436 }
29967ef6
XL
1437 None
1438 })
1439 .collect();
74b04a01 1440
29967ef6
XL
1441 debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds");
1442 matching_bounds
74b04a01
XL
1443 }
1444
29967ef6
XL
1445 /// Equates the trait in `obligation` with trait bound. If the two traits
1446 /// can be equated and the normalized trait bound doesn't contain inference
1447 /// variables or placeholders, the normalized bound is returned.
1448 fn match_normalize_trait_ref(
74b04a01
XL
1449 &mut self,
1450 obligation: &TraitObligation<'tcx>,
1451 trait_bound: ty::PolyTraitRef<'tcx>,
1452 placeholder_trait_ref: ty::TraitRef<'tcx>,
29967ef6 1453 ) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
74b04a01 1454 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
29967ef6
XL
1455 if placeholder_trait_ref.def_id != trait_bound.def_id() {
1456 // Avoid unnecessary normalization
1457 return Err(());
1458 }
1459
1460 let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1461 project::normalize_with_depth(
1462 self,
1463 obligation.param_env,
1464 obligation.cause.clone(),
1465 obligation.recursion_depth + 1,
fc512014 1466 trait_bound,
29967ef6
XL
1467 )
1468 });
74b04a01
XL
1469 self.infcx
1470 .at(&obligation.cause, obligation.param_env)
1471 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
29967ef6
XL
1472 .map(|InferOk { obligations: _, value: () }| {
1473 // This method is called within a probe, so we can't have
1474 // inference variables and placeholders escape.
1475 if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
1476 Some(trait_bound)
1477 } else {
1478 None
1479 }
1480 })
1481 .map_err(|_| ())
74b04a01
XL
1482 }
1483
1484 fn evaluate_where_clause<'o>(
1485 &mut self,
1486 stack: &TraitObligationStack<'o, 'tcx>,
1487 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1488 ) -> Result<EvaluationResult, OverflowError> {
1489 self.evaluation_probe(|this| {
1490 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
29967ef6 1491 Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
74b04a01
XL
1492 Err(()) => Ok(EvaluatedToErr),
1493 }
1494 })
1495 }
1496
5099ac24
FG
1497 /// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
1498 /// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
1499 /// and applying this env_predicate constrains any of the obligation's GAT substitutions.
1500 ///
1501 /// This behavior is a somewhat of a hack to prevent overconstraining inference variables
1502 /// in cases like #91762.
29967ef6
XL
1503 pub(super) fn match_projection_projections(
1504 &mut self,
1505 obligation: &ProjectionTyObligation<'tcx>,
6a06907d 1506 env_predicate: PolyProjectionPredicate<'tcx>,
29967ef6 1507 potentially_unnormalized_candidates: bool,
5099ac24 1508 ) -> ProjectionMatchesProjection {
29967ef6 1509 let mut nested_obligations = Vec::new();
6a06907d
XL
1510 let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
1511 obligation.cause.span,
1512 LateBoundRegionConversionTime::HigherRankedType,
1513 env_predicate,
1514 );
1515 let infer_projection = if potentially_unnormalized_candidates {
29967ef6
XL
1516 ensure_sufficient_stack(|| {
1517 project::normalize_with_depth_to(
1518 self,
1519 obligation.param_env,
1520 obligation.cause.clone(),
1521 obligation.recursion_depth + 1,
6a06907d 1522 infer_predicate.projection_ty,
29967ef6
XL
1523 &mut nested_obligations,
1524 )
1525 })
1526 } else {
6a06907d 1527 infer_predicate.projection_ty
29967ef6
XL
1528 };
1529
5099ac24
FG
1530 let is_match = self
1531 .infcx
29967ef6 1532 .at(&obligation.cause, obligation.param_env)
6a06907d 1533 .sup(obligation.predicate, infer_projection)
29967ef6
XL
1534 .map_or(false, |InferOk { obligations, value: () }| {
1535 self.evaluate_predicates_recursively(
1536 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1537 nested_obligations.into_iter().chain(obligations),
1538 )
1539 .map_or(false, |res| res.may_apply())
5099ac24
FG
1540 });
1541
1542 if is_match {
1543 let generics = self.tcx().generics_of(obligation.predicate.item_def_id);
1544 // FIXME(generic-associated-types): Addresses aggressive inference in #92917.
1545 // If this type is a GAT, and of the GAT substs resolve to something new,
1546 // that means that we must have newly inferred something about the GAT.
1547 // We should give up in that case.
1548 if !generics.params.is_empty()
1549 && obligation.predicate.substs[generics.parent_count..]
1550 .iter()
1551 .any(|&p| p.has_infer_types_or_consts() && self.infcx.shallow_resolve(p) != p)
1552 {
1553 ProjectionMatchesProjection::Ambiguous
1554 } else {
1555 ProjectionMatchesProjection::Yes
1556 }
1557 } else {
1558 ProjectionMatchesProjection::No
1559 }
29967ef6
XL
1560 }
1561
74b04a01
XL
1562 ///////////////////////////////////////////////////////////////////////////
1563 // WINNOW
1564 //
1565 // Winnowing is the process of attempting to resolve ambiguity by
1566 // probing further. During the winnowing process, we unify all
1567 // type variables and then we also attempt to evaluate recursive
1568 // bounds to see if they are satisfied.
1569
1570 /// Returns `true` if `victim` should be dropped in favor of
1571 /// `other`. Generally speaking we will drop duplicate
1572 /// candidates and prefer where-clause candidates.
1573 ///
1574 /// See the comment for "SelectionCandidate" for more details.
1575 fn candidate_should_be_dropped_in_favor_of(
1576 &mut self,
5099ac24 1577 sized_predicate: bool,
74b04a01
XL
1578 victim: &EvaluatedCandidate<'tcx>,
1579 other: &EvaluatedCandidate<'tcx>,
1580 needs_infer: bool,
1581 ) -> bool {
1582 if victim.candidate == other.candidate {
1583 return true;
1584 }
1585
1586 // Check if a bound would previously have been removed when normalizing
1587 // the param_env so that it can be given the lowest priority. See
1588 // #50825 for the motivation for this.
a2a8927a 1589 let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| {
5099ac24 1590 cand.is_global() && !cand.has_late_bound_regions()
3c0e092e 1591 };
74b04a01 1592
6a06907d 1593 // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
5099ac24 1594 // `DiscriminantKindCandidate`, and `ConstDropCandidate` to anything else.
f9f354fc
XL
1595 //
1596 // This is a fix for #53123 and prevents winnowing from accidentally extending the
1597 // lifetime of a variable.
29967ef6
XL
1598 match (&other.candidate, &victim.candidate) {
1599 (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
1600 bug!(
1601 "default implementations shouldn't be recorded \
1602 when there are other valid candidates"
1603 );
1604 }
1605
f9f354fc 1606 // (*)
6a06907d
XL
1607 (
1608 BuiltinCandidate { has_nested: false }
1609 | DiscriminantKindCandidate
c295e0f8 1610 | PointeeCandidate
5099ac24 1611 | ConstDropCandidate(_),
6a06907d
XL
1612 _,
1613 ) => true,
1614 (
1615 _,
1616 BuiltinCandidate { has_nested: false }
1617 | DiscriminantKindCandidate
c295e0f8 1618 | PointeeCandidate
5099ac24 1619 | ConstDropCandidate(_),
6a06907d 1620 ) => false,
29967ef6 1621
a2a8927a
XL
1622 (ParamCandidate(other), ParamCandidate(victim)) => {
1623 let same_except_bound_vars = other.skip_binder().trait_ref
1624 == victim.skip_binder().trait_ref
1625 && other.skip_binder().constness == victim.skip_binder().constness
1626 && other.skip_binder().polarity == victim.skip_binder().polarity
1627 && !other.skip_binder().trait_ref.has_escaping_bound_vars();
c295e0f8 1628 if same_except_bound_vars {
cdc7bbd5
XL
1629 // See issue #84398. In short, we can generate multiple ParamCandidates which are
1630 // the same except for unused bound vars. Just pick the one with the fewest bound vars
1631 // or the current one if tied (they should both evaluate to the same answer). This is
1632 // probably best characterized as a "hack", since we might prefer to just do our
1633 // best to *not* create essentially duplicate candidates in the first place.
a2a8927a
XL
1634 other.bound_vars().len() <= victim.bound_vars().len()
1635 } else if other.skip_binder().trait_ref == victim.skip_binder().trait_ref
1636 && victim.skip_binder().constness == ty::BoundConstness::NotConst
1637 && other.skip_binder().polarity == victim.skip_binder().polarity
94222f64 1638 {
fc512014
XL
1639 // Drop otherwise equivalent non-const candidates in favor of const candidates.
1640 true
1641 } else {
1642 false
1643 }
1644 }
29967ef6 1645
c295e0f8
XL
1646 // Drop otherwise equivalent non-const fn pointer candidates
1647 (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
1648
5099ac24
FG
1649 // If obligation is a sized predicate or the where-clause bound is
1650 // global, prefer the projection or object candidate. See issue
1651 // #50825 and #89352.
1652 (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1653 sized_predicate || is_global(cand)
1654 }
1655 (ParamCandidate(ref cand), ObjectCandidate(_) | ProjectionCandidate(_)) => {
1656 !(sized_predicate || is_global(cand))
1657 }
1658
29967ef6
XL
1659 // Global bounds from the where clause should be ignored
1660 // here (see issue #50825). Otherwise, we have a where
1661 // clause so don't go around looking for impls.
1662 // Arbitrarily give param candidates priority
1663 // over projection and object candidates.
1664 (
1665 ParamCandidate(ref cand),
74b04a01
XL
1666 ImplCandidate(..)
1667 | ClosureCandidate
1668 | GeneratorCandidate
c295e0f8 1669 | FnPointerCandidate { .. }
74b04a01
XL
1670 | BuiltinObjectCandidate
1671 | BuiltinUnsizeCandidate
94222f64 1672 | TraitUpcastingUnsizeCandidate(_)
74b04a01 1673 | BuiltinCandidate { .. }
5099ac24 1674 | TraitAliasCandidate(..),
a2a8927a 1675 ) => !is_global(cand),
29967ef6
XL
1676 (
1677 ImplCandidate(_)
1678 | ClosureCandidate
1679 | GeneratorCandidate
c295e0f8 1680 | FnPointerCandidate { .. }
29967ef6
XL
1681 | BuiltinObjectCandidate
1682 | BuiltinUnsizeCandidate
94222f64 1683 | TraitUpcastingUnsizeCandidate(_)
29967ef6
XL
1684 | BuiltinCandidate { has_nested: true }
1685 | TraitAliasCandidate(..),
1686 ParamCandidate(ref cand),
1687 ) => {
1688 // Prefer these to a global where-clause bound
1689 // (see issue #50825).
a2a8927a 1690 is_global(cand) && other.evaluation.must_apply_modulo_regions()
29967ef6
XL
1691 }
1692
1693 (ProjectionCandidate(i), ProjectionCandidate(j))
1694 | (ObjectCandidate(i), ObjectCandidate(j)) => {
1695 // Arbitrarily pick the lower numbered candidate for backwards
1696 // compatibility reasons. Don't let this affect inference.
1697 i < j && !needs_infer
1698 }
1699 (ObjectCandidate(_), ProjectionCandidate(_))
1700 | (ProjectionCandidate(_), ObjectCandidate(_)) => {
1701 bug!("Have both object and projection candidate")
1702 }
1703
1704 // Arbitrarily give projection and object candidates priority.
1705 (
1706 ObjectCandidate(_) | ProjectionCandidate(_),
74b04a01
XL
1707 ImplCandidate(..)
1708 | ClosureCandidate
1709 | GeneratorCandidate
c295e0f8 1710 | FnPointerCandidate { .. }
74b04a01
XL
1711 | BuiltinObjectCandidate
1712 | BuiltinUnsizeCandidate
94222f64 1713 | TraitUpcastingUnsizeCandidate(_)
74b04a01 1714 | BuiltinCandidate { .. }
29967ef6
XL
1715 | TraitAliasCandidate(..),
1716 ) => true,
1717
1718 (
1719 ImplCandidate(..)
1720 | ClosureCandidate
1721 | GeneratorCandidate
c295e0f8 1722 | FnPointerCandidate { .. }
29967ef6
XL
1723 | BuiltinObjectCandidate
1724 | BuiltinUnsizeCandidate
94222f64 1725 | TraitUpcastingUnsizeCandidate(_)
29967ef6
XL
1726 | BuiltinCandidate { .. }
1727 | TraitAliasCandidate(..),
1728 ObjectCandidate(_) | ProjectionCandidate(_),
1729 ) => false,
1730
1731 (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
74b04a01
XL
1732 // See if we can toss out `victim` based on specialization.
1733 // This requires us to know *for sure* that the `other` impl applies
1734 // i.e., `EvaluatedToOk`.
94222f64
XL
1735 //
1736 // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
1737 // to me but is required for `std` to compile, so I didn't change it
1738 // for now.
1739 let tcx = self.tcx();
74b04a01 1740 if other.evaluation.must_apply_modulo_regions() {
29967ef6
XL
1741 if tcx.specializes((other_def, victim_def)) {
1742 return true;
74b04a01 1743 }
94222f64
XL
1744 }
1745
1746 if other.evaluation.must_apply_considering_regions() {
1747 match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
29967ef6
XL
1748 Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
1749 // Subtle: If the predicate we are evaluating has inference
1750 // variables, do *not* allow discarding candidates due to
1751 // marker trait impls.
1752 //
1753 // Without this restriction, we could end up accidentally
1754 // constrainting inference variables based on an arbitrarily
1755 // chosen trait impl.
1756 //
1757 // Imagine we have the following code:
1758 //
1759 // ```rust
1760 // #[marker] trait MyTrait {}
1761 // impl MyTrait for u8 {}
1762 // impl MyTrait for bool {}
1763 // ```
1764 //
1765 // And we are evaluating the predicate `<_#0t as MyTrait>`.
1766 //
1767 // During selection, we will end up with one candidate for each
1768 // impl of `MyTrait`. If we were to discard one impl in favor
1769 // of the other, we would be left with one candidate, causing
1770 // us to "successfully" select the predicate, unifying
1771 // _#0t with (for example) `u8`.
1772 //
1773 // However, we have no reason to believe that this unification
1774 // is correct - we've essentially just picked an arbitrary
1775 // *possibility* for _#0t, and required that this be the *only*
1776 // possibility.
1777 //
1778 // Eventually, we will either:
1779 // 1) Unify all inference variables in the predicate through
1780 // some other means (e.g. type-checking of a function). We will
1781 // then be in a position to drop marker trait candidates
1782 // without constraining inference variables (since there are
1783 // none left to constrin)
1784 // 2) Be left with some unconstrained inference variables. We
1785 // will then correctly report an inference error, since the
1786 // existence of multiple marker trait impls tells us nothing
1787 // about which one should actually apply.
1788 !needs_infer
1789 }
1790 Some(_) => true,
1791 None => false,
94222f64 1792 }
29967ef6
XL
1793 } else {
1794 false
74b04a01
XL
1795 }
1796 }
29967ef6
XL
1797
1798 // Everything else is ambiguous
1799 (
1800 ImplCandidate(_)
1801 | ClosureCandidate
1802 | GeneratorCandidate
c295e0f8 1803 | FnPointerCandidate { .. }
29967ef6
XL
1804 | BuiltinObjectCandidate
1805 | BuiltinUnsizeCandidate
94222f64 1806 | TraitUpcastingUnsizeCandidate(_)
29967ef6
XL
1807 | BuiltinCandidate { has_nested: true }
1808 | TraitAliasCandidate(..),
1809 ImplCandidate(_)
1810 | ClosureCandidate
1811 | GeneratorCandidate
c295e0f8 1812 | FnPointerCandidate { .. }
29967ef6
XL
1813 | BuiltinObjectCandidate
1814 | BuiltinUnsizeCandidate
94222f64 1815 | TraitUpcastingUnsizeCandidate(_)
29967ef6
XL
1816 | BuiltinCandidate { has_nested: true }
1817 | TraitAliasCandidate(..),
1818 ) => false,
74b04a01
XL
1819 }
1820 }
1821
74b04a01
XL
1822 fn sized_conditions(
1823 &mut self,
1824 obligation: &TraitObligation<'tcx>,
1825 ) -> BuiltinImplConditions<'tcx> {
1826 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1827
1828 // NOTE: binder moved to (*)
1829 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1830
1b1a35ee 1831 match self_ty.kind() {
ba9703b0 1832 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
74b04a01
XL
1833 | ty::Uint(_)
1834 | ty::Int(_)
1835 | ty::Bool
1836 | ty::Float(_)
1837 | ty::FnDef(..)
1838 | ty::FnPtr(_)
1839 | ty::RawPtr(..)
1840 | ty::Char
1841 | ty::Ref(..)
1842 | ty::Generator(..)
1843 | ty::GeneratorWitness(..)
1844 | ty::Array(..)
1845 | ty::Closure(..)
1846 | ty::Never
f035d41b 1847 | ty::Error(_) => {
74b04a01
XL
1848 // safe for everything
1849 Where(ty::Binder::dummy(Vec::new()))
1850 }
1851
1852 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
1853
29967ef6
XL
1854 ty::Tuple(tys) => Where(
1855 obligation
1856 .predicate
1857 .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()),
1858 ),
74b04a01
XL
1859
1860 ty::Adt(def, substs) => {
1861 let sized_crit = def.sized_constraint(self.tcx());
1862 // (*) binder moved here
29967ef6
XL
1863 Where(
1864 obligation.predicate.rebind({
1865 sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
1866 }),
1867 )
74b04a01
XL
1868 }
1869
1870 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
1871 ty::Infer(ty::TyVar(_)) => Ambiguous,
1872
f9f354fc 1873 ty::Placeholder(..)
74b04a01 1874 | ty::Bound(..)
ba9703b0 1875 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
74b04a01
XL
1876 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1877 }
1878 }
1879 }
1880
1881 fn copy_clone_conditions(
1882 &mut self,
1883 obligation: &TraitObligation<'tcx>,
1884 ) -> BuiltinImplConditions<'tcx> {
1885 // NOTE: binder moved to (*)
1886 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
1887
1888 use self::BuiltinImplConditions::{Ambiguous, None, Where};
1889
29967ef6 1890 match *self_ty.kind() {
74b04a01
XL
1891 ty::Infer(ty::IntVar(_))
1892 | ty::Infer(ty::FloatVar(_))
1893 | ty::FnDef(..)
1894 | ty::FnPtr(_)
f035d41b 1895 | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
74b04a01
XL
1896
1897 ty::Uint(_)
1898 | ty::Int(_)
1899 | ty::Bool
1900 | ty::Float(_)
1901 | ty::Char
1902 | ty::RawPtr(..)
1903 | ty::Never
3c0e092e
XL
1904 | ty::Ref(_, _, hir::Mutability::Not)
1905 | ty::Array(..) => {
74b04a01
XL
1906 // Implementations provided in libcore
1907 None
1908 }
1909
1910 ty::Dynamic(..)
1911 | ty::Str
1912 | ty::Slice(..)
1913 | ty::Generator(..)
1914 | ty::GeneratorWitness(..)
1915 | ty::Foreign(..)
1916 | ty::Ref(_, _, hir::Mutability::Mut) => None,
1917
74b04a01
XL
1918 ty::Tuple(tys) => {
1919 // (*) binder moved here
29967ef6 1920 Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect()))
74b04a01
XL
1921 }
1922
ba9703b0 1923 ty::Closure(_, substs) => {
74b04a01 1924 // (*) binder moved here
29967ef6
XL
1925 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
1926 if let ty::Infer(ty::TyVar(_)) = ty.kind() {
1927 // Not yet resolved.
1928 Ambiguous
1929 } else {
1930 Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
1931 }
74b04a01
XL
1932 }
1933
1934 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
1935 // Fallback to whatever user-defined impls exist in this case.
1936 None
1937 }
1938
1939 ty::Infer(ty::TyVar(_)) => {
1940 // Unbound type variable. Might or might not have
1941 // applicable impls and so forth, depending on what
1942 // those type variables wind up being bound to.
1943 Ambiguous
1944 }
1945
f9f354fc 1946 ty::Placeholder(..)
74b04a01 1947 | ty::Bound(..)
ba9703b0 1948 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
74b04a01
XL
1949 bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
1950 }
1951 }
1952 }
1953
1954 /// For default impls, we need to break apart a type into its
1955 /// "constituent types" -- meaning, the types that it contains.
1956 ///
1957 /// Here are some (simple) examples:
1958 ///
1959 /// ```
1960 /// (i32, u32) -> [i32, u32]
1961 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1962 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1963 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1964 /// ```
cdc7bbd5
XL
1965 fn constituent_types_for_ty(
1966 &self,
1967 t: ty::Binder<'tcx, Ty<'tcx>>,
1968 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
fc512014 1969 match *t.skip_binder().kind() {
74b04a01
XL
1970 ty::Uint(_)
1971 | ty::Int(_)
1972 | ty::Bool
1973 | ty::Float(_)
1974 | ty::FnDef(..)
1975 | ty::FnPtr(_)
1976 | ty::Str
f035d41b 1977 | ty::Error(_)
ba9703b0 1978 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
74b04a01 1979 | ty::Never
fc512014 1980 | ty::Char => ty::Binder::dummy(Vec::new()),
74b04a01 1981
f9f354fc 1982 ty::Placeholder(..)
74b04a01
XL
1983 | ty::Dynamic(..)
1984 | ty::Param(..)
1985 | ty::Foreign(..)
1986 | ty::Projection(..)
1987 | ty::Bound(..)
ba9703b0 1988 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
74b04a01
XL
1989 bug!("asked to assemble constituent types of unexpected type: {:?}", t);
1990 }
1991
1992 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
fc512014 1993 t.rebind(vec![element_ty])
74b04a01
XL
1994 }
1995
fc512014 1996 ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
74b04a01
XL
1997
1998 ty::Tuple(ref tys) => {
1999 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
fc512014 2000 t.rebind(tys.iter().map(|k| k.expect_ty()).collect())
74b04a01
XL
2001 }
2002
29967ef6
XL
2003 ty::Closure(_, ref substs) => {
2004 let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
fc512014 2005 t.rebind(vec![ty])
29967ef6 2006 }
74b04a01 2007
ba9703b0 2008 ty::Generator(_, ref substs, _) => {
29967ef6 2009 let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
ba9703b0 2010 let witness = substs.as_generator().witness();
5099ac24 2011 t.rebind([ty].into_iter().chain(iter::once(witness)).collect())
74b04a01
XL
2012 }
2013
2014 ty::GeneratorWitness(types) => {
fc512014
XL
2015 debug_assert!(!types.has_escaping_bound_vars());
2016 types.map_bound(|types| types.to_vec())
74b04a01
XL
2017 }
2018
2019 // For `PhantomData<T>`, we pass `T`.
fc512014 2020 ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
74b04a01 2021
fc512014
XL
2022 ty::Adt(def, substs) => {
2023 t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
2024 }
74b04a01
XL
2025
2026 ty::Opaque(def_id, substs) => {
2027 // We can resolve the `impl Trait` to its concrete type,
2028 // which enforces a DAG between the functions requiring
2029 // the auto trait bounds in question.
fc512014 2030 t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
74b04a01
XL
2031 }
2032 }
2033 }
2034
2035 fn collect_predicates_for_types(
2036 &mut self,
2037 param_env: ty::ParamEnv<'tcx>,
2038 cause: ObligationCause<'tcx>,
2039 recursion_depth: usize,
2040 trait_def_id: DefId,
cdc7bbd5 2041 types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
74b04a01
XL
2042 ) -> Vec<PredicateObligation<'tcx>> {
2043 // Because the types were potentially derived from
2044 // higher-ranked obligations they may reference late-bound
f035d41b
XL
2045 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2046 // yield a type like `for<'a> &'a i32`. In general, we
74b04a01
XL
2047 // maintain the invariant that we never manipulate bound
2048 // regions, so we have to process these bound regions somehow.
2049 //
2050 // The strategy is to:
2051 //
2052 // 1. Instantiate those regions to placeholder regions (e.g.,
f035d41b
XL
2053 // `for<'a> &'a i32` becomes `&0 i32`.
2054 // 2. Produce something like `&'0 i32 : Copy`
2055 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
74b04a01
XL
2056
2057 types
fc512014 2058 .as_ref()
f035d41b 2059 .skip_binder() // binder moved -\
74b04a01
XL
2060 .iter()
2061 .flat_map(|ty| {
5099ac24 2062 let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(*ty); // <----/
74b04a01
XL
2063
2064 self.infcx.commit_unconditionally(|_| {
fc512014 2065 let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
74b04a01 2066 let Normalized { value: normalized_ty, mut obligations } =
f9f354fc
XL
2067 ensure_sufficient_stack(|| {
2068 project::normalize_with_depth(
2069 self,
2070 param_env,
2071 cause.clone(),
2072 recursion_depth,
fc512014 2073 placeholder_ty,
f9f354fc
XL
2074 )
2075 });
f035d41b 2076 let placeholder_obligation = predicate_for_trait_def(
74b04a01
XL
2077 self.tcx(),
2078 param_env,
2079 cause.clone(),
2080 trait_def_id,
2081 recursion_depth,
2082 normalized_ty,
2083 &[],
2084 );
f035d41b 2085 obligations.push(placeholder_obligation);
74b04a01
XL
2086 obligations
2087 })
2088 })
2089 .collect()
2090 }
2091
74b04a01
XL
2092 ///////////////////////////////////////////////////////////////////////////
2093 // Matching
2094 //
2095 // Matching is a common path used for both evaluation and
2096 // confirmation. It basically unifies types that appear in impls
2097 // and traits. This does affect the surrounding environment;
2098 // therefore, when used during evaluation, match routines must be
2099 // run inside of a `probe()` so that their side-effects are
2100 // contained.
2101
2102 fn rematch_impl(
2103 &mut self,
2104 impl_def_id: DefId,
2105 obligation: &TraitObligation<'tcx>,
74b04a01 2106 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
f035d41b 2107 match self.match_impl(impl_def_id, obligation) {
74b04a01
XL
2108 Ok(substs) => substs,
2109 Err(()) => {
2110 bug!(
2111 "Impl {:?} was matchable against {:?} but now is not",
2112 impl_def_id,
2113 obligation
2114 );
2115 }
2116 }
2117 }
2118
136023e0 2119 #[tracing::instrument(level = "debug", skip(self))]
74b04a01
XL
2120 fn match_impl(
2121 &mut self,
2122 impl_def_id: DefId,
2123 obligation: &TraitObligation<'tcx>,
74b04a01
XL
2124 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
2125 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2126
2127 // Before we create the substitutions and everything, first
2128 // consider a "quick reject". This avoids creating more types
2129 // and so forth that we need to.
2130 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2131 return Err(());
2132 }
2133
29967ef6 2134 let placeholder_obligation =
fc512014 2135 self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
f035d41b 2136 let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
74b04a01
XL
2137
2138 let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
2139
2140 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
2141
136023e0
XL
2142 debug!(?impl_trait_ref);
2143
74b04a01 2144 let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
f9f354fc
XL
2145 ensure_sufficient_stack(|| {
2146 project::normalize_with_depth(
2147 self,
2148 obligation.param_env,
2149 obligation.cause.clone(),
2150 obligation.recursion_depth + 1,
fc512014 2151 impl_trait_ref,
f9f354fc
XL
2152 )
2153 });
74b04a01 2154
29967ef6 2155 debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
74b04a01 2156
136023e0
XL
2157 let cause = ObligationCause::new(
2158 obligation.cause.span,
2159 obligation.cause.body_id,
c295e0f8 2160 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
136023e0
XL
2161 );
2162
74b04a01
XL
2163 let InferOk { obligations, .. } = self
2164 .infcx
136023e0 2165 .at(&cause, obligation.param_env)
f035d41b 2166 .eq(placeholder_obligation_trait_ref, impl_trait_ref)
74b04a01
XL
2167 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
2168 nested_obligations.extend(obligations);
2169
74b04a01
XL
2170 if !self.intercrate
2171 && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
2172 {
2173 debug!("match_impl: reservation impls only apply in intercrate mode");
2174 return Err(());
2175 }
2176
136023e0 2177 debug!(?impl_substs, ?nested_obligations, "match_impl: success");
74b04a01
XL
2178 Ok(Normalized { value: impl_substs, obligations: nested_obligations })
2179 }
2180
2181 fn fast_reject_trait_refs(
2182 &mut self,
2183 obligation: &TraitObligation<'_>,
2184 impl_trait_ref: &ty::TraitRef<'_>,
2185 ) -> bool {
2186 // We can avoid creating type variables and doing the full
2187 // substitution if we find that any of the input types, when
2188 // simplified, do not match.
2189
cdc7bbd5 2190 iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
ba9703b0
XL
2191 |(obligation_arg, impl_arg)| {
2192 match (obligation_arg.unpack(), impl_arg.unpack()) {
2193 (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
a2a8927a
XL
2194 // Note, we simplify parameters for the obligation but not the
2195 // impl so that we do not reject a blanket impl but do reject
2196 // more concrete impls if we're searching for `T: Trait`.
2197 let simplified_obligation_ty = fast_reject::simplify_type(
2198 self.tcx(),
2199 obligation_ty,
2200 SimplifyParams::Yes,
a2a8927a 2201 );
5099ac24
FG
2202 let simplified_impl_ty =
2203 fast_reject::simplify_type(self.tcx(), impl_ty, SimplifyParams::No);
ba9703b0
XL
2204
2205 simplified_obligation_ty.is_some()
2206 && simplified_impl_ty.is_some()
2207 && simplified_obligation_ty != simplified_impl_ty
2208 }
2209 (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
2210 // Lifetimes can never cause a rejection.
2211 false
2212 }
2213 (GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
2214 // Conservatively ignore consts (i.e. assume they might
2215 // unify later) until we have `fast_reject` support for
2216 // them (if we'll ever need it, even).
2217 false
2218 }
2219 _ => unreachable!(),
2220 }
74b04a01
XL
2221 },
2222 )
2223 }
2224
2225 /// Normalize `where_clause_trait_ref` and try to match it against
2226 /// `obligation`. If successful, return any predicates that
29967ef6 2227 /// result from the normalization.
74b04a01
XL
2228 fn match_where_clause_trait_ref(
2229 &mut self,
2230 obligation: &TraitObligation<'tcx>,
2231 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2232 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
2233 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2234 }
2235
2236 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2237 /// obligation is satisfied.
c295e0f8 2238 #[instrument(skip(self), level = "debug")]
74b04a01
XL
2239 fn match_poly_trait_ref(
2240 &mut self,
2241 obligation: &TraitObligation<'tcx>,
2242 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2243 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
74b04a01
XL
2244 self.infcx
2245 .at(&obligation.cause, obligation.param_env)
2246 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
2247 .map(|InferOk { obligations, .. }| obligations)
2248 .map_err(|_| ())
2249 }
2250
2251 ///////////////////////////////////////////////////////////////////////////
2252 // Miscellany
2253
2254 fn match_fresh_trait_refs(
2255 &self,
a2a8927a
XL
2256 previous: ty::PolyTraitPredicate<'tcx>,
2257 current: ty::PolyTraitPredicate<'tcx>,
74b04a01
XL
2258 param_env: ty::ParamEnv<'tcx>,
2259 ) -> bool {
2260 let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
2261 matcher.relate(previous, current).is_ok()
2262 }
2263
2264 fn push_stack<'o>(
2265 &mut self,
2266 previous_stack: TraitObligationStackList<'o, 'tcx>,
2267 obligation: &'o TraitObligation<'tcx>,
2268 ) -> TraitObligationStack<'o, 'tcx> {
a2a8927a 2269 let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
74b04a01
XL
2270
2271 let dfn = previous_stack.cache.next_dfn();
2272 let depth = previous_stack.depth() + 1;
2273 TraitObligationStack {
2274 obligation,
a2a8927a 2275 fresh_trait_pred,
74b04a01
XL
2276 reached_depth: Cell::new(depth),
2277 previous: previous_stack,
2278 dfn,
2279 depth,
2280 }
2281 }
2282
c295e0f8 2283 #[instrument(skip(self), level = "debug")]
74b04a01
XL
2284 fn closure_trait_ref_unnormalized(
2285 &mut self,
2286 obligation: &TraitObligation<'tcx>,
74b04a01
XL
2287 substs: SubstsRef<'tcx>,
2288 ) -> ty::PolyTraitRef<'tcx> {
ba9703b0 2289 let closure_sig = substs.as_closure().sig();
74b04a01 2290
29967ef6 2291 debug!(?closure_sig);
74b04a01
XL
2292
2293 // (1) Feels icky to skip the binder here, but OTOH we know
2294 // that the self-type is an unboxed closure type and hence is
2295 // in fact unparameterized (or at least does not reference any
2296 // regions bound in the obligation). Still probably some
2297 // refactoring could make this nicer.
2298 closure_trait_ref_and_return_type(
2299 self.tcx(),
2300 obligation.predicate.def_id(),
2301 obligation.predicate.skip_binder().self_ty(), // (1)
ba9703b0 2302 closure_sig,
74b04a01
XL
2303 util::TupleArgumentsFlag::No,
2304 )
2305 .map_bound(|(trait_ref, _)| trait_ref)
2306 }
2307
2308 fn generator_trait_ref_unnormalized(
2309 &mut self,
2310 obligation: &TraitObligation<'tcx>,
74b04a01
XL
2311 substs: SubstsRef<'tcx>,
2312 ) -> ty::PolyTraitRef<'tcx> {
ba9703b0 2313 let gen_sig = substs.as_generator().poly_sig();
74b04a01
XL
2314
2315 // (1) Feels icky to skip the binder here, but OTOH we know
2316 // that the self-type is an generator type and hence is
2317 // in fact unparameterized (or at least does not reference any
2318 // regions bound in the obligation). Still probably some
2319 // refactoring could make this nicer.
2320
2321 super::util::generator_trait_ref_and_outputs(
2322 self.tcx(),
2323 obligation.predicate.def_id(),
2324 obligation.predicate.skip_binder().self_ty(), // (1)
2325 gen_sig,
2326 )
2327 .map_bound(|(trait_ref, ..)| trait_ref)
2328 }
2329
2330 /// Returns the obligations that are implied by instantiating an
2331 /// impl or trait. The obligations are substituted and fully
2332 /// normalized. This is used when confirming an impl or default
2333 /// impl.
136023e0 2334 #[tracing::instrument(level = "debug", skip(self, cause, param_env))]
74b04a01
XL
2335 fn impl_or_trait_obligations(
2336 &mut self,
2337 cause: ObligationCause<'tcx>,
2338 recursion_depth: usize,
2339 param_env: ty::ParamEnv<'tcx>,
2340 def_id: DefId, // of impl or trait
2341 substs: SubstsRef<'tcx>, // for impl or trait
2342 ) -> Vec<PredicateObligation<'tcx>> {
74b04a01
XL
2343 let tcx = self.tcx();
2344
2345 // To allow for one-pass evaluation of the nested obligation,
2346 // each predicate must be preceded by the obligations required
2347 // to normalize it.
2348 // for example, if we have:
2349 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2350 // the impl will have the following predicates:
2351 // <V as Iterator>::Item = U,
2352 // U: Iterator, U: Sized,
2353 // V: Iterator, V: Sized,
2354 // <U as Iterator>::Item: Copy
2355 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2356 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2357 // `$1: Copy`, so we must ensure the obligations are emitted in
2358 // that order.
2359 let predicates = tcx.predicates_of(def_id);
136023e0 2360 debug!(?predicates);
74b04a01
XL
2361 assert_eq!(predicates.parent, None);
2362 let mut obligations = Vec::with_capacity(predicates.predicates.len());
2363 for (predicate, _) in predicates.predicates {
136023e0 2364 debug!(?predicate);
74b04a01
XL
2365 let predicate = normalize_with_depth_to(
2366 self,
2367 param_env,
2368 cause.clone(),
2369 recursion_depth,
fc512014 2370 predicate.subst(tcx, substs),
74b04a01
XL
2371 &mut obligations,
2372 );
2373 obligations.push(Obligation {
2374 cause: cause.clone(),
2375 recursion_depth,
2376 param_env,
2377 predicate,
2378 });
2379 }
2380
2381 // We are performing deduplication here to avoid exponential blowups
2382 // (#38528) from happening, but the real cause of the duplication is
2383 // unknown. What we know is that the deduplication avoids exponential
2384 // amount of predicates being propagated when processing deeply nested
2385 // types.
2386 //
2387 // This code is hot enough that it's worth avoiding the allocation
2388 // required for the FxHashSet when possible. Special-casing lengths 0,
2389 // 1 and 2 covers roughly 75-80% of the cases.
2390 if obligations.len() <= 1 {
2391 // No possibility of duplicates.
2392 } else if obligations.len() == 2 {
2393 // Only two elements. Drop the second if they are equal.
2394 if obligations[0] == obligations[1] {
2395 obligations.truncate(1);
2396 }
2397 } else {
2398 // Three or more elements. Use a general deduplication process.
2399 let mut seen = FxHashSet::default();
2400 obligations.retain(|i| seen.insert(i.clone()));
2401 }
2402
2403 obligations
2404 }
2405}
2406
ba9703b0
XL
2407trait TraitObligationExt<'tcx> {
2408 fn derived_cause(
2409 &self,
2410 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2411 ) -> ObligationCause<'tcx>;
2412}
2413
2414impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
ba9703b0 2415 fn derived_cause(
74b04a01
XL
2416 &self,
2417 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
2418 ) -> ObligationCause<'tcx> {
2419 /*!
2420 * Creates a cause for obligations that are derived from
2421 * `obligation` by a recursive search (e.g., for a builtin
2422 * bound, or eventually a `auto trait Foo`). If `obligation`
2423 * is itself a derived obligation, this is just a clone, but
2424 * otherwise we create a "derived obligation" cause so as to
2425 * keep track of the original root obligation for error
2426 * reporting.
2427 */
2428
2429 let obligation = self;
2430
2431 // NOTE(flaper87): As of now, it keeps track of the whole error
2432 // chain. Ideally, we should have a way to configure this either
2433 // by using -Z verbose or just a CLI argument.
2434 let derived_cause = DerivedObligationCause {
5099ac24 2435 parent_trait_pred: obligation.predicate,
a2a8927a 2436 parent_code: obligation.cause.clone_code(),
74b04a01
XL
2437 };
2438 let derived_code = variant(derived_cause);
2439 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2440 }
2441}
2442
2443impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2444 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2445 TraitObligationStackList::with(self)
2446 }
2447
2448 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2449 self.previous.cache
2450 }
2451
2452 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2453 self.list()
2454 }
2455
2456 /// Indicates that attempting to evaluate this stack entry
2457 /// required accessing something from the stack at depth `reached_depth`.
2458 fn update_reached_depth(&self, reached_depth: usize) {
2459 assert!(
17df50a5 2460 self.depth >= reached_depth,
74b04a01
XL
2461 "invoked `update_reached_depth` with something under this stack: \
2462 self.depth={} reached_depth={}",
2463 self.depth,
2464 reached_depth,
2465 );
29967ef6 2466 debug!(reached_depth, "update_reached_depth");
74b04a01
XL
2467 let mut p = self;
2468 while reached_depth < p.depth {
a2a8927a 2469 debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
74b04a01
XL
2470 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2471 p = p.previous.head.unwrap();
2472 }
2473 }
2474}
2475
2476/// The "provisional evaluation cache" is used to store intermediate cache results
2477/// when solving auto traits. Auto traits are unusual in that they can support
2478/// cycles. So, for example, a "proof tree" like this would be ok:
2479///
2480/// - `Foo<T>: Send` :-
2481/// - `Bar<T>: Send` :-
2482/// - `Foo<T>: Send` -- cycle, but ok
2483/// - `Baz<T>: Send`
2484///
2485/// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2486/// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2487/// For non-auto traits, this cycle would be an error, but for auto traits (because
2488/// they are coinductive) it is considered ok.
2489///
2490/// However, there is a complication: at the point where we have
2491/// "proven" `Bar<T>: Send`, we have in fact only proven it
2492/// *provisionally*. In particular, we proved that `Bar<T>: Send`
2493/// *under the assumption* that `Foo<T>: Send`. But what if we later
2494/// find out this assumption is wrong? Specifically, we could
2495/// encounter some kind of error proving `Baz<T>: Send`. In that case,
2496/// `Bar<T>: Send` didn't turn out to be true.
2497///
2498/// In Issue #60010, we found a bug in rustc where it would cache
2499/// these intermediate results. This was fixed in #60444 by disabling
2500/// *all* caching for things involved in a cycle -- in our example,
2501/// that would mean we don't cache that `Bar<T>: Send`. But this led
2502/// to large slowdowns.
2503///
2504/// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2505/// first requires proving `Bar<T>: Send` (which is true:
2506///
2507/// - `Foo<T>: Send` :-
2508/// - `Bar<T>: Send` :-
2509/// - `Foo<T>: Send` -- cycle, but ok
2510/// - `Baz<T>: Send`
2511/// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2512/// - `*const T: Send` -- but what if we later encounter an error?
2513///
2514/// The *provisional evaluation cache* resolves this issue. It stores
2515/// cache results that we've proven but which were involved in a cycle
2516/// in some way. We track the minimal stack depth (i.e., the
2517/// farthest from the top of the stack) that we are dependent on.
2518/// The idea is that the cache results within are all valid -- so long as
2519/// none of the nodes in between the current node and the node at that minimum
2520/// depth result in an error (in which case the cached results are just thrown away).
2521///
2522/// During evaluation, we consult this provisional cache and rely on
2523/// it. Accessing a cached value is considered equivalent to accessing
2524/// a result at `reached_depth`, so it marks the *current* solution as
2525/// provisional as well. If an error is encountered, we toss out any
2526/// provisional results added from the subtree that encountered the
2527/// error. When we pop the node at `reached_depth` from the stack, we
2528/// can commit all the things that remain in the provisional cache.
2529struct ProvisionalEvaluationCache<'tcx> {
2530 /// next "depth first number" to issue -- just a counter
2531 dfn: Cell<usize>,
2532
74b04a01
XL
2533 /// Map from cache key to the provisionally evaluated thing.
2534 /// The cache entries contain the result but also the DFN in which they
2535 /// were added. The DFN is used to clear out values on failure.
2536 ///
2537 /// Imagine we have a stack like:
2538 ///
2539 /// - `A B C` and we add a cache for the result of C (DFN 2)
2540 /// - Then we have a stack `A B D` where `D` has DFN 3
2541 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2542 /// - `E` generates various cache entries which have cyclic dependices on `B`
2543 /// - `A B D E F` and so forth
2544 /// - the DFN of `F` for example would be 5
2545 /// - then we determine that `E` is in error -- we will then clear
2546 /// all cache values whose DFN is >= 4 -- in this case, that
2547 /// means the cached value for `F`.
a2a8927a 2548 map: RefCell<FxHashMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
74b04a01
XL
2549}
2550
2551/// A cache value for the provisional cache: contains the depth-first
2552/// number (DFN) and result.
2553#[derive(Copy, Clone, Debug)]
2554struct ProvisionalEvaluation {
2555 from_dfn: usize,
17df50a5 2556 reached_depth: usize,
74b04a01 2557 result: EvaluationResult,
5099ac24
FG
2558 /// The `DepNodeIndex` created for the `evaluate_stack` call for this provisional
2559 /// evaluation. When we create an entry in the evaluation cache using this provisional
2560 /// cache entry (see `on_completion`), we use this `dep_node` to ensure that future reads from
2561 /// the cache will have all of the necessary incr comp dependencies tracked.
2562 dep_node: DepNodeIndex,
74b04a01
XL
2563}
2564
2565impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
2566 fn default() -> Self {
17df50a5 2567 Self { dfn: Cell::new(0), map: Default::default() }
74b04a01
XL
2568 }
2569}
2570
2571impl<'tcx> ProvisionalEvaluationCache<'tcx> {
2572 /// Get the next DFN in sequence (basically a counter).
2573 fn next_dfn(&self) -> usize {
2574 let result = self.dfn.get();
2575 self.dfn.set(result + 1);
2576 result
2577 }
2578
2579 /// Check the provisional cache for any result for
2580 /// `fresh_trait_ref`. If there is a hit, then you must consider
2581 /// it an access to the stack slots at depth
17df50a5
XL
2582 /// `reached_depth` (from the returned value).
2583 fn get_provisional(
2584 &self,
a2a8927a 2585 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
17df50a5 2586 ) -> Option<ProvisionalEvaluation> {
74b04a01 2587 debug!(
a2a8927a 2588 ?fresh_trait_pred,
29967ef6 2589 "get_provisional = {:#?}",
a2a8927a 2590 self.map.borrow().get(&fresh_trait_pred),
74b04a01 2591 );
a2a8927a 2592 Some(*self.map.borrow().get(&fresh_trait_pred)?)
74b04a01
XL
2593 }
2594
2595 /// Insert a provisional result into the cache. The result came
2596 /// from the node with the given DFN. It accessed a minimum depth
a2a8927a 2597 /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
74b04a01
XL
2598 /// and resulted in `result`.
2599 fn insert_provisional(
2600 &self,
2601 from_dfn: usize,
2602 reached_depth: usize,
a2a8927a 2603 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
74b04a01 2604 result: EvaluationResult,
5099ac24 2605 dep_node: DepNodeIndex,
74b04a01 2606 ) {
a2a8927a 2607 debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
74b04a01 2608
17df50a5
XL
2609 let mut map = self.map.borrow_mut();
2610
2611 // Subtle: when we complete working on the DFN `from_dfn`, anything
2612 // that remains in the provisional cache must be dependent on some older
2613 // stack entry than `from_dfn`. We have to update their depth with our transitive
2614 // depth in that case or else it would be referring to some popped note.
2615 //
2616 // Example:
2617 // A (reached depth 0)
2618 // ...
2619 // B // depth 1 -- reached depth = 0
2620 // C // depth 2 -- reached depth = 1 (should be 0)
2621 // B
2622 // A // depth 0
2623 // D (reached depth 1)
2624 // C (cache -- reached depth = 2)
2625 for (_k, v) in &mut *map {
2626 if v.from_dfn >= from_dfn {
2627 v.reached_depth = reached_depth.min(v.reached_depth);
2628 }
2629 }
74b04a01 2630
5099ac24
FG
2631 map.insert(
2632 fresh_trait_pred,
2633 ProvisionalEvaluation { from_dfn, reached_depth, result, dep_node },
2634 );
74b04a01
XL
2635 }
2636
2637 /// Invoked when the node with dfn `dfn` does not get a successful
2638 /// result. This will clear out any provisional cache entries
2639 /// that were added since `dfn` was created. This is because the
2640 /// provisional entries are things which must assume that the
2641 /// things on the stack at the time of their creation succeeded --
2642 /// since the failing node is presently at the top of the stack,
2643 /// these provisional entries must either depend on it or some
2644 /// ancestor of it.
2645 fn on_failure(&self, dfn: usize) {
29967ef6 2646 debug!(?dfn, "on_failure");
74b04a01
XL
2647 self.map.borrow_mut().retain(|key, eval| {
2648 if !eval.from_dfn >= dfn {
2649 debug!("on_failure: removing {:?}", key);
2650 false
2651 } else {
2652 true
2653 }
2654 });
2655 }
2656
2657 /// Invoked when the node at depth `depth` completed without
2658 /// depending on anything higher in the stack (if that completion
2659 /// was a failure, then `on_failure` should have been invoked
2660 /// already). The callback `op` will be invoked for each
2661 /// provisional entry that we can now confirm.
17df50a5
XL
2662 ///
2663 /// Note that we may still have provisional cache items remaining
2664 /// in the cache when this is done. For example, if there is a
2665 /// cycle:
2666 ///
2667 /// * A depends on...
2668 /// * B depends on A
2669 /// * C depends on...
2670 /// * D depends on C
2671 /// * ...
2672 ///
2673 /// Then as we complete the C node we will have a provisional cache
2674 /// with results for A, B, C, and D. This method would clear out
2675 /// the C and D results, but leave A and B provisional.
2676 ///
2677 /// This is determined based on the DFN: we remove any provisional
2678 /// results created since `dfn` started (e.g., in our example, dfn
2679 /// would be 2, representing the C node, and hence we would
2680 /// remove the result for D, which has DFN 3, but not the results for
2681 /// A and B, which have DFNs 0 and 1 respectively).
74b04a01
XL
2682 fn on_completion(
2683 &self,
17df50a5 2684 dfn: usize,
5099ac24 2685 mut op: impl FnMut(ty::PolyTraitPredicate<'tcx>, EvaluationResult, DepNodeIndex),
74b04a01 2686 ) {
17df50a5 2687 debug!(?dfn, "on_completion");
74b04a01 2688
a2a8927a 2689 for (fresh_trait_pred, eval) in
17df50a5
XL
2690 self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
2691 {
a2a8927a 2692 debug!(?fresh_trait_pred, ?eval, "on_completion");
74b04a01 2693
5099ac24 2694 op(fresh_trait_pred, eval.result, eval.dep_node);
74b04a01 2695 }
74b04a01
XL
2696 }
2697}
2698
2699#[derive(Copy, Clone)]
2700struct TraitObligationStackList<'o, 'tcx> {
2701 cache: &'o ProvisionalEvaluationCache<'tcx>,
2702 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
2703}
2704
2705impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
2706 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2707 TraitObligationStackList { cache, head: None }
2708 }
2709
2710 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
2711 TraitObligationStackList { cache: r.cache(), head: Some(r) }
2712 }
2713
2714 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2715 self.head
2716 }
2717
2718 fn depth(&self) -> usize {
2719 if let Some(head) = self.head { head.depth } else { 0 }
2720 }
2721}
2722
2723impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
2724 type Item = &'o TraitObligationStack<'o, 'tcx>;
2725
2726 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
fc512014
XL
2727 let o = self.head?;
2728 *self = o.previous;
2729 Some(o)
74b04a01
XL
2730 }
2731}
2732
2733impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
2734 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2735 write!(f, "TraitObligationStack({:?})", self.obligation)
2736 }
2737}
5099ac24
FG
2738
2739pub enum ProjectionMatchesProjection {
2740 Yes,
2741 Ambiguous,
2742 No,
2743}