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