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