Skip to main content

rustc_type_ir/
infer_ctxt.rs

1use core::fmt;
2use std::hash::{Hash, Hasher};
3
4use derive_where::derive_where;
5#[cfg(feature = "nightly")]
6use rustc_macros::{Decodable_NoContext, Encodable_NoContext, StableHash_NoContext};
7
8use crate::fold::TypeFoldable;
9use crate::inherent::*;
10use crate::relate::RelateResult;
11use crate::relate::combine::PredicateEmittingRelation;
12use crate::solve::VisibleForLeakCheck;
13use crate::{self as ty, Interner, TyVid};
14
15mod private {
16    pub trait Sealed {}
17
18    impl Sealed for super::CantBeErased {}
19    impl Sealed for super::MayBeErased {}
20}
21pub trait TypingModeErasedStatus: private::Sealed + Clone + Copy + Hash + fmt::Debug {}
22
23#[derive(#[automatically_derived]
impl ::core::clone::Clone for CantBeErased {
    #[inline]
    fn clone(&self) -> CantBeErased { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CantBeErased { }Copy, #[automatically_derived]
impl ::core::hash::Hash for CantBeErased {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        match *self {}
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for CantBeErased {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match *self {}
    }
}Debug)]
24pub enum CantBeErased {}
25#[derive(#[automatically_derived]
impl ::core::clone::Clone for MayBeErased {
    #[inline]
    fn clone(&self) -> MayBeErased { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MayBeErased { }Copy, #[automatically_derived]
impl ::core::hash::Hash for MayBeErased {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {}
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for MayBeErased {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "MayBeErased")
    }
}Debug)]
26#[cfg_attr(
27    feature = "nightly",
28    derive(const _: () =
    {
        impl<__E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for MayBeErased {
            fn encode(&self, __encoder: &mut __E) {
                match *self { MayBeErased => {} }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<__D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for MayBeErased {
            fn decode(__decoder: &mut __D) -> Self { MayBeErased }
        }
    };Decodable_NoContext, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for MayBeErased
            {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self { MayBeErased => {} }
            }
        }
    };StableHash_NoContext)
29)]
30pub struct MayBeErased;
31
32impl TypingModeErasedStatus for CantBeErased {}
33impl TypingModeErasedStatus for MayBeErased {}
34
35/// The current typing mode of an inference context. We unfortunately have some
36/// slightly different typing rules depending on the current context. See the
37/// doc comment for each variant for how and why they are used.
38///
39/// In most cases you can get the correct typing mode automatically via:
40/// - `mir::Body::typing_mode`
41/// - `rustc_lint::LateContext::typing_mode`
42///
43/// If neither of these functions are available, feel free to reach out to
44/// t-types for help.
45///
46/// Because typing rules get subtly different based on what typing mode we're in,
47/// subtle enough that changing the behavior of typing modes can sometimes cause
48/// changes that we don't even have tests for, we'd like to enforce the rule that
49/// any place where we specialize behavior based on the typing mode, we match
50/// *exhaustively* on the typing mode. That way, it's easy to determine all the
51/// places that must change when anything about typing modes changes.
52///
53/// Hence, `TypingMode` does not implement `Eq`, though [`TypingModeEqWrapper`] is available
54/// in the rare case that you do need this. Most cases where this currently matters is
55/// where we pass typing modes through the query system and want to cache based on it.
56/// See also `#[rustc_must_match_exhaustively]`, which tries to detect non-exhaustive
57/// matches.
58///
59/// Since matching on typing mode to single out `Coherence` is so common, and `Coherence`
60/// is so different from the other modes: see also [`is_coherence`](TypingMode::is_coherence)
61#[automatically_derived]
impl<I: Interner, S: TypingModeErasedStatus> ::core::fmt::Debug for
    TypingMode<I, S> where I: Interner {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            TypingMode::Coherence =>
                ::core::fmt::Formatter::write_str(__f, "Coherence"),
            TypingMode::Analysis {
                defining_opaque_types_and_generators: ref __field_defining_opaque_types_and_generators
                } => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f, "Analysis");
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "defining_opaque_types_and_generators",
                    __field_defining_opaque_types_and_generators);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
            TypingMode::Borrowck {
                defining_opaque_types: ref __field_defining_opaque_types } =>
                {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f, "Borrowck");
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "defining_opaque_types", __field_defining_opaque_types);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
            TypingMode::PostBorrowckAnalysis {
                defined_opaque_types: ref __field_defined_opaque_types } => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f,
                        "PostBorrowckAnalysis");
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "defined_opaque_types", __field_defined_opaque_types);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
            TypingMode::PostAnalysis =>
                ::core::fmt::Formatter::write_str(__f, "PostAnalysis"),
            TypingMode::ErasedNotCoherence(ref __field_0) => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_tuple(__f,
                        "ErasedNotCoherence");
                ::core::fmt::DebugTuple::field(&mut __builder, __field_0);
                ::core::fmt::DebugTuple::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Clone, Copy, Hash, Debug; I: Interner)]
