Skip to main content

rustc_trait_selection/traits/
auto_trait.rs

1//! Support code for rustdoc and external tools.
2//! You really don't want to be using this unless you need to.
3
4use std::collections::VecDeque;
5use std::iter;
6
7use rustc_data_structures::fx::{FxIndexMap, FxIndexSet, IndexEntry};
8use rustc_data_structures::unord::UnordSet;
9use rustc_hir::def_id::CRATE_DEF_ID;
10use rustc_infer::infer::DefineOpaqueTypes;
11use rustc_middle::ty::{Region, RegionVid};
12use rustc_span::DUMMY_SP;
13use tracing::debug;
14
15use 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;
21
22// 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: &RegionTarget<'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) {
                (RegionTarget::Region(__self_0),
                    RegionTarget::Region(__arg1_0)) => __self_0 == __arg1_0,
                (RegionTarget::RegionVid(__self_0),
                    RegionTarget::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) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            RegionTarget::Region(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            RegionTarget::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]
    fn clone(&self) -> RegionTarget<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Region<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<RegionVid>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for RegionTarget<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RegionTarget::Region(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Region",
                    &__self_0),
            RegionTarget::RegionVid(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "RegionVid", &__self_0),
        }
    }
}Debug)]
24pub enum RegionTarget<'tcx> {
25    Region(Region<'tcx>),
26    RegionVid(RegionVid),
27}
28
29#[derive(#[automatically_derived]
impl<'tcx> ::core::default::Default for RegionDeps<'tcx> {
    #[inline]
    fn default() -> RegionDeps<'tcx> {
        RegionDeps {
            larger: ::core::default::Default::default(),
            smaller: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for RegionDeps<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "RegionDeps",
            "larger", &self.larger, "smaller", &&self.smaller)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for RegionDeps<'tcx> {
    #[inline]
    fn clone(&self) -> RegionDeps<'tcx> {
        RegionDeps {
            larger: ::core::clone::Clone::clone(&self.larger),
            smaller: ::core::clone::Clone::clone(&self.smaller),
        }
    }
}Clone)]
30pub struct RegionDeps<'tcx> {
31    pub larger: FxIndexSet<RegionTarget<'tcx>>,
32    pub smaller: FxIndexSet<RegionTarget<'tcx>>,
33}
34
35pub enum AutoTraitResult<A> {
36    NoImpl,
37    ExplicitImpl,
38    PositiveImpl(A),
39    NegativeImpl,
40}
41
42pub struct AutoTraitInfo<'cx> {
43    pub full_user_env: ty::ParamEnv<'cx>,
44    pub region_data: RegionConstraintData<'cx>,
45    pub vid_to_region: FxIndexMap<ty::RegionVid, ty::Region<'cx>>,
46}
47
48pub struct AutoTraitFinder<'tcx> {
49    tcx: TyCtxt<'tcx>,
50}
51
52impl<'tcx> AutoTraitFinder<'tcx> {
53    pub fn new(tcx: TyCtxt<'tcx>) -> Self {
54        AutoTraitFinder { tcx }
55    }
56
57    /// 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.
75    pub fn find_auto_trait_generics<A>(
76        &self,
77        ty: Ty<'tcx>,
78        typing_env: ty::TypingEnv<'tcx>,
79        trait_did: DefId,
80        mut auto_trait_callback: impl FnMut(AutoTraitInfo<'tcx>) -> A,
81    ) -> AutoTraitResult<A> {
82        let tcx = self.tcx;
83
84        if tcx.next_trait_solver_globally() {
85            return self.find_auto_trait_generics_next_solver(
86                ty,
87                typing_env,
88                trait_did,
89                auto_trait_callback,
90            );
91        }
92
93        let trait_ref = ty::TraitRef::new(tcx, trait_did, [ty]);
94
95        let (infcx, orig_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
96        let mut selcx = SelectionContext::new(&infcx);
97        for polarity in [ty::ClausePolarity::Positive, ty::ClausePolarity::Negative] {
98            let result = selcx.select(&Obligation::new(
99                tcx,
100                ObligationCause::dummy(),
101                orig_env,
102                ty::TraitClause { trait_ref, polarity },
103            ));
104            if let Ok(Some(ImplSource::UserDefined(_))) = result {
105                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:105",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(105u32),
                        ::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");
106                // If an explicit impl exists, it always takes priority over an auto impl
107                return AutoTraitResult::ExplicitImpl;
108            }
109        }
110
111        let (infcx, orig_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
112        let mut fresh_preds = FxIndexSet::default();
113
114        // Due to the way projections are handled by SelectionContext, we need to run
115        // evaluate_predicates twice: once on the original param env, and once on the result of
116        // the first evaluate_predicates call.
117        //
118        // The problem is this: most of rustc, including SelectionContext and traits::project,
119        // are designed to work with a concrete usage of a type (e.g., Vec<u8>
120        // fn<T>() { Vec<T> }. This information will generally never change - given
121        // the 'T' in fn<T>() { ... }, we'll never know anything else about 'T'.
122        // If we're unable to prove that 'T' implements a particular trait, we're done -
123        // there's nothing left to do but error out.
124        //
125        // However, synthesizing an auto trait impl works differently. Here, we start out with
126        // a set of initial conditions - the ParamEnv of the struct/enum/union we're dealing
127        // with - and progressively discover the conditions we need to fulfill for it to
128        // implement a certain auto trait. This ends up breaking two assumptions made by trait
129        // selection and projection:
130        //
131        // * We can always cache the result of a particular trait selection for the lifetime of
132        // an InfCtxt
133        // * Given a projection bound such as '<T as SomeTrait>::SomeItem = K', if 'T:
134        // SomeTrait' doesn't hold, then we don't need to care about the 'SomeItem = K'
135        //
136        // We fix the first assumption by manually clearing out all of the InferCtxt's caches
137        // in between calls to SelectionContext.select. This allows us to keep all of the
138        // intermediate types we create bound to the 'tcx lifetime, rather than needing to lift
139        // them between calls.
140        //
141        // We fix the second assumption by reprocessing the result of our first call to
142        // evaluate_predicates. Using the example of '<T as SomeTrait>::SomeItem = K', our first
143        // pass will pick up 'T: SomeTrait', but not 'SomeItem = K'. On our second pass,
144        // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing
145        // SelectionContext to return it back to us.
146
147        let Some((new_env, user_env)) =
148            self.evaluate_predicates(&infcx, trait_did, ty, orig_env, orig_env, &mut fresh_preds)
149        else {
150            return AutoTraitResult::NegativeImpl;
151        };
152
153        let (full_env, full_user_env) = self
154            .evaluate_predicates(&infcx, trait_did, ty, new_env, user_env, &mut fresh_preds)
155            .unwrap_or_else(|| {
156                {
    ::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:?}")
157            });
158
159        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:159",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(159u32),
                        ::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!(
160            "find_auto_trait_generics({:?}): fulfilling \
161             with {:?}",
162            trait_ref, full_env
163        );
164
165        // At this point, we already have all of the bounds we need. FulfillmentContext is used
166        // to store all of the necessary region/lifetime bounds in the InferContext, as well as
167        // an additional sanity check.
168        let ocx = ObligationCtxt::new(&infcx);
169        ocx.register_bound(ObligationCause::dummy(), full_env, ty, trait_did);
170        let errors = ocx.evaluate_obligations_error_on_ambiguity();
171        if !errors.no_errors() {
172            {
    ::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:?}");
173        }
174
175        let outlives_env = OutlivesEnvironment::new(&infcx, CRATE_DEF_ID, full_env, []);
176        let _ = infcx.process_registered_region_obligations(&outlives_env, DUMMY_SP);
177
178        let region_data = infcx.inner.borrow_mut().unwrap_region_constraints().data().clone();
179
180        let vid_to_region = self.map_vid_to_region(&region_data);
181
182        let info = AutoTraitInfo { full_user_env, region_data, vid_to_region };
183
184        AutoTraitResult::PositiveImpl(auto_trait_callback(info))
185    }
186
187    fn find_auto_trait_generics_next_solver<A>(
188        &self,
189        ty: Ty<'tcx>,
190        typing_env: ty::TypingEnv<'tcx>,
191        trait_did: DefId,
192        mut auto_trait_callback: impl FnMut(AutoTraitInfo<'tcx>) -> A,
193    ) -> AutoTraitResult<A> {
194        // When the new solver is enabled globally we keep things deliberately
195        // simple. The precise auto-trait synthesis depends on old-solver
196        // internals, so here we only synthesize a simple field-based auto-trait
197        // impl for ADTs.
198        //
199        // If the self type is not an ADT we return `NoImpl` instead of trying
200        // to do anything fancy. To decide whether to emit a negative impl, we
201        // replace the ADT's generic arguments with inference variables and
202        // check whether the auto trait can hold. A true error from that probe
203        // becomes a `NegativeImpl`, otherwise we continue on to emit the
204        // imprecise field-based impl.
205        //
206        // This keeps rustdoc from ICE-ing while `-Znext-solver=globally` is
207        // used for testing, even if the generated synthetic impls are less
208        // precise.
209        let tcx = self.tcx;
210        let ty::Adt(adt_def, args) = *ty.kind() else {
211            return AutoTraitResult::NoImpl;
212        };
213
214        let mut disqualifying_impl = None;
215        tcx.for_each_relevant_impl(trait_did, ty, |impl_def_id| {
216            disqualifying_impl = Some(impl_def_id);
217        });
218        if let Some(impl_def_id) = disqualifying_impl {
219            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:219",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(219u32),
                        ::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!(
220                "find_auto_trait_generics({:?}): possible manual impl {impl_def_id:?} found, bailing",
221                ty::TraitRef::new(tcx, trait_did, [ty]),
222            );
223            return AutoTraitResult::ExplicitImpl;
224        }
225
226        let (infcx, orig_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
227        let field_clauses = adt_def
228            .all_fields()
229            .map(|field| field.ty(tcx, args).skip_norm_wip())
230            .filter(|field_ty| field_ty.has_non_region_param())
231            .map(|field_ty| {
232                ty::TraitClause {
233                    trait_ref: ty::TraitRef::new(tcx, trait_did, [field_ty]),
234                    polarity: ty::ClausePolarity::Positive,
235                }
236                .upcast(tcx)
237            })
238            .collect::<Vec<ty::Clause<'tcx>>>();
239        let full_user_env = ty::ParamEnv::new(tcx, orig_env.caller_bounds().chain(field_clauses));
240
241        let fresh_args = infcx.fresh_args_for_item(DUMMY_SP, adt_def.did());
242        let fresh_ty = ty::EarlyBinder::bind(tcx, ty).instantiate(tcx, fresh_args).skip_norm_wip();
243        let ocx = ObligationCtxt::new(&infcx);
244        ocx.register_bound(ObligationCause::dummy(), orig_env, fresh_ty, trait_did);
245        let errors = ocx.try_evaluate_obligations();
246        if !errors.no_errors() {
247            return AutoTraitResult::NegativeImpl;
248        }
249
250        let info = AutoTraitInfo {
251            full_user_env,
252            region_data: RegionConstraintData::default(),
253            vid_to_region: FxIndexMap::default(),
254        };
255        AutoTraitResult::PositiveImpl(auto_trait_callback(info))
256    }
257
258    /// The core logic responsible for computing the bounds for our synthesized impl.
259    ///
260    /// To calculate the bounds, we call `SelectionContext.select` in a loop. Like
261    /// `FulfillmentContext`, we recursively select the nested obligations of predicates we
262    /// encounter. However, whenever we encounter an `UnimplementedError` involving a type
263    /// parameter, we add it to our `ParamEnv`. Since our goal is to determine when a particular
264    /// type implements an auto trait, Unimplemented errors tell us what conditions need to be met.
265    ///
266    /// This method ends up working somewhat similarly to `FulfillmentContext`, but with a few key
267    /// differences. `FulfillmentContext` works under the assumption that it's dealing with concrete
268    /// user code. According, it considers all possible ways that a `Predicate` could be met, which
269    /// isn't always what we want for a synthesized impl. For example, given the predicate `T:
270    /// Iterator`, `FulfillmentContext` can end up reporting an Unimplemented error for `T:
271    /// IntoIterator` -- since there's an implementation of `Iterator` where `T: IntoIterator`,
272    /// `FulfillmentContext` will drive `SelectionContext` to consider that impl before giving up.
273    /// If we were to rely on `FulfillmentContext`s decision, we might end up synthesizing an impl
274    /// like this:
275    /// ```ignore (illustrative)
276    /// impl<T> Send for Foo<T> where T: IntoIterator
277    /// ```
278    /// While it might be technically true that Foo implements Send where `T: IntoIterator`,
279    /// the bound is overly restrictive - it's really only necessary that `T: Iterator`.
280    ///
281    /// For this reason, `evaluate_predicates` handles predicates with type variables specially.
282    /// When we encounter an `Unimplemented` error for a bound such as `T: Iterator`, we immediately
283    /// add it to our `ParamEnv`, and add it to our stack for recursive evaluation. When we later
284    /// select it, we'll pick up any nested bounds, without ever inferring that `T: IntoIterator`
285    /// needs to hold.
286    ///
287    /// One additional consideration is supertrait bounds. Normally, a `ParamEnv` is only ever
288    /// constructed once for a given type. As part of the construction process, the `ParamEnv` will
289    /// have any supertrait bounds normalized -- e.g., if we have a type `struct Foo<T: Copy>`, the
290    /// `ParamEnv` will contain `T: Copy` and `T: Clone`, since `Copy: Clone`. When we construct our
291    /// own `ParamEnv`, we need to do this ourselves, through `traits::elaborate`, or
292    /// else `SelectionContext` will choke on the missing predicates. However, this should never
293    /// show up in the final synthesized generics: we don't want our generated docs page to contain
294    /// something like `T: Copy + Clone`, as that's redundant. Therefore, we keep track of a
295    /// separate `user_env`, which only holds the predicates that will actually be displayed to the
296    /// user.
297    fn evaluate_predicates(
298        &self,
299        infcx: &InferCtxt<'tcx>,
300        trait_did: DefId,
301        ty: Ty<'tcx>,
302        param_env: ty::ParamEnv<'tcx>,
303        user_env: ty::ParamEnv<'tcx>,
304        fresh_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
305    ) -> Option<(ty::ParamEnv<'tcx>, ty::ParamEnv<'tcx>)> {
306        let tcx = infcx.tcx;
307
308        // Don't try to process any nested obligations involving predicates
309        // that are already in the `ParamEnv` (modulo regions): we already
310        // know that they must hold.
311        for clause in param_env.caller_bounds() {
312            fresh_preds.insert(self.clean_pred(infcx, clause.as_predicate()));
313        }
314
315        let mut select = SelectionContext::new(infcx);
316
317        let mut already_visited = UnordSet::new();
318        let mut predicates = VecDeque::new();
319        predicates.push_back(ty::Binder::dummy(ty::TraitClause {
320            trait_ref: ty::TraitRef::new(infcx.tcx, trait_did, [ty]),
321
322            // Auto traits are positive
323            polarity: ty::ClausePolarity::Positive,
324        }));
325
326        let computed_clauses = param_env.caller_bounds();
327        let mut user_computed_clauses: FxIndexSet<_> = user_env.caller_bounds().collect();
328
329        let mut new_env = param_env;
330        let dummy_cause = ObligationCause::dummy();
331
332        while let Some(pred) = predicates.pop_front() {
333            if !already_visited.insert(pred) {
334                continue;
335            }
336
337            // Call `infcx.deeply_resolve_ignoring_regions` to see if we can
338            // get rid of any inference variables.
339            let obligation = infcx.deeply_resolve_ignoring_regions(Obligation::new(
340                tcx,
341                dummy_cause.clone(),
342                new_env,
343                pred,
344            ));
345            let result = select.poly_select(&obligation);
346
347            match result {
348                Ok(Some(ref impl_source)) => {
349                    // If we see an explicit negative impl (e.g., `impl !Send for MyStruct`),
350                    // we immediately bail out, since it's impossible for us to continue.
351
352                    if let ImplSource::UserDefined(ImplSourceUserDefinedData {
353                        impl_def_id, ..
354                    }) = impl_source
355                    {
356                        // Blame 'tidy' for the weird bracket placement.
357                        if infcx.tcx.impl_polarity(*impl_def_id) != ty::ImplPolarity::Positive {
358                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:358",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(358u32),
                        ::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!(
359                                "evaluate_nested_obligations: found explicit negative impl\
360                                        {:?}, bailing out",
361                                impl_def_id
362                            );
363                            return None;
364                        }
365                    }
366
367                    let obligations = impl_source.borrow_nested_obligations().iter().cloned();
368
369                    if !self.evaluate_nested_obligations(
370                        ty,
371                        obligations,
372                        &mut user_computed_clauses,
373                        fresh_preds,
374                        &mut predicates,
375                        &mut select,
376                    ) {
377                        return None;
378                    }
379                }
380                Ok(None) => {}
381                Err(SelectionError::Unimplemented) => {
382                    if self.is_param_no_infer(pred.skip_binder().trait_ref.args) {
383                        already_visited.remove(&pred);
384                        self.add_user_clause(&mut user_computed_clauses, pred.upcast(self.tcx));
385                        predicates.push_back(pred);
386                    } else {
387                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:387",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(387u32),
                        ::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!(
388                            "evaluate_nested_obligations: `Unimplemented` found, bailing: \
389                             {:?} {:?} {:?}",
390                            ty,
391                            pred,
392                            pred.skip_binder().trait_ref.args
393                        );
394                        return None;
395                    }
396                }
397                _ => {
    ::core::panicking::panic_fmt(format_args!("Unexpected error for \'{0:?}\': {1:?}",
            ty, result));
}panic!("Unexpected error for '{ty:?}': {result:?}"),
398            };
399
400            let normalized_preds = elaborate(
401                tcx,
402                computed_clauses.clone().chain(user_computed_clauses.iter().cloned()),
403            );
404            new_env = ty::ParamEnv::new(tcx, normalized_preds);
405        }
406
407        let final_user_env = ty::ParamEnv::new(tcx, user_computed_clauses.into_iter());
408        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:408",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(408u32),
                        ::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!(
409            "evaluate_nested_obligations(ty={:?}, trait_did={:?}): succeeded with '{:?}' \
410             '{:?}'",
411            ty, trait_did, new_env, final_user_env
412        );
413
414        Some((new_env, final_user_env))
415    }
416
417    /// This method is designed to work around the following issue:
418    /// When we compute auto trait bounds, we repeatedly call `SelectionContext.select`,
419    /// progressively building a `ParamEnv` based on the results we get.
420    /// However, our usage of `SelectionContext` differs from its normal use within the compiler,
421    /// in that we capture and re-reprocess predicates from `Unimplemented` errors.
422    ///
423    /// This can lead to a corner case when dealing with region parameters.
424    /// During our selection loop in `evaluate_predicates`, we might end up with
425    /// two trait predicates that differ only in their region parameters:
426    /// one containing a HRTB lifetime parameter, and one containing a 'normal'
427    /// lifetime parameter. For example:
428    /// ```ignore (illustrative)
429    /// T as MyTrait<'a>
430    /// T as MyTrait<'static>
431    /// ```
432    /// If we put both of these predicates in our computed `ParamEnv`, we'll
433    /// confuse `SelectionContext`, since it will (correctly) view both as being applicable.
434    ///
435    /// To solve this, we pick the 'more strict' lifetime bound -- i.e., the HRTB
436    /// Our end goal is to generate a user-visible description of the conditions
437    /// under which a type implements an auto trait. A trait predicate involving
438    /// a HRTB means that the type needs to work with any choice of lifetime,
439    /// not just one specific lifetime (e.g., `'static`).
440    fn add_user_clause(
441        &self,
442        user_computed_clauses: &mut FxIndexSet<ty::Clause<'tcx>>,
443        new_clause: ty::Clause<'tcx>,
444    ) {
445        let mut should_add_new = true;
446        user_computed_clauses.retain(|&old_clause| {
447            if let (ty::ClauseKind::Trait(new_trait), ty::ClauseKind::Trait(old_trait)) =
448                (new_clause.kind().skip_binder(), old_clause.kind().skip_binder())
449            {
450                if new_trait.def_id() == old_trait.def_id() {
451                    let new_args = new_trait.trait_ref.args;
452                    let old_args = old_trait.trait_ref.args;
453
454                    if !new_args.terms().eq(old_args.terms()) {
455                        // We can't compare lifetimes if the types are different,
456                        // so skip checking `old_clause`.
457                        return true;
458                    }
459
460                    for (new_region, old_region) in
461                        iter::zip(new_args.regions(), old_args.regions())
462                    {
463                        match (new_region.kind(), old_region.kind()) {
464                            // If both predicates have an `ReBound` (a HRTB) in the
465                            // same spot, we do nothing.
466                            (ty::ReBound(_, _), ty::ReBound(_, _)) => {}
467
468                            (ty::ReBound(_, _), _) | (_, ty::ReVar(_)) => {
469                                // One of these is true:
470                                // The new predicate has a HRTB in a spot where the old
471                                // predicate does not (if they both had a HRTB, the previous
472                                // match arm would have executed). A HRBT is a 'stricter'
473                                // bound than anything else, so we want to keep the newer
474                                // predicate (with the HRBT) in place of the old predicate.
475                                //
476                                // OR
477                                //
478                                // The old predicate has a region variable where the new
479                                // predicate has some other kind of region. An region
480                                // variable isn't something we can actually display to a user,
481                                // so we choose their new predicate (which doesn't have a region
482                                // variable).
483                                //
484                                // In both cases, we want to remove the old predicate,
485                                // from `user_computed_clauses`, and replace it with the new
486                                // one. Having both the old and the new
487                                // predicate in a `ParamEnv` would confuse `SelectionContext`.
488                                //
489                                // We're currently in the predicate passed to 'retain',
490                                // so we return `false` to remove the old predicate from
491                                // `user_computed_clauses`.
492                                return false;
493                            }
494                            (_, ty::ReBound(_, _)) | (ty::ReVar(_), _) => {
495                                // This is the opposite situation as the previous arm.
496                                // One of these is true:
497                                //
498                                // The old predicate has a HRTB lifetime in a place where the
499                                // new predicate does not.
500                                //
501                                // OR
502                                //
503                                // The new predicate has a region variable where the old
504                                // predicate has some other type of region.
505                                //
506                                // We want to leave the old
507                                // predicate in `user_computed_clauses`, and skip adding
508                                // new_clause to `user_computed_params`.
509                                should_add_new = false
510                            }
511                            _ => {}
512                        }
513                    }
514                }
515            }
516            true
517        });
518
519        if should_add_new {
520            user_computed_clauses.insert(new_clause);
521        }
522    }
523
524    /// This is very similar to `handle_lifetimes`. However, instead of matching `ty::Region`s
525    /// to each other, we match `ty::RegionVid`s to `ty::Region`s.
526    fn map_vid_to_region<'cx>(
527        &self,
528        regions: &RegionConstraintData<'cx>,
529    ) -> FxIndexMap<ty::RegionVid, ty::Region<'cx>> {
530        let mut vid_map = FxIndexMap::<RegionTarget<'cx>, RegionDeps<'cx>>::default();
531        let mut finished_map = FxIndexMap::default();
532
533        for c in regions.constraints.iter().flat_map(|(c, _)| c.iter_outlives()) {
534            match c.kind {
535                ConstraintKind::VarSubVar => {
536                    let sub_vid = c.sub.as_var();
537                    let sup_vid = c.sup.as_var();
538                    {
539                        let deps1 = vid_map.entry(RegionTarget::RegionVid(sub_vid)).or_default();
540                        deps1.larger.insert(RegionTarget::RegionVid(sup_vid));
541                    }
542
543                    let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default();
544                    deps2.smaller.insert(RegionTarget::RegionVid(sub_vid));
545                }
546                ConstraintKind::RegSubVar => {
547                    let sup_vid = c.sup.as_var();
548                    {
549                        let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default();
550                        deps1.larger.insert(RegionTarget::RegionVid(sup_vid));
551                    }
552
553                    let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default();
554                    deps2.smaller.insert(RegionTarget::Region(c.sub));
555                }
556                ConstraintKind::VarSubReg => {
557                    let sub_vid = c.sub.as_var();
558                    finished_map.insert(sub_vid, c.sup);
559                }
560                ConstraintKind::RegSubReg => {
561                    {
562                        let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default();
563                        deps1.larger.insert(RegionTarget::Region(c.sup));
564                    }
565
566                    let deps2 = vid_map.entry(RegionTarget::Region(c.sup)).or_default();
567                    deps2.smaller.insert(RegionTarget::Region(c.sub));
568                }
569
570                ConstraintKind::VarEqVar | ConstraintKind::VarEqReg | ConstraintKind::RegEqReg => {
571                    ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
572                }
573            }
574        }
575
576        while !vid_map.is_empty() {
577            let target = *vid_map.keys().next().unwrap();
578            let deps = vid_map.swap_remove(&target).unwrap();
579
580            for smaller in deps.smaller.iter() {
581                for larger in deps.larger.iter() {
582                    match (smaller, larger) {
583                        (&RegionTarget::Region(_), &RegionTarget::Region(_)) => {
584                            if let IndexEntry::Occupied(v) = vid_map.entry(*smaller) {
585                                let smaller_deps = v.into_mut();
586                                smaller_deps.larger.insert(*larger);
587                                smaller_deps.larger.swap_remove(&target);
588                            }
589
590                            if let IndexEntry::Occupied(v) = vid_map.entry(*larger) {
591                                let larger_deps = v.into_mut();
592                                larger_deps.smaller.insert(*smaller);
593                                larger_deps.smaller.swap_remove(&target);
594                            }
595                        }
596                        (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => {
597                            finished_map.insert(v1, r1);
598                        }
599                        (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => {
600                            // Do nothing; we don't care about regions that are smaller than vids.
601                        }
602                        (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => {
603                            if let IndexEntry::Occupied(v) = vid_map.entry(*smaller) {
604                                let smaller_deps = v.into_mut();
605                                smaller_deps.larger.insert(*larger);
606                                smaller_deps.larger.swap_remove(&target);
607                            }
608
609                            if let IndexEntry::Occupied(v) = vid_map.entry(*larger) {
610                                let larger_deps = v.into_mut();
611                                larger_deps.smaller.insert(*smaller);
612                                larger_deps.smaller.swap_remove(&target);
613                            }
614                        }
615                    }
616                }
617            }
618        }
619
620        finished_map
621    }
622
623    fn is_param_no_infer(&self, args: GenericArgsRef<'tcx>) -> bool {
624        self.is_of_param(args.type_at(0)) && !args.terms().any(|t| t.has_infer_types())
625    }
626
627    pub fn is_of_param(&self, ty: Ty<'tcx>) -> bool {
628        match ty.kind() {
629            ty::Param(_) => true,
630            ty::Alias(_, p @ ty::AliasTy { kind: ty::Projection { .. }, .. }) => {
631                self.is_of_param(p.self_ty())
632            }
633            _ => false,
634        }
635    }
636
637    fn is_self_referential_projection(&self, p: ty::PolyProjectionClause<'tcx>) -> bool {
638        if let Some(ty) = p.term().skip_binder().as_type() {
639            #[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())
640        } else {
641            false
642        }
643    }
644
645    fn evaluate_nested_obligations(
646        &self,
647        ty: Ty<'_>,
648        nested: impl Iterator<Item = PredicateObligation<'tcx>>,
649        computed_clauses: &mut FxIndexSet<ty::Clause<'tcx>>,
650        fresh_preds: &mut FxIndexSet<ty::Predicate<'tcx>>,
651        predicates: &mut VecDeque<ty::PolyTraitClause<'tcx>>,
652        selcx: &mut SelectionContext<'_, 'tcx>,
653    ) -> bool {
654        let dummy_cause = ObligationCause::dummy();
655
656        for obligation in nested {
657            let is_new_pred =
658                fresh_preds.insert(self.clean_pred(selcx.infcx, obligation.predicate));
659
660            // Resolve any inference variables that we can, to help selection succeed
661            let predicate = selcx.infcx.deeply_resolve_ignoring_regions(obligation.predicate);
662
663            // We only add a predicate as a user-displayable bound if
664            // it involves a generic parameter, and doesn't contain
665            // any inference variables.
666            //
667            // Displaying a bound involving a concrete type (instead of a generic
668            // parameter) would be pointless, since it's always true
669            // (e.g. u8: Copy)
670            // Displaying an inference variable is impossible, since they're
671            // an internal compiler detail without a defined visual representation
672            //
673            // We check this by calling is_of_param on the relevant types
674            // from the various possible predicates
675
676            let bound_predicate = predicate.kind();
677            match bound_predicate.skip_binder() {
678                ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => {
679                    // Add this to `predicates` so that we end up calling `select`
680                    // with it. If this predicate ends up being unimplemented,
681                    // then `evaluate_predicates` will handle adding it the `ParamEnv`
682                    // if possible.
683                    predicates.push_back(bound_predicate.rebind(p));
684                }
685                ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(c)) => {
686                    let p = bound_predicate.rebind(c);
687                    if self.is_param_no_infer(p.skip_binder().trait_ref.args) && is_new_pred {
688                        self.add_user_clause(computed_clauses, predicate.expect_clause());
689                    }
690                }
691                ty::PredicateKind::Clause(ty::ClauseKind::Projection(p)) => {
692                    let p = bound_predicate.rebind(p);
693                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:693",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(693u32),
                        ::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!(
694                        "evaluate_nested_obligations: examining projection predicate {:?}",
695                        predicate
696                    );
697
698                    // As described above, we only want to display
699                    // bounds which include a generic parameter but don't include
700                    // an inference variable.
701                    // Additionally, we check if we've seen this predicate before,
702                    // to avoid rendering duplicate bounds to the user.
703                    if self.is_param_no_infer(p.skip_binder().projection_term.args)
704                        && !p.term().skip_binder().has_infer_types()
705                        && is_new_pred
706                    {
707                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:707",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(707u32),
                        ::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!(
708                            "evaluate_nested_obligations: adding projection predicate \
709                            to computed_clauses: {:?}",
710                            predicate
711                        );
712
713                        // Under unusual circumstances, we can end up with a self-referential
714                        // projection predicate. For example:
715                        // <T as MyType>::Value == <T as MyType>::Value
716                        // Not only is displaying this to the user pointless,
717                        // having it in the ParamEnv will cause an issue if we try to call
718                        // poly_project_and_unify_type on the predicate, since this kind of
719                        // predicate will normally never end up in a ParamEnv.
720                        //
721                        // For these reasons, we ignore these weird predicates,
722                        // ensuring that we're able to properly synthesize an auto trait impl
723                        if self.is_self_referential_projection(p) {
724                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:724",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(724u32),
                        ::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!(
725                                "evaluate_nested_obligations: encountered a projection
726                                 predicate equating a type with itself! Skipping"
727                            );
728                        } else {
729                            self.add_user_clause(computed_clauses, predicate.expect_clause());
730                        }
731                    }
732
733                    // There are three possible cases when we project a predicate:
734                    //
735                    // 1. We encounter an error. This means that it's impossible for
736                    // our current type to implement the auto trait - there's bound
737                    // that we could add to our ParamEnv that would 'fix' this kind
738                    // of error, as it's not caused by an unimplemented type.
739                    //
740                    // 2. We successfully project the predicate (Ok(Some(_))), generating
741                    //  some subobligations. We then process these subobligations
742                    //  like any other generated sub-obligations.
743                    //
744                    // 3. We receive an 'ambiguous' result (Ok(None))
745                    // If we were actually trying to compile a crate,
746                    // we would need to re-process this obligation later.
747                    // However, all we care about is finding out what bounds
748                    // are needed for our type to implement a particular auto trait.
749                    // We've already added this obligation to our computed ParamEnv
750                    // above (if it was necessary). Therefore, we don't need
751                    // to do any further processing of the obligation.
752                    //
753                    // Note that we *must* try to project *all* projection predicates
754                    // we encounter, even ones without inference variable.
755                    // This ensures that we detect any projection errors,
756                    // which indicate that our type can *never* implement the given
757                    // auto trait. In that case, we will generate an explicit negative
758                    // impl (e.g. 'impl !Send for MyType'). However, we don't
759                    // try to process any of the generated subobligations -
760                    // they contain no new information, since we already know
761                    // that our type implements the projected-through trait,
762                    // and can lead to weird region issues.
763                    //
764                    // Normally, we'll generate a negative impl as a result of encountering
765                    // a type with an explicit negative impl of an auto trait
766                    // (for example, raw pointers have !Send and !Sync impls)
767                    // However, through some **interesting** manipulations of the type
768                    // system, it's actually possible to write a type that never
769                    // implements an auto trait due to a projection error, not a normal
770                    // negative impl error. To properly handle this case, we need
771                    // to ensure that we catch any potential projection errors,
772                    // and turn them into an explicit negative impl for our type.
773                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:773",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(773u32),
                        ::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);
774
775                    match project::poly_project_and_unify_term(selcx, &obligation.with(self.tcx, p))
776                    {
777                        ProjectAndUnifyResult::MismatchedProjectionTypes(e) => {
778                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:778",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(778u32),
                        ::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!(
779                                "evaluate_nested_obligations: Unable to unify predicate \
780                                 '{:?}' '{:?}', bailing out",
781                                ty, e
782                            );
783                            return false;
784                        }
785                        ProjectAndUnifyResult::Recursive => {
786                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs:786",
                        "rustc_trait_selection::traits::auto_trait",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_trait_selection/src/traits/auto_trait.rs"),
                        ::tracing_core::__macro_support::Option::Some(786u32),
                        ::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");
787                            return false;
788                        }
789                        ProjectAndUnifyResult::Holds(v) => {
790                            // We only care about sub-obligations
791                            // when we started out trying to unify
792                            // some inference variables. See the comment above
793                            // for more information
794                            if p.term().skip_binder().has_infer_types() {
795                                if !self.evaluate_nested_obligations(
796                                    ty,
797                                    v.into_iter(),
798                                    computed_clauses,
799                                    fresh_preds,
800                                    predicates,
801                                    selcx,
802                                ) {
803                                    return false;
804                                }
805                            }
806                        }
807                        ProjectAndUnifyResult::FailedNormalization => {
808                            // It's ok not to make progress when have no inference variables -
809                            // in that case, we were only performing unification to check if an
810                            // error occurred (which would indicate that it's impossible for our
811                            // type to implement the auto trait).
812                            // However, we should always make progress (either by generating
813                            // subobligations or getting an error) when we started off with
814                            // inference variables
815                            if p.term().skip_binder().has_infer_types() {
816                                {
    ::core::panicking::panic_fmt(format_args!("Unexpected result when selecting {0:?} {1:?}",
            ty, obligation));
}panic!("Unexpected result when selecting {ty:?} {obligation:?}")
817                            }
818                        }
819                    }
820                }
821                ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(binder)) => {
822                    let binder = bound_predicate.rebind(binder);
823                    selcx.infcx.enter_forall(binder, |pred| {
824                        selcx.infcx.register_region_outlives_constraint(
825                            pred,
826                            ty::VisibleForLeakCheck::Yes,
827                            &dummy_cause,
828                        );
829                    });
830                }
831                ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(binder)) => {
832                    let binder = bound_predicate.rebind(binder);
833                    match (
834                        binder.no_bound_vars(),
835                        binder.map_bound_ref(|pred| pred.0).no_bound_vars(),
836                    ) {
837                        (None, Some(t_a)) => {
838                            selcx.infcx.register_type_outlives_constraint(
839                                t_a,
840                                selcx.infcx.tcx.lifetimes.re_static,
841                                &dummy_cause,
842                            );
843                        }
844                        (Some(ty::OutlivesClause(t_a, r_b)), _) => {
845                            selcx.infcx.register_type_outlives_constraint(t_a, r_b, &dummy_cause);
846                        }
847                        _ => {}
848                    };
849                }
850                ty::PredicateKind::ConstEquate(c1, c2) => {
851                    let evaluate = |c: ty::Const<'tcx>| {
852                        if let ty::ConstKind::Alias(_, alias_const) = c.kind() {
853                            let ct = super::try_evaluate_const(
854                                selcx.infcx,
855                                c,
856                                obligation.param_env,
857                                |ty| Ok::<_, !>(ty.skip_norm_wip()),
858                            );
859
860                            if let Err(EvaluateConstErr::InvalidConstParamTy(_)) = ct {
861                                let span = alias_const.kind.def_span(self.tcx);
862                                self.tcx
863                                    .dcx()
864                                    .emit_err(UnableToConstructConstantValue { span, alias_const });
865                            }
866
867                            ct
868                        } else {
869                            Ok(c)
870                        }
871                    };
872
873                    match (evaluate(c1), evaluate(c2)) {
874                        (Ok(c1), Ok(c2)) => {
875                            match selcx.infcx.at(&obligation.cause, obligation.param_env).eq(
876                                DefineOpaqueTypes::Yes,
877                                c1,
878                                c2,
879                            ) {
880                                Ok(_) => (),
881                                Err(_) => return false,
882                            }
883                        }
884                        _ => return false,
885                    }
886                }
887
888                // There's not really much we can do with these predicates -
889                // we start out with a `ParamEnv` with no inference variables,
890                // and these don't correspond to adding any new bounds to
891                // the `ParamEnv`.
892                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(..))
893                | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..))
894                | ty::PredicateKind::NormalizesTo(..)
895                | ty::PredicateKind::DynCompatible(..)
896                | ty::PredicateKind::Subtype(..)
897                | ty::PredicateKind::Coerce(..)
898                | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(_)) => {}
899                ty::PredicateKind::Ambiguous => return false,
900
901                // FIXME(generic_const_exprs): you can absolutely add this as a where clauses
902                ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) => return false,
903            };
904        }
905        true
906    }
907
908    pub fn clean_pred(
909        &self,
910        infcx: &InferCtxt<'tcx>,
911        p: ty::Predicate<'tcx>,
912    ) -> ty::Predicate<'tcx> {
913        p.fold_with(&mut TypeFreshener::new(infcx))
914    }
915}