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::fmt::{self, Display};
7use std::ops::ControlFlow;
8use std::{assert_matches, cmp};
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, DeepRejectCtxt, GenericArgsRef, PolyProjectionPredicate,
30SizedTraitKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, TypingMode, Upcast, elaborate,
31may_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 with_query_mode(
203 infcx: &'cx InferCtxt<'tcx>,
204 query_mode: TraitQueryMode,
205 ) -> SelectionContext<'cx, 'tcx> {
206{
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:206",
"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(206u32),
::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");
207SelectionContext { query_mode, ..SelectionContext::new(infcx) }
208 }
209210/// Enables tracking of intercrate ambiguity causes. See
211 /// the documentation of [`Self::intercrate_ambiguity_causes`] for more.
212pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
213match self.infcx.typing_mode() {
TypingMode::Coherence => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"TypingMode::Coherence", ::core::option::Option::None);
}
};assert_matches!(self.infcx.typing_mode(), TypingMode::Coherence);
214if !self.intercrate_ambiguity_causes.is_none() {
::core::panicking::panic("assertion failed: self.intercrate_ambiguity_causes.is_none()")
};assert!(self.intercrate_ambiguity_causes.is_none());
215self.intercrate_ambiguity_causes = Some(FxIndexSet::default());
216{
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:216",
"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(216u32),
::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");
217 }
218219/// Gets the intercrate ambiguity causes collected since tracking
220 /// was enabled and disables tracking at the same time. If
221 /// tracking is not enabled, just returns an empty vector.
222pub fn take_intercrate_ambiguity_causes(
223&mut self,
224 ) -> FxIndexSet<IntercrateAmbiguityCause<'tcx>> {
225match self.infcx.typing_mode() {
TypingMode::Coherence => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"TypingMode::Coherence", ::core::option::Option::None);
}
};assert_matches!(self.infcx.typing_mode(), TypingMode::Coherence);
226self.intercrate_ambiguity_causes.take().unwrap_or_default()
227 }
228229pub fn tcx(&self) -> TyCtxt<'tcx> {
230self.infcx.tcx
231 }
232233///////////////////////////////////////////////////////////////////////////
234 // Selection
235 //
236 // The selection phase tries to identify *how* an obligation will
237 // be resolved. For example, it will identify which impl or
238 // parameter bound is to be used. The process can be inconclusive
239 // if the self type in the obligation is not fully inferred. Selection
240 // can result in an error in one of two ways:
241 //
242 // 1. If no applicable impl or parameter bound can be found.
243 // 2. If the output type parameters in the obligation do not match
244 // those specified by the impl/bound. For example, if the obligation
245 // is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
246 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
247248/// Attempts to satisfy the obligation. If successful, this will affect the surrounding
249 /// type environment by performing unification.
250x;#[instrument(level = "debug", skip(self), ret)]251pub fn poly_select(
252&mut self,
253 obligation: &PolyTraitObligation<'tcx>,
254 ) -> SelectionResult<'tcx, Selection<'tcx>> {
255assert!(!self.infcx.next_trait_solver());
256257let candidate = match self.select_from_obligation(obligation) {
258Err(SelectionError::Overflow(OverflowError::Canonical)) => {
259// In standard mode, overflow must have been caught and reported
260 // earlier.
261assert!(self.query_mode == TraitQueryMode::Canonical);
262return Err(SelectionError::Overflow(OverflowError::Canonical));
263 }
264Err(e) => {
265return Err(e);
266 }
267Ok(None) => {
268return Ok(None);
269 }
270Ok(Some(candidate)) => candidate,
271 };
272273match self.confirm_candidate(obligation, candidate) {
274Err(SelectionError::Overflow(OverflowError::Canonical)) => {
275assert!(self.query_mode == TraitQueryMode::Canonical);
276Err(SelectionError::Overflow(OverflowError::Canonical))
277 }
278Err(e) => Err(e),
279Ok(candidate) => Ok(Some(candidate)),
280 }
281 }
282283pub fn select(
284&mut self,
285 obligation: &TraitObligation<'tcx>,
286 ) -> SelectionResult<'tcx, Selection<'tcx>> {
287if self.infcx.next_trait_solver() {
288return self.infcx.select_in_new_trait_solver(obligation);
289 }
290291self.poly_select(&Obligation {
292 cause: obligation.cause.clone(),
293 param_env: obligation.param_env,
294 predicate: ty::Binder::dummy(obligation.predicate),
295 recursion_depth: obligation.recursion_depth,
296 })
297 }
298299fn select_from_obligation(
300&mut self,
301 obligation: &PolyTraitObligation<'tcx>,
302 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
303if 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());
304305let pec = &ProvisionalEvaluationCache::default();
306let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
307308self.candidate_from_obligation(&stack)
309 }
310311x;#[instrument(level = "debug", skip(self), ret)]312fn candidate_from_obligation<'o>(
313&mut self,
314 stack: &TraitObligationStack<'o, 'tcx>,
315 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
316debug_assert!(!self.infcx.next_trait_solver());
317// Watch out for overflow. This intentionally bypasses (and does
318 // not update) the cache.
319self.check_recursion_limit(stack.obligation, stack.obligation)?;
320321// Check the cache. Note that we freshen the trait-ref
322 // separately rather than using `stack.fresh_trait_pred` --
323 // this is because we want the unbound variables to be
324 // replaced with fresh types starting from index 0.
325let cache_fresh_trait_pred =
326 stack.obligation.predicate.fold_with(&mut TypeFreshener::new(self.infcx));
327debug!(?cache_fresh_trait_pred);
328debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
329330if let Some(c) =
331self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
332 {
333debug!("CACHE HIT");
334return c;
335 }
336337// If no match, compute result and insert into cache.
338 //
339 // FIXME(nikomatsakis) -- this cache is not taking into
340 // account cycles that may have occurred in forming the
341 // candidate. I don't know of any specific problems that
342 // result but it seems awfully suspicious.
343let (candidate, dep_node) =
344self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
345346debug!("CACHE MISS");
347self.insert_candidate_cache(
348 stack.obligation.param_env,
349 cache_fresh_trait_pred,
350 dep_node,
351 candidate.clone(),
352 );
353 candidate
354 }
355356fn candidate_from_obligation_no_cache<'o>(
357&mut self,
358 stack: &TraitObligationStack<'o, 'tcx>,
359 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
360if let Err(conflict) = self.is_knowable(stack) {
361{
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:361",
"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(361u32),
::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");
362if self.intercrate_ambiguity_causes.is_some() {
363{
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:363",
"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(363u32),
::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");
364// Heuristics: show the diagnostics when there are no candidates in crate.
365if let Ok(candidate_set) = self.assemble_candidates(stack) {
366let mut no_candidates_apply = true;
367368for c in candidate_set.vec.iter() {
369if self.evaluate_candidate(stack, c)?.may_apply() {
370 no_candidates_apply = false;
371break;
372 }
373 }
374375if !candidate_set.ambiguous && no_candidates_apply {
376let trait_ref = self.infcx.resolve_vars_if_possible(
377stack.obligation.predicate.skip_binder().trait_ref,
378 );
379if !trait_ref.references_error() {
380let self_ty = trait_ref.self_ty();
381let self_ty = self_ty.has_concrete_skeleton().then(|| self_ty);
382let cause = if let Conflict::Upstream = conflict {
383 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty }
384 } else {
385 IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty }
386 };
387{
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:387",
"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(387u32),
::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");
388self.intercrate_ambiguity_causes.as_mut().unwrap().insert(cause);
389 }
390 }
391 }
392 }
393return Ok(None);
394 }
395396let candidate_set = self.assemble_candidates(stack)?;
397398if candidate_set.ambiguous {
399{
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:399",
"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(399u32),
::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");
400return Ok(None);
401 }
402403let candidates = candidate_set.vec;
404405{
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", "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());
406407// At this point, we know that each of the entries in the
408 // candidate set is *individually* applicable. Now we have to
409 // figure out if they contain mutual incompatibilities. This
410 // frequently arises if we have an unconstrained input type --
411 // for example, we are looking for `$0: Eq` where `$0` is some
412 // unconstrained type variable. In that case, we'll get a
413 // candidate which assumes $0 == int, one that assumes `$0 ==
414 // usize`, etc. This spells an ambiguity.
415416let mut candidates = self.filter_impls(candidates, stack.obligation);
417418// If there is more than one candidate, first winnow them down
419 // by considering extra conditions (nested obligations and so
420 // forth). We don't winnow if there is exactly one
421 // candidate. This is a relatively minor distinction but it
422 // can lead to better inference and error-reporting. An
423 // example would be if there was an impl:
424 //
425 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
426 //
427 // and we were to see some code `foo.push_clone()` where `boo`
428 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
429 // we were to winnow, we'd wind up with zero candidates.
430 // Instead, we select the right impl now but report "`Bar` does
431 // not implement `Clone`".
432if candidates.len() == 1 {
433return self.filter_reservation_impls(candidates.pop().unwrap());
434 }
435436// Winnow, but record the exact outcome of evaluation, which
437 // is needed for specialization. Propagate overflow if it occurs.
438let candidates = candidates439 .into_iter()
440 .map(|c| match self.evaluate_candidate(stack, &c) {
441Ok(eval) if eval.may_apply() => {
442Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
443 }
444Ok(_) => Ok(None),
445Err(OverflowError::Canonical) => {
446Err(SelectionError::Overflow(OverflowError::Canonical))
447 }
448Err(OverflowError::Error(e)) => {
449Err(SelectionError::Overflow(OverflowError::Error(e)))
450 }
451 })
452 .flat_map(Result::transpose)
453 .collect::<Result<Vec<_>, _>>()?;
454455{
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:455",
"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(455u32),
::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());
456// If there are *NO* candidates, then there are no impls --
457 // that we know of, anyway. Note that in the case where there
458 // are unbound type variables within the obligation, it might
459 // be the case that you could still satisfy the obligation
460 // from another crate by instantiating the type variables with
461 // a type from another crate that does have an impl. This case
462 // is checked for in `evaluate_stack` (and hence users
463 // who might care about this case, like coherence, should use
464 // that function).
465if candidates.is_empty() {
466// If there's an error type, 'downgrade' our result from
467 // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
468 // emitting additional spurious errors, since we're guaranteed
469 // to have emitted at least one.
470if stack.obligation.predicate.references_error() {
471{
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:471",
"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(471u32),
::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");
472Ok(None)
473 } else {
474Err(SelectionError::Unimplemented)
475 }
476 } else {
477let has_non_region_infer = stack.obligation.predicate.has_non_region_infer();
478let candidate_preference_mode =
479CandidatePreferenceMode::compute(self.tcx(), stack.obligation.predicate.def_id());
480if let Some(candidate) =
481self.winnow_candidates(has_non_region_infer, candidate_preference_mode, candidates)
482 {
483self.filter_reservation_impls(candidate)
484 } else {
485Ok(None)
486 }
487 }
488 }
489490///////////////////////////////////////////////////////////////////////////
491 // EVALUATION
492 //
493 // Tests whether an obligation can be selected or whether an impl
494 // can be applied to particular types. It skips the "confirmation"
495 // step and hence completely ignores output type parameters.
496 //
497 // The result is "true" if the obligation *may* hold and "false" if
498 // we can be sure it does not.
499500/// Evaluates whether the obligation `obligation` can be satisfied
501 /// and returns an `EvaluationResult`. This is meant for the
502 /// *initial* call.
503 ///
504 /// Do not use this directly, use `infcx.evaluate_obligation` instead.
505pub fn evaluate_root_obligation(
506&mut self,
507 obligation: &PredicateObligation<'tcx>,
508 ) -> Result<EvaluationResult, OverflowError> {
509if true {
if !!self.infcx.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.infcx.next_trait_solver()")
};
};debug_assert!(!self.infcx.next_trait_solver());
510self.evaluation_probe(|this| {
511let goal =
512this.infcx.resolve_vars_if_possible((obligation.predicate, obligation.param_env));
513let mut result = this.evaluate_predicate_recursively(
514TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
515obligation.clone(),
516 )?;
517// If the predicate has done any inference, then downgrade the
518 // result to ambiguous.
519if this.infcx.resolve_vars_if_possible(goal) != goal {
520result = result.max(EvaluatedToAmbig);
521 }
522Ok(result)
523 })
524 }
525526/// Computes the evaluation result of `op`, discarding any constraints.
527 ///
528 /// This also runs for leak check to allow higher ranked region errors to impact
529 /// selection. By default it checks for leaks from all universes created inside of
530 /// `op`, but this can be overwritten if necessary.
531fn evaluation_probe(
532&mut self,
533 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
534 ) -> Result<EvaluationResult, OverflowError> {
535self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
536let outer_universe = self.infcx.universe();
537let result = op(self)?;
538539match self.infcx.leak_check(outer_universe, Some(snapshot)) {
540Ok(()) => {}
541Err(_) => return Ok(EvaluatedToErr),
542 }
543544if self.infcx.opaque_types_added_in_snapshot(snapshot) {
545return Ok(result.max(EvaluatedToOkModuloOpaqueTypes));
546 }
547548if self.infcx.region_constraints_added_in_snapshot(snapshot) {
549Ok(result.max(EvaluatedToOkModuloRegions))
550 } else {
551Ok(result)
552 }
553 })
554 }
555556/// Evaluates the predicates in `predicates` recursively. This may
557 /// guide inference. If this is not desired, run it inside of a
558 /// is run within an inference probe.
559 /// `probe`.
560#[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(560u32),
::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")]561fn evaluate_predicates_recursively<'o, I>(
562&mut self,
563 stack: TraitObligationStackList<'o, 'tcx>,
564 predicates: I,
565 ) -> Result<EvaluationResult, OverflowError>
566where
567I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
568 {
569let mut result = EvaluatedToOk;
570for mut obligation in predicates {
571 obligation.set_depth_from_parent(stack.depth());
572let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
573if let EvaluatedToErr = eval {
574// fast-path - EvaluatedToErr is the top of the lattice,
575 // so we don't need to look on the other predicates.
576return Ok(EvaluatedToErr);
577 } else {
578 result = cmp::max(result, eval);
579 }
580 }
581Ok(result)
582 }
583584x;#[instrument(
585 level = "debug",
586 skip(self, previous_stack),
587 fields(previous_stack = ?previous_stack.head())
588 ret,
589 )]590fn evaluate_predicate_recursively<'o>(
591&mut self,
592 previous_stack: TraitObligationStackList<'o, 'tcx>,
593 obligation: PredicateObligation<'tcx>,
594 ) -> Result<EvaluationResult, OverflowError> {
595debug_assert!(!self.infcx.next_trait_solver());
596// `previous_stack` stores a `PolyTraitObligation`, while `obligation` is
597 // a `PredicateObligation`. These are distinct types, so we can't
598 // use any `Option` combinator method that would force them to be
599 // the same.
600match previous_stack.head() {
601Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
602None => self.check_recursion_limit(&obligation, &obligation)?,
603 }
604605if sizedness_fast_path(self.tcx(), obligation.predicate, obligation.param_env) {
606return Ok(EvaluatedToOk);
607 }
608609 ensure_sufficient_stack(|| {
610let bound_predicate = obligation.predicate.kind();
611match bound_predicate.skip_binder() {
612 ty::PredicateKind::Clause(ty::ClauseKind::Trait(t)) => {
613let t = bound_predicate.rebind(t);
614debug_assert!(!t.has_escaping_bound_vars());
615let obligation = obligation.with(self.tcx(), t);
616self.evaluate_trait_predicate_recursively(previous_stack, obligation)
617 }
618619 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(data)) => {
620self.infcx.enter_forall(bound_predicate.rebind(data), |data| {
621match effects::evaluate_host_effect_obligation(
622self,
623&obligation.with(self.tcx(), data),
624 ) {
625Ok(nested) => {
626self.evaluate_predicates_recursively(previous_stack, nested)
627 }
628Err(effects::EvaluationFailure::Ambiguous) => Ok(EvaluatedToAmbig),
629Err(effects::EvaluationFailure::NoSolution) => Ok(EvaluatedToErr),
630 }
631 })
632 }
633634 ty::PredicateKind::Subtype(p) => {
635let p = bound_predicate.rebind(p);
636// Does this code ever run?
637match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
638Ok(Ok(InferOk { obligations, .. })) => {
639self.evaluate_predicates_recursively(previous_stack, obligations)
640 }
641Ok(Err(_)) => Ok(EvaluatedToErr),
642Err(..) => Ok(EvaluatedToAmbig),
643 }
644 }
645646 ty::PredicateKind::Coerce(p) => {
647let p = bound_predicate.rebind(p);
648// Does this code ever run?
649match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
650Ok(Ok(InferOk { obligations, .. })) => {
651self.evaluate_predicates_recursively(previous_stack, obligations)
652 }
653Ok(Err(_)) => Ok(EvaluatedToErr),
654Err(..) => Ok(EvaluatedToAmbig),
655 }
656 }
657658 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
659if term.is_trivially_wf(self.tcx()) {
660return Ok(EvaluatedToOk);
661 }
662663// So, there is a bit going on here. First, `WellFormed` predicates
664 // are coinductive, like trait predicates with auto traits.
665 // This means that we need to detect if we have recursively
666 // evaluated `WellFormed(X)`. Otherwise, we would run into
667 // a "natural" overflow error.
668 //
669 // Now, the next question is whether we need to do anything
670 // special with caching. Considering the following tree:
671 // - `WF(Foo<T>)`
672 // - `Bar<T>: Send`
673 // - `WF(Foo<T>)`
674 // - `Foo<T>: Trait`
675 // In this case, the innermost `WF(Foo<T>)` should return
676 // `EvaluatedToOk`, since it's coinductive. Then if
677 // `Bar<T>: Send` is resolved to `EvaluatedToOk`, it can be
678 // inserted into a cache (because without thinking about `WF`
679 // goals, it isn't in a cycle). If `Foo<T>: Trait` later doesn't
680 // hold, then `Bar<T>: Send` shouldn't hold. Therefore, we
681 // *do* need to keep track of coinductive cycles.
682683let cache = previous_stack.cache;
684let dfn = cache.next_dfn();
685686for stack_term in previous_stack.cache.wf_args.borrow().iter().rev() {
687if stack_term.0 != term {
688continue;
689 }
690debug!("WellFormed({:?}) on stack", term);
691if let Some(stack) = previous_stack.head {
692// Okay, let's imagine we have two different stacks:
693 // `T: NonAutoTrait -> WF(T) -> T: NonAutoTrait`
694 // `WF(T) -> T: NonAutoTrait -> WF(T)`
695 // Because of this, we need to check that all
696 // predicates between the WF goals are coinductive.
697 // Otherwise, we can say that `T: NonAutoTrait` is
698 // true.
699 // Let's imagine we have a predicate stack like
700 // `Foo: Bar -> WF(T) -> T: NonAutoTrait -> T: Auto`
701 // depth ^1 ^2 ^3
702 // and the current predicate is `WF(T)`. `wf_args`
703 // would contain `(T, 1)`. We want to check all
704 // trait predicates greater than `1`. The previous
705 // stack would be `T: Auto`.
706let cycle = stack.iter().take_while(|s| s.depth > stack_term.1);
707let tcx = self.tcx();
708let cycle = cycle.map(|stack| stack.obligation.predicate.upcast(tcx));
709if self.coinductive_match(cycle) {
710 stack.update_reached_depth(stack_term.1);
711return Ok(EvaluatedToOk);
712 } else {
713return Ok(EvaluatedToAmbigStackDependent);
714 }
715 }
716return Ok(EvaluatedToOk);
717 }
718719match wf::obligations(
720self.infcx,
721 obligation.param_env,
722 obligation.cause.body_id,
723 obligation.recursion_depth + 1,
724 term,
725 obligation.cause.span,
726 ) {
727Some(obligations) => {
728 cache.wf_args.borrow_mut().push((term, previous_stack.depth()));
729let result =
730self.evaluate_predicates_recursively(previous_stack, obligations);
731 cache.wf_args.borrow_mut().pop();
732733let result = result?;
734735if !result.must_apply_modulo_regions() {
736 cache.on_failure(dfn);
737 }
738739 cache.on_completion(dfn);
740741Ok(result)
742 }
743None => Ok(EvaluatedToAmbig),
744 }
745 }
746747 ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(pred)) => {
748// A global type with no free lifetimes or generic parameters
749 // outlives anything.
750if pred.0.has_free_regions()
751 || pred.0.has_bound_regions()
752 || pred.0.has_non_region_infer()
753 || pred.0.has_non_region_infer()
754 {
755Ok(EvaluatedToOkModuloRegions)
756 } else {
757Ok(EvaluatedToOk)
758 }
759 }
760761 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..)) => {
762// We do not consider region relationships when evaluating trait matches.
763Ok(EvaluatedToOkModuloRegions)
764 }
765766 ty::PredicateKind::DynCompatible(trait_def_id) => {
767if self.tcx().is_dyn_compatible(trait_def_id) {
768Ok(EvaluatedToOk)
769 } else {
770Ok(EvaluatedToErr)
771 }
772 }
773774 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
775let data = bound_predicate.rebind(data);
776let project_obligation = obligation.with(self.tcx(), data);
777match project::poly_project_and_unify_term(self, &project_obligation) {
778 ProjectAndUnifyResult::Holds(mut subobligations) => {
779'compute_res: {
780// If we've previously marked this projection as 'complete', then
781 // use the final cached result (either `EvaluatedToOk` or
782 // `EvaluatedToOkModuloRegions`), and skip re-evaluating the
783 // sub-obligations.
784if let Some(key) =
785 ProjectionCacheKey::from_poly_projection_obligation(
786self,
787&project_obligation,
788 )
789 && let Some(cached_res) = self
790.infcx
791 .inner
792 .borrow_mut()
793 .projection_cache()
794 .is_complete(key)
795 {
796break 'compute_res Ok(cached_res);
797 }
798799// Need to explicitly set the depth of nested goals here as
800 // projection obligations can cycle by themselves and in
801 // `evaluate_predicates_recursively` we only add the depth
802 // for parent trait goals because only these get added to the
803 // `TraitObligationStackList`.
804for subobligation in subobligations.iter_mut() {
805 subobligation.set_depth_from_parent(obligation.recursion_depth);
806 }
807let res = self.evaluate_predicates_recursively(
808 previous_stack,
809 subobligations,
810 );
811if let Ok(eval_rslt) = res
812 && (eval_rslt == EvaluatedToOk
813 || eval_rslt == EvaluatedToOkModuloRegions)
814 && let Some(key) =
815 ProjectionCacheKey::from_poly_projection_obligation(
816self,
817&project_obligation,
818 )
819 {
820// If the result is something that we can cache, then mark this
821 // entry as 'complete'. This will allow us to skip evaluating the
822 // subobligations at all the next time we evaluate the projection
823 // predicate.
824self.infcx
825 .inner
826 .borrow_mut()
827 .projection_cache()
828 .complete(key, eval_rslt);
829 }
830 res
831 }
832 }
833 ProjectAndUnifyResult::FailedNormalization => Ok(EvaluatedToAmbig),
834 ProjectAndUnifyResult::Recursive => Ok(EvaluatedToAmbigStackDependent),
835 ProjectAndUnifyResult::MismatchedProjectionTypes(_) => Ok(EvaluatedToErr),
836 }
837 }
838839 ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(symbol)) => {
840if may_use_unstable_feature(self.infcx, obligation.param_env, symbol) {
841Ok(EvaluatedToOk)
842 } else {
843Ok(EvaluatedToAmbig)
844 }
845 }
846847 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(uv)) => {
848match const_evaluatable::is_const_evaluatable(
849self.infcx,
850 uv,
851 obligation.param_env,
852 obligation.cause.span,
853 ) {
854Ok(()) => Ok(EvaluatedToOk),
855Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
856Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
857Err(_) => Ok(EvaluatedToErr),
858 }
859 }
860861 ty::PredicateKind::ConstEquate(c1, c2) => {
862let tcx = self.tcx();
863assert!(
864 tcx.features().generic_const_exprs(),
865"`ConstEquate` without a feature gate: {c1:?} {c2:?}",
866 );
867868 {
869let c1 = tcx.expand_abstract_consts(c1);
870let c2 = tcx.expand_abstract_consts(c2);
871debug!(
872"evaluate_predicate_recursively: equating consts:\nc1= {:?}\nc2= {:?}",
873 c1, c2
874 );
875876use rustc_hir::def::DefKind;
877match (c1.kind(), c2.kind()) {
878 (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b))
879if a.def == b.def
880 && matches!(
881 tcx.def_kind(a.def),
882 DefKind::AssocConst { .. }
883 ) =>
884 {
885if let Ok(InferOk { obligations, value: () }) = self
886.infcx
887 .at(&obligation.cause, obligation.param_env)
888// Can define opaque types as this is only reachable with
889 // `generic_const_exprs`
890.eq(
891 DefineOpaqueTypes::Yes,
892 ty::AliasTerm::from(a),
893 ty::AliasTerm::from(b),
894 )
895 {
896return self.evaluate_predicates_recursively(
897 previous_stack,
898 obligations,
899 );
900 }
901 }
902 (_, ty::ConstKind::Unevaluated(_))
903 | (ty::ConstKind::Unevaluated(_), _) => (),
904 (_, _) => {
905if let Ok(InferOk { obligations, value: () }) = self
906.infcx
907 .at(&obligation.cause, obligation.param_env)
908// Can define opaque types as this is only reachable with
909 // `generic_const_exprs`
910.eq(DefineOpaqueTypes::Yes, c1, c2)
911 {
912return self.evaluate_predicates_recursively(
913 previous_stack,
914 obligations,
915 );
916 }
917 }
918 }
919 }
920921let evaluate = |c: ty::Const<'tcx>| {
922if let ty::ConstKind::Unevaluated(_) = c.kind() {
923match crate::traits::try_evaluate_const(
924self.infcx,
925 c,
926 obligation.param_env,
927 ) {
928Ok(val) => Ok(val),
929Err(e) => Err(e),
930 }
931 } else {
932Ok(c)
933 }
934 };
935936match (evaluate(c1), evaluate(c2)) {
937 (Ok(c1), Ok(c2)) => {
938match self.infcx.at(&obligation.cause, obligation.param_env).eq(
939// Can define opaque types as this is only reachable with
940 // `generic_const_exprs`
941DefineOpaqueTypes::Yes,
942 c1,
943 c2,
944 ) {
945Ok(inf_ok) => self.evaluate_predicates_recursively(
946 previous_stack,
947 inf_ok.into_obligations(),
948 ),
949Err(_) => Ok(EvaluatedToErr),
950 }
951 }
952 (Err(EvaluateConstErr::InvalidConstParamTy(..)), _)
953 | (_, Err(EvaluateConstErr::InvalidConstParamTy(..))) => Ok(EvaluatedToErr),
954 (Err(EvaluateConstErr::EvaluationFailure(..)), _)
955 | (_, Err(EvaluateConstErr::EvaluationFailure(..))) => Ok(EvaluatedToErr),
956 (Err(EvaluateConstErr::HasGenericsOrInfers), _)
957 | (_, Err(EvaluateConstErr::HasGenericsOrInfers)) => {
958if c1.has_non_region_infer() || c2.has_non_region_infer() {
959Ok(EvaluatedToAmbig)
960 } else {
961// Two different constants using generic parameters ~> error.
962Ok(EvaluatedToErr)
963 }
964 }
965 }
966 }
967 ty::PredicateKind::NormalizesTo(..) => {
968bug!("NormalizesTo is only used by the new solver")
969 }
970 ty::PredicateKind::AliasRelate(..) => {
971bug!("AliasRelate is only used by the new solver")
972 }
973 ty::PredicateKind::Ambiguous => Ok(EvaluatedToAmbig),
974 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
975let ct = self.infcx.shallow_resolve_const(ct);
976let ct_ty = match ct.kind() {
977 ty::ConstKind::Infer(_) => {
978return Ok(EvaluatedToAmbig);
979 }
980 ty::ConstKind::Error(_) => return Ok(EvaluatedToOk),
981 ty::ConstKind::Value(cv) => cv.ty,
982 ty::ConstKind::Unevaluated(uv) => {
983self.tcx().type_of(uv.def).instantiate(self.tcx(), uv.args)
984 }
985// FIXME(generic_const_exprs): See comment in `fulfill.rs`
986ty::ConstKind::Expr(_) => return Ok(EvaluatedToOk),
987 ty::ConstKind::Placeholder(_) => {
988bug!("placeholder const {:?} in old solver", ct)
989 }
990 ty::ConstKind::Bound(_, _) => bug!("escaping bound vars in {:?}", ct),
991 ty::ConstKind::Param(param_ct) => {
992 param_ct.find_const_ty_from_env(obligation.param_env)
993 }
994 };
995996match self.infcx.at(&obligation.cause, obligation.param_env).eq(
997// Only really exercised by generic_const_exprs
998DefineOpaqueTypes::Yes,
999 ct_ty,
1000 ty,
1001 ) {
1002Ok(inf_ok) => self.evaluate_predicates_recursively(
1003 previous_stack,
1004 inf_ok.into_obligations(),
1005 ),
1006Err(_) => Ok(EvaluatedToErr),
1007 }
1008 }
1009 }
1010 })
1011 }
10121013x;#[instrument(skip(self, previous_stack), level = "debug", ret)]1014fn evaluate_trait_predicate_recursively<'o>(
1015&mut self,
1016 previous_stack: TraitObligationStackList<'o, 'tcx>,
1017mut obligation: PolyTraitObligation<'tcx>,
1018 ) -> Result<EvaluationResult, OverflowError> {
1019if !matches!(self.infcx.typing_mode(), TypingMode::Coherence)
1020 && obligation.is_global()
1021 && obligation.param_env.caller_bounds().iter().all(|bound| bound.has_param())
1022 {
1023// If a param env has no global bounds, global obligations do not
1024 // depend on its particular value in order to work, so we can clear
1025 // out the param env and get better caching.
1026debug!("in global");
1027 obligation.param_env = ty::ParamEnv::empty();
1028 }
10291030let stack = self.push_stack(previous_stack, &obligation);
1031let fresh_trait_pred = stack.fresh_trait_pred;
1032let param_env = obligation.param_env;
10331034debug!(?fresh_trait_pred);
10351036// If a trait predicate is in the (local or global) evaluation cache,
1037 // then we know it holds without cycles.
1038if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
1039debug!("CACHE HIT");
1040return Ok(result);
1041 }
10421043if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
1044debug!("PROVISIONAL CACHE HIT");
1045 stack.update_reached_depth(result.reached_depth);
1046return Ok(result.result);
1047 }
10481049// Check if this is a match for something already on the
1050 // stack. If so, we don't want to insert the result into the
1051 // main cache (it is cycle dependent) nor the provisional
1052 // cache (which is meant for things that have completed but
1053 // for a "backedge" -- this result *is* the backedge).
1054if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
1055return Ok(cycle_result);
1056 }
10571058let (result, dep_node) = self.in_task(|this| {
1059let mut result = this.evaluate_stack(&stack)?;
10601061// fix issue #103563, we don't normalize
1062 // nested obligations which produced by `TraitDef` candidate
1063 // (i.e. using bounds on assoc items as assumptions).
1064 // because we don't have enough information to
1065 // normalize these obligations before evaluating.
1066 // so we will try to normalize the obligation and evaluate again.
1067 // we will replace it with new solver in the future.
1068if EvaluationResult::EvaluatedToErr == result
1069 && fresh_trait_pred.has_aliases()
1070 && fresh_trait_pred.is_global()
1071 {
1072let mut nested_obligations = PredicateObligations::new();
1073let predicate = normalize_with_depth_to(
1074 this,
1075 param_env,
1076 obligation.cause.clone(),
1077 obligation.recursion_depth + 1,
1078 obligation.predicate,
1079&mut nested_obligations,
1080 );
1081if predicate != obligation.predicate {
1082let mut nested_result = EvaluationResult::EvaluatedToOk;
1083for obligation in nested_obligations {
1084 nested_result = cmp::max(
1085 this.evaluate_predicate_recursively(previous_stack, obligation)?,
1086 nested_result,
1087 );
1088 }
10891090if nested_result.must_apply_modulo_regions() {
1091let obligation = obligation.with(this.tcx(), predicate);
1092 result = cmp::max(
1093 nested_result,
1094 this.evaluate_trait_predicate_recursively(previous_stack, obligation)?,
1095 );
1096 }
1097 }
1098 }
10991100 Ok::<_, OverflowError>(result)
1101 });
11021103let result = result?;
11041105if !result.must_apply_modulo_regions() {
1106 stack.cache().on_failure(stack.dfn);
1107 }
11081109let reached_depth = stack.reached_depth.get();
1110if reached_depth >= stack.depth {
1111debug!("CACHE MISS");
1112self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
1113 stack.cache().on_completion(stack.dfn);
1114 } else {
1115debug!("PROVISIONAL");
1116debug!(
1117"caching provisionally because {:?} \
1118 is a cycle participant (at depth {}, reached depth {})",
1119 fresh_trait_pred, stack.depth, reached_depth,
1120 );
11211122 stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_pred, result);
1123 }
11241125Ok(result)
1126 }
11271128/// If there is any previous entry on the stack that precisely
1129 /// matches this obligation, then we can assume that the
1130 /// obligation is satisfied for now (still all other conditions
1131 /// must be met of course). One obvious case this comes up is
1132 /// marker traits like `Send`. Think of a linked list:
1133 ///
1134 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
1135 ///
1136 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
1137 /// `Option<Box<List<T>>>` is `Send`, and in turn
1138 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
1139 /// `Send`.
1140 ///
1141 /// Note that we do this comparison using the `fresh_trait_pred`
1142 /// fields. Because these have all been freshened using
1143 /// `self.freshener`, we can be sure that (a) this will not
1144 /// affect the inferencer state and (b) that if we see two
1145 /// fresh regions with the same index, they refer to the same
1146 /// unbound type variable.
1147fn check_evaluation_cycle(
1148&mut self,
1149 stack: &TraitObligationStack<'_, 'tcx>,
1150 ) -> Option<EvaluationResult> {
1151if let Some(cycle_depth) = stack1152 .iter()
1153 .skip(1) // Skip top-most frame.
1154.find(|prev| {
1155stack.obligation.param_env == prev.obligation.param_env
1156 && stack.fresh_trait_pred == prev.fresh_trait_pred
1157 })
1158 .map(|stack| stack.depth)
1159 {
1160{
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:1160",
"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(1160u32),
::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);
11611162// If we have a stack like `A B C D E A`, where the top of
1163 // the stack is the final `A`, then this will iterate over
1164 // `A, E, D, C, B` -- i.e., all the participants apart
1165 // from the cycle head. We mark them as participating in a
1166 // cycle. This suppresses caching for those nodes. See
1167 // `in_cycle` field for more details.
1168stack.update_reached_depth(cycle_depth);
11691170// Subtle: when checking for a coinductive cycle, we do
1171 // not compare using the "freshened trait refs" (which
1172 // have erased regions) but rather the fully explicit
1173 // trait refs. This is important because it's only a cycle
1174 // if the regions match exactly.
1175let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
1176let tcx = self.tcx();
1177let cycle = cycle.map(|stack| stack.obligation.predicate.upcast(tcx));
1178if self.coinductive_match(cycle) {
1179{
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:1179",
"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(1179u32),
::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");
1180Some(EvaluatedToOk)
1181 } else {
1182{
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:1182",
"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(1182u32),
::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");
1183Some(EvaluatedToAmbigStackDependent)
1184 }
1185 } else {
1186None1187 }
1188 }
11891190fn evaluate_stack<'o>(
1191&mut self,
1192 stack: &TraitObligationStack<'o, 'tcx>,
1193 ) -> Result<EvaluationResult, OverflowError> {
1194if true {
if !!self.infcx.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.infcx.next_trait_solver()")
};
};debug_assert!(!self.infcx.next_trait_solver());
1195// In intercrate mode, whenever any of the generics are unbound,
1196 // there can always be an impl. Even if there are no impls in
1197 // this crate, perhaps the type would be unified with
1198 // something from another crate that does provide an impl.
1199 //
1200 // In intra mode, we must still be conservative. The reason is
1201 // that we want to avoid cycles. Imagine an impl like:
1202 //
1203 // impl<T:Eq> Eq for Vec<T>
1204 //
1205 // and a trait reference like `$0 : Eq` where `$0` is an
1206 // unbound variable. When we evaluate this trait-reference, we
1207 // will unify `$0` with `Vec<$1>` (for some fresh variable
1208 // `$1`), on the condition that `$1 : Eq`. We will then wind
1209 // up with many candidates (since that are other `Eq` impls
1210 // that apply) and try to winnow things down. This results in
1211 // a recursive evaluation that `$1 : Eq` -- as you can
1212 // imagine, this is just where we started. To avoid that, we
1213 // check for unbound variables and return an ambiguous (hence possible)
1214 // match if we've seen this trait before.
1215 //
1216 // This suffices to allow chains like `FnMut` implemented in
1217 // terms of `Fn` etc, but we could probably make this more
1218 // precise still.
1219let unbound_input_types =
1220stack.fresh_trait_pred.skip_binder().trait_ref.args.types().any(|ty| ty.is_fresh());
12211222if unbound_input_types1223 && stack.iter().skip(1).any(|prev| {
1224stack.obligation.param_env == prev.obligation.param_env
1225 && self.match_fresh_trait_preds(stack.fresh_trait_pred, prev.fresh_trait_pred)
1226 })
1227 {
1228{
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:1228",
"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(1228u32),
::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");
1229return Ok(EvaluatedToAmbigStackDependent);
1230 }
12311232match self.candidate_from_obligation(stack) {
1233Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1234Ok(None) => Ok(EvaluatedToAmbig),
1235Err(SelectionError::Overflow(OverflowError::Canonical)) => {
1236Err(OverflowError::Canonical)
1237 }
1238Err(..) => Ok(EvaluatedToErr),
1239 }
1240 }
12411242/// For defaulted traits, we use a co-inductive strategy to solve, so
1243 /// that recursion is ok. This routine returns `true` if the top of the
1244 /// stack (`cycle[0]`):
1245 ///
1246 /// - is a coinductive trait: an auto-trait or `Sized`,
1247 /// - it also appears in the backtrace at some position `X`,
1248 /// - all the predicates at positions `X..` between `X` and the top are
1249 /// also coinductive traits.
1250pub(crate) fn coinductive_match<I>(&mut self, mut cycle: I) -> bool1251where
1252I: Iterator<Item = ty::Predicate<'tcx>>,
1253 {
1254cycle.all(|p| match p.kind().skip_binder() {
1255 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
1256self.infcx.tcx.trait_is_coinductive(data.def_id())
1257 }
1258 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => {
1259// FIXME(generic_const_exprs): GCE needs well-formedness predicates to be
1260 // coinductive, but GCE is on the way out anyways, so this should eventually
1261 // be replaced with `false`.
1262self.infcx.tcx.features().generic_const_exprs()
1263 }
1264_ => false,
1265 })
1266 }
12671268/// Further evaluates `candidate` to decide whether all type parameters match and whether nested
1269 /// obligations are met. Returns whether `candidate` remains viable after this further
1270 /// scrutiny.
1271x;#[instrument(
1272 level = "debug",
1273 skip(self, stack),
1274 fields(depth = stack.obligation.recursion_depth),
1275 ret
1276 )]1277fn evaluate_candidate<'o>(
1278&mut self,
1279 stack: &TraitObligationStack<'o, 'tcx>,
1280 candidate: &SelectionCandidate<'tcx>,
1281 ) -> Result<EvaluationResult, OverflowError> {
1282let mut result = self.evaluation_probe(|this| {
1283match this.confirm_candidate(stack.obligation, candidate.clone()) {
1284Ok(selection) => {
1285debug!(?selection);
1286 this.evaluate_predicates_recursively(
1287 stack.list(),
1288 selection.nested_obligations().into_iter(),
1289 )
1290 }
1291Err(..) => Ok(EvaluatedToErr),
1292 }
1293 })?;
12941295// If we erased any lifetimes, then we want to use
1296 // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
1297 // as your final result. The result will be cached using
1298 // the freshened trait predicate as a key, so we need
1299 // our result to be correct by *any* choice of original lifetimes,
1300 // not just the lifetime choice for this particular (non-erased)
1301 // predicate.
1302 // See issue #80691
1303if stack.fresh_trait_pred.has_erased_regions() {
1304 result = result.max(EvaluatedToOkModuloRegions);
1305 }
13061307Ok(result)
1308 }
13091310fn check_evaluation_cache(
1311&self,
1312 param_env: ty::ParamEnv<'tcx>,
1313 trait_pred: ty::PolyTraitPredicate<'tcx>,
1314 ) -> Option<EvaluationResult> {
1315let infcx = self.infcx;
1316let tcx = infcx.tcx;
1317if self.can_use_global_caches(param_env, trait_pred) {
1318let key = (infcx.typing_env(param_env), trait_pred);
1319if let Some(res) = tcx.evaluation_cache.get(&key, tcx) {
1320Some(res)
1321 } else {
1322if 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);
1323None1324 }
1325 } else {
1326self.infcx.evaluation_cache.get(&(param_env, trait_pred), tcx)
1327 }
1328 }
13291330fn insert_evaluation_cache(
1331&mut self,
1332 param_env: ty::ParamEnv<'tcx>,
1333 trait_pred: ty::PolyTraitPredicate<'tcx>,
1334 dep_node: DepNodeIndex,
1335 result: EvaluationResult,
1336 ) {
1337// Avoid caching results that depend on more than just the trait-ref
1338 // - the stack can create recursion.
1339if result.is_stack_dependent() {
1340return;
1341 }
13421343let infcx = self.infcx;
1344let tcx = infcx.tcx;
1345if self.can_use_global_caches(param_env, trait_pred) {
1346{
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:1346",
"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(1346u32),
::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");
1347// This may overwrite the cache with the same value
1348tcx.evaluation_cache.insert(
1349 (infcx.typing_env(param_env), trait_pred),
1350dep_node,
1351result,
1352 );
1353return;
1354 } else {
1355{
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:1355",
"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(1355u32),
::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");
1356self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result);
1357 }
1358 }
13591360fn check_recursion_depth<T>(
1361&self,
1362 depth: usize,
1363 error_obligation: &Obligation<'tcx, T>,
1364 ) -> Result<(), OverflowError>
1365where
1366T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + Clone,
1367 {
1368if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
1369match self.query_mode {
1370 TraitQueryMode::Standard => {
1371if let Some(e) = self.infcx.tainted_by_errors() {
1372return Err(OverflowError::Error(e));
1373 }
1374self.infcx.err_ctxt().report_overflow_obligation(error_obligation, true);
1375 }
1376 TraitQueryMode::Canonical => {
1377return Err(OverflowError::Canonical);
1378 }
1379 }
1380 }
1381Ok(())
1382 }
13831384/// Checks that the recursion limit has not been exceeded.
1385 ///
1386 /// The weird return type of this function allows it to be used with the `try` (`?`)
1387 /// operator within certain functions.
1388#[inline(always)]
1389fn check_recursion_limit<T: Display + TypeFoldable<TyCtxt<'tcx>>, V>(
1390&self,
1391 obligation: &Obligation<'tcx, T>,
1392 error_obligation: &Obligation<'tcx, V>,
1393 ) -> Result<(), OverflowError>
1394where
1395V: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + Clone,
1396 {
1397self.check_recursion_depth(obligation.recursion_depth, error_obligation)
1398 }
13991400fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1401where
1402OP: FnOnce(&mut Self) -> R,
1403 {
1404self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self))
1405 }
14061407/// filter_impls filters candidates that have a positive impl for a negative
1408 /// goal and a negative impl for a positive goal
1409#[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(1409u32),
::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:1415",
"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(1415u32),
::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:1434",
"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(1434u32),
::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))]1410fn filter_impls(
1411&mut self,
1412 candidates: Vec<SelectionCandidate<'tcx>>,
1413 obligation: &PolyTraitObligation<'tcx>,
1414 ) -> Vec<SelectionCandidate<'tcx>> {
1415trace!("{candidates:#?}");
1416let tcx = self.tcx();
1417let mut result = Vec::with_capacity(candidates.len());
14181419for candidate in candidates {
1420if let ImplCandidate(def_id) = candidate {
1421match (tcx.impl_polarity(def_id), obligation.polarity()) {
1422 (ty::ImplPolarity::Reservation, _)
1423 | (ty::ImplPolarity::Positive, ty::PredicatePolarity::Positive)
1424 | (ty::ImplPolarity::Negative, ty::PredicatePolarity::Negative) => {
1425 result.push(candidate);
1426 }
1427_ => {}
1428 }
1429 } else {
1430 result.push(candidate);
1431 }
1432 }
14331434trace!("{result:#?}");
1435 result
1436 }
14371438/// filter_reservation_impls filter reservation impl for any goal as ambiguous
1439#[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(1439u32),
::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 =
{
#[allow(deprecated)]
{
{
'done:
{
for i in tcx.get_all_attrs(def_id) {
#[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:1452",
"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(1452u32),
::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))]1440fn filter_reservation_impls(
1441&mut self,
1442 candidate: SelectionCandidate<'tcx>,
1443 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1444let tcx = self.tcx();
1445// Treat reservation impls as ambiguity.
1446if let ImplCandidate(def_id) = candidate
1447 && let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id)
1448 {
1449if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
1450let message = find_attr!(tcx, def_id, RustcReservationImpl(_, message) => *message);
1451if let Some(message) = message {
1452debug!(
1453"filter_reservation_impls: \
1454 reservation impl ambiguity on {:?}",
1455 def_id
1456 );
1457 intercrate_ambiguity_clauses
1458 .insert(IntercrateAmbiguityCause::ReservationImpl { message });
1459 }
1460 }
1461return Ok(None);
1462 }
1463Ok(Some(candidate))
1464 }
14651466fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Result<(), Conflict> {
1467let obligation = &stack.obligation;
1468match self.infcx.typing_mode() {
1469TypingMode::Coherence => {}
1470TypingMode::Analysis { .. }
1471 | TypingMode::Borrowck { .. }
1472 | TypingMode::PostBorrowckAnalysis { .. }
1473 | TypingMode::PostAnalysis => return Ok(()),
1474 }
14751476{
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:1476",
"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(1476u32),
::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()");
14771478let predicate = self.infcx.resolve_vars_if_possible(obligation.predicate);
14791480// Okay to skip binder because of the nature of the
1481 // trait-ref-is-knowable check, which does not care about
1482 // bound regions.
1483let trait_ref = predicate.skip_binder().trait_ref;
14841485 coherence::trait_ref_is_knowable(self.infcx, trait_ref, |ty| Ok::<_, !>(ty)).into_ok()
1486 }
14871488/// Returns `true` if the global caches can be used.
1489fn can_use_global_caches(
1490&self,
1491 param_env: ty::ParamEnv<'tcx>,
1492 pred: ty::PolyTraitPredicate<'tcx>,
1493 ) -> bool {
1494// If there are any inference variables in the `ParamEnv`, then we
1495 // always use a cache local to this particular scope. Otherwise, we
1496 // switch to a global cache.
1497if param_env.has_infer() || pred.has_infer() {
1498return false;
1499 }
15001501match self.infcx.typing_mode() {
1502// Avoid using the global cache during coherence and just rely
1503 // on the local cache. It is really just a simplification to
1504 // avoid us having to fear that coherence results "pollute"
1505 // the master cache. Since coherence executes pretty quickly,
1506 // it's not worth going to more trouble to increase the
1507 // hit-rate, I don't think.
1508TypingMode::Coherence => false,
1509// Avoid using the global cache when we're defining opaque types
1510 // as their hidden type may impact the result of candidate selection.
1511 //
1512 // HACK: This is still theoretically unsound. Goals can indirectly rely
1513 // on opaques in the defining scope, and it's easier to do so with TAIT.
1514 // However, if we disqualify *all* goals from being cached, perf suffers.
1515 // This is likely fixed by better caching in general in the new solver.
1516 // See: <https://github.com/rust-lang/rust/issues/132064>.
1517TypingMode::Analysis {
1518 defining_opaque_types_and_generators: defining_opaque_types,
1519 }
1520 | TypingMode::Borrowck { defining_opaque_types } => {
1521defining_opaque_types.is_empty()
1522 || (!pred.has_opaque_types() && !pred.has_coroutines())
1523 }
1524// The hidden types of `defined_opaque_types` is not local to the current
1525 // inference context, so we can freely move this to the global cache.
1526TypingMode::PostBorrowckAnalysis { .. } => true,
1527// The global cache is only used if there are no opaque types in
1528 // the defining scope or we're outside of analysis.
1529 //
1530 // FIXME(#132279): This is still incorrect as we treat opaque types
1531 // and default associated items differently between these two modes.
1532TypingMode::PostAnalysis => true,
1533 }
1534 }
15351536fn check_candidate_cache(
1537&mut self,
1538 param_env: ty::ParamEnv<'tcx>,
1539 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1540 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1541let infcx = self.infcx;
1542let tcx = infcx.tcx;
1543let pred = cache_fresh_trait_pred.skip_binder();
15441545if self.can_use_global_caches(param_env, cache_fresh_trait_pred) {
1546if let Some(res) = tcx.selection_cache.get(&(infcx.typing_env(param_env), pred), tcx) {
1547return Some(res);
1548 } else if truecfg!(debug_assertions) {
1549match infcx.selection_cache.get(&(param_env, pred), tcx) {
1550None | Some(Err(SelectionError::Overflow(OverflowError::Canonical))) => {}
1551 res => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected local cache result: {0:?}",
res))bug!("unexpected local cache result: {res:?}"),
1552 }
1553 }
1554 }
15551556// Subtle: we need to check the local cache even if we're able to use the
1557 // global cache as we don't cache overflow in the global cache but need to
1558 // cache it as otherwise rustdoc hangs when compiling diesel.
1559infcx.selection_cache.get(&(param_env, pred), tcx)
1560 }
15611562/// Determines whether can we safely cache the result
1563 /// of selecting an obligation. This is almost always `true`,
1564 /// except when dealing with certain `ParamCandidate`s.
1565 ///
1566 /// Ordinarily, a `ParamCandidate` will contain no inference variables,
1567 /// since it was usually produced directly from a `DefId`. However,
1568 /// certain cases (currently only librustdoc's blanket impl finder),
1569 /// a `ParamEnv` may be explicitly constructed with inference types.
1570 /// When this is the case, we do *not* want to cache the resulting selection
1571 /// candidate. This is due to the fact that it might not always be possible
1572 /// to equate the obligation's trait ref and the candidate's trait ref,
1573 /// if more constraints end up getting added to an inference variable.
1574 ///
1575 /// Because of this, we always want to re-run the full selection
1576 /// process for our obligation the next time we see it, since
1577 /// we might end up picking a different `SelectionCandidate` (or none at all).
1578fn can_cache_candidate(
1579&self,
1580 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1581 ) -> bool {
1582match result {
1583Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.has_infer(),
1584_ => true,
1585 }
1586 }
15871588#[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(1588u32),
::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:1601",
"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(1601u32),
::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:1609",
"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(1609u32),
::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:1622",
"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(1622u32),
::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")]1589fn insert_candidate_cache(
1590&mut self,
1591 param_env: ty::ParamEnv<'tcx>,
1592 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1593 dep_node: DepNodeIndex,
1594 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1595 ) {
1596let infcx = self.infcx;
1597let tcx = infcx.tcx;
1598let pred = cache_fresh_trait_pred.skip_binder();
15991600if !self.can_cache_candidate(&candidate) {
1601debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
1602return;
1603 }
16041605if self.can_use_global_caches(param_env, cache_fresh_trait_pred) {
1606if let Err(SelectionError::Overflow(OverflowError::Canonical)) = candidate {
1607// Don't cache overflow globally; we only produce this in certain modes.
1608} else {
1609debug!(?pred, ?candidate, "insert_candidate_cache global");
1610debug_assert!(!candidate.has_infer());
16111612// This may overwrite the cache with the same value.
1613tcx.selection_cache.insert(
1614 (infcx.typing_env(param_env), pred),
1615 dep_node,
1616 candidate,
1617 );
1618return;
1619 }
1620 }
16211622debug!(?pred, ?candidate, "insert_candidate_cache local");
1623self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate);
1624 }
16251626/// Looks at the item bounds of the projection or opaque type.
1627 /// If this is a nested rigid projection, such as
1628 /// `<<T as Tr1>::Assoc as Tr2>::Assoc`, consider the item bounds
1629 /// on both `Tr1::Assoc` and `Tr2::Assoc`, since we may encounter
1630 /// relative bounds on both via the `associated_type_bounds` feature.
1631pub(super) fn for_each_item_bound<T>(
1632&mut self,
1633mut self_ty: Ty<'tcx>,
1634mut for_each: impl FnMut(
1635&mut Self,
1636 ty::Clause<'tcx>,
1637usize,
1638AliasBoundKind,
1639 ) -> ControlFlow<T, ()>,
1640 on_ambiguity: impl FnOnce(),
1641 ) -> ControlFlow<T, ()> {
1642let mut idx = 0;
1643let mut alias_bound_kind = AliasBoundKind::SelfBounds;
16441645loop {
1646let (kind, alias_ty) = match *self_ty.kind() {
1647 ty::Alias(kind @ (ty::Projection | ty::Opaque), alias_ty) => (kind, alias_ty),
1648 ty::Infer(ty::TyVar(_)) => {
1649on_ambiguity();
1650return ControlFlow::Continue(());
1651 }
1652_ => return ControlFlow::Continue(()),
1653 };
16541655// HACK: On subsequent recursions, we only care about bounds that don't
1656 // share the same type as `self_ty`. This is because for truly rigid
1657 // projections, we will never be able to equate, e.g. `<T as Tr>::A`
1658 // with `<<T as Tr>::A as Tr>::A`.
1659let relevant_bounds = if alias_bound_kind == AliasBoundKind::NonSelfBounds {
1660self.tcx().item_non_self_bounds(alias_ty.def_id)
1661 } else {
1662self.tcx().item_self_bounds(alias_ty.def_id)
1663 };
16641665for bound in relevant_bounds.instantiate(self.tcx(), alias_ty.args) {
1666 for_each(self, bound, idx, alias_bound_kind)?;
1667 idx += 1;
1668 }
16691670if kind == ty::Projection {
1671self_ty = alias_ty.self_ty();
1672 } else {
1673return ControlFlow::Continue(());
1674 }
16751676alias_bound_kind = AliasBoundKind::NonSelfBounds;
1677 }
1678 }
16791680/// Equates the trait in `obligation` with trait bound. If the two traits
1681 /// can be equated and the normalized trait bound doesn't contain inference
1682 /// variables or placeholders, the normalized bound is returned.
1683fn match_normalize_trait_ref(
1684&mut self,
1685 obligation: &PolyTraitObligation<'tcx>,
1686 placeholder_trait_ref: ty::TraitRef<'tcx>,
1687 trait_bound: ty::PolyTraitRef<'tcx>,
1688 ) -> Result<Option<ty::TraitRef<'tcx>>, ()> {
1689if 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());
1690if placeholder_trait_ref.def_id != trait_bound.def_id() {
1691// Avoid unnecessary normalization
1692return Err(());
1693 }
16941695let drcx = DeepRejectCtxt::relate_rigid_rigid(self.infcx.tcx);
1696let obligation_args = obligation.predicate.skip_binder().trait_ref.args;
1697if !drcx.args_may_unify(obligation_args, trait_bound.skip_binder().args) {
1698return Err(());
1699 }
17001701let trait_bound = self.infcx.instantiate_binder_with_fresh_vars(
1702obligation.cause.span,
1703HigherRankedType,
1704trait_bound,
1705 );
1706let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
1707normalize_with_depth(
1708self,
1709obligation.param_env,
1710obligation.cause.clone(),
1711obligation.recursion_depth + 1,
1712trait_bound,
1713 )
1714 });
1715self.infcx
1716 .at(&obligation.cause, obligation.param_env)
1717 .eq(DefineOpaqueTypes::No, placeholder_trait_ref, trait_bound)
1718 .map(|InferOk { obligations: _, value: () }| {
1719// This method is called within a probe, so we can't have
1720 // inference variables and placeholders escape.
1721if !trait_bound.has_infer() && !trait_bound.has_placeholders() {
1722Some(trait_bound)
1723 } else {
1724None1725 }
1726 })
1727 .map_err(|_| ())
1728 }
17291730fn where_clause_may_apply<'o>(
1731&mut self,
1732 stack: &TraitObligationStack<'o, 'tcx>,
1733 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1734 ) -> Result<EvaluationResult, OverflowError> {
1735self.evaluation_probe(|this| {
1736match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1737Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
1738Err(()) => Ok(EvaluatedToErr),
1739 }
1740 })
1741 }
17421743/// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
1744 /// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
1745 /// and applying this env_predicate constrains any of the obligation's GAT parameters.
1746 ///
1747 /// This behavior is a somewhat of a hack to prevent over-constraining inference variables
1748 /// in cases like #91762.
1749pub(super) fn match_projection_projections(
1750&mut self,
1751 obligation: &ProjectionTermObligation<'tcx>,
1752 env_predicate: PolyProjectionPredicate<'tcx>,
1753 potentially_unnormalized_candidates: bool,
1754 ) -> ProjectionMatchesProjection {
1755if true {
match (&obligation.predicate.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!(obligation.predicate.def_id, env_predicate.item_def_id());
17561757let mut nested_obligations = PredicateObligations::new();
1758let infer_predicate = self.infcx.instantiate_binder_with_fresh_vars(
1759obligation.cause.span,
1760 BoundRegionConversionTime::HigherRankedType,
1761env_predicate,
1762 );
1763let infer_projection = if potentially_unnormalized_candidates {
1764ensure_sufficient_stack(|| {
1765normalize_with_depth_to(
1766self,
1767obligation.param_env,
1768obligation.cause.clone(),
1769obligation.recursion_depth + 1,
1770infer_predicate.projection_term,
1771&mut nested_obligations,
1772 )
1773 })
1774 } else {
1775infer_predicate.projection_term
1776 };
17771778let is_match = self1779 .infcx
1780 .at(&obligation.cause, obligation.param_env)
1781 .eq(DefineOpaqueTypes::No, obligation.predicate, infer_projection)
1782 .is_ok_and(|InferOk { obligations, value: () }| {
1783self.evaluate_predicates_recursively(
1784TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
1785nested_obligations.into_iter().chain(obligations),
1786 )
1787 .is_ok_and(|res| res.may_apply())
1788 });
17891790if is_match {
1791let generics = self.tcx().generics_of(obligation.predicate.def_id);
1792// FIXME(generic_associated_types): Addresses aggressive inference in #92917.
1793 // If this type is a GAT, and of the GAT args resolve to something new,
1794 // that means that we must have newly inferred something about the GAT.
1795 // We should give up in that case.
1796 //
1797 // This only detects one layer of inference, which is probably not what we actually
1798 // want, but fixing it causes some ambiguity:
1799 // <https://github.com/rust-lang/rust/issues/125196>.
1800if !generics.is_own_empty()
1801 && obligation.predicate.args[generics.parent_count..].iter().any(|&p| {
1802p.has_non_region_infer()
1803 && match p.kind() {
1804 ty::GenericArgKind::Const(ct) => {
1805self.infcx.shallow_resolve_const(ct) != ct1806 }
1807 ty::GenericArgKind::Type(ty) => self.infcx.shallow_resolve(ty) != ty,
1808 ty::GenericArgKind::Lifetime(_) => false,
1809 }
1810 })
1811 {
1812 ProjectionMatchesProjection::Ambiguous1813 } else {
1814 ProjectionMatchesProjection::Yes1815 }
1816 } else {
1817 ProjectionMatchesProjection::No1818 }
1819 }
1820}
18211822/// ## Winnowing
1823///
1824/// Winnowing is the process of attempting to resolve ambiguity by
1825/// probing further. During the winnowing process, we unify all
1826/// type variables and then we also attempt to evaluate recursive
1827/// bounds to see if they are satisfied.
1828impl<'tcx> SelectionContext<'_, 'tcx> {
1829/// If there are multiple ways to prove a trait goal, we make some
1830 /// *fairly arbitrary* choices about which candidate is actually used.
1831 ///
1832 /// For more details, look at the implementation of this method :)
1833x;#[instrument(level = "debug", skip(self), ret)]1834fn winnow_candidates(
1835&mut self,
1836 has_non_region_infer: bool,
1837 candidate_preference_mode: CandidatePreferenceMode,
1838mut candidates: Vec<EvaluatedCandidate<'tcx>>,
1839 ) -> Option<SelectionCandidate<'tcx>> {
1840if candidates.len() == 1 {
1841return Some(candidates.pop().unwrap().candidate);
1842 }
18431844// We prefer `Sized` candidates over everything.
1845let mut sized_candidates =
1846 candidates.iter().filter(|c| matches!(c.candidate, SizedCandidate));
1847if let Some(sized_candidate) = sized_candidates.next() {
1848// There should only ever be a single sized candidate
1849 // as they would otherwise overlap.
1850debug_assert_eq!(sized_candidates.next(), None);
1851// Only prefer the built-in `Sized` candidate if its nested goals are certain.
1852 // Otherwise, we may encounter failure later on if inference causes this candidate
1853 // to not hold, but a where clause would've applied instead.
1854if sized_candidate.evaluation.must_apply_modulo_regions() {
1855return Some(sized_candidate.candidate.clone());
1856 } else {
1857return None;
1858 }
1859 }
18601861// Before we consider where-bounds, we have to deduplicate them here and also
1862 // drop where-bounds in case the same where-bound exists without bound vars.
1863 // This is necessary as elaborating super-trait bounds may result in duplicates.
1864'search_victim: loop {
1865for (i, this) in candidates.iter().enumerate() {
1866let ParamCandidate(this) = this.candidate else { continue };
1867for (j, other) in candidates.iter().enumerate() {
1868if i == j {
1869continue;
1870 }
18711872let ParamCandidate(other) = other.candidate else { continue };
1873if this == other {
1874 candidates.remove(j);
1875continue 'search_victim;
1876 }
18771878if this.skip_binder().trait_ref == other.skip_binder().trait_ref
1879 && this.skip_binder().polarity == other.skip_binder().polarity
1880 && !this.skip_binder().trait_ref.has_escaping_bound_vars()
1881 {
1882 candidates.remove(j);
1883continue 'search_victim;
1884 }
1885 }
1886 }
18871888break;
1889 }
18901891let mut alias_bounds = candidates.iter().filter_map(|c| {
1892if let ProjectionCandidate { idx, kind } = c.candidate {
1893Some((idx, kind))
1894 } else {
1895None
1896}
1897 });
1898// Extract non-nested alias bound candidates, will be preferred over where bounds if
1899 // we're proving an auto-trait, sizedness trait or default trait.
1900if matches!(candidate_preference_mode, CandidatePreferenceMode::Marker) {
1901match alias_bounds
1902 .clone()
1903 .filter_map(|(idx, kind)| (kind == AliasBoundKind::SelfBounds).then_some(idx))
1904 .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) })
1905 {
1906Some(Some(idx)) => {
1907return Some(ProjectionCandidate { idx, kind: AliasBoundKind::SelfBounds });
1908 }
1909Some(None) => {}
1910None => return None,
1911 }
1912 }
19131914// The next highest priority is for non-global where-bounds. However, while we don't
1915 // prefer global where-clauses here, we do bail with ambiguity when encountering both
1916 // a global and a non-global where-clause.
1917 //
1918 // Our handling of where-bounds is generally fairly messy but necessary for backwards
1919 // compatibility, see #50825 for why we need to handle global where-bounds like this.
1920let is_global = |c: ty::PolyTraitPredicate<'tcx>| c.is_global() && !c.has_bound_vars();
1921let param_candidates = candidates
1922 .iter()
1923 .filter_map(|c| if let ParamCandidate(p) = c.candidate { Some(p) } else { None });
1924let mut has_global_bounds = false;
1925let mut param_candidate = None;
1926for c in param_candidates {
1927if is_global(c) {
1928 has_global_bounds = true;
1929 } else if param_candidate.replace(c).is_some() {
1930// Ambiguity, two potentially different where-clauses
1931return None;
1932 }
1933 }
1934if let Some(predicate) = param_candidate {
1935// Ambiguity, a global and a non-global where-bound.
1936if has_global_bounds {
1937return None;
1938 } else {
1939return Some(ParamCandidate(predicate));
1940 }
1941 }
19421943// Prefer alias-bounds over blanket impls for rigid associated types. This is
1944 // fairly arbitrary but once again necessary for backwards compatibility.
1945 // If there are multiple applicable candidates which don't affect type inference,
1946 // choose the one with the lowest index.
1947match alias_bounds.try_reduce(|(c1, k1), (c2, k2)| {
1948if has_non_region_infer {
1949None
1950} else if c1 < c2 {
1951Some((c1, k1))
1952 } else {
1953Some((c2, k2))
1954 }
1955 }) {
1956Some(Some((idx, kind))) => return Some(ProjectionCandidate { idx, kind }),
1957Some(None) => {}
1958None => return None,
1959 }
19601961// Need to prioritize builtin trait object impls as `<dyn Any as Any>::type_id`
1962 // should use the vtable method and not the method provided by the user-defined
1963 // impl `impl<T: ?Sized> Any for T { .. }`. This really shouldn't exist but is
1964 // necessary due to #57893. We again arbitrarily prefer the applicable candidate
1965 // with the lowest index.
1966 //
1967 // We do not want to use these impls to guide inference in case a user-written impl
1968 // may also apply.
1969let object_bound = candidates
1970 .iter()
1971 .filter_map(|c| if let ObjectCandidate(i) = c.candidate { Some(i) } else { None })
1972 .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) });
1973match object_bound {
1974Some(Some(index)) => {
1975return if has_non_region_infer
1976 && candidates.iter().any(|c| matches!(c.candidate, ImplCandidate(_)))
1977 {
1978None
1979} else {
1980Some(ObjectCandidate(index))
1981 };
1982 }
1983Some(None) => {}
1984None => return None,
1985 }
1986// Same for upcasting.
1987let upcast_bound = candidates
1988 .iter()
1989 .filter_map(|c| {
1990if let TraitUpcastingUnsizeCandidate(i) = c.candidate { Some(i) } else { None }
1991 })
1992 .try_reduce(|c1, c2| if has_non_region_infer { None } else { Some(c1.min(c2)) });
1993match upcast_bound {
1994Some(Some(index)) => return Some(TraitUpcastingUnsizeCandidate(index)),
1995Some(None) => {}
1996None => return None,
1997 }
19981999// Finally, handle overlapping user-written impls.
2000let impls = candidates.iter().filter_map(|c| {
2001if let ImplCandidate(def_id) = c.candidate {
2002Some((def_id, c.evaluation))
2003 } else {
2004None
2005}
2006 });
2007let mut impl_candidate = None;
2008for c in impls {
2009if let Some(prev) = impl_candidate.replace(c) {
2010if self.prefer_lhs_over_victim(has_non_region_infer, c, prev.0) {
2011// Ok, prefer `c` over the previous entry
2012} else if self.prefer_lhs_over_victim(has_non_region_infer, prev, c.0) {
2013// Ok, keep `prev` instead of the new entry
2014impl_candidate = Some(prev);
2015 } else {
2016// Ambiguity, two potentially different where-clauses
2017return None;
2018 }
2019 }
2020 }
2021if let Some((def_id, _evaluation)) = impl_candidate {
2022// Don't use impl candidates which overlap with other candidates.
2023 // This should pretty much only ever happen with malformed impls.
2024if candidates.iter().all(|c| match c.candidate {
2025 SizedCandidate
2026 | BuiltinCandidate
2027 | TransmutabilityCandidate
2028 | AutoImplCandidate
2029 | ClosureCandidate { .. }
2030 | AsyncClosureCandidate
2031 | AsyncFnKindHelperCandidate
2032 | CoroutineCandidate
2033 | FutureCandidate
2034 | IteratorCandidate
2035 | AsyncIteratorCandidate
2036 | FnPointerCandidate
2037 | TraitAliasCandidate
2038 | TraitUpcastingUnsizeCandidate(_)
2039 | BuiltinObjectCandidate
2040 | BuiltinUnsizeCandidate
2041 | PointerLikeCandidate
2042 | BikeshedGuaranteedNoDropCandidate => false,
2043// Non-global param candidates have already been handled, global
2044 // where-bounds get ignored.
2045ParamCandidate(_) | ImplCandidate(_) => true,
2046 ProjectionCandidate { .. } | ObjectCandidate(_) => unreachable!(),
2047 }) {
2048return Some(ImplCandidate(def_id));
2049 } else {
2050return None;
2051 }
2052 }
20532054if candidates.len() == 1 {
2055Some(candidates.pop().unwrap().candidate)
2056 } else {
2057// Also try ignoring all global where-bounds and check whether we end
2058 // with a unique candidate in this case.
2059let mut not_a_global_where_bound = candidates
2060 .into_iter()
2061 .filter(|c| !matches!(c.candidate, ParamCandidate(p) if is_global(p)));
2062 not_a_global_where_bound
2063 .next()
2064 .map(|c| c.candidate)
2065 .filter(|_| not_a_global_where_bound.next().is_none())
2066 }
2067 }
20682069fn prefer_lhs_over_victim(
2070&self,
2071 has_non_region_infer: bool,
2072 (lhs, lhs_evaluation): (DefId, EvaluationResult),
2073 victim: DefId,
2074 ) -> bool {
2075let tcx = self.tcx();
2076// See if we can toss out `victim` based on specialization.
2077 //
2078 // While this requires us to know *for sure* that the `lhs` impl applies
2079 // we still use modulo regions here. This is fine as specialization currently
2080 // assumes that specializing impls have to be always applicable, meaning that
2081 // the only allowed region constraints may be constraints also present on the default impl.
2082if lhs_evaluation.must_apply_modulo_regions() {
2083if tcx.specializes((lhs, victim)) {
2084return true;
2085 }
2086 }
20872088match tcx.impls_are_allowed_to_overlap(lhs, victim) {
2089// For candidates which already reference errors it doesn't really
2090 // matter what we do 🤷
2091Some(ty::ImplOverlapKind::Permitted { marker: false }) => {
2092lhs_evaluation.must_apply_considering_regions()
2093 }
2094Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
2095// Subtle: If the predicate we are evaluating has inference
2096 // variables, do *not* allow discarding candidates due to
2097 // marker trait impls.
2098 //
2099 // Without this restriction, we could end up accidentally
2100 // constraining inference variables based on an arbitrarily
2101 // chosen trait impl.
2102 //
2103 // Imagine we have the following code:
2104 //
2105 // ```rust
2106 // #[marker] trait MyTrait {}
2107 // impl MyTrait for u8 {}
2108 // impl MyTrait for bool {}
2109 // ```
2110 //
2111 // And we are evaluating the predicate `<_#0t as MyTrait>`.
2112 //
2113 // During selection, we will end up with one candidate for each
2114 // impl of `MyTrait`. If we were to discard one impl in favor
2115 // of the other, we would be left with one candidate, causing
2116 // us to "successfully" select the predicate, unifying
2117 // _#0t with (for example) `u8`.
2118 //
2119 // However, we have no reason to believe that this unification
2120 // is correct - we've essentially just picked an arbitrary
2121 // *possibility* for _#0t, and required that this be the *only*
2122 // possibility.
2123 //
2124 // Eventually, we will either:
2125 // 1) Unify all inference variables in the predicate through
2126 // some other means (e.g. type-checking of a function). We will
2127 // then be in a position to drop marker trait candidates
2128 // without constraining inference variables (since there are
2129 // none left to constrain)
2130 // 2) Be left with some unconstrained inference variables. We
2131 // will then correctly report an inference error, since the
2132 // existence of multiple marker trait impls tells us nothing
2133 // about which one should actually apply.
2134!has_non_region_infer && lhs_evaluation.must_apply_considering_regions()
2135 }
2136None => false,
2137 }
2138 }
2139}
21402141impl<'tcx> SelectionContext<'_, 'tcx> {
2142fn sizedness_conditions(
2143&mut self,
2144 self_ty: Ty<'tcx>,
2145 sizedness: SizedTraitKind,
2146 ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
2147match self_ty.kind() {
2148 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2149 | ty::Uint(_)
2150 | ty::Int(_)
2151 | ty::Bool2152 | ty::Float(_)
2153 | ty::FnDef(..)
2154 | ty::FnPtr(..)
2155 | ty::RawPtr(..)
2156 | ty::Char2157 | ty::Ref(..)
2158 | ty::Coroutine(..)
2159 | ty::CoroutineWitness(..)
2160 | ty::Array(..)
2161 | ty::Closure(..)
2162 | ty::CoroutineClosure(..)
2163 | ty::Never2164 | ty::Error(_) => ty::Binder::dummy(::alloc::vec::Vec::new()vec![]),
21652166 ty::Str | ty::Slice(_) | ty::Dynamic(..) => match sizedness {
2167 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"),
2168 SizedTraitKind::MetaSized => ty::Binder::dummy(::alloc::vec::Vec::new()vec![]),
2169 },
21702171 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"),
21722173 ty::Tuple(tys) => {
2174 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]))
2175 }
21762177 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]),
21782179 ty::Adt(def, args) => {
2180if let Some(crit) = def.sizedness_constraint(self.tcx(), sizedness) {
2181 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)]))vec![crit.instantiate(self.tcx(), args)])
2182 } else {
2183 ty::Binder::dummy(::alloc::vec::Vec::new()vec![])
2184 }
2185 }
21862187 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]),
21882189 ty::Alias(..)
2190 | ty::Param(_)
2191 | ty::Placeholder(..)
2192 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
2193 | ty::Bound(..) => {
2194::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);
2195 }
2196 }
2197 }
21982199fn copy_clone_conditions(&mut self, self_ty: Ty<'tcx>) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
2200match *self_ty.kind() {
2201 ty::FnDef(..) | ty::FnPtr(..) | ty::Error(_) => ty::Binder::dummy(::alloc::vec::Vec::new()vec![]),
22022203 ty::Uint(_)
2204 | ty::Int(_)
2205 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2206 | ty::Bool2207 | ty::Float(_)
2208 | ty::Char2209 | ty::RawPtr(..)
2210 | ty::Never2211 | ty::Ref(_, _, hir::Mutability::Not)
2212 | ty::Array(..) => {
2213{
::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")2214 }
22152216// FIXME(unsafe_binder): Should we conditionally
2217 // (i.e. universally) implement copy/clone?
2218 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"),
22192220 ty::Tuple(tys) => {
2221// (*) binder moved here
2222ty::Binder::dummy(tys.iter().collect())
2223 }
22242225 ty::Pat(ty, _) => {
2226// (*) binder moved here
2227 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])
2228 }
22292230 ty::Coroutine(def_id, args) => match self.tcx().coroutine_movability(def_id) {
2231 hir::Movability::Static => {
2232{
::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")2233 }
2234 hir::Movability::Movable => {
2235if self.tcx().features().coroutine_clone() {
2236 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![
2237 args.as_coroutine().tupled_upvars_ty(),
2238 Ty::new_coroutine_witness_for_coroutine(self.tcx(), def_id, args),
2239 ])
2240 } else {
2241{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("tried to assemble `Clone` for coroutine without enabled feature")));
}unreachable!(
2242"tried to assemble `Clone` for coroutine without enabled feature"
2243)2244 }
2245 }
2246 },
22472248 ty::CoroutineWitness(def_id, args) => self2249 .infcx
2250 .tcx
2251 .coroutine_hidden_types(def_id)
2252 .instantiate(self.infcx.tcx, args)
2253 .map_bound(|witness| witness.types.to_vec()),
22542255 ty::Closure(_, args) => ty::Binder::dummy(args.as_closure().upvar_tys().to_vec()),
22562257 ty::CoroutineClosure(_, args) => {
2258 ty::Binder::dummy(args.as_coroutine_closure().upvar_tys().to_vec())
2259 }
22602261 ty::Foreign(..)
2262 | ty::Str2263 | ty::Slice(_)
2264 | ty::Dynamic(..)
2265 | ty::Adt(..)
2266 | ty::Alias(..)
2267 | ty::Param(..)
2268 | ty::Placeholder(..)
2269 | ty::Bound(..)
2270 | ty::Ref(_, _, ty::Mutability::Mut)
2271 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2272::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);
2273 }
2274 }
2275 }
22762277fn coroutine_is_gen(&mut self, self_ty: Ty<'tcx>) -> bool {
2278#[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, ..)
2279if self.tcx().coroutine_is_gen(did))2280 }
22812282/// For default impls, we need to break apart a type into its
2283 /// "constituent types" -- meaning, the types that it contains.
2284 ///
2285 /// Here are some (simple) examples:
2286 ///
2287 /// ```ignore (illustrative)
2288 /// (i32, u32) -> [i32, u32]
2289 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2290 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2291 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2292 /// ```
2293x;#[instrument(level = "debug", skip(self), ret)]2294fn constituent_types_for_auto_trait(
2295&self,
2296 t: Ty<'tcx>,
2297 ) -> Result<ty::Binder<'tcx, AutoImplConstituents<'tcx>>, SelectionError<'tcx>> {
2298Ok(match *t.kind() {
2299 ty::Uint(_)
2300 | ty::Int(_)
2301 | ty::Bool
2302 | ty::Float(_)
2303 | ty::FnDef(..)
2304 | ty::FnPtr(..)
2305 | ty::Error(_)
2306 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2307 | ty::Never
2308 | ty::Char => {
2309 ty::Binder::dummy(AutoImplConstituents { types: vec![], assumptions: vec![] })
2310 }
23112312// This branch is only for `experimental_default_bounds`.
2313 // Other foreign types were rejected earlier in
2314 // `assemble_candidates_from_auto_impls`.
2315ty::Foreign(..) => {
2316 ty::Binder::dummy(AutoImplConstituents { types: vec![], assumptions: vec![] })
2317 }
23182319 ty::UnsafeBinder(ty) => {
2320 ty.map_bound(|ty| AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2321 }
23222323// Treat this like `struct str([u8]);`
2324ty::Str => ty::Binder::dummy(AutoImplConstituents {
2325 types: vec![Ty::new_slice(self.tcx(), self.tcx().types.u8)],
2326 assumptions: vec![],
2327 }),
23282329 ty::Placeholder(..)
2330 | ty::Dynamic(..)
2331 | ty::Param(..)
2332 | ty::Alias(ty::Projection | ty::Inherent | ty::Free, ..)
2333 | ty::Bound(..)
2334 | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2335bug!("asked to assemble constituent types of unexpected type: {:?}", t);
2336 }
23372338 ty::RawPtr(element_ty, _) | ty::Ref(_, element_ty, _) => {
2339 ty::Binder::dummy(AutoImplConstituents {
2340 types: vec![element_ty],
2341 assumptions: vec![],
2342 })
2343 }
23442345 ty::Pat(ty, _) | ty::Array(ty, _) | ty::Slice(ty) => {
2346 ty::Binder::dummy(AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2347 }
23482349 ty::Tuple(tys) => {
2350// (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2351ty::Binder::dummy(AutoImplConstituents {
2352 types: tys.iter().collect(),
2353 assumptions: vec![],
2354 })
2355 }
23562357 ty::Closure(_, args) => {
2358let ty = self.infcx.shallow_resolve(args.as_closure().tupled_upvars_ty());
2359 ty::Binder::dummy(AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2360 }
23612362 ty::CoroutineClosure(_, args) => {
2363let ty = self.infcx.shallow_resolve(args.as_coroutine_closure().tupled_upvars_ty());
2364 ty::Binder::dummy(AutoImplConstituents { types: vec![ty], assumptions: vec![] })
2365 }
23662367 ty::Coroutine(def_id, args) => {
2368let ty = self.infcx.shallow_resolve(args.as_coroutine().tupled_upvars_ty());
2369let tcx = self.tcx();
2370let witness = Ty::new_coroutine_witness_for_coroutine(tcx, def_id, args);
2371 ty::Binder::dummy(AutoImplConstituents {
2372 types: vec![ty, witness],
2373 assumptions: vec![],
2374 })
2375 }
23762377 ty::CoroutineWitness(def_id, args) => self
2378.infcx
2379 .tcx
2380 .coroutine_hidden_types(def_id)
2381 .instantiate(self.infcx.tcx, args)
2382 .map_bound(|witness| AutoImplConstituents {
2383 types: witness.types.to_vec(),
2384 assumptions: witness.assumptions.to_vec(),
2385 }),
23862387// For `PhantomData<T>`, we pass `T`.
2388ty::Adt(def, args) if def.is_phantom_data() => {
2389 ty::Binder::dummy(AutoImplConstituents {
2390 types: args.types().collect(),
2391 assumptions: vec![],
2392 })
2393 }
23942395 ty::Adt(def, args) => ty::Binder::dummy(AutoImplConstituents {
2396 types: def.all_fields().map(|f| f.ty(self.tcx(), args)).collect(),
2397 assumptions: vec![],
2398 }),
23992400 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
2401if self.infcx.can_define_opaque_ty(def_id) {
2402unreachable!()
2403 } else {
2404// We can resolve the opaque type to its hidden type,
2405 // which enforces a DAG between the functions requiring
2406 // the auto trait bounds in question.
2407match self.tcx().type_of_opaque(def_id) {
2408Ok(ty) => ty::Binder::dummy(AutoImplConstituents {
2409 types: vec![ty.instantiate(self.tcx(), args)],
2410 assumptions: vec![],
2411 }),
2412Err(_) => {
2413return Err(SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id));
2414 }
2415 }
2416 }
2417 }
2418 })
2419 }
24202421fn collect_predicates_for_types(
2422&mut self,
2423 param_env: ty::ParamEnv<'tcx>,
2424 cause: ObligationCause<'tcx>,
2425 recursion_depth: usize,
2426 trait_def_id: DefId,
2427 types: Vec<Ty<'tcx>>,
2428 ) -> PredicateObligations<'tcx> {
2429// Because the types were potentially derived from
2430 // higher-ranked obligations they may reference late-bound
2431 // regions. For example, `for<'a> Foo<&'a i32> : Copy` would
2432 // yield a type like `for<'a> &'a i32`. In general, we
2433 // maintain the invariant that we never manipulate bound
2434 // regions, so we have to process these bound regions somehow.
2435 //
2436 // The strategy is to:
2437 //
2438 // 1. Instantiate those regions to placeholder regions (e.g.,
2439 // `for<'a> &'a i32` becomes `&0 i32`.
2440 // 2. Produce something like `&'0 i32 : Copy`
2441 // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
24422443types2444 .into_iter()
2445 .flat_map(|placeholder_ty| {
2446let Normalized { value: normalized_ty, mut obligations } =
2447ensure_sufficient_stack(|| {
2448normalize_with_depth(
2449self,
2450param_env,
2451cause.clone(),
2452recursion_depth,
2453placeholder_ty,
2454 )
2455 });
24562457let tcx = self.tcx();
2458let trait_ref = if tcx.generics_of(trait_def_id).own_params.len() == 1 {
2459 ty::TraitRef::new(tcx, trait_def_id, [normalized_ty])
2460 } else {
2461// If this is an ill-formed auto/built-in trait, then synthesize
2462 // new error args for the missing generics.
2463let err_args = ty::GenericArgs::extend_with_error(
2464tcx,
2465trait_def_id,
2466&[normalized_ty.into()],
2467 );
2468 ty::TraitRef::new_from_args(tcx, trait_def_id, err_args)
2469 };
24702471let obligation = Obligation::new(self.tcx(), cause.clone(), param_env, trait_ref);
2472obligations.push(obligation);
2473obligations2474 })
2475 .collect()
2476 }
24772478///////////////////////////////////////////////////////////////////////////
2479 // Matching
2480 //
2481 // Matching is a common path used for both evaluation and
2482 // confirmation. It basically unifies types that appear in impls
2483 // and traits. This does affect the surrounding environment;
2484 // therefore, when used during evaluation, match routines must be
2485 // run inside of a `probe()` so that their side-effects are
2486 // contained.
24872488fn rematch_impl(
2489&mut self,
2490 impl_def_id: DefId,
2491 obligation: &PolyTraitObligation<'tcx>,
2492 ) -> Normalized<'tcx, GenericArgsRef<'tcx>> {
2493let impl_trait_header = self.tcx().impl_trait_header(impl_def_id);
2494match self.match_impl(impl_def_id, impl_trait_header, obligation) {
2495Ok(args) => args,
2496Err(()) => {
2497let predicate = self.infcx.resolve_vars_if_possible(obligation.predicate);
2498::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")2499 }
2500 }
2501 }
25022503x;#[instrument(level = "debug", skip(self), ret)]2504fn match_impl(
2505&mut self,
2506 impl_def_id: DefId,
2507 impl_trait_header: ty::ImplTraitHeader<'tcx>,
2508 obligation: &PolyTraitObligation<'tcx>,
2509 ) -> Result<Normalized<'tcx, GenericArgsRef<'tcx>>, ()> {
2510let placeholder_obligation =
2511self.infcx.enter_forall_and_leak_universe(obligation.predicate);
2512let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
25132514let impl_args = self.infcx.fresh_args_for_item(obligation.cause.span, impl_def_id);
25152516let trait_ref = impl_trait_header.trait_ref.instantiate(self.tcx(), impl_args);
2517debug!(?impl_trait_header);
25182519let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
2520 ensure_sufficient_stack(|| {
2521 normalize_with_depth(
2522self,
2523 obligation.param_env,
2524 obligation.cause.clone(),
2525 obligation.recursion_depth + 1,
2526 trait_ref,
2527 )
2528 });
25292530debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
25312532let cause = ObligationCause::new(
2533 obligation.cause.span,
2534 obligation.cause.body_id,
2535 ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
2536 );
25372538let InferOk { obligations, .. } = self
2539.infcx
2540 .at(&cause, obligation.param_env)
2541 .eq(DefineOpaqueTypes::No, placeholder_obligation_trait_ref, impl_trait_ref)
2542 .map_err(|e| {
2543debug!("match_impl: failed eq_trait_refs due to `{}`", e.to_string(self.tcx()))
2544 })?;
2545 nested_obligations.extend(obligations);
25462547if impl_trait_header.polarity == ty::ImplPolarity::Reservation
2548 && !matches!(self.infcx.typing_mode(), TypingMode::Coherence)
2549 {
2550debug!("reservation impls only apply in intercrate mode");
2551return Err(());
2552 }
25532554Ok(Normalized { value: impl_args, obligations: nested_obligations })
2555 }
25562557fn match_upcast_principal(
2558&mut self,
2559 obligation: &PolyTraitObligation<'tcx>,
2560 unnormalized_upcast_principal: ty::PolyTraitRef<'tcx>,
2561 a_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2562 b_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2563 a_region: ty::Region<'tcx>,
2564 b_region: ty::Region<'tcx>,
2565 ) -> SelectionResult<'tcx, PredicateObligations<'tcx>> {
2566let tcx = self.tcx();
2567let mut nested = PredicateObligations::new();
25682569// We may upcast to auto traits that are either explicitly listed in
2570 // the object type's bounds, or implied by the principal trait ref's
2571 // supertraits.
2572let a_auto_traits: FxIndexSet<DefId> = a_data2573 .auto_traits()
2574 .chain(a_data.principal_def_id().into_iter().flat_map(|principal_def_id| {
2575 elaborate::supertrait_def_ids(tcx, principal_def_id)
2576 .filter(|def_id| tcx.trait_is_auto(*def_id))
2577 }))
2578 .collect();
25792580let upcast_principal = normalize_with_depth_to(
2581self,
2582obligation.param_env,
2583obligation.cause.clone(),
2584obligation.recursion_depth + 1,
2585unnormalized_upcast_principal,
2586&mut nested,
2587 );
25882589for bound in b_data {
2590match bound.skip_binder() {
2591// Check that a_ty's supertrait (upcast_principal) is compatible
2592 // with the target (b_ty).
2593ty::ExistentialPredicate::Trait(target_principal) => {
2594let hr_source_principal = upcast_principal.map_bound(|trait_ref| {
2595 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
2596 });
2597let hr_target_principal = bound.rebind(target_principal);
25982599 nested.extend(
2600self.infcx
2601 .enter_forall(hr_target_principal, |target_principal| {
2602let source_principal =
2603self.infcx.instantiate_binder_with_fresh_vars(
2604 obligation.cause.span,
2605 HigherRankedType,
2606 hr_source_principal,
2607 );
2608self.infcx.at(&obligation.cause, obligation.param_env).eq_trace(
2609 DefineOpaqueTypes::Yes,
2610 ToTrace::to_trace(
2611&obligation.cause,
2612 hr_target_principal,
2613 hr_source_principal,
2614 ),
2615 target_principal,
2616 source_principal,
2617 )
2618 })
2619 .map_err(|_| SelectionError::Unimplemented)?
2620.into_obligations(),
2621 );
2622 }
2623// Check that b_ty's projection is satisfied by exactly one of
2624 // a_ty's projections. First, we look through the list to see if
2625 // any match. If not, error. Then, if *more* than one matches, we
2626 // return ambiguity. Otherwise, if exactly one matches, equate
2627 // it with b_ty's projection.
2628ty::ExistentialPredicate::Projection(target_projection) => {
2629let hr_target_projection = bound.rebind(target_projection);
26302631let mut matching_projections =
2632 a_data.projection_bounds().filter(|&hr_source_projection| {
2633// Eager normalization means that we can just use can_eq
2634 // here instead of equating and processing obligations.
2635hr_source_projection.item_def_id() == hr_target_projection.item_def_id()
2636 && self.infcx.probe(|_| {
2637self.infcx
2638 .enter_forall(hr_target_projection, |target_projection| {
2639let source_projection =
2640self.infcx.instantiate_binder_with_fresh_vars(
2641 obligation.cause.span,
2642 HigherRankedType,
2643 hr_source_projection,
2644 );
2645self.infcx
2646 .at(&obligation.cause, obligation.param_env)
2647 .eq_trace(
2648 DefineOpaqueTypes::Yes,
2649 ToTrace::to_trace(
2650&obligation.cause,
2651 hr_target_projection,
2652 hr_source_projection,
2653 ),
2654 target_projection,
2655 source_projection,
2656 )
2657 })
2658 .is_ok()
2659 })
2660 });
26612662let Some(hr_source_projection) = matching_projections.next() else {
2663return Err(SelectionError::Unimplemented);
2664 };
2665if matching_projections.next().is_some() {
2666return Ok(None);
2667 }
2668 nested.extend(
2669self.infcx
2670 .enter_forall(hr_target_projection, |target_projection| {
2671let source_projection =
2672self.infcx.instantiate_binder_with_fresh_vars(
2673 obligation.cause.span,
2674 HigherRankedType,
2675 hr_source_projection,
2676 );
2677self.infcx.at(&obligation.cause, obligation.param_env).eq_trace(
2678 DefineOpaqueTypes::Yes,
2679 ToTrace::to_trace(
2680&obligation.cause,
2681 hr_target_projection,
2682 hr_source_projection,
2683 ),
2684 target_projection,
2685 source_projection,
2686 )
2687 })
2688 .map_err(|_| SelectionError::Unimplemented)?
2689.into_obligations(),
2690 );
2691 }
2692// Check that b_ty's auto traits are present in a_ty's bounds.
2693ty::ExistentialPredicate::AutoTrait(def_id) => {
2694if !a_auto_traits.contains(&def_id) {
2695return Err(SelectionError::Unimplemented);
2696 }
2697 }
2698 }
2699 }
27002701nested.push(Obligation::with_depth(
2702tcx,
2703obligation.cause.clone(),
2704obligation.recursion_depth + 1,
2705obligation.param_env,
2706 ty::Binder::dummy(ty::OutlivesPredicate(a_region, b_region)),
2707 ));
27082709Ok(Some(nested))
2710 }
27112712/// Normalize `where_clause_trait_ref` and try to match it against
2713 /// `obligation`. If successful, return any predicates that
2714 /// result from the normalization.
2715fn match_where_clause_trait_ref(
2716&mut self,
2717 obligation: &PolyTraitObligation<'tcx>,
2718 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
2719 ) -> Result<PredicateObligations<'tcx>, ()> {
2720self.match_poly_trait_ref(obligation, where_clause_trait_ref)
2721 }
27222723/// Returns `Ok` if `poly_trait_ref` being true implies that the
2724 /// obligation is satisfied.
2725#[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(2725u32),
::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")]2726fn match_poly_trait_ref(
2727&mut self,
2728 obligation: &PolyTraitObligation<'tcx>,
2729 poly_trait_ref: ty::PolyTraitRef<'tcx>,
2730 ) -> Result<PredicateObligations<'tcx>, ()> {
2731let predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
2732let trait_ref = self.infcx.instantiate_binder_with_fresh_vars(
2733 obligation.cause.span,
2734 HigherRankedType,
2735 poly_trait_ref,
2736 );
2737self.infcx
2738 .at(&obligation.cause, obligation.param_env)
2739 .eq(DefineOpaqueTypes::No, predicate.trait_ref, trait_ref)
2740 .map(|InferOk { obligations, .. }| obligations)
2741 .map_err(|_| ())
2742 }
27432744///////////////////////////////////////////////////////////////////////////
2745 // Miscellany
27462747fn match_fresh_trait_preds(
2748&self,
2749 previous: ty::PolyTraitPredicate<'tcx>,
2750 current: ty::PolyTraitPredicate<'tcx>,
2751 ) -> bool {
2752let mut matcher = _match::MatchAgainstFreshVars::new(self.tcx());
2753matcher.relate(previous, current).is_ok()
2754 }
27552756fn push_stack<'o>(
2757&mut self,
2758 previous_stack: TraitObligationStackList<'o, 'tcx>,
2759 obligation: &'o PolyTraitObligation<'tcx>,
2760 ) -> TraitObligationStack<'o, 'tcx> {
2761let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
27622763let dfn = previous_stack.cache.next_dfn();
2764let depth = previous_stack.depth() + 1;
2765TraitObligationStack {
2766obligation,
2767fresh_trait_pred,
2768 reached_depth: Cell::new(depth),
2769 previous: previous_stack,
2770dfn,
2771depth,
2772 }
2773 }
27742775#[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(2775u32),
::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")]2776fn closure_trait_ref_unnormalized(
2777&mut self,
2778 self_ty: Ty<'tcx>,
2779 fn_trait_def_id: DefId,
2780 ) -> ty::PolyTraitRef<'tcx> {
2781let ty::Closure(_, args) = *self_ty.kind() else {
2782bug!("expected closure, found {self_ty}");
2783 };
2784let closure_sig = args.as_closure().sig();
27852786 closure_trait_ref_and_return_type(
2787self.tcx(),
2788 fn_trait_def_id,
2789 self_ty,
2790 closure_sig,
2791 util::TupleArgumentsFlag::No,
2792 )
2793 .map_bound(|(trait_ref, _)| trait_ref)
2794 }
27952796/// Returns the obligations that are implied by instantiating an
2797 /// impl or trait. The obligations are instantiated and fully
2798 /// normalized. This is used when confirming an impl or default
2799 /// impl.
2800#[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(2800u32),
::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, &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)
{
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))]2801fn impl_or_trait_obligations(
2802&mut self,
2803 cause: &ObligationCause<'tcx>,
2804 recursion_depth: usize,
2805 param_env: ty::ParamEnv<'tcx>,
2806 def_id: DefId, // of impl or trait
2807args: GenericArgsRef<'tcx>, // for impl or trait
2808parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2809 ) -> PredicateObligations<'tcx> {
2810let tcx = self.tcx();
28112812// To allow for one-pass evaluation of the nested obligation,
2813 // each predicate must be preceded by the obligations required
2814 // to normalize it.
2815 // for example, if we have:
2816 // impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
2817 // the impl will have the following predicates:
2818 // <V as Iterator>::Item = U,
2819 // U: Iterator, U: Sized,
2820 // V: Iterator, V: Sized,
2821 // <U as Iterator>::Item: Copy
2822 // When we instantiate, say, `V => IntoIter<u32>, U => $0`, the last
2823 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2824 // `$1: Copy`, so we must ensure the obligations are emitted in
2825 // that order.
2826let predicates = tcx.predicates_of(def_id);
2827assert_eq!(predicates.parent, None);
2828let predicates = predicates.instantiate_own(tcx, args);
2829let mut obligations = PredicateObligations::with_capacity(predicates.len());
2830for (index, (predicate, span)) in predicates.into_iter().enumerate() {
2831let cause = if tcx.is_lang_item(parent_trait_pred.def_id(), LangItem::CoerceUnsized) {
2832 cause.clone()
2833 } else {
2834 cause.clone().derived_cause(parent_trait_pred, |derived| {
2835 ObligationCauseCode::ImplDerived(Box::new(ImplDerivedCause {
2836 derived,
2837 impl_or_alias_def_id: def_id,
2838 impl_def_predicate_index: Some(index),
2839 span,
2840 }))
2841 })
2842 };
2843let clause = normalize_with_depth_to(
2844self,
2845 param_env,
2846 cause.clone(),
2847 recursion_depth,
2848 predicate,
2849&mut obligations,
2850 );
2851 obligations.push(Obligation {
2852 cause,
2853 recursion_depth,
2854 param_env,
2855 predicate: clause.as_predicate(),
2856 });
2857 }
28582859// Register any outlives obligations from the trait here, cc #124336.
2860if tcx.def_kind(def_id) == (DefKind::Impl { of_trait: true }) {
2861for clause in tcx.impl_super_outlives(def_id).iter_instantiated(tcx, args) {
2862let clause = normalize_with_depth_to(
2863self,
2864 param_env,
2865 cause.clone(),
2866 recursion_depth,
2867 clause,
2868&mut obligations,
2869 );
2870 obligations.push(Obligation {
2871 cause: cause.clone(),
2872 recursion_depth,
2873 param_env,
2874 predicate: clause.as_predicate(),
2875 });
2876 }
2877 }
28782879 obligations
2880 }
28812882pub(super) fn should_stall_coroutine(&self, def_id: DefId) -> bool {
2883match self.infcx.typing_mode() {
2884TypingMode::Analysis { defining_opaque_types_and_generators: stalled_generators } => {
2885def_id.as_local().is_some_and(|def_id| stalled_generators.contains(&def_id))
2886 }
2887TypingMode::Coherence2888 | TypingMode::PostAnalysis2889 | TypingMode::Borrowck { defining_opaque_types: _ }
2890 | TypingMode::PostBorrowckAnalysis { defined_opaque_types: _ } => false,
2891 }
2892 }
2893}
28942895impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2896fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2897TraitObligationStackList::with(self)
2898 }
28992900fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
2901self.previous.cache
2902 }
29032904fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
2905self.list()
2906 }
29072908/// Indicates that attempting to evaluate this stack entry
2909 /// required accessing something from the stack at depth `reached_depth`.
2910fn update_reached_depth(&self, reached_depth: usize) {
2911if !(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!(
2912self.depth >= reached_depth,
2913"invoked `update_reached_depth` with something under this stack: \
2914 self.depth={} reached_depth={}",
2915self.depth,
2916 reached_depth,
2917 );
2918{
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:2918",
"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(2918u32),
::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");
2919let mut p = self;
2920while reached_depth < p.depth {
2921{
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:2921",
"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(2921u32),
::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");
2922 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
2923 p = p.previous.head.unwrap();
2924 }
2925 }
2926}
29272928/// The "provisional evaluation cache" is used to store intermediate cache results
2929/// when solving auto traits. Auto traits are unusual in that they can support
2930/// cycles. So, for example, a "proof tree" like this would be ok:
2931///
2932/// - `Foo<T>: Send` :-
2933/// - `Bar<T>: Send` :-
2934/// - `Foo<T>: Send` -- cycle, but ok
2935/// - `Baz<T>: Send`
2936///
2937/// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
2938/// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
2939/// For non-auto traits, this cycle would be an error, but for auto traits (because
2940/// they are coinductive) it is considered ok.
2941///
2942/// However, there is a complication: at the point where we have
2943/// "proven" `Bar<T>: Send`, we have in fact only proven it
2944/// *provisionally*. In particular, we proved that `Bar<T>: Send`
2945/// *under the assumption* that `Foo<T>: Send`. But what if we later
2946/// find out this assumption is wrong? Specifically, we could
2947/// encounter some kind of error proving `Baz<T>: Send`. In that case,
2948/// `Bar<T>: Send` didn't turn out to be true.
2949///
2950/// In Issue #60010, we found a bug in rustc where it would cache
2951/// these intermediate results. This was fixed in #60444 by disabling
2952/// *all* caching for things involved in a cycle -- in our example,
2953/// that would mean we don't cache that `Bar<T>: Send`. But this led
2954/// to large slowdowns.
2955///
2956/// Specifically, imagine this scenario, where proving `Baz<T>: Send`
2957/// first requires proving `Bar<T>: Send` (which is true:
2958///
2959/// - `Foo<T>: Send` :-
2960/// - `Bar<T>: Send` :-
2961/// - `Foo<T>: Send` -- cycle, but ok
2962/// - `Baz<T>: Send`
2963/// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
2964/// - `*const T: Send` -- but what if we later encounter an error?
2965///
2966/// The *provisional evaluation cache* resolves this issue. It stores
2967/// cache results that we've proven but which were involved in a cycle
2968/// in some way. We track the minimal stack depth (i.e., the
2969/// farthest from the top of the stack) that we are dependent on.
2970/// The idea is that the cache results within are all valid -- so long as
2971/// none of the nodes in between the current node and the node at that minimum
2972/// depth result in an error (in which case the cached results are just thrown away).
2973///
2974/// During evaluation, we consult this provisional cache and rely on
2975/// it. Accessing a cached value is considered equivalent to accessing
2976/// a result at `reached_depth`, so it marks the *current* solution as
2977/// provisional as well. If an error is encountered, we toss out any
2978/// provisional results added from the subtree that encountered the
2979/// error. When we pop the node at `reached_depth` from the stack, we
2980/// can commit all the things that remain in the provisional cache.
2981struct ProvisionalEvaluationCache<'tcx> {
2982/// next "depth first number" to issue -- just a counter
2983dfn: Cell<usize>,
29842985/// Map from cache key to the provisionally evaluated thing.
2986 /// The cache entries contain the result but also the DFN in which they
2987 /// were added. The DFN is used to clear out values on failure.
2988 ///
2989 /// Imagine we have a stack like:
2990 ///
2991 /// - `A B C` and we add a cache for the result of C (DFN 2)
2992 /// - Then we have a stack `A B D` where `D` has DFN 3
2993 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
2994 /// - `E` generates various cache entries which have cyclic dependencies on `B`
2995 /// - `A B D E F` and so forth
2996 /// - the DFN of `F` for example would be 5
2997 /// - then we determine that `E` is in error -- we will then clear
2998 /// all cache values whose DFN is >= 4 -- in this case, that
2999 /// means the cached value for `F`.
3000map: RefCell<FxIndexMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
30013002/// The stack of terms that we assume to be well-formed because a `WF(term)` predicate
3003 /// is on the stack above (and because of wellformedness is coinductive).
3004 /// In an "ideal" world, this would share a stack with trait predicates in
3005 /// `TraitObligationStack`. However, trait predicates are *much* hotter than
3006 /// `WellFormed` predicates, and it's very likely that the additional matches
3007 /// will have a perf effect. The value here is the well-formed `GenericArg`
3008 /// and the depth of the trait predicate *above* that well-formed predicate.
3009wf_args: RefCell<Vec<(ty::Term<'tcx>, usize)>>,
3010}
30113012/// A cache value for the provisional cache: contains the depth-first
3013/// number (DFN) and result.
3014#[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)]
3015struct ProvisionalEvaluation {
3016 from_dfn: usize,
3017 reached_depth: usize,
3018 result: EvaluationResult,
3019}
30203021impl<'tcx> Defaultfor ProvisionalEvaluationCache<'tcx> {
3022fn default() -> Self {
3023Self { dfn: Cell::new(0), map: Default::default(), wf_args: Default::default() }
3024 }
3025}
30263027impl<'tcx> ProvisionalEvaluationCache<'tcx> {
3028/// Get the next DFN in sequence (basically a counter).
3029fn next_dfn(&self) -> usize {
3030let result = self.dfn.get();
3031self.dfn.set(result + 1);
3032result3033 }
30343035/// Check the provisional cache for any result for
3036 /// `fresh_trait_pred`. If there is a hit, then you must consider
3037 /// it an access to the stack slots at depth
3038 /// `reached_depth` (from the returned value).
3039fn get_provisional(
3040&self,
3041 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
3042 ) -> Option<ProvisionalEvaluation> {
3043{
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:3043",
"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(3043u32),
::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!(
3044?fresh_trait_pred,
3045"get_provisional = {:#?}",
3046self.map.borrow().get(&fresh_trait_pred),
3047 );
3048Some(*self.map.borrow().get(&fresh_trait_pred)?)
3049 }
30503051/// Insert a provisional result into the cache. The result came
3052 /// from the node with the given DFN. It accessed a minimum depth
3053 /// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
3054 /// and resulted in `result`.
3055fn insert_provisional(
3056&self,
3057 from_dfn: usize,
3058 reached_depth: usize,
3059 fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
3060 result: EvaluationResult,
3061 ) {
3062{
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:3062",
"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(3062u32),
::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");
30633064let mut map = self.map.borrow_mut();
30653066// Subtle: when we complete working on the DFN `from_dfn`, anything
3067 // that remains in the provisional cache must be dependent on some older
3068 // stack entry than `from_dfn`. We have to update their depth with our transitive
3069 // depth in that case or else it would be referring to some popped note.
3070 //
3071 // Example:
3072 // A (reached depth 0)
3073 // ...
3074 // B // depth 1 -- reached depth = 0
3075 // C // depth 2 -- reached depth = 1 (should be 0)
3076 // B
3077 // A // depth 0
3078 // D (reached depth 1)
3079 // C (cache -- reached depth = 2)
3080for (_k, v) in &mut *map {
3081if v.from_dfn >= from_dfn {
3082 v.reached_depth = reached_depth.min(v.reached_depth);
3083 }
3084 }
30853086map.insert(fresh_trait_pred, ProvisionalEvaluation { from_dfn, reached_depth, result });
3087 }
30883089/// Invoked when the node with dfn `dfn` does not get a successful
3090 /// result. This will clear out any provisional cache entries
3091 /// that were added since `dfn` was created. This is because the
3092 /// provisional entries are things which must assume that the
3093 /// things on the stack at the time of their creation succeeded --
3094 /// since the failing node is presently at the top of the stack,
3095 /// these provisional entries must either depend on it or some
3096 /// ancestor of it.
3097fn on_failure(&self, dfn: usize) {
3098{
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:3098",
"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(3098u32),
::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");
3099self.map.borrow_mut().retain(|key, eval| {
3100if !eval.from_dfn >= dfn {
3101{
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:3101",
"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(3101u32),
::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);
3102false
3103} else {
3104true
3105}
3106 });
3107 }
31083109/// Invoked when the node at depth `depth` completed without
3110 /// depending on anything higher in the stack (if that completion
3111 /// was a failure, then `on_failure` should have been invoked
3112 /// already).
3113 ///
3114 /// Note that we may still have provisional cache items remaining
3115 /// in the cache when this is done. For example, if there is a
3116 /// cycle:
3117 ///
3118 /// * A depends on...
3119 /// * B depends on A
3120 /// * C depends on...
3121 /// * D depends on C
3122 /// * ...
3123 ///
3124 /// Then as we complete the C node we will have a provisional cache
3125 /// with results for A, B, C, and D. This method would clear out
3126 /// the C and D results, but leave A and B provisional.
3127 ///
3128 /// This is determined based on the DFN: we remove any provisional
3129 /// results created since `dfn` started (e.g., in our example, dfn
3130 /// would be 2, representing the C node, and hence we would
3131 /// remove the result for D, which has DFN 3, but not the results for
3132 /// A and B, which have DFNs 0 and 1 respectively).
3133 ///
3134 /// Note that we *do not* attempt to cache these cycle participants
3135 /// in the evaluation cache. Doing so would require carefully computing
3136 /// the correct `DepNode` to store in the cache entry:
3137 /// cycle participants may implicitly depend on query results
3138 /// related to other participants in the cycle, due to our logic
3139 /// which examines the evaluation stack.
3140 ///
3141 /// We used to try to perform this caching,
3142 /// but it lead to multiple incremental compilation ICEs
3143 /// (see #92987 and #96319), and was very hard to understand.
3144 /// Fortunately, removing the caching didn't seem to
3145 /// have a performance impact in practice.
3146fn on_completion(&self, dfn: usize) {
3147{
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:3147",
"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(3147u32),
::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");
3148self.map.borrow_mut().retain(|fresh_trait_pred, eval| {
3149if eval.from_dfn >= dfn {
3150{
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:3150",
"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(3150u32),
::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");
3151return false;
3152 }
3153true
3154});
3155 }
3156}
31573158#[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)]
3159struct TraitObligationStackList<'o, 'tcx> {
3160 cache: &'o ProvisionalEvaluationCache<'tcx>,
3161 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
3162}
31633164impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
3165fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3166TraitObligationStackList { cache, head: None }
3167 }
31683169fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
3170TraitObligationStackList { cache: r.cache(), head: Some(r) }
3171 }
31723173fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3174self.head
3175 }
31763177fn depth(&self) -> usize {
3178if let Some(head) = self.head { head.depth } else { 0 }
3179 }
3180}
31813182impl<'o, 'tcx> Iteratorfor TraitObligationStackList<'o, 'tcx> {
3183type Item = &'o TraitObligationStack<'o, 'tcx>;
31843185fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
3186let o = self.head?;
3187*self = o.previous;
3188Some(o)
3189 }
3190}
31913192impl<'o, 'tcx> fmt::Debugfor TraitObligationStack<'o, 'tcx> {
3193fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3194f.write_fmt(format_args!("TraitObligationStack({0:?})", self.obligation))write!(f, "TraitObligationStack({:?})", self.obligation)3195 }
3196}
31973198pub(crate) enum ProjectionMatchesProjection {
3199 Yes,
3200 Ambiguous,
3201 No,
3202}
32033204#[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)]
3205pub(crate) struct AutoImplConstituents<'tcx> {
3206pub types: Vec<Ty<'tcx>>,
3207pub assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
3208}