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