1//! Support code for rustdoc and external tools.
2//! You really don't want to be using this unless you need to.
34use std::collections::VecDeque;
5use std::iter;
67use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, IndexEntry};
8use rustc_data_structures::unord::UnordSet;
9use rustc_hir::def_id::CRATE_DEF_ID;
10use rustc_infer::infer::{DefineOpaqueTypes, RegionVariableOrigin};
11use rustc_middle::ty::{Region, RegionVid};
12use rustc_span::DUMMY_SP;
13use tracing::debug;
1415use super::*;
16use crate::diagnostics::UnableToConstructConstantValue;
17use crate::infer::TypeFreshener;
18use crate::infer::region_constraints::{ConstraintKind, RegionConstraintData};
19use crate::regions::OutlivesEnvironmentBuildExt;
20use crate::traits::project::ProjectAndUnifyResult;
2122// FIXME(twk): this is obviously not nice to duplicate like that
23#[derive(#[automatically_derived]impl<'tcx> ::core::cmp::Eq for RegionTarget<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Region<'tcx>>;
let _: ::core::cmp::AssertParamIsEq<RegionVid>;
}
}Eq, #[automatically_derived]impl<'tcx> ::core::marker::StructuralPartialEq for
RegionTarget<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::cmp::PartialEq for
RegionTarget<'tcx> {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Region(__self_0), Self::Region(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::RegionVid(__self_0), Self::RegionVid(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]impl<'tcx> ::core::hash::Hash for RegionTarget<'tcx> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state);
match self {
Self::Region(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::RegionVid(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
}
}
}Hash, #[automatically_derived]impl<'tcx> ::core::marker::Copy for RegionTarget<'tcx>
{
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for RegionTarget<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for RegionTarget<'tcx>
{
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Region<'tcx>>;
let _: ::core::clone::AssertParamIsClone<RegionVid>;
*self
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for RegionTarget<'tcx> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Region(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Region", &__self_0),
Self::RegionVid(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"RegionVid", &__self_0),
}
}
}Debug)]
24pub enum RegionTarget<'tcx> {
25 Region(Region<'tcx>),
26 RegionVid(RegionVid),
27}
2829#[derive(#[automatically_derived]impl<'tcx> ::core::default::Default for
RegionDeps<'tcx> {
#[inline]
fn default() -> Self {
RegionDeps {
larger: ::core::default::Default::default(),
smaller: ::core::default::Default::default(),
}
}
}Default, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for RegionDeps<'tcx> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"RegionDeps larger smaller", &self.larger, &&self.smaller)
}
}Debug, #[automatically_derived]impl<'tcx> ::core::clone::Clone for RegionDeps<'tcx> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
RegionDeps {
larger: ::core::clone::Clone::clone(&self.larger),
smaller: ::core::clone::Clone::clone(&self.smaller),
}
}
}Clone)]
30pub struct RegionDeps<'tcx> {
31pub larger: FxIndexSet<RegionTarget<'tcx>>,
32pub smaller: FxIndexSet<RegionTarget<'tcx>>,
33}
3435pub enum AutoTraitResult<A> {
36 NoImpl,
37 ExplicitImpl,
38 PositiveImpl(A),
39 NegativeImpl,
40}
4142pub struct AutoTraitInfo<'cx> {
43pub full_user_env: ty::ParamEnv<'cx>,
44pub region_data: RegionConstraintData<'cx>,
45pub vid_to_region: FxIndexMap<ty::RegionVid, ty::Region<'cx>>,
46}
4748pub struct AutoTraitFinder<'tcx> {
49 tcx: TyCtxt<'tcx>,
50}
5152impl<'tcx> AutoTraitFinder<'tcx> {
53pub fn new(tcx: TyCtxt<'tcx>) -> Self {
54AutoTraitFinder { tcx }
55 }
5657/// Makes a best effort to determine whether and under which conditions an auto trait is
58 /// implemented for a type. For example, if you have
59 ///
60 /// ```
61 /// struct Foo<T> { data: Box<T> }
62 /// ```
63 ///
64 /// then this might return that `Foo<T>: Send` if `T: Send` (encoded in the AutoTraitResult
65 /// type). The analysis attempts to account for custom impls as well as other complex cases.
66 /// This result is intended for use by rustdoc and other such consumers.
67 ///
68 /// (Note that due to the coinductive nature of Send, the full and correct result is actually
69 /// quite simple to generate. That is, when a type has no custom impl, it is Send iff its field
70 /// types are all Send. So, in our example, we might have that `Foo<T>: Send` if `Box<T>: Send`.
71 /// But this is often not the best way to present to the user.)
72 ///
73 /// Warning: The API should be considered highly unstable, and it may be refactored or removed
74 /// in the future.
75pub fn find_auto_trait_generics<A>(
76&self,
77 ty: Ty<'tcx>,
78 typing_env: ty::TypingEnv<'tcx>,
79 trait_did: DefId,
80mut auto_trait_callback: impl FnMut(AutoTraitInfo<'tcx>) -> A,
81 ) -> AutoTraitResult<A> {
82let tcx = self.tcx;
8384// Without `#![feature(forget_trait)]`, assume absolutely all types are forget.
85 // Without `#![feature(move_trait)]`, assume absolutely all types are move.
86if !tcx.features().forget_trait() && tcx.is_forget_trait(trait_did)
87 || !tcx.features().move_trait() && tcx.is_move_trait(trait_did)
88 {
89let info = AutoTraitInfo {
90 full_user_env: typing_env.param_env,
91 region_data: Default::default(),
92 vid_to_region: Default::default(),
93 };
94return AutoTraitResult::PositiveImpl(auto_trait_callback(info));
95 }
9697if tcx.next_trait_solver_globally() {
98return self.find_auto_trait_generics_next_solver(
99ty,
100typing_env,
101trait_did,
102auto_trait_callback,
103 );
104 }
105106let trait_ref = ty::TraitRef::new(tcx, trait_did, [ty]);
107108let (infcx, orig_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
109let mut selcx = SelectionContext::new(&infcx);
110for polarity in [ty::ClausePolarity::Positive, ty::ClausePolarity::Negative] {
111let result = selcx.select(&Obligation::new(
112 tcx,
113 ObligationCause::dummy(),
114 orig_env,
115 ty::TraitClause { trait_ref, polarity },
116 ));
117if let Ok(Some(ImplSource::UserDefined(_))) = result {
118{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:118",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(118u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("find_auto_trait_generics({0:?}): manual impl found, bailing out",
trait_ref) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("find_auto_trait_generics({trait_ref:?}): manual impl found, bailing out");
119// If an explicit impl exists, it always takes priority over an auto impl
120return AutoTraitResult::ExplicitImpl;
121 }
122 }
123124let (infcx, orig_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
125let mut fresh_preds = FxIndexSet::default();
126127// Due to the way projections are handled by SelectionContext, we need to run
128 // evaluate_predicates twice: once on the original param env, and once on the result of
129 // the first evaluate_predicates call.
130 //
131 // The problem is this: most of rustc, including SelectionContext and traits::project,
132 // are designed to work with a concrete usage of a type (e.g., Vec<u8>
133 // fn<T>() { Vec<T> }. This information will generally never change - given
134 // the 'T' in fn<T>() { ... }, we'll never know anything else about 'T'.
135 // If we're unable to prove that 'T' implements a particular trait, we're done -
136 // there's nothing left to do but error out.
137 //
138 // However, synthesizing an auto trait impl works differently. Here, we start out with
139 // a set of initial conditions - the ParamEnv of the struct/enum/union we're dealing
140 // with - and progressively discover the conditions we need to fulfill for it to
141 // implement a certain auto trait. This ends up breaking two assumptions made by trait
142 // selection and projection:
143 //
144 // * We can always cache the result of a particular trait selection for the lifetime of
145 // an InfCtxt
146 // * Given a projection bound such as '<T as SomeTrait>::SomeItem = K', if 'T:
147 // SomeTrait' doesn't hold, then we don't need to care about the 'SomeItem = K'
148 //
149 // We fix the first assumption by manually clearing out all of the InferCtxt's caches
150 // in between calls to SelectionContext.select. This allows us to keep all of the
151 // intermediate types we create bound to the 'tcx lifetime, rather than needing to lift
152 // them between calls.
153 //
154 // We fix the second assumption by reprocessing the result of our first call to
155 // evaluate_predicates. Using the example of '<T as SomeTrait>::SomeItem = K', our first
156 // pass will pick up 'T: SomeTrait', but not 'SomeItem = K'. On our second pass,
157 // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing
158 // SelectionContext to return it back to us.
159160let Some((new_env, user_env)) =
161self.evaluate_predicates(&infcx, trait_did, ty, orig_env, orig_env, &mut fresh_preds)
162else {
163return AutoTraitResult::NegativeImpl;
164 };
165166let (full_env, full_user_env) = self167 .evaluate_predicates(&infcx, trait_did, ty, new_env, user_env, &mut fresh_preds)
168 .unwrap_or_else(|| {
169{
::core::panicking::panic_fmt(format_args!("Failed to fully process: {0:?} {1:?} {2:?}",
ty, trait_did, orig_env));
}panic!("Failed to fully process: {ty:?} {trait_did:?} {orig_env:?}")170 });
171172{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:172",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(172u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("find_auto_trait_generics({0:?}): fulfilling with {1:?}",
trait_ref, full_env) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
173"find_auto_trait_generics({:?}): fulfilling \
174 with {:?}",
175 trait_ref, full_env
176 );
177178// At this point, we already have all of the bounds we need. FulfillmentContext is used
179 // to store all of the necessary region/lifetime bounds in the InferContext, as well as
180 // an additional sanity check.
181let ocx = ObligationCtxt::new(&infcx);
182ocx.register_bound(ObligationCause::dummy(), full_env, ty, trait_did);
183let errors = ocx.evaluate_obligations_error_on_ambiguity();
184if !errors.no_errors() {
185{
::core::panicking::panic_fmt(format_args!("Unable to fulfill trait {0:?} for \'{1:?}\': {2:?}",
trait_did, ty, errors));
};panic!("Unable to fulfill trait {trait_did:?} for '{ty:?}': {errors:?}");
186 }
187188let outlives_env = OutlivesEnvironment::new(&infcx, CRATE_DEF_ID, full_env, []);
189let _ = infcx.process_registered_type_outlives_constraints(&outlives_env);
190191// FIXME(-Zassumptions-on-binders): Handle solver_data
192let region_data =
193infcx.inner.borrow_mut().unwrap_region_constraints().legacy_data().clone();
194195let vid_to_region = self.map_vid_to_region(®ion_data);
196197let info = AutoTraitInfo { full_user_env, region_data, vid_to_region };
198199 AutoTraitResult::PositiveImpl(auto_trait_callback(info))
200 }
201202fn find_auto_trait_generics_next_solver<A>(
203&self,
204 ty: Ty<'tcx>,
205 typing_env: ty::TypingEnv<'tcx>,
206 trait_did: DefId,
207mut auto_trait_callback: impl FnMut(AutoTraitInfo<'tcx>) -> A,
208 ) -> AutoTraitResult<A> {
209// When the new solver is enabled globally we keep things deliberately
210 // simple. The precise auto-trait synthesis depends on old-solver
211 // internals, so here we only synthesize a simple field-based auto-trait
212 // impl for ADTs, primitives and some simple types such as tuples.
213 //
214 // If the self type is none of those we return `NoImpl` instead of trying
215 // to do anything fancy. To decide whether to emit a negative impl, we
216 // replace the ty's generic arguments with inference variables and
217 // check whether the auto trait can hold. A true error from that probe
218 // becomes a `NegativeImpl`, otherwise we continue on to emit the
219 // imprecise field-based impl.
220 //
221 // This keeps rustdoc from ICE-ing while `-Znext-solver=globally` is
222 // used for testing, even if the generated synthetic impls are less
223 // precise.
224match *ty.kind() {
225// Uninteresting or shouldn't be encountered types.
226 // Perhaps we'd like to assert on the later, but since this is
227 // a makeshift hack so let's not break things.
228ty::Foreign(_)
229 | ty::FnDef(_, _)
230 | ty::UnsafeBinder(_)
231 | ty::Dynamic(_, _)
232 | ty::Closure(_, _)
233 | ty::CoroutineClosure(_, _)
234 | ty::Coroutine(_, _)
235 | ty::CoroutineWitness(_, _)
236 | ty::Bound(_, _)
237 | ty::Placeholder(_)
238 | ty::Infer(_)
239 | ty::Error(_)
240 | ty::Param(_) => {
241return AutoTraitResult::NoImpl;
242 }
243244 ty::Bool245 | ty::Char246 | ty::Int(_)
247 | ty::Uint(_)
248 | ty::Float(_)
249 | ty::Adt(_, _)
250 | ty::Str251 | ty::Array(_, _)
252 | ty::Pat(_, _)
253 | ty::Slice(_)
254 | ty::RawPtr(_, _)
255 | ty::Ref(_, _, _)
256 | ty::FnPtr(_, _)
257 | ty::Never258 | ty::Tuple(_)
259 | ty::Alias(_, _) => {}
260261 ty::View(..) => {
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("FIXME: View type")));
}unimplemented!("FIXME: View type"),
262 }
263264let tcx = self.tcx;
265266let mut disqualifying_impl = None;
267tcx.for_each_relevant_impl(trait_did, ty, |impl_def_id| {
268disqualifying_impl = Some(impl_def_id);
269 });
270if let Some(impl_def_id) = disqualifying_impl {
271{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:271",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(271u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("find_auto_trait_generics({0:?}): possible manual impl {1:?} found, bailing",
ty::TraitRef::new(tcx, trait_did, [ty]), impl_def_id) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
272"find_auto_trait_generics({:?}): possible manual impl {impl_def_id:?} found, bailing",
273 ty::TraitRef::new(tcx, trait_did, [ty]),
274 );
275return AutoTraitResult::ExplicitImpl;
276 }
277278let (infcx, orig_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
279let fresh_ty = if !ty.has_param() {
280ty281 } else {
282// We manually instantiate the generic args with inference variables
283 // here to also trivially handle builtin types.
284let mut tys = FxHashMap::default();
285let mut regions = FxHashMap::default();
286let mut consts = FxHashMap::default();
287ty.fold_with(&mut ty::BottomUpFolder {
288tcx,
289 ty_op: |ty| {
290let ty::Param(_) = *ty.kind() else {
291return ty;
292 };
293*tys.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
294 },
295 lt_op: |lt| {
296let ty::ReEarlyParam(param) = lt.kind() else {
297return lt;
298 };
299*regions.entry(lt).or_insert_with(|| {
300infcx.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
301DUMMY_SP, param.name,
302 ))
303 })
304 },
305 ct_op: |ct| {
306let ty::ConstKind::Param(_) = ct.kind() else {
307return ct;
308 };
309*consts.entry(ct).or_insert_with(|| infcx.next_const_var(DUMMY_SP))
310 },
311 })
312 };
313let ocx = ObligationCtxt::new(&infcx);
314ocx.register_bound(ObligationCause::dummy(), orig_env, fresh_ty, trait_did);
315let errors = ocx.try_evaluate_obligations();
316if !errors.no_errors() {
317return AutoTraitResult::NegativeImpl;
318 }
319320/// Gather types that needs to be the RHS of the where bounds for auto trait impls,
321 /// by recursing into each field type. This is a recursive function rather than a
322 /// `TypeVisitor` because we have to look into nested fields.
323fn gather_constituent_tys<'tcx>(
324 tcx: TyCtxt<'tcx>,
325 ty: Ty<'tcx>,
326 trait_did: DefId,
327 constituents: &mut Vec<Ty<'tcx>>,
328 visited: &mut FxHashSet<Ty<'tcx>>,
329 depth: usize,
330 ) {
331if !tcx.recursion_limit().value_within_limit(depth) {
332return;
333 }
334335if !visited.insert(ty) {
336return;
337 }
338339let depth = depth + 1;
340341// If the type has any explicit impl for the trait, we just add a
342 // `where {type}: Trait` bound instead of recursing into its nested fields.
343let mut has_disqualifying_impl = false;
344tcx.for_each_relevant_impl(trait_did, ty, |_| {
345has_disqualifying_impl = true;
346 });
347if has_disqualifying_impl {
348constituents.push(ty);
349return;
350 }
351352match *ty.kind() {
353 ty::Param(_) => {
354constituents.push(ty);
355 }
356357// Primitive types which don't need to consider generics
358ty::Bool359 | ty::Char360 | ty::Int(_)
361 | ty::Uint(_)
362 | ty::Float(_)
363 | ty::Never364 | ty::Str365 | ty::FnPtr(_, _) => {}
366367 ty::Adt(adt_def, args) => {
368// For `PhantomData<T>`, we pass `T`.
369if adt_def.is_phantom_data() {
370gather_constituent_tys(
371tcx,
372args.type_at(0),
373trait_did,
374constituents,
375visited,
376depth,
377 );
378return;
379 }
380381for field_ty in
382adt_def.all_fields().map(|field| field.ty(tcx, args).skip_norm_wip())
383 {
384 gather_constituent_tys(
385 tcx,
386 field_ty,
387 trait_did,
388 constituents,
389 visited,
390 depth,
391 );
392 }
393 }
394395 ty::RawPtr(elem, _) | ty::Ref(_, elem, _) => {
396gather_constituent_tys(tcx, elem, trait_did, constituents, visited, depth);
397 }
398399 ty::Array(elem, _) | ty::Pat(elem, _) | ty::Slice(elem) => {
400gather_constituent_tys(tcx, elem, trait_did, constituents, visited, depth);
401 }
402 ty::Tuple(tys) => {
403for elem in tys {
404 gather_constituent_tys(tcx, elem, trait_did, constituents, visited, depth);
405 }
406 }
407408// Aliases can be mentioned in fields
409ty::Alias(_, _) => {
410constituents.push(ty);
411 }
412413 ty::Foreign(_)
414 | ty::FnDef(_, _)
415 | ty::UnsafeBinder(_)
416 | ty::Dynamic(_, _)
417 | ty::Closure(_, _)
418 | ty::CoroutineClosure(_, _)
419 | ty::Coroutine(_, _)
420 | ty::CoroutineWitness(_, _)
421 | ty::Bound(_, _)
422 | ty::Placeholder(_)
423 | ty::Infer(_)
424 | ty::Error(_) => {}
425426 ty::View(..) => {
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("FIXME: View type")));
}unimplemented!("FIXME: View type"),
427 }
428 }
429430let mut constituent_tys = ::alloc::vec::Vec::new()vec![];
431gather_constituent_tys(
432tcx,
433ty,
434trait_did,
435&mut constituent_tys,
436&mut Default::default(),
4370,
438 );
439440let full_user_env: Vec<_> = orig_env441 .caller_bounds()
442 .all_clauses_interned(tcx)
443 .iter()
444 .chain(constituent_tys.into_iter().map(|constituent_ty| {
445 ty::TraitClause {
446 trait_ref: ty::TraitRef::new(tcx, trait_did, [constituent_ty]),
447 polarity: ty::ClausePolarity::Positive,
448 }
449 .upcast(tcx)
450 }))
451 .collect();
452let full_user_env = if full_user_env.has_aliases() {
453// We already have `normalize_param_env_or_error` and this does
454 // the similar thing. But we cannot use it because..
455 //
456 // - `normalize_param_env_or_error` elaborates the clauses but
457 // we don't want to do that here.
458 // - Instead of erroring, we'd like to just fallback to
459 // unnormalized clauses.
460 //
461 // And `normalize_param_env_or_error` normalizes outlives clauses
462 // separately to avoid lots of inferred otlives predicates on
463 // assoc types causing problems but we don't need to do that because
464 // we don't elaborate the clauses to be normalized.
465let elaborated_env: Vec<_> =
466 util::elaborate(tcx, full_user_env.iter().copied()).collect();
467let elaborated_env = ty::set_type_aliases_to_rigid(tcx, elaborated_env);
468let elaborated_env =
469 ty::ParamEnv::new(tcx, set_projection_term_to_non_rigid(tcx, elaborated_env));
470let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
471let ocx = ObligationCtxt::new(&infcx);
472let normalized = ocx.normalize(
473&ObligationCause::dummy(),
474elaborated_env,
475Unnormalized::new_wip(full_user_env.clone()),
476 );
477478let errors = ocx.evaluate_obligations_error_on_ambiguity();
479let normalized = infcx.deeply_resolve_ignoring_regions(normalized);
480481if errors.has_errors() || normalized.has_infer() { full_user_env } else { normalized }
482 } else {
483full_user_env484 };
485486let info = AutoTraitInfo {
487 full_user_env: ty::ParamEnv::new(tcx, full_user_env),
488 region_data: RegionConstraintData::default(),
489 vid_to_region: FxIndexMap::default(),
490 };
491 AutoTraitResult::PositiveImpl(auto_trait_callback(info))
492 }
493494/// The core logic responsible for computing the bounds for our synthesized impl.
495 ///
496 /// To calculate the bounds, we call `SelectionContext.select` in a loop. Like
497 /// `FulfillmentContext`, we recursively select the nested obligations of predicates we
498 /// encounter. However, whenever we encounter an `UnimplementedError` involving a type
499 /// parameter, we add it to our `ParamEnv`. Since our goal is to determine when a particular
500 /// type implements an auto trait, Unimplemented errors tell us what conditions need to be met.
501 ///
502 /// This method ends up working somewhat similarly to `FulfillmentContext`, but with a few key
503 /// differences. `FulfillmentContext` works under the assumption that it's dealing with concrete
504 /// user code. According, it considers all possible ways that a `Predicate` could be met, which
505 /// isn't always what we want for a synthesized impl. For example, given the predicate `T:
506 /// Iterator`, `FulfillmentContext` can end up reporting an Unimplemented error for `T:
507 /// IntoIterator` -- since there's an implementation of `Iterator` where `T: IntoIterator`,
508 /// `FulfillmentContext` will drive `SelectionContext` to consider that impl before giving up.
509 /// If we were to rely on `FulfillmentContext`s decision, we might end up synthesizing an impl
510 /// like this:
511 /// ```ignore (illustrative)
512 /// impl<T> Send for Foo<T> where T: IntoIterator
513 /// ```
514 /// While it might be technically true that Foo implements Send where `T: IntoIterator`,
515 /// the bound is overly restrictive - it's really only necessary that `T: Iterator`.
516 ///
517 /// For this reason, `evaluate_predicates` handles predicates with type variables specially.
518 /// When we encounter an `Unimplemented` error for a bound such as `T: Iterator`, we immediately
519 /// add it to our `ParamEnv`, and add it to our stack for recursive evaluation. When we later
520 /// select it, we'll pick up any nested bounds, without ever inferring that `T: IntoIterator`
521 /// needs to hold.
522 ///
523 /// One additional consideration is supertrait bounds. Normally, a `ParamEnv` is only ever
524 /// constructed once for a given type. As part of the construction process, the `ParamEnv` will
525 /// have any supertrait bounds normalized -- e.g., if we have a type `struct Foo<T: Copy>`, the
526 /// `ParamEnv` will contain `T: Copy` and `T: Clone`, since `Copy: Clone`. When we construct our
527 /// own `ParamEnv`, we need to do this ourselves, through `traits::elaborate`, or
528 /// else `SelectionContext` will choke on the missing predicates. However, this should never
529 /// show up in the final synthesized generics: we don't want our generated docs page to contain
530 /// something like `T: Copy + Clone`, as that's redundant. Therefore, we keep track of a
531 /// separate `user_env`, which only holds the predicates that will actually be displayed to the
532 /// user.
533fn evaluate_predicates(
534&self,
535 infcx: &InferCtxt<'tcx>,
536 trait_did: DefId,
537 ty: Ty<'tcx>,
538 param_env: ty::ParamEnv<'tcx>,
539 user_env: ty::ParamEnv<'tcx>,
540 fresh_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
541 ) -> Option<(ty::ParamEnv<'tcx>, ty::ParamEnv<'tcx>)> {
542let tcx = infcx.tcx;
543544// Don't try to process any nested obligations involving predicates
545 // that are already in the `ParamEnv` (modulo regions): we already
546 // know that they must hold.
547for clause in param_env.caller_bounds().all_clauses_interned(infcx.tcx).iter() {
548 fresh_preds.insert(self.clean_pred(infcx, clause.as_predicate()));
549 }
550551let mut select = SelectionContext::new(infcx);
552553let mut already_visited = UnordSet::new();
554let mut predicates = VecDeque::new();
555predicates.push_back(ty::Binder::dummy(ty::TraitClause {
556 trait_ref: ty::TraitRef::new(infcx.tcx, trait_did, [ty]),
557558// Auto traits are positive
559polarity: ty::ClausePolarity::Positive,
560 }));
561562let computed_clauses =
563param_env.caller_bounds().all_clauses_interned(infcx.tcx).iter().collect::<Vec<_>>();
564let mut user_computed_clauses: FxIndexSet<_> =
565user_env.caller_bounds().all_clauses_interned(infcx.tcx).iter().collect();
566let mut prev_user_computed_clauses = None::<FxIndexSet<_>>;
567568let mut new_env = param_env;
569let dummy_cause = ObligationCause::dummy();
570571while let Some(pred) = predicates.pop_front() {
572if !already_visited.insert(pred) {
573continue;
574 }
575576// Call `infcx.deeply_resolve_ignoring_regions` to see if we can
577 // get rid of any inference variables.
578let obligation = infcx.deeply_resolve_ignoring_regions(Obligation::new(
579 tcx,
580 dummy_cause.clone(),
581 new_env,
582 pred,
583 ));
584let result = select.poly_select(&obligation);
585586match result {
587Ok(Some(ref impl_source)) => {
588// If we see an explicit negative impl (e.g., `impl !Send for MyStruct`),
589 // we immediately bail out, since it's impossible for us to continue.
590591if let ImplSource::UserDefined(ImplSourceUserDefinedData {
592 impl_def_id, ..
593 }) = impl_source
594 {
595// Blame 'tidy' for the weird bracket placement.
596if infcx.tcx.impl_polarity(*impl_def_id) != ty::ImplPolarity::Positive {
597{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:597",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(597u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("evaluate_nested_obligations: found explicit negative impl{0:?}, bailing out",
impl_def_id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
598"evaluate_nested_obligations: found explicit negative impl\
599 {:?}, bailing out",
600 impl_def_id
601 );
602return None;
603 }
604 }
605606let obligations = impl_source.borrow_nested_obligations().iter().cloned();
607608if !self.evaluate_nested_obligations(
609 ty,
610 obligations,
611&mut user_computed_clauses,
612 fresh_preds,
613&mut predicates,
614&mut select,
615 ) {
616return None;
617 }
618 }
619Ok(None) => {}
620Err(SelectionError::Unimplemented) => {
621if self.is_param_no_infer(pred.skip_binder().trait_ref.args) {
622 already_visited.remove(&pred);
623self.add_user_clause(&mut user_computed_clauses, pred.upcast(self.tcx));
624 predicates.push_back(pred);
625 } else {
626{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:626",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(626u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("evaluate_nested_obligations: `Unimplemented` found, bailing: {0:?} {1:?} {2:?}",
ty, pred, pred.skip_binder().trait_ref.args) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
627"evaluate_nested_obligations: `Unimplemented` found, bailing: \
628 {:?} {:?} {:?}",
629 ty,
630 pred,
631 pred.skip_binder().trait_ref.args
632 );
633return None;
634 }
635 }
636_ => {
::core::panicking::panic_fmt(format_args!("Unexpected error for \'{0:?}\': {1:?}",
ty, result));
}panic!("Unexpected error for '{ty:?}': {result:?}"),
637 };
638639// `computed_clauses` doesn't change, only `user_computed_clauses` does.
640 // except not always! If it didn't, we can stop here.
641if prev_user_computed_clauses
642 .as_ref()
643 .is_some_and(|prev| prev == &user_computed_clauses)
644 {
645continue;
646 }
647 prev_user_computed_clauses = Some(user_computed_clauses.clone());
648649let normalized_preds = elaborate(
650 tcx,
651 computed_clauses.iter().copied().chain(user_computed_clauses.iter().cloned()),
652 );
653 new_env = ty::ParamEnv::new(tcx, normalized_preds);
654 }
655656let final_user_env = ty::ParamEnv::new(tcx, user_computed_clauses.into_iter());
657{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:657",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(657u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("evaluate_nested_obligations(ty={0:?}, trait_did={1:?}): succeeded with \'{2:?}\' \'{3:?}\'",
ty, trait_did, new_env, final_user_env) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
658"evaluate_nested_obligations(ty={:?}, trait_did={:?}): succeeded with '{:?}' \
659 '{:?}'",
660 ty, trait_did, new_env, final_user_env
661 );
662663Some((new_env, final_user_env))
664 }
665666/// This method is designed to work around the following issue:
667 /// When we compute auto trait bounds, we repeatedly call `SelectionContext.select`,
668 /// progressively building a `ParamEnv` based on the results we get.
669 /// However, our usage of `SelectionContext` differs from its normal use within the compiler,
670 /// in that we capture and re-reprocess predicates from `Unimplemented` errors.
671 ///
672 /// This can lead to a corner case when dealing with region parameters.
673 /// During our selection loop in `evaluate_predicates`, we might end up with
674 /// two trait predicates that differ only in their region parameters:
675 /// one containing a HRTB lifetime parameter, and one containing a 'normal'
676 /// lifetime parameter. For example:
677 /// ```ignore (illustrative)
678 /// T as MyTrait<'a>
679 /// T as MyTrait<'static>
680 /// ```
681 /// If we put both of these predicates in our computed `ParamEnv`, we'll
682 /// confuse `SelectionContext`, since it will (correctly) view both as being applicable.
683 ///
684 /// To solve this, we pick the 'more strict' lifetime bound -- i.e., the HRTB
685 /// Our end goal is to generate a user-visible description of the conditions
686 /// under which a type implements an auto trait. A trait predicate involving
687 /// a HRTB means that the type needs to work with any choice of lifetime,
688 /// not just one specific lifetime (e.g., `'static`).
689fn add_user_clause(
690&self,
691 user_computed_clauses: &mut FxIndexSet<ty::Clause<'tcx>>,
692 new_clause: ty::Clause<'tcx>,
693 ) {
694let mut should_add_new = true;
695user_computed_clauses.retain(|&old_clause| {
696if let (ty::ClauseKind::Trait(new_trait), ty::ClauseKind::Trait(old_trait)) =
697 (new_clause.kind().skip_binder(), old_clause.kind().skip_binder())
698 {
699if new_trait.def_id() == old_trait.def_id() {
700let new_args = new_trait.trait_ref.args;
701let old_args = old_trait.trait_ref.args;
702703if !new_args.terms().eq(old_args.terms()) {
704// We can't compare lifetimes if the types are different,
705 // so skip checking `old_clause`.
706return true;
707 }
708709for (new_region, old_region) in
710iter::zip(new_args.regions(), old_args.regions())
711 {
712match (new_region.kind(), old_region.kind()) {
713// If both predicates have an `ReBound` (a HRTB) in the
714 // same spot, we do nothing.
715(ty::ReBound(_, _), ty::ReBound(_, _)) => {}
716717 (ty::ReBound(_, _), _) | (_, ty::ReVar(_)) => {
718// One of these is true:
719 // The new predicate has a HRTB in a spot where the old
720 // predicate does not (if they both had a HRTB, the previous
721 // match arm would have executed). A HRBT is a 'stricter'
722 // bound than anything else, so we want to keep the newer
723 // predicate (with the HRBT) in place of the old predicate.
724 //
725 // OR
726 //
727 // The old predicate has a region variable where the new
728 // predicate has some other kind of region. An region
729 // variable isn't something we can actually display to a user,
730 // so we choose their new predicate (which doesn't have a region
731 // variable).
732 //
733 // In both cases, we want to remove the old predicate,
734 // from `user_computed_clauses`, and replace it with the new
735 // one. Having both the old and the new
736 // predicate in a `ParamEnv` would confuse `SelectionContext`.
737 //
738 // We're currently in the predicate passed to 'retain',
739 // so we return `false` to remove the old predicate from
740 // `user_computed_clauses`.
741return false;
742 }
743 (_, ty::ReBound(_, _)) | (ty::ReVar(_), _) => {
744// This is the opposite situation as the previous arm.
745 // One of these is true:
746 //
747 // The old predicate has a HRTB lifetime in a place where the
748 // new predicate does not.
749 //
750 // OR
751 //
752 // The new predicate has a region variable where the old
753 // predicate has some other type of region.
754 //
755 // We want to leave the old
756 // predicate in `user_computed_clauses`, and skip adding
757 // new_clause to `user_computed_params`.
758should_add_new = false
759}
760_ => {}
761 }
762 }
763 }
764 }
765true
766});
767768if should_add_new {
769user_computed_clauses.insert(new_clause);
770 }
771 }
772773/// This is very similar to `handle_lifetimes`. However, instead of matching `ty::Region`s
774 /// to each other, we match `ty::RegionVid`s to `ty::Region`s.
775fn map_vid_to_region<'cx>(
776&self,
777 regions: &RegionConstraintData<'cx>,
778 ) -> FxIndexMap<ty::RegionVid, ty::Region<'cx>> {
779let mut vid_map = FxIndexMap::<RegionTarget<'cx>, RegionDeps<'cx>>::default();
780let mut finished_map = FxIndexMap::default();
781782for c in regions.constraints.iter().flat_map(|(c, _)| c.iter_outlives()) {
783match c.kind {
784 ConstraintKind::VarSubVar => {
785let sub_vid = c.sub.as_var();
786let sup_vid = c.sup.as_var();
787 {
788let deps1 = vid_map.entry(RegionTarget::RegionVid(sub_vid)).or_default();
789 deps1.larger.insert(RegionTarget::RegionVid(sup_vid));
790 }
791792let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default();
793 deps2.smaller.insert(RegionTarget::RegionVid(sub_vid));
794 }
795 ConstraintKind::RegSubVar => {
796let sup_vid = c.sup.as_var();
797 {
798let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default();
799 deps1.larger.insert(RegionTarget::RegionVid(sup_vid));
800 }
801802let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default();
803 deps2.smaller.insert(RegionTarget::Region(c.sub));
804 }
805 ConstraintKind::VarSubReg => {
806let sub_vid = c.sub.as_var();
807 finished_map.insert(sub_vid, c.sup);
808 }
809 ConstraintKind::RegSubReg => {
810 {
811let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default();
812 deps1.larger.insert(RegionTarget::Region(c.sup));
813 }
814815let deps2 = vid_map.entry(RegionTarget::Region(c.sup)).or_default();
816 deps2.smaller.insert(RegionTarget::Region(c.sub));
817 }
818819 ConstraintKind::VarEqVar | ConstraintKind::VarEqReg | ConstraintKind::RegEqReg => {
820::core::panicking::unreachable_default_msg()unreachable!()821 }
822 }
823 }
824825while !vid_map.is_empty() {
826let target = *vid_map.keys().next().unwrap();
827let deps = vid_map.swap_remove(&target).unwrap();
828829for smaller in deps.smaller.iter() {
830for larger in deps.larger.iter() {
831match (smaller, larger) {
832 (&RegionTarget::Region(_), &RegionTarget::Region(_)) => {
833if let IndexEntry::Occupied(v) = vid_map.entry(*smaller) {
834let smaller_deps = v.into_mut();
835 smaller_deps.larger.insert(*larger);
836 smaller_deps.larger.swap_remove(&target);
837 }
838839if let IndexEntry::Occupied(v) = vid_map.entry(*larger) {
840let larger_deps = v.into_mut();
841 larger_deps.smaller.insert(*smaller);
842 larger_deps.smaller.swap_remove(&target);
843 }
844 }
845 (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => {
846 finished_map.insert(v1, r1);
847 }
848 (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
849// Do nothing; we don't care about regions that are smaller than vids.
850}
851 (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
852if let IndexEntry::Occupied(v) = vid_map.entry(*smaller) {
853let smaller_deps = v.into_mut();
854 smaller_deps.larger.insert(*larger);
855 smaller_deps.larger.swap_remove(&target);
856 }
857858if let IndexEntry::Occupied(v) = vid_map.entry(*larger) {
859let larger_deps = v.into_mut();
860 larger_deps.smaller.insert(*smaller);
861 larger_deps.smaller.swap_remove(&target);
862 }
863 }
864 }
865 }
866 }
867 }
868869finished_map870 }
871872fn is_param_no_infer(&self, args: GenericArgs<'tcx>) -> bool {
873self.is_of_param(args.type_at(0)) && !args.terms().any(|t| t.has_infer_types())
874 }
875876pub fn is_of_param(&self, ty: Ty<'tcx>) -> bool {
877match ty.kind() {
878 ty::Param(_) => true,
879 ty::Alias(_, p @ ty::AliasTy { kind: ty::Projection { .. }, .. }) => {
880self.is_of_param(p.self_ty())
881 }
882_ => false,
883 }
884 }
885886fn is_self_referential_projection(&self, p: ty::PolyProjectionClause<'tcx>) -> bool {
887if let Some(ty) = p.term().skip_binder().as_type() {
888#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { .. }, .. }) if
proj == &p.skip_binder().projection_term.expect_ty() => true,
_ => false,
}matches!(ty.kind(), ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { .. }, .. }) if proj == &p.skip_binder().projection_term.expect_ty())889 } else {
890false
891}
892 }
893894fn evaluate_nested_obligations(
895&self,
896 ty: Ty<'_>,
897 nested: impl Iterator<Item = PredicateObligation<'tcx>>,
898 computed_clauses: &mut FxIndexSet<ty::Clause<'tcx>>,
899 fresh_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
900 predicates: &mut VecDeque<ty::PolyTraitClause<'tcx>>,
901 selcx: &mut SelectionContext<'_, 'tcx>,
902 ) -> bool {
903let dummy_cause = ObligationCause::dummy();
904905for obligation in nested {
906let is_new_pred =
907 fresh_preds.insert(self.clean_pred(selcx.infcx, obligation.predicate));
908909// Resolve any inference variables that we can, to help selection succeed
910let predicate = selcx.infcx.deeply_resolve_ignoring_regions(obligation.predicate);
911912// We only add a predicate as a user-displayable bound if
913 // it involves a generic parameter, and doesn't contain
914 // any inference variables.
915 //
916 // Displaying a bound involving a concrete type (instead of a generic
917 // parameter) would be pointless, since it's always true
918 // (e.g. u8: Copy)
919 // Displaying an inference variable is impossible, since they're
920 // an internal compiler detail without a defined visual representation
921 //
922 // We check this by calling is_of_param on the relevant types
923 // from the various possible predicates
924925let bound_predicate = predicate.kind();
926match bound_predicate.skip_binder() {
927 ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => {
928// Add this to `predicates` so that we end up calling `select`
929 // with it. If this predicate ends up being unimplemented,
930 // then `evaluate_predicates` will handle adding it the `ParamEnv`
931 // if possible.
932predicates.push_back(bound_predicate.rebind(p));
933 }
934 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(c)) => {
935let p = bound_predicate.rebind(c);
936if self.is_param_no_infer(p.skip_binder().trait_ref.args) && is_new_pred {
937self.add_user_clause(computed_clauses, predicate.expect_clause());
938 }
939 }
940 ty::PredicateKind::Clause(ty::ClauseKind::Projection(p)) => {
941let p = bound_predicate.rebind(p);
942{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:942",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(942u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("evaluate_nested_obligations: examining projection predicate {0:?}",
predicate) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
943"evaluate_nested_obligations: examining projection predicate {:?}",
944 predicate
945 );
946947// As described above, we only want to display
948 // bounds which include a generic parameter but don't include
949 // an inference variable.
950 // Additionally, we check if we've seen this predicate before,
951 // to avoid rendering duplicate bounds to the user.
952if self.is_param_no_infer(p.skip_binder().projection_term.args)
953 && !p.term().skip_binder().has_infer_types()
954 && is_new_pred
955 {
956{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:956",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(956u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("evaluate_nested_obligations: adding projection predicate to computed_clauses: {0:?}",
predicate) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
957"evaluate_nested_obligations: adding projection predicate \
958 to computed_clauses: {:?}",
959 predicate
960 );
961962// Under unusual circumstances, we can end up with a self-referential
963 // projection predicate. For example:
964 // <T as MyType>::Value == <T as MyType>::Value
965 // Not only is displaying this to the user pointless,
966 // having it in the ParamEnv will cause an issue if we try to call
967 // poly_project_and_unify_type on the predicate, since this kind of
968 // predicate will normally never end up in a ParamEnv.
969 //
970 // For these reasons, we ignore these weird predicates,
971 // ensuring that we're able to properly synthesize an auto trait impl
972if self.is_self_referential_projection(p) {
973{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:973",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(973u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("evaluate_nested_obligations: encountered a projection\n predicate equating a type with itself! Skipping")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
974"evaluate_nested_obligations: encountered a projection
975 predicate equating a type with itself! Skipping"
976);
977 } else {
978self.add_user_clause(computed_clauses, predicate.expect_clause());
979 }
980 }
981982// There are three possible cases when we project a predicate:
983 //
984 // 1. We encounter an error. This means that it's impossible for
985 // our current type to implement the auto trait - there's bound
986 // that we could add to our ParamEnv that would 'fix' this kind
987 // of error, as it's not caused by an unimplemented type.
988 //
989 // 2. We successfully project the predicate (Ok(Some(_))), generating
990 // some subobligations. We then process these subobligations
991 // like any other generated sub-obligations.
992 //
993 // 3. We receive an 'ambiguous' result (Ok(None))
994 // If we were actually trying to compile a crate,
995 // we would need to re-process this obligation later.
996 // However, all we care about is finding out what bounds
997 // are needed for our type to implement a particular auto trait.
998 // We've already added this obligation to our computed ParamEnv
999 // above (if it was necessary). Therefore, we don't need
1000 // to do any further processing of the obligation.
1001 //
1002 // Note that we *must* try to project *all* projection predicates
1003 // we encounter, even ones without inference variable.
1004 // This ensures that we detect any projection errors,
1005 // which indicate that our type can *never* implement the given
1006 // auto trait. In that case, we will generate an explicit negative
1007 // impl (e.g. 'impl !Send for MyType'). However, we don't
1008 // try to process any of the generated subobligations -
1009 // they contain no new information, since we already know
1010 // that our type implements the projected-through trait,
1011 // and can lead to weird region issues.
1012 //
1013 // Normally, we'll generate a negative impl as a result of encountering
1014 // a type with an explicit negative impl of an auto trait
1015 // (for example, raw pointers have !Send and !Sync impls)
1016 // However, through some **interesting** manipulations of the type
1017 // system, it's actually possible to write a type that never
1018 // implements an auto trait due to a projection error, not a normal
1019 // negative impl error. To properly handle this case, we need
1020 // to ensure that we catch any potential projection errors,
1021 // and turn them into an explicit negative impl for our type.
1022{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:1022",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(1022u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Projecting and unifying projection predicate {0:?}",
predicate) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("Projecting and unifying projection predicate {:?}", predicate);
10231024match project::poly_project_and_unify_term(selcx, &obligation.with(self.tcx, p))
1025 {
1026 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => {
1027{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:1027",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(1027u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("evaluate_nested_obligations: Unable to unify predicate \'{0:?}\' \'{1:?}\', bailing out",
ty, e) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1028"evaluate_nested_obligations: Unable to unify predicate \
1029 '{:?}' '{:?}', bailing out",
1030 ty, e
1031 );
1032return false;
1033 }
1034 ProjectAndUnifyResult::Recursive => {
1035{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs:1035",
"rustc_trait_selection::traits::auto_trait",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
::tracing_core::__macro_support::Option::Some(1035u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::auto_trait"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("evaluate_nested_obligations: recursive projection predicate")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("evaluate_nested_obligations: recursive projection predicate");
1036return false;
1037 }
1038 ProjectAndUnifyResult::Holds(v) => {
1039// We only care about sub-obligations
1040 // when we started out trying to unify
1041 // some inference variables. See the comment above
1042 // for more information
1043if p.term().skip_binder().has_infer_types() {
1044if !self.evaluate_nested_obligations(
1045 ty,
1046 v.into_iter(),
1047 computed_clauses,
1048 fresh_preds,
1049 predicates,
1050 selcx,
1051 ) {
1052return false;
1053 }
1054 }
1055 }
1056 ProjectAndUnifyResult::FailedNormalization => {
1057// It's ok not to make progress when have no inference variables -
1058 // in that case, we were only performing unification to check if an
1059 // error occurred (which would indicate that it's impossible for our
1060 // type to implement the auto trait).
1061 // However, we should always make progress (either by generating
1062 // subobligations or getting an error) when we started off with
1063 // inference variables
1064if p.term().skip_binder().has_infer_types() {
1065{
::core::panicking::panic_fmt(format_args!("Unexpected result when selecting {0:?} {1:?}",
ty, obligation));
}panic!("Unexpected result when selecting {ty:?} {obligation:?}")1066 }
1067 }
1068 }
1069 }
1070 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(binder)) => {
1071let binder = bound_predicate.rebind(binder);
1072 selcx.infcx.enter_forall(binder, |pred| {
1073 selcx.infcx.register_region_outlives_constraint(
1074 pred,
1075 ty::VisibleForLeakCheck::Yes,
1076&dummy_cause,
1077 );
1078 });
1079 }
1080 ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(binder)) => {
1081let binder = bound_predicate.rebind(binder);
1082match (
1083 binder.no_bound_vars(),
1084 binder.map_bound_ref(|pred| pred.0).no_bound_vars(),
1085 ) {
1086 (None, Some(t_a)) => {
1087 selcx.infcx.register_type_outlives_constraint(
1088 t_a,
1089 selcx.infcx.tcx.lifetimes.re_static,
1090&dummy_cause,
1091 );
1092 }
1093 (Some(ty::OutlivesClause(t_a, r_b)), _) => {
1094 selcx.infcx.register_type_outlives_constraint(t_a, r_b, &dummy_cause);
1095 }
1096_ => {}
1097 };
1098 }
1099 ty::PredicateKind::ConstEquate(c1, c2) => {
1100let evaluate = |c: ty::Const<'tcx>| {
1101if let ty::ConstKind::Alias(_, alias_const) = c.kind() {
1102let ct = super::try_evaluate_const(
1103 selcx.infcx,
1104 c,
1105 obligation.param_env,
1106 |ty| Ok::<_, !>(ty.skip_norm_wip()),
1107 );
11081109if let Err(EvaluateConstErr::InvalidConstParamTy(_)) = ct {
1110let span = alias_const.kind.def_span(self.tcx);
1111self.tcx
1112 .dcx()
1113 .emit_err(UnableToConstructConstantValue { span, alias_const });
1114 }
11151116 ct
1117 } else {
1118Ok(c)
1119 }
1120 };
11211122match (evaluate(c1), evaluate(c2)) {
1123 (Ok(c1), Ok(c2)) => {
1124match selcx.infcx.eq_raw(
1125&obligation.cause,
1126 obligation.param_env,
1127 DefineOpaqueTypes::Yes,
1128 c1,
1129 c2,
1130 ) {
1131Ok(_) => (),
1132Err(_) => return false,
1133 }
1134 }
1135_ => return false,
1136 }
1137 }
11381139// There's not really much we can do with these predicates -
1140 // we start out with a `ParamEnv` with no inference variables,
1141 // and these don't correspond to adding any new bounds to
1142 // the `ParamEnv`.
1143ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(..))
1144 | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..))
1145 | ty::PredicateKind::NormalizesTo(..)
1146 | ty::PredicateKind::DynCompatible(..)
1147 | ty::PredicateKind::Subtype(..)
1148 | ty::PredicateKind::Coerce(..)
1149 | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(_)) => {}
1150 ty::PredicateKind::Ambiguous => return false,
11511152// FIXME(generic_const_exprs): you can absolutely add this as a where clauses
1153ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) => return false,
11541155 ty::PredicateKind::Clause(ty::ClauseKind::CompressedTrait(_)) => ::core::panicking::unreachable_default_msg()unreachable!(),
1156 };
1157 }
1158true
1159}
11601161pub fn clean_pred(
1162&self,
1163 infcx: &InferCtxt<'tcx>,
1164 p: ty::Predicate<'tcx>,
1165 ) -> ty::Predicate<'tcx> {
1166p.fold_with(&mut TypeFreshener::new(infcx))
1167 }
1168}