62#[cfg_attr(
63    feature = "nightly",
64    derive(const _: () =
    {
        impl<I: Interner, S: TypingModeErasedStatus,
            __E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<__E>
            for TypingMode<I, S> where
            I::LocalDefIds: ::rustc_serialize::Encodable<__E>,
            S: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        TypingMode::Coherence => { 0usize }
                        TypingMode::Analysis {
                            defining_opaque_types_and_generators: ref __binding_0 } => {
                            1usize
                        }
                        TypingMode::Borrowck {
                            defining_opaque_types: ref __binding_0 } => {
                            2usize
                        }
                        TypingMode::PostBorrowckAnalysis {
                            defined_opaque_types: ref __binding_0 } => {
                            3usize
                        }
                        TypingMode::PostAnalysis => { 4usize }
                        TypingMode::ErasedNotCoherence(ref __binding_0) => {
                            5usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    TypingMode::Coherence => {}
                    TypingMode::Analysis {
                        defining_opaque_types_and_generators: ref __binding_0 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    TypingMode::Borrowck {
                        defining_opaque_types: ref __binding_0 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    TypingMode::PostBorrowckAnalysis {
                        defined_opaque_types: ref __binding_0 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    TypingMode::PostAnalysis => {}
                    TypingMode::ErasedNotCoherence(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<I: Interner, S: TypingModeErasedStatus,
            __D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<__D>
            for TypingMode<I, S> where
            I::LocalDefIds: ::rustc_serialize::Decodable<__D>,
            S: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { TypingMode::Coherence }
                    1usize => {
                        TypingMode::Analysis {
                            defining_opaque_types_and_generators: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    2usize => {
                        TypingMode::Borrowck {
                            defining_opaque_types: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    3usize => {
                        TypingMode::PostBorrowckAnalysis {
                            defined_opaque_types: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    4usize => { TypingMode::PostAnalysis }
                    5usize => {
                        TypingMode::ErasedNotCoherence(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `TypingMode`, expected 0..6, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<I: Interner, S: TypingModeErasedStatus>
            ::rustc_data_structures::stable_hash::StableHash for
            TypingMode<I, S> where
            I::LocalDefIds: ::rustc_data_structures::stable_hash::StableHash,
            S: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    TypingMode::Coherence => {}
                    TypingMode::Analysis {
                        defining_opaque_types_and_generators: ref __binding_0 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    TypingMode::Borrowck {
                        defining_opaque_types: ref __binding_0 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    TypingMode::PostBorrowckAnalysis {
                        defined_opaque_types: ref __binding_0 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    TypingMode::PostAnalysis => {}
                    TypingMode::ErasedNotCoherence(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext)
65)]
66pub enum TypingMode<I: Interner, S: TypingModeErasedStatus = MayBeErased> {
67    /// When checking whether impls overlap, we check whether any obligations
68    /// are guaranteed to never hold when unifying the impls. This requires us
69    /// to be complete: we must never fail to prove something which may actually
70    /// hold.
71    ///
72    /// In this typing mode we bail with ambiguity in case its not knowable
73    /// whether a trait goal may hold, e.g. because the trait may get implemented
74    /// in a downstream or sibling crate.
75    ///
76    /// We also have to be careful when generalizing aliases inside of higher-ranked
77    /// types to not unnecessarily constrain any inference variables.
78    Coherence,
79    /// Analysis includes type inference, checking that items are well-formed, and
80    /// pretty much everything else which may emit proper type errors to the user.
81    ///
82    /// We only normalize opaque types which may get defined by the current body,
83    /// which are stored in `defining_opaque_types`.
84    ///
85    /// We also refuse to project any associated type that is marked `default`.
86    /// Non-`default` ("final") types are always projected. This is necessary in
87    /// general for soundness of specialization. However, we *could* allow projections
88    /// in fully-monomorphic cases. We choose not to, because we prefer for `default type`
89    /// to force the type definition to be treated abstractly by any consumers of the
90    /// impl. Concretely, that means that the following example will
91    /// fail to compile:
92    ///
93    /// ```compile_fail,E0308
94    /// #![feature(specialization)]
95    /// trait Assoc {
96    ///     type Output;
97    /// }
98    ///
99    /// impl<T> Assoc for T {
100    ///     default type Output = bool;
101    /// }
102    ///
103    /// fn main() {
104    ///     let x: <() as Assoc>::Output = true;
105    /// }
106    /// ```
107    Analysis { defining_opaque_types_and_generators: I::LocalDefIds },
108    /// The behavior during MIR borrowck is identical to `TypingMode::Analysis`
109    /// except that the initial value for opaque types is the type computed during
110    /// HIR typeck with unique unconstrained region inference variables.
111    ///
112    /// This is currently only used with by the new solver as it results in new
113    /// non-universal defining uses of opaque types, which is a breaking change.
114    /// See tests/ui/impl-trait/non-defining-use/as-projection-term.rs.
115    Borrowck { defining_opaque_types: I::LocalDefIds },
116    /// Any analysis after borrowck for a given body should be able to use all the
117    /// hidden types defined by borrowck, without being able to define any new ones.
118    ///
119    /// This is currently only used by the new solver, but should be implemented in
120    /// the old solver as well.
121    PostBorrowckAnalysis { defined_opaque_types: I::LocalDefIds },
122    /// After analysis, mostly during codegen and MIR optimizations, we're able to
123    /// reveal all opaque types. As the hidden type should *never* be observable
124    /// directly by the user, this should not be used by checks which may expose
125    /// such details to the user.
126    ///
127    /// There are some exceptions to this as for example `layout_of` and const-evaluation
128    /// always run in `PostAnalysis` mode, even when used during analysis. This exposes
129    /// some information about the underlying type to users, but not the type itself.
130    PostAnalysis,
131
132    /// The typing modes above (except coherence) only differ in how they handle
133    ///
134    /// - Generators
135    /// - Opaque types
136    /// - Specialization (in `PostAnalysis`)
137    ///
138    /// We replace all of them with this `TypingMode` in the first attempt at canonicalization.
139    /// If, during that attempt, we try to access information about opaques or generators
140    /// we bail out, setting a field on `EvalCtxt` that indicates the canonicalization must be
141    /// rerun in the original typing mode.
142    ///
143    /// `TypingMode::Coherence` is not replaced by this and is always kept as-is.
144    ErasedNotCoherence(S),
145}
146
147/// We want to highly discourage using equality checks on typing modes.
148/// Instead you should match, **exhaustively**, so when we ever modify the enum we get a compile
149/// error. Only use `TypingModeEqWrapper` when you really really really have to.
150/// Prefer unwrapping `TypingModeEqWrapper` in apis that should return a `TypingMode` whenever
151/// possible, and if you ever get an `TypingModeEqWrapper`, prefer unwrapping it and matching on it **exhaustively**.
152#[automatically_derived]
impl<I: Interner> ::core::fmt::Debug for TypingModeEqWrapper<I> where
    I: Interner {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            TypingModeEqWrapper(ref __field_0) => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_tuple(__f,
                        "TypingModeEqWrapper");
                ::core::fmt::DebugTuple::field(&mut __builder, __field_0);
                ::core::fmt::DebugTuple::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Clone, Copy, Debug; I: Interner)]
153#[cfg_attr(
154    feature = "nightly",
155    derive(const _: () =
    {
        impl<I: Interner, __E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for TypingModeEqWrapper<I> where
            TypingMode<I, MayBeErased>: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    TypingModeEqWrapper(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<I: Interner, __D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for TypingModeEqWrapper<I> where
            TypingMode<I, MayBeErased>: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                TypingModeEqWrapper(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<I: Interner> ::rustc_data_structures::stable_hash::StableHash for
            TypingModeEqWrapper<I> where
            TypingMode<I,
            MayBeErased>: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    TypingModeEqWrapper(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext)
156)]
157pub struct TypingModeEqWrapper<I: Interner>(pub TypingMode<I, MayBeErased>);
158
159impl<I: Interner> Hash for TypingModeEqWrapper<I> {
160    fn hash<H: Hasher>(&self, state: &mut H) {
161        self.0.hash(state);
162    }
163}
164
165impl<I: Interner> PartialEq for TypingModeEqWrapper<I> {
166    fn eq(&self, other: &Self) -> bool {
167        match (self.0, other.0) {
168            (TypingMode::Coherence, TypingMode::Coherence) => true,
169            (
170                TypingMode::Analysis { defining_opaque_types_and_generators: l },
171                TypingMode::Analysis { defining_opaque_types_and_generators: r },
172            ) => l == r,
173            (
174                TypingMode::Borrowck { defining_opaque_types: l },
175                TypingMode::Borrowck { defining_opaque_types: r },
176            ) => l == r,
177            (
178                TypingMode::PostBorrowckAnalysis { defined_opaque_types: l },
179                TypingMode::PostBorrowckAnalysis { defined_opaque_types: r },
180            ) => l == r,
181            (TypingMode::PostAnalysis, TypingMode::PostAnalysis) => true,
182            (
183                TypingMode::ErasedNotCoherence(MayBeErased),
184                TypingMode::ErasedNotCoherence(MayBeErased),
185            ) => true,
186            (
187                TypingMode::Coherence
188                | TypingMode::Analysis { .. }
189                | TypingMode::Borrowck { .. }
190                | TypingMode::PostBorrowckAnalysis { .. }
191                | TypingMode::PostAnalysis
192                | TypingMode::ErasedNotCoherence(MayBeErased),
193                _,
194            ) => false,
195        }
196    }
197}
198
199impl<I: Interner> Eq for TypingModeEqWrapper<I> {}
200
201impl<I: Interner, S: TypingModeErasedStatus> TypingMode<I, S> {
202    /// There are a bunch of places in the compiler where we single out `Coherence`,
203    /// and alter behavior. We'd like to *always* match on `TypingMode` exhaustively,
204    /// but not having this method leads to a bunch of noisy code.
205    ///
206    /// See also the documentation on [`TypingMode`] about exhaustive matching.
207    pub fn is_coherence(&self) -> bool {
208        match self {
209            TypingMode::Coherence => true,
210            TypingMode::Analysis { .. }
211            | TypingMode::Borrowck { .. }
212            | TypingMode::PostBorrowckAnalysis { .. }
213            | TypingMode::PostAnalysis
214            | TypingMode::ErasedNotCoherence(_) => false,
215        }
216    }
217
218    /// There are a bunch of places in the trait solver where we single out `Coherence`,
219    /// and alter behavior. We'd like to *always* match on `TypingMode` exhaustively,
220    /// but not having this method leads to a bunch of noisy code.
221    ///
222    /// See also the documentation on [`TypingMode`] about exhaustive matching.
223    pub fn is_erased_not_coherence(&self) -> bool {
224        match self {
225            TypingMode::ErasedNotCoherence(_) => true,
226            TypingMode::Coherence
227            | TypingMode::Analysis { .. }
228            | TypingMode::Borrowck { .. }
229            | TypingMode::PostBorrowckAnalysis { .. }
230            | TypingMode::PostAnalysis => false,
231        }
232    }
233}
234
235impl<I: Interner> TypingMode<I, MayBeErased> {
236    /// Only call this when you're sure you're outside the next trait solver!
237    /// That means either not in the trait solver, or in code that is old-solver only.
238    ///
239    /// See the comment on `InferCtxt::typing_mode_raw`
240    pub fn assert_not_erased(self) -> TypingMode<I, CantBeErased> {
241        match self {
242            TypingMode::Coherence => TypingMode::Coherence,
243            TypingMode::Analysis { defining_opaque_types_and_generators } => {
244                TypingMode::Analysis { defining_opaque_types_and_generators }
245            }
246            TypingMode::Borrowck { defining_opaque_types } => {
247                TypingMode::Borrowck { defining_opaque_types }
248            }
249            TypingMode::PostBorrowckAnalysis { defined_opaque_types } => {
250                TypingMode::PostBorrowckAnalysis { defined_opaque_types }
251            }
252            TypingMode::PostAnalysis => TypingMode::PostAnalysis,
253            TypingMode::ErasedNotCoherence(MayBeErased) => {
    ::core::panicking::panic_fmt(format_args!("Called `assert_not_erased` from a place that can be called by the trait solver in `TypingMode::ErasedNotCoherence`. `TypingMode` is `ErasedNotCoherence` in a place where that should be impossible"));
}panic!(
254                "Called `assert_not_erased` from a place that can be called by the trait solver in `TypingMode::ErasedNotCoherence`. `TypingMode` is `ErasedNotCoherence` in a place where that should be impossible"
255            ),
256        }
257    }
258}
259
260impl<I: Interner> TypingMode<I, CantBeErased> {
261    /// Analysis outside of a body does not define any opaque types.
262    pub fn non_body_analysis() -> TypingMode<I> {
263        TypingMode::Analysis { defining_opaque_types_and_generators: Default::default() }
264    }
265
266    pub fn typeck_for_body(cx: I, body_def_id: I::LocalDefId) -> TypingMode<I> {
267        TypingMode::Analysis {
268            defining_opaque_types_and_generators: cx
269                .opaque_types_and_coroutines_defined_by(body_def_id),
270        }
271    }
272
273    /// While typechecking a body, we need to be able to define the opaque
274    /// types defined by that body.
275    ///
276    /// FIXME: This will be removed because it's generally not correct to define
277    /// opaques outside of HIR typeck.
278    pub fn analysis_in_body(cx: I, body_def_id: I::LocalDefId) -> TypingMode<I> {
279        TypingMode::Analysis {
280            defining_opaque_types_and_generators: cx.opaque_types_defined_by(body_def_id),
281        }
282    }
283
284    pub fn borrowck(cx: I, body_def_id: I::LocalDefId) -> TypingMode<I> {
285        let defining_opaque_types = cx.opaque_types_defined_by(body_def_id);
286        if defining_opaque_types.is_empty() {
287            TypingMode::non_body_analysis()
288        } else {
289            TypingMode::Borrowck { defining_opaque_types }
290        }
291    }
292
293    pub fn post_borrowck_analysis(cx: I, body_def_id: I::LocalDefId) -> TypingMode<I> {
294        let defined_opaque_types = cx.opaque_types_defined_by(body_def_id);
295        if defined_opaque_types.is_empty() {
296            TypingMode::non_body_analysis()
297        } else {
298            TypingMode::PostBorrowckAnalysis { defined_opaque_types }
299        }
300    }
301}
302
303impl<I: Interner> From<TypingMode<I, CantBeErased>> for TypingMode<I, MayBeErased> {
304    fn from(value: TypingMode<I, CantBeErased>) -> Self {
305        match value {
306            TypingMode::Coherence => TypingMode::Coherence,
307            TypingMode::Analysis { defining_opaque_types_and_generators } => {
308                TypingMode::Analysis { defining_opaque_types_and_generators }
309            }
310            TypingMode::Borrowck { defining_opaque_types } => {
311                TypingMode::Borrowck { defining_opaque_types }
312            }
313            TypingMode::PostBorrowckAnalysis { defined_opaque_types } => {
314                TypingMode::PostBorrowckAnalysis { defined_opaque_types }
315            }
316            TypingMode::PostAnalysis => TypingMode::PostAnalysis,
317        }
318    }
319}
320
321#[cfg_attr(feature = "nightly", rustc_diagnostic_item = "type_ir_infer_ctxt_like")]
322pub trait InferCtxtLike: Sized {
323    type Interner: Interner;
324    fn cx(&self) -> Self::Interner;
325
326    /// Whether the new trait solver is enabled. This only exists because rustc
327    /// shares code between the new and old trait solvers; for all other users,
328    /// this should always be true. If this is unknowingly false and you try to
329    /// use the new trait solver, things will break badly.
330    fn next_trait_solver(&self) -> bool {
331        true
332    }
333
334    fn disable_trait_solver_fast_paths(&self) -> bool;
335
336    fn typing_mode_raw(&self) -> TypingMode<Self::Interner>;
337
338    fn universe(&self) -> ty::UniverseIndex;
339    fn create_next_universe(&self) -> ty::UniverseIndex;
340
341    fn insert_placeholder_assumptions(
342        &self,
343        u: ty::UniverseIndex,
344        assumptions: Option<crate::region_constraint::Assumptions<Self::Interner>>,
345    );
346    fn get_placeholder_assumptions(
347        &self,
348        u: ty::UniverseIndex,
349    ) -> Option<crate::region_constraint::Assumptions<Self::Interner>>;
350    fn get_solver_region_constraint(
351        &self,
352    ) -> crate::region_constraint::RegionConstraint<Self::Interner>;
353    fn overwrite_solver_region_constraint(
354        &self,
355        constraint: crate::region_constraint::RegionConstraint<Self::Interner>,
356    );
357
358    fn universe_of_ty(&self, ty: ty::TyVid) -> Option<ty::UniverseIndex>;
359    fn universe_of_lt(&self, lt: ty::RegionVid) -> Option<ty::UniverseIndex>;
360    fn universe_of_ct(&self, ct: ty::ConstVid) -> Option<ty::UniverseIndex>;
361
362    fn root_ty_var(&self, var: ty::TyVid) -> ty::TyVid;
363    fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid;
364    fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid;
365
366    fn opportunistic_resolve_ty_var(&self, vid: ty::TyVid) -> <Self::Interner as Interner>::Ty;
367    fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> <Self::Interner as Interner>::Ty;
368    fn opportunistic_resolve_float_var(
369        &self,
370        vid: ty::FloatVid,
371    ) -> <Self::Interner as Interner>::Ty;
372    fn opportunistic_resolve_ct_var(
373        &self,
374        vid: ty::ConstVid,
375    ) -> <Self::Interner as Interner>::Const;
376    fn opportunistic_resolve_lt_var(
377        &self,
378        vid: ty::RegionVid,
379    ) -> <Self::Interner as Interner>::Region;
380
381    fn is_changed_arg(&self, arg: <Self::Interner as Interner>::GenericArg) -> bool;
382
383    fn next_region_infer(&self) -> <Self::Interner as Interner>::Region;
384    fn next_ty_infer(&self) -> <Self::Interner as Interner>::Ty;
385    fn next_const_infer(&self) -> <Self::Interner as Interner>::Const;
386    fn fresh_args_for_item(
387        &self,
388        def_id: <Self::Interner as Interner>::DefId,
389    ) -> <Self::Interner as Interner>::GenericArgs;
390
391    fn instantiate_binder_with_infer<T: TypeFoldable<Self::Interner> + Copy>(
392        &self,
393        value: ty::Binder<Self::Interner, T>,
394    ) -> T;
395
396    fn enter_forall<T: TypeFoldable<Self::Interner>, U>(
397        &self,
398        value: ty::Binder<Self::Interner, T>,
399        f: impl FnOnce(T) -> U,
400    ) -> U;
401
402    fn equate_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid);
403    fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid);
404    fn equate_int_vids_raw(&self, a: ty::IntVid, b: ty::IntVid);
405    fn equate_float_vids_raw(&self, a: ty::FloatVid, b: ty::FloatVid);
406    fn equate_const_vids_raw(&self, a: ty::ConstVid, b: ty::ConstVid);
407
408    fn instantiate_ty_var_raw<R: PredicateEmittingRelation<Self>>(
409        &self,
410        relation: &mut R,
411        target_is_expected: bool,
412        target_vid: ty::TyVid,
413        instantiation_variance: ty::Variance,
414        source_ty: <Self::Interner as Interner>::Ty,
415    ) -> RelateResult<Self::Interner, ()>;
416    fn instantiate_int_var_raw(&self, vid: ty::IntVid, value: ty::IntVarValue);
417    fn instantiate_float_var_raw(&self, vid: ty::FloatVid, value: ty::FloatVarValue);
418    fn instantiate_const_var_raw<R: PredicateEmittingRelation<Self>>(
419        &self,
420        relation: &mut R,
421        target_is_expected: bool,
422        target_vid: ty::ConstVid,
423        source_ct: <Self::Interner as Interner>::Const,
424    ) -> RelateResult<Self::Interner, ()>;
425
426    fn set_tainted_by_errors(&self, e: <Self::Interner as Interner>::ErrorGuaranteed);
427
428    fn shallow_resolve(
429        &self,
430        ty: <Self::Interner as Interner>::Ty,
431    ) -> <Self::Interner as Interner>::Ty;
432    fn shallow_resolve_const(
433        &self,
434        ty: <Self::Interner as Interner>::Const,
435    ) -> <Self::Interner as Interner>::Const;
436
437    fn resolve_vars_if_possible<T>(&self, value: T) -> T
438    where
439        T: TypeFoldable<Self::Interner>;
440
441    fn probe<T>(&self, probe: impl FnOnce() -> T) -> T;
442
443    fn sub_regions(
444        &self,
445        sub: <Self::Interner as Interner>::Region,
446        sup: <Self::Interner as Interner>::Region,
447        vis: VisibleForLeakCheck,
448        span: <Self::Interner as Interner>::Span,
449    );
450
451    fn equate_regions(
452        &self,
453        a: <Self::Interner as Interner>::Region,
454        b: <Self::Interner as Interner>::Region,
455        vis: VisibleForLeakCheck,
456        span: <Self::Interner as Interner>::Span,
457    );
458
459    fn register_solver_region_constraint(
460        &self,
461        c: crate::region_constraint::RegionConstraint<Self::Interner>,
462    );
463
464    fn register_ty_outlives(
465        &self,
466        ty: <Self::Interner as Interner>::Ty,
467        r: <Self::Interner as Interner>::Region,
468        span: <Self::Interner as Interner>::Span,
469    );
470
471    type OpaqueTypeStorageEntries: OpaqueTypeStorageEntries;
472    fn opaque_types_storage_num_entries(&self) -> Self::OpaqueTypeStorageEntries;
473    fn clone_opaque_types_lookup_table(
474        &self,
475    ) -> Vec<(ty::OpaqueTypeKey<Self::Interner>, <Self::Interner as Interner>::Ty)>;
476    fn clone_duplicate_opaque_types(
477        &self,
478    ) -> Vec<(ty::OpaqueTypeKey<Self::Interner>, <Self::Interner as Interner>::Ty)>;
479    fn clone_opaque_types_added_since(
480        &self,
481        prev_entries: Self::OpaqueTypeStorageEntries,
482    ) -> Vec<(ty::OpaqueTypeKey<Self::Interner>, <Self::Interner as Interner>::Ty)>;
483    fn opaques_with_sub_unified_hidden_type(&self, ty: TyVid) -> Vec<ty::AliasTy<Self::Interner>>;
484
485    fn register_hidden_type_in_storage(
486        &self,
487        opaque_type_key: ty::OpaqueTypeKey<Self::Interner>,
488        hidden_ty: <Self::Interner as Interner>::Ty,
489        span: <Self::Interner as Interner>::Span,
490    ) -> Option<<Self::Interner as Interner>::Ty>;
491    fn add_duplicate_opaque_type(
492        &self,
493        opaque_type_key: ty::OpaqueTypeKey<Self::Interner>,
494        hidden_ty: <Self::Interner as Interner>::Ty,
495        span: <Self::Interner as Interner>::Span,
496    );
497
498    fn reset_opaque_types(&self);
499}
500
501pub fn may_use_unstable_feature<'a, I: Interner, Infcx>(
502    infcx: &'a Infcx,
503    param_env: I::ParamEnv,
504    symbol: I::Symbol,
505) -> bool
506where
507    Infcx: InferCtxtLike<Interner = I>,
508{
509    // Iterate through all goals in param_env to find the one that has the same symbol.
510    for pred in param_env.caller_bounds().iter() {
511        if let ty::ClauseKind::UnstableFeature(sym) = pred.kind().skip_binder() {
512            if sym == symbol {
513                return true;
514            }
515        }
516    }
517
518    // During codegen we must assume that all feature bounds hold as we may be
519    // monomorphizing a body from an upstream crate which had an unstable feature
520    // enabled that we do not.
521    //
522    // Coherence should already report overlap errors involving unstable impls
523    // as the affected code would otherwise break when stabilizing this feature.
524    // It is also easily possible to accidentally cause unsoundness this way as
525    // we have to always enable unstable impls during codegen.
526    //
527    // Return ambiguity can also prevent people from writing code which depends on inference guidance
528    // that might no longer work after the impl is stabilised,
529    // tests/ui/unstable-feature-bound/unstable_impl_method_selection.rs is one of the example.
530    //
531    // Note: `feature_bound_holds_in_crate` does not consider a feature to be enabled
532    // if we are in std/core even if there is a corresponding `feature` attribute on the crate.
533
534    match infcx.typing_mode_raw().assert_not_erased() {
535        TypingMode::Coherence
536        | TypingMode::Analysis { .. }
537        | TypingMode::Borrowck { .. }
538        | TypingMode::PostBorrowckAnalysis { .. } => {
539            infcx.cx().features().feature_bound_holds_in_crate(symbol)
540        }
541        TypingMode::PostAnalysis => true,
542    }
543}