Skip to main content

rustc_infer/infer/
mod.rs

1use std::cell::{Cell, RefCell};
2use std::fmt;
3
4pub use at::DefineOpaqueTypes;
5use free_regions::RegionRelations;
6pub use freshen::TypeFreshener;
7use lexical_region_resolve::LexicalRegionResolutions;
8pub use lexical_region_resolve::RegionResolutionError;
9pub use opaque_types::{OpaqueTypeStorage, OpaqueTypeStorageEntries, OpaqueTypeTable};
10use region_constraints::{
11    GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
12};
13pub use relate::StructurallyRelateAliases;
14pub use relate::combine::PredicateEmittingRelation;
15use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
16use rustc_data_structures::undo_log::{Rollback, UndoLogs};
17use rustc_data_structures::unify as ut;
18use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
19use rustc_hir::def_id::{DefId, LocalDefId};
20use rustc_hir::{self as hir, HirId};
21use rustc_index::IndexVec;
22use rustc_macros::extension;
23pub use rustc_macros::{TypeFoldable, TypeVisitable};
24use rustc_middle::bug;
25use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
26use rustc_middle::mir::ConstraintCategory;
27use rustc_middle::traits::select;
28use rustc_middle::traits::solve::Goal;
29use rustc_middle::ty::error::{ExpectedFound, TypeError};
30use rustc_middle::ty::{
31    self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
32    GenericArgsRef, GenericParamDefKind, InferConst, IntVid, OpaqueTypeKey, ProvisionalHiddenType,
33    PseudoCanonicalInput, Term, TermKind, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder,
34    TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
35};
36use rustc_span::{DUMMY_SP, Span, Symbol};
37use snapshot::undo_log::InferCtxtUndoLogs;
38use tracing::{debug, instrument};
39use type_variable::TypeVariableOrigin;
40
41use crate::infer::snapshot::undo_log::UndoLog;
42use crate::infer::type_variable::FloatVariableOrigin;
43use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
44use crate::traits::{
45    self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
46    TraitEngine,
47};
48
49pub mod at;
50pub mod canonical;
51mod context;
52mod free_regions;
53mod freshen;
54mod lexical_region_resolve;
55mod opaque_types;
56pub mod outlives;
57mod projection;
58pub mod region_constraints;
59pub mod relate;
60pub mod resolve;
61pub(crate) mod snapshot;
62mod type_variable;
63mod unify_key;
64
65/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
66/// around `PredicateObligations<'tcx>`, but it has one important property:
67/// because `InferOk` is marked with `#[must_use]`, if you have a method
68/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
69/// `infcx.f()?;` you'll get a warning about the obligations being discarded
70/// without use, which is probably unintentional and has been a source of bugs
71/// in the past.
72#[must_use]
73#[derive(#[automatically_derived]
impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug for InferOk<'tcx, T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "InferOk",
            "value", &self.value, "obligations", &&self.obligations)
    }
}Debug)]
74pub struct InferOk<'tcx, T> {
75    pub value: T,
76    pub obligations: PredicateObligations<'tcx>,
77}
78pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
79
80pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
81
82pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
83    ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
84>;
85
86/// This type contains all the things within `InferCtxt` that sit within a
87/// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
88/// operations are hot enough that we want only one call to `borrow_mut` per
89/// call to `start_snapshot` and `rollback_to`.
90#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for InferCtxtInner<'tcx> {
    #[inline]
    fn clone(&self) -> InferCtxtInner<'tcx> {
        InferCtxtInner {
            undo_log: ::core::clone::Clone::clone(&self.undo_log),
            projection_cache: ::core::clone::Clone::clone(&self.projection_cache),
            type_variable_storage: ::core::clone::Clone::clone(&self.type_variable_storage),
            const_unification_storage: ::core::clone::Clone::clone(&self.const_unification_storage),
            int_unification_storage: ::core::clone::Clone::clone(&self.int_unification_storage),
            float_unification_storage: ::core::clone::Clone::clone(&self.float_unification_storage),
            float_origin_origin_storage: ::core::clone::Clone::clone(&self.float_origin_origin_storage),
            region_constraint_storage: ::core::clone::Clone::clone(&self.region_constraint_storage),
            region_obligations: ::core::clone::Clone::clone(&self.region_obligations),
            region_assumptions: ::core::clone::Clone::clone(&self.region_assumptions),
            hir_typeck_potentially_region_dependent_goals: ::core::clone::Clone::clone(&self.hir_typeck_potentially_region_dependent_goals),
            opaque_type_storage: ::core::clone::Clone::clone(&self.opaque_type_storage),
        }
    }
}Clone)]
91pub struct InferCtxtInner<'tcx> {
92    undo_log: InferCtxtUndoLogs<'tcx>,
93
94    /// Cache for projections.
95    ///
96    /// This cache is snapshotted along with the infcx.
97    projection_cache: traits::ProjectionCacheStorage<'tcx>,
98
99    /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
100    /// that might instantiate a general type variable have an order,
101    /// represented by its upper and lower bounds.
102    type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
103
104    /// Map from const parameter variable to the kind of const it represents.
105    const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
106
107    /// Map from integral variable to the kind of integer it represents.
108    int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
109
110    /// Map from floating variable to the kind of float it represents.
111    float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
112
113    /// Map from floating variable to the origin span it came from, and the HirId that should be
114    /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
115    /// so can be removed once the `f32` fallback is removed.
116    float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
117
118    /// Tracks the set of region variables and the constraints between them.
119    ///
120    /// This is initially `Some(_)` but when
121    /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
122    /// -- further attempts to perform unification, etc., may fail if new
123    /// region constraints would've been added.
124    region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
125
126    /// A set of constraints that regionck must validate.
127    ///
128    /// Each constraint has the form `T:'a`, meaning "some type `T` must
129    /// outlive the lifetime 'a". These constraints derive from
130    /// instantiated type parameters. So if you had a struct defined
131    /// like the following:
132    /// ```ignore (illustrative)
133    /// struct Foo<T: 'static> { ... }
134    /// ```
135    /// In some expression `let x = Foo { ... }`, it will
136    /// instantiate the type parameter `T` with a fresh type `$0`. At
137    /// the same time, it will record a region obligation of
138    /// `$0: 'static`. This will get checked later by regionck. (We
139    /// can't generally check these things right away because we have
140    /// to wait until types are resolved.)
141    region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
142
143    /// The outlives bounds that we assume must hold about placeholders that
144    /// come from instantiating the binder of coroutine-witnesses. These bounds
145    /// are deduced from the well-formedness of the witness's types, and are
146    /// necessary because of the way we anonymize the regions in a coroutine,
147    /// which may cause types to no longer be considered well-formed.
148    region_assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
149
150    /// `-Znext-solver`: Successfully proven goals during HIR typeck which
151    /// reference inference variables and get reproven in case MIR type check
152    /// fails to prove something.
153    ///
154    /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
155    hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
156
157    /// Caches for opaque type inference.
158    opaque_type_storage: OpaqueTypeStorage<'tcx>,
159}
160
161impl<'tcx> InferCtxtInner<'tcx> {
162    fn new() -> InferCtxtInner<'tcx> {
163        InferCtxtInner {
164            undo_log: InferCtxtUndoLogs::default(),
165
166            projection_cache: Default::default(),
167            type_variable_storage: Default::default(),
168            const_unification_storage: Default::default(),
169            int_unification_storage: Default::default(),
170            float_unification_storage: Default::default(),
171            float_origin_origin_storage: Default::default(),
172            region_constraint_storage: Some(Default::default()),
173            region_obligations: Default::default(),
174            region_assumptions: Default::default(),
175            hir_typeck_potentially_region_dependent_goals: Default::default(),
176            opaque_type_storage: Default::default(),
177        }
178    }
179
180    #[inline]
181    pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
182        &self.region_obligations
183    }
184
185    #[inline]
186    pub fn region_assumptions(&self) -> &[ty::ArgOutlivesPredicate<'tcx>] {
187        &self.region_assumptions
188    }
189
190    #[inline]
191    pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
192        self.projection_cache.with_log(&mut self.undo_log)
193    }
194
195    #[inline]
196    fn try_type_variables_probe_ref(
197        &self,
198        vid: ty::TyVid,
199    ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
200        // Uses a read-only view of the unification table, this way we don't
201        // need an undo log.
202        self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
203    }
204
205    #[inline]
206    fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
207        self.type_variable_storage.with_log(&mut self.undo_log)
208    }
209
210    #[inline]
211    pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
212        self.opaque_type_storage.with_log(&mut self.undo_log)
213    }
214
215    #[inline]
216    fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
217        self.int_unification_storage.with_log(&mut self.undo_log)
218    }
219
220    #[inline]
221    fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
222        self.float_unification_storage.with_log(&mut self.undo_log)
223    }
224
225    #[inline]
226    fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
227        self.const_unification_storage.with_log(&mut self.undo_log)
228    }
229
230    #[inline]
231    pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
232        self.region_constraint_storage
233            .as_mut()
234            .expect("region constraints already solved")
235            .with_log(&mut self.undo_log)
236    }
237}
238
239pub struct InferCtxt<'tcx> {
240    pub tcx: TyCtxt<'tcx>,
241
242    /// The mode of this inference context, see the struct documentation
243    /// for more details.
244    typing_mode: TypingMode<'tcx>,
245
246    /// Whether this inference context should care about region obligations in
247    /// the root universe. Most notably, this is used during HIR typeck as region
248    /// solving is left to borrowck instead.
249    pub considering_regions: bool,
250    /// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
251    /// need to make sure we don't rely on region identity in the trait solver or when
252    /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
253    /// free region with a unique inference variable. If HIR typeck ends up depending on two
254    /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
255    /// resulting in an ICE.
256    ///
257    /// The trait solver sometimes depends on regions being identical. As a concrete example
258    /// the trait solver ignores other candidates if one candidate exists without any constraints.
259    /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
260    /// occurrence of `'a` with a unique region the goal now equates these regions. See
261    /// the tests in trait-system-refactor-initiative#27 for concrete examples.
262    ///
263    /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
264    /// This is still insufficient as inference variables may *hide* region variables, so e.g.
265    /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
266    /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
267    /// stash all successfully proven goals which reference inference variables and then reprove
268    /// them after writeback.
269    pub in_hir_typeck: bool,
270
271    /// If set, this flag causes us to skip the 'leak check' during
272    /// higher-ranked subtyping operations. This flag is a temporary one used
273    /// to manage the removal of the leak-check: for the time being, we still run the
274    /// leak-check, but we issue warnings.
275    skip_leak_check: bool,
276
277    pub inner: RefCell<InferCtxtInner<'tcx>>,
278
279    /// Once region inference is done, the values for each variable.
280    lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
281
282    /// Caches the results of trait selection. This cache is used
283    /// for things that depends on inference variables or placeholders.
284    pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
285
286    /// Caches the results of trait evaluation. This cache is used
287    /// for things that depends on inference variables or placeholders.
288    pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
289
290    /// The set of predicates on which errors have been reported, to
291    /// avoid reporting the same error twice.
292    pub reported_trait_errors:
293        RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
294
295    pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
296
297    /// When an error occurs, we want to avoid reporting "derived"
298    /// errors that are due to this original failure. We have this
299    /// flag that one can set whenever one creates a type-error that
300    /// is due to an error in a prior pass.
301    ///
302    /// Don't read this flag directly, call `is_tainted_by_errors()`
303    /// and `set_tainted_by_errors()`.
304    tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
305
306    /// What is the innermost universe we have created? Starts out as
307    /// `UniverseIndex::root()` but grows from there as we enter
308    /// universal quantifiers.
309    ///
310    /// N.B., at present, we exclude the universal quantifiers on the
311    /// item we are type-checking, and just consider those names as
312    /// part of the root universe. So this would only get incremented
313    /// when we enter into a higher-ranked (`for<..>`) type or trait
314    /// bound.
315    universe: Cell<ty::UniverseIndex>,
316
317    next_trait_solver: bool,
318
319    pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
320}
321
322/// See the `error_reporting` module for more details.
323#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ValuePairs<'tcx> {
    #[inline]
    fn clone(&self) -> ValuePairs<'tcx> {
        let _:
                ::core::clone::AssertParamIsClone<ExpectedFound<ty::Region<'tcx>>>;
        let _:
                ::core::clone::AssertParamIsClone<ExpectedFound<ty::Term<'tcx>>>;
        let _:
                ::core::clone::AssertParamIsClone<ExpectedFound<ty::AliasTerm<'tcx>>>;
        let _:
                ::core::clone::AssertParamIsClone<ExpectedFound<ty::TraitRef<'tcx>>>;
        let _:
                ::core::clone::AssertParamIsClone<ExpectedFound<ty::PolyFnSig<'tcx>>>;
        let _:
                ::core::clone::AssertParamIsClone<ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>>;
        let _:
                ::core::clone::AssertParamIsClone<ExpectedFound<ty::PolyExistentialProjection<'tcx>>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ValuePairs<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ValuePairs<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ValuePairs::Regions(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Regions", &__self_0),
            ValuePairs::Terms(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Terms",
                    &__self_0),
            ValuePairs::Aliases(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Aliases", &__self_0),
            ValuePairs::TraitRefs(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TraitRefs", &__self_0),
            ValuePairs::PolySigs(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "PolySigs", &__self_0),
            ValuePairs::ExistentialTraitRef(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ExistentialTraitRef", &__self_0),
            ValuePairs::ExistentialProjection(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ExistentialProjection", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for ValuePairs<'tcx> {
    #[inline]
    fn eq(&self, other: &ValuePairs<'tcx>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ValuePairs::Regions(__self_0), ValuePairs::Regions(__arg1_0))
                    => __self_0 == __arg1_0,
                (ValuePairs::Terms(__self_0), ValuePairs::Terms(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (ValuePairs::Aliases(__self_0), ValuePairs::Aliases(__arg1_0))
                    => __self_0 == __arg1_0,
                (ValuePairs::TraitRefs(__self_0),
                    ValuePairs::TraitRefs(__arg1_0)) => __self_0 == __arg1_0,
                (ValuePairs::PolySigs(__self_0),
                    ValuePairs::PolySigs(__arg1_0)) => __self_0 == __arg1_0,
                (ValuePairs::ExistentialTraitRef(__self_0),
                    ValuePairs::ExistentialTraitRef(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (ValuePairs::ExistentialProjection(__self_0),
                    ValuePairs::ExistentialProjection(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for ValuePairs<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<ExpectedFound<ty::Region<'tcx>>>;
        let _: ::core::cmp::AssertParamIsEq<ExpectedFound<ty::Term<'tcx>>>;
        let _:
                ::core::cmp::AssertParamIsEq<ExpectedFound<ty::AliasTerm<'tcx>>>;
        let _:
                ::core::cmp::AssertParamIsEq<ExpectedFound<ty::TraitRef<'tcx>>>;
        let _:
                ::core::cmp::AssertParamIsEq<ExpectedFound<ty::PolyFnSig<'tcx>>>;
        let _:
                ::core::cmp::AssertParamIsEq<ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>>;
        let _:
                ::core::cmp::AssertParamIsEq<ExpectedFound<ty::PolyExistentialProjection<'tcx>>>;
    }
}Eq, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ValuePairs<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        ValuePairs::Regions(__binding_0) => {
                            ValuePairs::Regions(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        ValuePairs::Terms(__binding_0) => {
                            ValuePairs::Terms(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        ValuePairs::Aliases(__binding_0) => {
                            ValuePairs::Aliases(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        ValuePairs::TraitRefs(__binding_0) => {
                            ValuePairs::TraitRefs(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        ValuePairs::PolySigs(__binding_0) => {
                            ValuePairs::PolySigs(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        ValuePairs::ExistentialTraitRef(__binding_0) => {
                            ValuePairs::ExistentialTraitRef(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        ValuePairs::ExistentialProjection(__binding_0) => {
                            ValuePairs::ExistentialProjection(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    ValuePairs::Regions(__binding_0) => {
                        ValuePairs::Regions(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    ValuePairs::Terms(__binding_0) => {
                        ValuePairs::Terms(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    ValuePairs::Aliases(__binding_0) => {
                        ValuePairs::Aliases(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    ValuePairs::TraitRefs(__binding_0) => {
                        ValuePairs::TraitRefs(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    ValuePairs::PolySigs(__binding_0) => {
                        ValuePairs::PolySigs(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    ValuePairs::ExistentialTraitRef(__binding_0) => {
                        ValuePairs::ExistentialTraitRef(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    ValuePairs::ExistentialProjection(__binding_0) => {
                        ValuePairs::ExistentialProjection(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ValuePairs<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    ValuePairs::Regions(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    ValuePairs::Terms(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    ValuePairs::Aliases(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    ValuePairs::TraitRefs(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    ValuePairs::PolySigs(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    ValuePairs::ExistentialTraitRef(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    ValuePairs::ExistentialProjection(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
324pub enum ValuePairs<'tcx> {
325    Regions(ExpectedFound<ty::Region<'tcx>>),
326    Terms(ExpectedFound<ty::Term<'tcx>>),
327    Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
328    TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
329    PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
330    ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
331    ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
332}
333
334impl<'tcx> ValuePairs<'tcx> {
335    pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
336        if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
337            && let Some(expected) = expected.as_type()
338            && let Some(found) = found.as_type()
339        {
340            Some((expected, found))
341        } else {
342            None
343        }
344    }
345}
346
347/// The trace designates the path through inference that we took to
348/// encounter an error or subtyping constraint.
349///
350/// See the `error_reporting` module for more details.
351#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeTrace<'tcx> {
    #[inline]
    fn clone(&self) -> TypeTrace<'tcx> {
        TypeTrace {
            cause: ::core::clone::Clone::clone(&self.cause),
            values: ::core::clone::Clone::clone(&self.values),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypeTrace<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "TypeTrace",
            "cause", &self.cause, "values", &&self.values)
    }
}Debug)]
352pub struct TypeTrace<'tcx> {
353    pub cause: ObligationCause<'tcx>,
354    pub values: ValuePairs<'tcx>,
355}
356
357/// The origin of a `r1 <= r2` constraint.
358///
359/// See `error_reporting` module for more details
360#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for SubregionOrigin<'tcx> {
    #[inline]
    fn clone(&self) -> SubregionOrigin<'tcx> {
        match self {
            SubregionOrigin::Subtype(__self_0) =>
                SubregionOrigin::Subtype(::core::clone::Clone::clone(__self_0)),
            SubregionOrigin::RelateObjectBound(__self_0) =>
                SubregionOrigin::RelateObjectBound(::core::clone::Clone::clone(__self_0)),
            SubregionOrigin::RelateParamBound(__self_0, __self_1, __self_2) =>
                SubregionOrigin::RelateParamBound(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1),
                    ::core::clone::Clone::clone(__self_2)),
            SubregionOrigin::RelateRegionParamBound(__self_0, __self_1) =>
                SubregionOrigin::RelateRegionParamBound(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            SubregionOrigin::Reborrow(__self_0) =>
                SubregionOrigin::Reborrow(::core::clone::Clone::clone(__self_0)),
            SubregionOrigin::ReferenceOutlivesReferent(__self_0, __self_1) =>
                SubregionOrigin::ReferenceOutlivesReferent(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            SubregionOrigin::CompareImplItemObligation {
                span: __self_0,
                impl_item_def_id: __self_1,
                trait_item_def_id: __self_2 } =>
                SubregionOrigin::CompareImplItemObligation {
                    span: ::core::clone::Clone::clone(__self_0),
                    impl_item_def_id: ::core::clone::Clone::clone(__self_1),
                    trait_item_def_id: ::core::clone::Clone::clone(__self_2),
                },
            SubregionOrigin::CheckAssociatedTypeBounds {
                parent: __self_0,
                impl_item_def_id: __self_1,
                trait_item_def_id: __self_2 } =>
                SubregionOrigin::CheckAssociatedTypeBounds {
                    parent: ::core::clone::Clone::clone(__self_0),
                    impl_item_def_id: ::core::clone::Clone::clone(__self_1),
                    trait_item_def_id: ::core::clone::Clone::clone(__self_2),
                },
            SubregionOrigin::AscribeUserTypeProvePredicate(__self_0) =>
                SubregionOrigin::AscribeUserTypeProvePredicate(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for SubregionOrigin<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            SubregionOrigin::Subtype(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Subtype", &__self_0),
            SubregionOrigin::RelateObjectBound(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "RelateObjectBound", &__self_0),
            SubregionOrigin::RelateParamBound(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "RelateParamBound", __self_0, __self_1, &__self_2),
            SubregionOrigin::RelateRegionParamBound(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "RelateRegionParamBound", __self_0, &__self_1),
            SubregionOrigin::Reborrow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Reborrow", &__self_0),
            SubregionOrigin::ReferenceOutlivesReferent(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "ReferenceOutlivesReferent", __self_0, &__self_1),
            SubregionOrigin::CompareImplItemObligation {
                span: __self_0,
                impl_item_def_id: __self_1,
                trait_item_def_id: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "CompareImplItemObligation", "span", __self_0,
                    "impl_item_def_id", __self_1, "trait_item_def_id",
                    &__self_2),
            SubregionOrigin::CheckAssociatedTypeBounds {
                parent: __self_0,
                impl_item_def_id: __self_1,
                trait_item_def_id: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "CheckAssociatedTypeBounds", "parent", __self_0,
                    "impl_item_def_id", __self_1, "trait_item_def_id",
                    &__self_2),
            SubregionOrigin::AscribeUserTypeProvePredicate(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AscribeUserTypeProvePredicate", &__self_0),
        }
    }
}Debug)]
361pub enum SubregionOrigin<'tcx> {
362    /// Arose from a subtyping relation
363    Subtype(Box<TypeTrace<'tcx>>),
364
365    /// When casting `&'a T` to an `&'b Trait` object,
366    /// relating `'a` to `'b`.
367    RelateObjectBound(Span),
368
369    /// Some type parameter was instantiated with the given type,
370    /// and that type must outlive some region.
371    RelateParamBound(Span, Ty<'tcx>, Option<Span>),
372
373    /// The given region parameter was instantiated with a region
374    /// that must outlive some other region.
375    RelateRegionParamBound(Span, Option<Ty<'tcx>>),
376
377    /// Creating a pointer `b` to contents of another reference.
378    Reborrow(Span),
379
380    /// (&'a &'b T) where a >= b
381    ReferenceOutlivesReferent(Ty<'tcx>, Span),
382
383    /// Comparing the signature and requirements of an impl method against
384    /// the containing trait.
385    CompareImplItemObligation {
386        span: Span,
387        impl_item_def_id: LocalDefId,
388        trait_item_def_id: DefId,
389    },
390
391    /// Checking that the bounds of a trait's associated type hold for a given impl.
392    CheckAssociatedTypeBounds {
393        parent: Box<SubregionOrigin<'tcx>>,
394        impl_item_def_id: LocalDefId,
395        trait_item_def_id: DefId,
396    },
397
398    AscribeUserTypeProvePredicate(Span),
399}
400
401// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
402#[cfg(target_pointer_width = "64")]
403const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
404
405impl<'tcx> SubregionOrigin<'tcx> {
406    pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
407        match self {
408            Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
409            Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
410            _ => ConstraintCategory::BoringNoLocation,
411        }
412    }
413}
414
415/// Times when we replace bound regions with existentials:
416#[derive(#[automatically_derived]
impl ::core::clone::Clone for BoundRegionConversionTime {
    #[inline]
    fn clone(&self) -> BoundRegionConversionTime {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BoundRegionConversionTime { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for BoundRegionConversionTime {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            BoundRegionConversionTime::FnCall =>
                ::core::fmt::Formatter::write_str(f, "FnCall"),
            BoundRegionConversionTime::HigherRankedType =>
                ::core::fmt::Formatter::write_str(f, "HigherRankedType"),
            BoundRegionConversionTime::AssocTypeProjection(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AssocTypeProjection", &__self_0),
        }
    }
}Debug)]
417pub enum BoundRegionConversionTime {
418    /// when a fn is called
419    FnCall,
420
421    /// when two higher-ranked types are compared
422    HigherRankedType,
423
424    /// when projecting an associated type
425    AssocTypeProjection(DefId),
426}
427
428/// Reasons to create a region inference variable.
429///
430/// See `error_reporting` module for more details.
431#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for RegionVariableOrigin<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for RegionVariableOrigin<'tcx> {
    #[inline]
    fn clone(&self) -> RegionVariableOrigin<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        let _: ::core::clone::AssertParamIsClone<ty::BoundRegionKind<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<BoundRegionConversionTime>;
        let _: ::core::clone::AssertParamIsClone<ty::UpvarId>;
        let _:
                ::core::clone::AssertParamIsClone<NllRegionVariableOrigin<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for RegionVariableOrigin<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RegionVariableOrigin::Misc(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Misc",
                    &__self_0),
            RegionVariableOrigin::PatternRegion(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "PatternRegion", &__self_0),
            RegionVariableOrigin::BorrowRegion(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "BorrowRegion", &__self_0),
            RegionVariableOrigin::Autoref(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Autoref", &__self_0),
            RegionVariableOrigin::Coercion(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Coercion", &__self_0),
            RegionVariableOrigin::RegionParameterDefinition(__self_0,
                __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "RegionParameterDefinition", __self_0, &__self_1),
            RegionVariableOrigin::BoundRegion(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "BoundRegion", __self_0, __self_1, &__self_2),
            RegionVariableOrigin::UpvarRegion(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "UpvarRegion", __self_0, &__self_1),
            RegionVariableOrigin::Nll(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Nll",
                    &__self_0),
        }
    }
}Debug)]
432pub enum RegionVariableOrigin<'tcx> {
433    /// Region variables created for ill-categorized reasons.
434    ///
435    /// They mostly indicate places in need of refactoring.
436    Misc(Span),
437
438    /// Regions created by a `&P` or `[...]` pattern.
439    PatternRegion(Span),
440
441    /// Regions created by `&` operator.
442    BorrowRegion(Span),
443
444    /// Regions created as part of an autoref of a method receiver.
445    Autoref(Span),
446
447    /// Regions created as part of an automatic coercion.
448    Coercion(Span),
449
450    /// Region variables created as the values for early-bound regions.
451    ///
452    /// FIXME(@lcnr): This should also store a `DefId`, similar to
453    /// `TypeVariableOrigin`.
454    RegionParameterDefinition(Span, Symbol),
455
456    /// Region variables created when instantiating a binder with
457    /// existential variables, e.g. when calling a function or method.
458    BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
459
460    UpvarRegion(ty::UpvarId, Span),
461
462    /// This origin is used for the inference variables that we create
463    /// during NLL region processing.
464    Nll(NllRegionVariableOrigin<'tcx>),
465}
466
467#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for NllRegionVariableOrigin<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for NllRegionVariableOrigin<'tcx> {
    #[inline]
    fn clone(&self) -> NllRegionVariableOrigin<'tcx> {
        let _: ::core::clone::AssertParamIsClone<ty::PlaceholderRegion<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Option<Symbol>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for NllRegionVariableOrigin<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            NllRegionVariableOrigin::FreeRegion =>
                ::core::fmt::Formatter::write_str(f, "FreeRegion"),
            NllRegionVariableOrigin::Placeholder(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Placeholder", &__self_0),
            NllRegionVariableOrigin::Existential { name: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Existential", "name", &__self_0),
        }
    }
}Debug)]
468pub enum NllRegionVariableOrigin<'tcx> {
469    /// During NLL region processing, we create variables for free
470    /// regions that we encounter in the function signature and
471    /// elsewhere. This origin indices we've got one of those.
472    FreeRegion,
473
474    /// "Universal" instantiation of a higher-ranked region (e.g.,
475    /// from a `for<'a> T` binder). Meant to represent "any region".
476    Placeholder(ty::PlaceholderRegion<'tcx>),
477
478    Existential {
479        name: Option<Symbol>,
480    },
481}
482
483#[derive(#[automatically_derived]
impl ::core::marker::Copy for FixupError { }Copy, #[automatically_derived]
impl ::core::clone::Clone for FixupError {
    #[inline]
    fn clone(&self) -> FixupError {
        let _: ::core::clone::AssertParamIsClone<TyOrConstInferVar>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for FixupError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "FixupError",
            "unresolved", &&self.unresolved)
    }
}Debug)]
484pub struct FixupError {
485    unresolved: TyOrConstInferVar,
486}
487
488impl fmt::Display for FixupError {
489    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
490        match self.unresolved {
491            TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
492                f,
493                "cannot determine the type of this integer; \
494                 add a suffix to specify the type explicitly"
495            ),
496            TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
497                f,
498                "cannot determine the type of this number; \
499                 add a suffix to specify the type explicitly"
500            ),
501            TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
502            TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
503        }
504    }
505}
506
507/// See the `region_obligations` field for more information.
508#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeOutlivesConstraint<'tcx> {
    #[inline]
    fn clone(&self) -> TypeOutlivesConstraint<'tcx> {
        TypeOutlivesConstraint {
            sub_region: ::core::clone::Clone::clone(&self.sub_region),
            sup_type: ::core::clone::Clone::clone(&self.sup_type),
            origin: ::core::clone::Clone::clone(&self.origin),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypeOutlivesConstraint<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "TypeOutlivesConstraint", "sub_region", &self.sub_region,
            "sup_type", &self.sup_type, "origin", &&self.origin)
    }
}Debug)]
509pub struct TypeOutlivesConstraint<'tcx> {
510    pub sub_region: ty::Region<'tcx>,
511    pub sup_type: Ty<'tcx>,
512    pub origin: SubregionOrigin<'tcx>,
513}
514
515/// Used to configure inference contexts before their creation.
516pub struct InferCtxtBuilder<'tcx> {
517    tcx: TyCtxt<'tcx>,
518    considering_regions: bool,
519    in_hir_typeck: bool,
520    skip_leak_check: bool,
521    /// Whether we should use the new trait solver in the local inference context,
522    /// which affects things like which solver is used in `predicate_may_hold`.
523    next_trait_solver: bool,
524}
525
526impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
    fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
        InferCtxtBuilder {
            tcx: self,
            considering_regions: true,
            in_hir_typeck: false,
            skip_leak_check: false,
            next_trait_solver: self.next_trait_solver_globally(),
        }
    }
}#[extension(pub trait TyCtxtInferExt<'tcx>)]
527impl<'tcx> TyCtxt<'tcx> {
528    fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
529        InferCtxtBuilder {
530            tcx: self,
531            considering_regions: true,
532            in_hir_typeck: false,
533            skip_leak_check: false,
534            next_trait_solver: self.next_trait_solver_globally(),
535        }
536    }
537}
538
539impl<'tcx> InferCtxtBuilder<'tcx> {
540    pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
541        self.next_trait_solver = next_trait_solver;
542        self
543    }
544
545    pub fn ignoring_regions(mut self) -> Self {
546        self.considering_regions = false;
547        self
548    }
549
550    pub fn in_hir_typeck(mut self) -> Self {
551        self.in_hir_typeck = true;
552        self
553    }
554
555    pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
556        self.skip_leak_check = skip_leak_check;
557        self
558    }
559
560    /// Given a canonical value `C` as a starting point, create an
561    /// inference context that contains each of the bound values
562    /// within instantiated as a fresh variable. The `f` closure is
563    /// invoked with the new infcx, along with the instantiated value
564    /// `V` and a instantiation `S`. This instantiation `S` maps from
565    /// the bound values in `C` to their instantiated values in `V`
566    /// (in other words, `S(C) = V`).
567    pub fn build_with_canonical<T>(
568        mut self,
569        span: Span,
570        input: &CanonicalQueryInput<'tcx, T>,
571    ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
572    where
573        T: TypeFoldable<TyCtxt<'tcx>>,
574    {
575        let infcx = self.build(input.typing_mode.0);
576        let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
577        (infcx, value, args)
578    }
579
580    pub fn build_with_typing_env(
581        mut self,
582        typing_env: TypingEnv<'tcx>,
583    ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
584        (self.build(typing_env.typing_mode()), typing_env.param_env)
585    }
586
587    pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
588        let InferCtxtBuilder {
589            tcx,
590            considering_regions,
591            in_hir_typeck,
592            skip_leak_check,
593            next_trait_solver,
594        } = *self;
595        InferCtxt {
596            tcx,
597            typing_mode,
598            considering_regions,
599            in_hir_typeck,
600            skip_leak_check,
601            inner: RefCell::new(InferCtxtInner::new()),
602            lexical_region_resolutions: RefCell::new(None),
603            selection_cache: Default::default(),
604            evaluation_cache: Default::default(),
605            reported_trait_errors: Default::default(),
606            reported_signature_mismatch: Default::default(),
607            tainted_by_errors: Cell::new(None),
608            universe: Cell::new(ty::UniverseIndex::ROOT),
609            next_trait_solver,
610            obligation_inspector: Cell::new(None),
611        }
612    }
613}
614
615impl<'tcx, T> InferOk<'tcx, T> {
616    /// Extracts `value`, registering any obligations into `fulfill_cx`.
617    pub fn into_value_registering_obligations<E: 'tcx>(
618        self,
619        infcx: &InferCtxt<'tcx>,
620        fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
621    ) -> T {
622        let InferOk { value, obligations } = self;
623        fulfill_cx.register_predicate_obligations(infcx, obligations);
624        value
625    }
626}
627
628impl<'tcx> InferOk<'tcx, ()> {
629    pub fn into_obligations(self) -> PredicateObligations<'tcx> {
630        self.obligations
631    }
632}
633
634impl<'tcx> InferCtxt<'tcx> {
635    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
636        self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
637    }
638
639    pub fn next_trait_solver(&self) -> bool {
640        self.next_trait_solver
641    }
642
643    #[inline(always)]
644    pub fn typing_mode(&self) -> TypingMode<'tcx> {
645        self.typing_mode
646    }
647
648    /// Returns the origin of the type variable identified by `vid`.
649    ///
650    /// No attempt is made to resolve `vid` to its root variable.
651    pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
652        self.inner.borrow_mut().type_variables().var_origin(vid)
653    }
654
655    /// Returns the origin of the float type variable identified by `vid`.
656    ///
657    /// No attempt is made to resolve `vid` to its root variable.
658    pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
659        self.inner.borrow_mut().float_origin_origin_storage[vid]
660    }
661
662    /// Returns the origin of the const variable identified by `vid`
663    // FIXME: We should store origins separately from the unification table
664    // so this doesn't need to be optional.
665    pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
666        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
667            ConstVariableValue::Known { .. } => None,
668            ConstVariableValue::Unknown { origin, .. } => Some(origin),
669        }
670    }
671
672    pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
673        let mut inner = self.inner.borrow_mut();
674        let mut vars: Vec<Ty<'_>> = inner
675            .type_variables()
676            .unresolved_variables()
677            .into_iter()
678            .map(|t| Ty::new_var(self.tcx, t))
679            .collect();
680        vars.extend(
681            (0..inner.int_unification_table().len())
682                .map(|i| ty::IntVid::from_usize(i))
683                .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
684                .map(|v| Ty::new_int_var(self.tcx, v)),
685        );
686        vars.extend(
687            (0..inner.float_unification_table().len())
688                .map(|i| ty::FloatVid::from_usize(i))
689                .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
690                .map(|v| Ty::new_float_var(self.tcx, v)),
691        );
692        vars
693    }
694
695    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("sub_regions",
                                    "rustc_infer::infer", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(695u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&["origin", "a", "b",
                                                    "vis"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin,
                a, b, vis);
        }
    }
}#[instrument(skip(self), level = "debug")]
696    pub fn sub_regions(
697        &self,
698        origin: SubregionOrigin<'tcx>,
699        a: ty::Region<'tcx>,
700        b: ty::Region<'tcx>,
701        vis: ty::VisibleForLeakCheck,
702    ) {
703        self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
704    }
705
706    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("equate_regions",
                                    "rustc_infer::infer", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(706u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&["origin", "a", "b",
                                                    "vis"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin,
                a, b, vis);
        }
    }
}#[instrument(skip(self), level = "debug")]
707    pub fn equate_regions(
708        &self,
709        origin: SubregionOrigin<'tcx>,
710        a: ty::Region<'tcx>,
711        b: ty::Region<'tcx>,
712        vis: ty::VisibleForLeakCheck,
713    ) {
714        self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
715    }
716
717    /// Processes a `Coerce` predicate from the fulfillment context.
718    /// This is NOT the preferred way to handle coercion, which is to
719    /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
720    ///
721    /// This method here is actually a fallback that winds up being
722    /// invoked when `FnCtxt::coerce` encounters unresolved type variables
723    /// and records a coercion predicate. Presently, this method is equivalent
724    /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
725    /// actually requiring `a <: b`. This is of course a valid coercion,
726    /// but it's not as flexible as `FnCtxt::coerce` would be.
727    ///
728    /// (We may refactor this in the future, but there are a number of
729    /// practical obstacles. Among other things, `FnCtxt::coerce` presently
730    /// records adjustments that are required on the HIR in order to perform
731    /// the coercion, and we don't currently have a way to manage that.)
732    pub fn coerce_predicate(
733        &self,
734        cause: &ObligationCause<'tcx>,
735        param_env: ty::ParamEnv<'tcx>,
736        predicate: ty::PolyCoercePredicate<'tcx>,
737    ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
738        let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
739            a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
740            a: p.a,
741            b: p.b,
742        });
743        self.subtype_predicate(cause, param_env, subtype_predicate)
744    }
745
746    pub fn subtype_predicate(
747        &self,
748        cause: &ObligationCause<'tcx>,
749        param_env: ty::ParamEnv<'tcx>,
750        predicate: ty::PolySubtypePredicate<'tcx>,
751    ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
752        // Check for two unresolved inference variables, in which case we can
753        // make no progress. This is partly a micro-optimization, but it's
754        // also an opportunity to "sub-unify" the variables. This isn't
755        // *necessary* to prevent cycles, because they would eventually be sub-unified
756        // anyhow during generalization, but it helps with diagnostics (we can detect
757        // earlier that they are sub-unified).
758        //
759        // Note that we can just skip the binders here because
760        // type variables can't (at present, at
761        // least) capture any of the things bound by this binder.
762        //
763        // Note that this sub here is not just for diagnostics - it has semantic
764        // effects as well.
765        let r_a = self.shallow_resolve(predicate.skip_binder().a);
766        let r_b = self.shallow_resolve(predicate.skip_binder().b);
767        match (r_a.kind(), r_b.kind()) {
768            (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
769                self.sub_unify_ty_vids_raw(a_vid, b_vid);
770                return Err((a_vid, b_vid));
771            }
772            _ => {}
773        }
774
775        self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
776            if a_is_expected {
777                Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
778            } else {
779                Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
780            }
781        })
782    }
783
784    /// Number of type variables created so far.
785    pub fn num_ty_vars(&self) -> usize {
786        self.inner.borrow_mut().type_variables().num_vars()
787    }
788
789    pub fn next_ty_vid(&self, span: Span) -> TyVid {
790        self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
791    }
792
793    pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
794        self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
795    }
796
797    pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
798        let origin = TypeVariableOrigin { span, param_def_id: None };
799        self.inner.borrow_mut().type_variables().new_var(universe, origin)
800    }
801
802    pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
803        self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
804    }
805
806    pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
807        let vid = self.next_ty_vid_with_origin(origin);
808        Ty::new_var(self.tcx, vid)
809    }
810
811    pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
812        let vid = self.next_ty_vid_in_universe(span, universe);
813        Ty::new_var(self.tcx, vid)
814    }
815
816    pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
817        self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
818    }
819
820    pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
821        let vid = self
822            .inner
823            .borrow_mut()
824            .const_unification_table()
825            .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
826            .vid;
827        ty::Const::new_var(self.tcx, vid)
828    }
829
830    pub fn next_const_var_in_universe(
831        &self,
832        span: Span,
833        universe: ty::UniverseIndex,
834    ) -> ty::Const<'tcx> {
835        let origin = ConstVariableOrigin { span, param_def_id: None };
836        let vid = self
837            .inner
838            .borrow_mut()
839            .const_unification_table()
840            .new_key(ConstVariableValue::Unknown { origin, universe })
841            .vid;
842        ty::Const::new_var(self.tcx, vid)
843    }
844
845    pub fn next_int_var(&self) -> Ty<'tcx> {
846        let next_int_var_id =
847            self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
848        Ty::new_int_var(self.tcx, next_int_var_id)
849    }
850
851    pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
852        let mut inner = self.inner.borrow_mut();
853        let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
854        let origin = FloatVariableOrigin { span, lint_id };
855        let span_index = inner.float_origin_origin_storage.push(origin);
856        if true {
    match (&next_float_var_id, &span_index) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(next_float_var_id, span_index);
857        Ty::new_float_var(self.tcx, next_float_var_id)
858    }
859
860    /// Creates a fresh region variable with the next available index.
861    /// The variable will be created in the maximum universe created
862    /// thus far, allowing it to name any region created thus far.
863    pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
864        self.next_region_var_in_universe(origin, self.universe())
865    }
866
867    /// Creates a fresh region variable with the next available index
868    /// in the given universe; typically, you can use
869    /// `next_region_var` and just use the maximal universe.
870    pub fn next_region_var_in_universe(
871        &self,
872        origin: RegionVariableOrigin<'tcx>,
873        universe: ty::UniverseIndex,
874    ) -> ty::Region<'tcx> {
875        let region_var =
876            self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
877        ty::Region::new_var(self.tcx, region_var)
878    }
879
880    pub fn next_term_var_of_kind(&self, term: ty::Term<'tcx>, span: Span) -> ty::Term<'tcx> {
881        match term.kind() {
882            ty::TermKind::Ty(_) => self.next_ty_var(span).into(),
883            ty::TermKind::Const(_) => self.next_const_var(span).into(),
884        }
885    }
886
887    /// Return the universe that the region `r` was created in. For
888    /// most regions (e.g., `'static`, named regions from the user,
889    /// etc) this is the root universe U0. For inference variables or
890    /// placeholders, however, it will return the universe which they
891    /// are associated.
892    pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
893        self.inner.borrow_mut().unwrap_region_constraints().universe(r)
894    }
895
896    /// Number of region variables created so far.
897    pub fn num_region_vars(&self) -> usize {
898        self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
899    }
900
901    /// Just a convenient wrapper of `next_region_var` for using during NLL.
902    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("next_nll_region_var",
                                    "rustc_infer::infer", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(902u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&["origin"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        { self.next_region_var(RegionVariableOrigin::Nll(origin)) }
    }
}#[instrument(skip(self), level = "debug")]
903    pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
904        self.next_region_var(RegionVariableOrigin::Nll(origin))
905    }
906
907    /// Just a convenient wrapper of `next_region_var` for using during NLL.
908    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("next_nll_region_var_in_universe",
                                    "rustc_infer::infer", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(908u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&["origin",
                                                    "universe"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&universe)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin),
                universe)
        }
    }
}#[instrument(skip(self), level = "debug")]
909    pub fn next_nll_region_var_in_universe(
910        &self,
911        origin: NllRegionVariableOrigin<'tcx>,
912        universe: ty::UniverseIndex,
913    ) -> ty::Region<'tcx> {
914        self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
915    }
916
917    pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
918        match param.kind {
919            GenericParamDefKind::Lifetime => {
920                // Create a region inference variable for the given
921                // region parameter definition.
922                self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
923                    span, param.name,
924                ))
925                .into()
926            }
927            GenericParamDefKind::Type { .. } => {
928                // Create a type inference variable for the given
929                // type parameter definition. The generic parameters are
930                // for actual parameters that may be referred to by
931                // the default of this type parameter, if it exists.
932                // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
933                // used in a path such as `Foo::<T, U>::new()` will
934                // use an inference variable for `C` with `[T, U]`
935                // as the generic parameters for the default, `(T, U)`.
936                let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
937                    self.universe(),
938                    TypeVariableOrigin { param_def_id: Some(param.def_id), span },
939                );
940
941                Ty::new_var(self.tcx, ty_var_id).into()
942            }
943            GenericParamDefKind::Const { .. } => {
944                let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
945                let const_var_id = self
946                    .inner
947                    .borrow_mut()
948                    .const_unification_table()
949                    .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
950                    .vid;
951                ty::Const::new_var(self.tcx, const_var_id).into()
952            }
953        }
954    }
955
956    /// Given a set of generics defined on a type or impl, returns the generic parameters mapping
957    /// each type/region parameter to a fresh inference variable.
958    pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
959        GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
960    }
961
962    /// Returns `true` if errors have been reported since this infcx was
963    /// created. This is sometimes used as a heuristic to skip
964    /// reporting errors that often occur as a result of earlier
965    /// errors, but where it's hard to be 100% sure (e.g., unresolved
966    /// inference variables, regionck errors).
967    #[must_use = "this method does not have any side effects"]
968    pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
969        self.tainted_by_errors.get()
970    }
971
972    /// Set the "tainted by errors" flag to true. We call this when we
973    /// observe an error from a prior pass.
974    pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
975        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/mod.rs:975",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(975u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("set_tainted_by_errors(ErrorGuaranteed)")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("set_tainted_by_errors(ErrorGuaranteed)");
976        self.tainted_by_errors.set(Some(e));
977    }
978
979    pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
980        let mut inner = self.inner.borrow_mut();
981        let inner = &mut *inner;
982        inner.unwrap_region_constraints().var_origin(vid)
983    }
984
985    /// Clone the list of variable regions. This is used only during NLL processing
986    /// to put the set of region variables into the NLL region context.
987    pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
988        let inner = self.inner.borrow();
989        if !!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log) {
    ::core::panicking::panic("assertion failed: !UndoLogs::<UndoLog<\'_>>::in_snapshot(&inner.undo_log)")
};assert!(!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log));
990        let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
991        if !storage.data.is_empty() {
    { ::core::panicking::panic_fmt(format_args!("{0:#?}", storage.data)); }
};assert!(storage.data.is_empty(), "{:#?}", storage.data);
992        // We clone instead of taking because borrowck still wants to use the
993        // inference context after calling this for diagnostics and the new
994        // trait solver.
995        storage.var_infos.clone()
996    }
997
998    pub fn has_opaque_types_in_storage(&self) -> bool {
999        !self.inner.borrow().opaque_type_storage.is_empty()
1000    }
1001
1002    x;#[instrument(level = "debug", skip(self), ret)]
1003    pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1004        self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1005    }
1006
1007    x;#[instrument(level = "debug", skip(self), ret)]
1008    pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1009        self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1010    }
1011
1012    pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1013        if !self.next_trait_solver() {
1014            return false;
1015        }
1016
1017        let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1018        let inner = &mut *self.inner.borrow_mut();
1019        let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1020        inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1021            if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1022                let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1023                if opaque_sub_vid == ty_sub_vid {
1024                    return true;
1025                }
1026            }
1027
1028            false
1029        })
1030    }
1031
1032    /// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1033    ///
1034    /// This only checks for a subtype relation, it does not require equality.
1035    pub fn opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> Vec<ty::AliasTy<'tcx>> {
1036        // Avoid accidentally allowing more code to compile with the old solver.
1037        if !self.next_trait_solver() {
1038            return ::alloc::vec::Vec::new()vec![];
1039        }
1040
1041        let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1042        let inner = &mut *self.inner.borrow_mut();
1043        // This is iffy, can't call `type_variables()` as we're already
1044        // borrowing the `opaque_type_storage` here.
1045        let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1046        inner
1047            .opaque_type_storage
1048            .iter_opaque_types()
1049            .filter_map(|(key, hidden_ty)| {
1050                if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1051                    let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1052                    if opaque_sub_vid == ty_sub_vid {
1053                        return Some(ty::AliasTy::new_from_args(
1054                            self.tcx,
1055                            ty::Opaque { def_id: key.def_id.into() },
1056                            key.args,
1057                        ));
1058                    }
1059                }
1060
1061                None
1062            })
1063            .collect()
1064    }
1065
1066    #[inline(always)]
1067    pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1068        if true {
    if !!self.next_trait_solver() {
        ::core::panicking::panic("assertion failed: !self.next_trait_solver()")
    };
};debug_assert!(!self.next_trait_solver());
1069        match self.typing_mode() {
1070            TypingMode::Analysis {
1071                defining_opaque_types_and_generators: defining_opaque_types,
1072            }
1073            | TypingMode::Borrowck { defining_opaque_types } => {
1074                id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1075            }
1076            // FIXME(#132279): This function is quite weird in post-analysis
1077            // and post-borrowck analysis mode. We may need to modify its uses
1078            // to support PostBorrowckAnalysis in the old solver as well.
1079            TypingMode::Coherence
1080            | TypingMode::PostBorrowckAnalysis { .. }
1081            | TypingMode::PostAnalysis => false,
1082        }
1083    }
1084
1085    pub fn push_hir_typeck_potentially_region_dependent_goal(
1086        &self,
1087        goal: PredicateObligation<'tcx>,
1088    ) {
1089        let mut inner = self.inner.borrow_mut();
1090        inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1091        inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1092    }
1093
1094    pub fn take_hir_typeck_potentially_region_dependent_goals(
1095        &self,
1096    ) -> Vec<PredicateObligation<'tcx>> {
1097        if !!self.in_snapshot() {
    {
        ::core::panicking::panic_fmt(format_args!("cannot take goals in a snapshot"));
    }
};assert!(!self.in_snapshot(), "cannot take goals in a snapshot");
1098        std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1099    }
1100
1101    pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1102        self.resolve_vars_if_possible(t).to_string()
1103    }
1104
1105    /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1106    /// universe index of `TyVar(vid)`.
1107    pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1108        use self::type_variable::TypeVariableValue;
1109
1110        match self.inner.borrow_mut().type_variables().probe(vid) {
1111            TypeVariableValue::Known { value } => Ok(value),
1112            TypeVariableValue::Unknown { universe } => Err(universe),
1113        }
1114    }
1115
1116    pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1117        if let ty::Infer(v) = *ty.kind() {
1118            match v {
1119                ty::TyVar(v) => {
1120                    // Not entirely obvious: if `typ` is a type variable,
1121                    // it can be resolved to an int/float variable, which
1122                    // can then be recursively resolved, hence the
1123                    // recursion. Note though that we prevent type
1124                    // variables from unifying to other type variables
1125                    // directly (though they may be embedded
1126                    // structurally), and we prevent cycles in any case,
1127                    // so this recursion should always be of very limited
1128                    // depth.
1129                    //
1130                    // Note: if these two lines are combined into one we get
1131                    // dynamic borrow errors on `self.inner`.
1132                    let known = self.inner.borrow_mut().type_variables().probe(v).known();
1133                    known.map_or(ty, |t| self.shallow_resolve(t))
1134                }
1135
1136                ty::IntVar(v) => {
1137                    match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1138                        ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1139                        ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1140                        ty::IntVarValue::Unknown => ty,
1141                    }
1142                }
1143
1144                ty::FloatVar(v) => {
1145                    match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1146                        ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1147                        ty::FloatVarValue::Unknown => ty,
1148                    }
1149                }
1150
1151                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1152            }
1153        } else {
1154            ty
1155        }
1156    }
1157
1158    pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1159        match ct.kind() {
1160            ty::ConstKind::Infer(infer_ct) => match infer_ct {
1161                InferConst::Var(vid) => self
1162                    .inner
1163                    .borrow_mut()
1164                    .const_unification_table()
1165                    .probe_value(vid)
1166                    .known()
1167                    .unwrap_or(ct),
1168                InferConst::Fresh(_) => ct,
1169            },
1170            ty::ConstKind::Param(_)
1171            | ty::ConstKind::Bound(_, _)
1172            | ty::ConstKind::Placeholder(_)
1173            | ty::ConstKind::Unevaluated(_)
1174            | ty::ConstKind::Value(_)
1175            | ty::ConstKind::Error(_)
1176            | ty::ConstKind::Expr(_) => ct,
1177        }
1178    }
1179
1180    pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1181        match term.kind() {
1182            ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1183            ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1184        }
1185    }
1186
1187    pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1188        self.inner.borrow_mut().type_variables().root_var(var)
1189    }
1190
1191    pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1192        self.inner.borrow_mut().type_variables().sub_unify(a, b);
1193    }
1194
1195    pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1196        self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1197    }
1198
1199    pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1200        self.inner.borrow_mut().float_unification_table().find(var)
1201    }
1202
1203    pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1204        self.inner.borrow_mut().const_unification_table().find(var).vid
1205    }
1206
1207    /// Resolves an int var to a rigid int type, if it was constrained to one,
1208    /// or else the root int var in the unification table.
1209    pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1210        let mut inner = self.inner.borrow_mut();
1211        let value = inner.int_unification_table().probe_value(vid);
1212        match value {
1213            ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1214            ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1215            ty::IntVarValue::Unknown => {
1216                Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1217            }
1218        }
1219    }
1220
1221    /// Resolves a float var to a rigid int type, if it was constrained to one,
1222    /// or else the root float var in the unification table.
1223    pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1224        let mut inner = self.inner.borrow_mut();
1225        let value = inner.float_unification_table().probe_value(vid);
1226        match value {
1227            ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1228            ty::FloatVarValue::Unknown => {
1229                Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1230            }
1231        }
1232    }
1233
1234    /// Where possible, replaces type/const variables in
1235    /// `value` with their final value. Note that region variables
1236    /// are unaffected. If a type/const variable has not been unified, it
1237    /// is left as is. This is an idempotent operation that does
1238    /// not affect inference state in any way and so you can do it
1239    /// at will.
1240    pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1241    where
1242        T: TypeFoldable<TyCtxt<'tcx>>,
1243    {
1244        if let Err(guar) = value.error_reported() {
1245            self.set_tainted_by_errors(guar);
1246        }
1247        if !value.has_non_region_infer() {
1248            return value;
1249        }
1250        let mut r = resolve::OpportunisticVarResolver::new(self);
1251        value.fold_with(&mut r)
1252    }
1253
1254    pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1255    where
1256        T: TypeFoldable<TyCtxt<'tcx>>,
1257    {
1258        if !value.has_infer() {
1259            return value; // Avoid duplicated type-folding.
1260        }
1261        let mut r = InferenceLiteralEraser { tcx: self.tcx };
1262        value.fold_with(&mut r)
1263    }
1264
1265    pub fn try_resolve_const_var(
1266        &self,
1267        vid: ty::ConstVid,
1268    ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1269        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1270            ConstVariableValue::Known { value } => Ok(value),
1271            ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1272        }
1273    }
1274
1275    /// Attempts to resolve all type/region/const variables in
1276    /// `value`. Region inference must have been run already (e.g.,
1277    /// by calling `resolve_regions_and_report_errors`). If some
1278    /// variable was never unified, an `Err` results.
1279    ///
1280    /// This method is idempotent, but it not typically not invoked
1281    /// except during the writeback phase.
1282    pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1283        match resolve::fully_resolve(self, value) {
1284            Ok(value) => {
1285                if value.has_non_region_infer() {
1286                    ::rustc_middle::util::bug::bug_fmt(format_args!("`{0:?}` is not fully resolved",
        value));bug!("`{value:?}` is not fully resolved");
1287                }
1288                if value.has_infer_regions() {
1289                    let guar = self.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0:?}` is not fully resolved",
                value))
    })format!("`{value:?}` is not fully resolved"));
1290                    Ok(fold_regions(self.tcx, value, |re, _| {
1291                        if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1292                    }))
1293                } else {
1294                    Ok(value)
1295                }
1296            }
1297            Err(e) => Err(e),
1298        }
1299    }
1300
1301    // Instantiates the bound variables in a given binder with fresh inference
1302    // variables in the current universe.
1303    //
1304    // Use this method if you'd like to find some generic parameters of the binder's
1305    // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1306    // that corresponds to your use case, consider whether or not you should
1307    // use [`InferCtxt::enter_forall`] instead.
1308    pub fn instantiate_binder_with_fresh_vars<T>(
1309        &self,
1310        span: Span,
1311        lbrct: BoundRegionConversionTime,
1312        value: ty::Binder<'tcx, T>,
1313    ) -> T
1314    where
1315        T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1316    {
1317        if let Some(inner) = value.no_bound_vars() {
1318            return inner;
1319        }
1320
1321        let bound_vars = value.bound_vars();
1322        let mut args = Vec::with_capacity(bound_vars.len());
1323
1324        for bound_var_kind in bound_vars {
1325            let arg: ty::GenericArg<'_> = match bound_var_kind {
1326                ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1327                ty::BoundVariableKind::Region(br) => {
1328                    self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1329                }
1330                ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1331            };
1332            args.push(arg);
1333        }
1334
1335        struct ToFreshVars<'tcx> {
1336            args: Vec<ty::GenericArg<'tcx>>,
1337        }
1338
1339        impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1340            fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1341                self.args[br.var.index()].expect_region()
1342            }
1343            fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1344                self.args[bt.var.index()].expect_ty()
1345            }
1346            fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1347                self.args[bc.var.index()].expect_const()
1348            }
1349        }
1350        let delegate = ToFreshVars { args };
1351        self.tcx.replace_bound_vars_uncached(value, delegate)
1352    }
1353
1354    /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1355    pub(crate) fn verify_generic_bound(
1356        &self,
1357        origin: SubregionOrigin<'tcx>,
1358        kind: GenericKind<'tcx>,
1359        a: ty::Region<'tcx>,
1360        bound: VerifyBound<'tcx>,
1361    ) {
1362        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/mod.rs:1362",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1362u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("verify_generic_bound({0:?}, {1:?} <: {2:?})",
                                                    kind, a, bound) as &dyn Value))])
            });
    } else { ; }
};debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1363
1364        self.inner
1365            .borrow_mut()
1366            .unwrap_region_constraints()
1367            .verify_generic_bound(origin, kind, a, bound);
1368    }
1369
1370    /// Obtains the latest type of the given closure; this may be a
1371    /// closure in the current function, in which case its
1372    /// `ClosureKind` may not yet be known.
1373    pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1374        let unresolved_kind_ty = match *closure_ty.kind() {
1375            ty::Closure(_, args) => args.as_closure().kind_ty(),
1376            ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1377            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0}",
        closure_ty))bug!("unexpected type {closure_ty}"),
1378        };
1379        let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1380        closure_kind_ty.to_opt_closure_kind()
1381    }
1382
1383    pub fn universe(&self) -> ty::UniverseIndex {
1384        self.universe.get()
1385    }
1386
1387    /// Creates and return a fresh universe that extends all previous
1388    /// universes. Updates `self.universe` to that new universe.
1389    pub fn create_next_universe(&self) -> ty::UniverseIndex {
1390        let u = self.universe.get().next_universe();
1391        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/mod.rs:1391",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1391u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("create_next_universe {0:?}",
                                                    u) as &dyn Value))])
            });
    } else { ; }
};debug!("create_next_universe {u:?}");
1392        self.universe.set(u);
1393        u
1394    }
1395
1396    /// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1397    /// which contains the necessary information to use the trait system without
1398    /// using canonicalization or carrying this inference context around.
1399    pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1400        let typing_mode = match self.typing_mode() {
1401            // FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1402            // to handle them without proper canonicalization. This means we may cause cycle
1403            // errors and fail to reveal opaques while inside of bodies. We should rename this
1404            // function and require explicit comments on all use-sites in the future.
1405            ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1406            | ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1407                TypingMode::non_body_analysis()
1408            }
1409            mode @ (ty::TypingMode::Coherence
1410            | ty::TypingMode::PostBorrowckAnalysis { .. }
1411            | ty::TypingMode::PostAnalysis) => mode,
1412        };
1413        ty::TypingEnv::new(param_env, typing_mode)
1414    }
1415
1416    /// Similar to [`Self::canonicalize_query`], except that it returns
1417    /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1418    /// `param_env` to not contain any inference variables or placeholders.
1419    pub fn pseudo_canonicalize_query<V>(
1420        &self,
1421        param_env: ty::ParamEnv<'tcx>,
1422        value: V,
1423    ) -> PseudoCanonicalInput<'tcx, V>
1424    where
1425        V: TypeVisitable<TyCtxt<'tcx>>,
1426    {
1427        if true {
    if !!value.has_infer() {
        ::core::panicking::panic("assertion failed: !value.has_infer()")
    };
};debug_assert!(!value.has_infer());
1428        if true {
    if !!value.has_placeholders() {
        ::core::panicking::panic("assertion failed: !value.has_placeholders()")
    };
};debug_assert!(!value.has_placeholders());
1429        if true {
    if !!param_env.has_infer() {
        ::core::panicking::panic("assertion failed: !param_env.has_infer()")
    };
};debug_assert!(!param_env.has_infer());
1430        if true {
    if !!param_env.has_placeholders() {
        ::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
    };
};debug_assert!(!param_env.has_placeholders());
1431        self.typing_env(param_env).as_query_input(value)
1432    }
1433
1434    /// The returned function is used in a fast path. If it returns `true` the variable is
1435    /// unchanged, `false` indicates that the status is unknown.
1436    #[inline]
1437    pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1438        // This hoists the borrow/release out of the loop body.
1439        let inner = self.inner.try_borrow();
1440
1441        move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1442            (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1443                use self::type_variable::TypeVariableValue;
1444
1445                #[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
    {
    Some(TypeVariableValue::Unknown { .. }) => true,
    _ => false,
}matches!(
1446                    inner.try_type_variables_probe_ref(ty_var),
1447                    Some(TypeVariableValue::Unknown { .. })
1448                )
1449            }
1450            _ => false,
1451        }
1452    }
1453
1454    /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1455    ///   * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1456    ///   * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1457    ///
1458    /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1459    /// inlined, despite being large, because it has only two call sites that
1460    /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1461    /// inference variables), and it handles both `Ty` and `ty::Const` without
1462    /// having to resort to storing full `GenericArg`s in `stalled_on`.
1463    #[inline(always)]
1464    pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1465        match infer_var {
1466            TyOrConstInferVar::Ty(v) => {
1467                use self::type_variable::TypeVariableValue;
1468
1469                // If `inlined_probe` returns a `Known` value, it never equals
1470                // `ty::Infer(ty::TyVar(v))`.
1471                match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1472                    TypeVariableValue::Unknown { .. } => false,
1473                    TypeVariableValue::Known { .. } => true,
1474                }
1475            }
1476
1477            TyOrConstInferVar::TyInt(v) => {
1478                // If `inlined_probe_value` returns a value it's always a
1479                // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1480                // `ty::Infer(_)`.
1481                self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1482            }
1483
1484            TyOrConstInferVar::TyFloat(v) => {
1485                // If `probe_value` returns a value it's always a
1486                // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1487                //
1488                // Not `inlined_probe_value(v)` because this call site is colder.
1489                self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1490            }
1491
1492            TyOrConstInferVar::Const(v) => {
1493                // If `probe_value` returns a `Known` value, it never equals
1494                // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1495                //
1496                // Not `inlined_probe_value(v)` because this call site is colder.
1497                match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1498                    ConstVariableValue::Unknown { .. } => false,
1499                    ConstVariableValue::Known { .. } => true,
1500                }
1501            }
1502        }
1503    }
1504
1505    /// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1506    pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1507        if true {
    if !self.obligation_inspector.get().is_none() {
        {
            ::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
        }
    };
};debug_assert!(
1508            self.obligation_inspector.get().is_none(),
1509            "shouldn't override a set obligation inspector"
1510        );
1511        self.obligation_inspector.set(Some(inspector));
1512    }
1513}
1514
1515/// Helper for [InferCtxt::ty_or_const_infer_var_changed] (see comment on that), currently
1516/// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1517#[derive(#[automatically_derived]
impl ::core::marker::Copy for TyOrConstInferVar { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TyOrConstInferVar {
    #[inline]
    fn clone(&self) -> TyOrConstInferVar {
        let _: ::core::clone::AssertParamIsClone<TyVid>;
        let _: ::core::clone::AssertParamIsClone<IntVid>;
        let _: ::core::clone::AssertParamIsClone<FloatVid>;
        let _: ::core::clone::AssertParamIsClone<ConstVid>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for TyOrConstInferVar {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TyOrConstInferVar::Ty(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ty",
                    &__self_0),
            TyOrConstInferVar::TyInt(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "TyInt",
                    &__self_0),
            TyOrConstInferVar::TyFloat(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TyFloat", &__self_0),
            TyOrConstInferVar::Const(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Const",
                    &__self_0),
        }
    }
}Debug)]
1518pub enum TyOrConstInferVar {
1519    /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1520    Ty(TyVid),
1521    /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1522    TyInt(IntVid),
1523    /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1524    TyFloat(FloatVid),
1525
1526    /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1527    Const(ConstVid),
1528}
1529
1530impl<'tcx> TyOrConstInferVar {
1531    /// Tries to extract an inference variable from a type or a constant, returns `None`
1532    /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1533    /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1534    pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1535        match arg.kind() {
1536            GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1537            GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1538            GenericArgKind::Lifetime(_) => None,
1539        }
1540    }
1541
1542    /// Tries to extract an inference variable from a type or a constant, returns `None`
1543    /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1544    /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1545    pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1546        match term.kind() {
1547            TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1548            TermKind::Const(ct) => Self::maybe_from_const(ct),
1549        }
1550    }
1551
1552    /// Tries to extract an inference variable from a type, returns `None`
1553    /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1554    fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1555        match *ty.kind() {
1556            ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1557            ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1558            ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1559            _ => None,
1560        }
1561    }
1562
1563    /// Tries to extract an inference variable from a constant, returns `None`
1564    /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1565    fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1566        match ct.kind() {
1567            ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1568            _ => None,
1569        }
1570    }
1571}
1572
1573/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1574/// Used only for diagnostics.
1575struct InferenceLiteralEraser<'tcx> {
1576    tcx: TyCtxt<'tcx>,
1577}
1578
1579impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1580    fn cx(&self) -> TyCtxt<'tcx> {
1581        self.tcx
1582    }
1583
1584    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1585        match ty.kind() {
1586            ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1587            ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1588            _ => ty.super_fold_with(self),
1589        }
1590    }
1591}
1592
1593impl<'tcx> TypeTrace<'tcx> {
1594    pub fn span(&self) -> Span {
1595        self.cause.span
1596    }
1597
1598    pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1599        TypeTrace {
1600            cause: cause.clone(),
1601            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1602        }
1603    }
1604
1605    pub fn trait_refs(
1606        cause: &ObligationCause<'tcx>,
1607        a: ty::TraitRef<'tcx>,
1608        b: ty::TraitRef<'tcx>,
1609    ) -> TypeTrace<'tcx> {
1610        TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1611    }
1612
1613    pub fn consts(
1614        cause: &ObligationCause<'tcx>,
1615        a: ty::Const<'tcx>,
1616        b: ty::Const<'tcx>,
1617    ) -> TypeTrace<'tcx> {
1618        TypeTrace {
1619            cause: cause.clone(),
1620            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1621        }
1622    }
1623}
1624
1625impl<'tcx> SubregionOrigin<'tcx> {
1626    pub fn span(&self) -> Span {
1627        match *self {
1628            SubregionOrigin::Subtype(ref a) => a.span(),
1629            SubregionOrigin::RelateObjectBound(a) => a,
1630            SubregionOrigin::RelateParamBound(a, ..) => a,
1631            SubregionOrigin::RelateRegionParamBound(a, _) => a,
1632            SubregionOrigin::Reborrow(a) => a,
1633            SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1634            SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1635            SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1636            SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1637        }
1638    }
1639
1640    pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1641    where
1642        F: FnOnce() -> Self,
1643    {
1644        match *cause.code() {
1645            traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1646                SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1647            }
1648
1649            traits::ObligationCauseCode::CompareImplItem {
1650                impl_item_def_id,
1651                trait_item_def_id,
1652                kind: _,
1653            } => SubregionOrigin::CompareImplItemObligation {
1654                span: cause.span,
1655                impl_item_def_id,
1656                trait_item_def_id,
1657            },
1658
1659            traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1660                impl_item_def_id,
1661                trait_item_def_id,
1662            } => SubregionOrigin::CheckAssociatedTypeBounds {
1663                impl_item_def_id,
1664                trait_item_def_id,
1665                parent: Box::new(default()),
1666            },
1667
1668            traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1669                SubregionOrigin::AscribeUserTypeProvePredicate(span)
1670            }
1671
1672            traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1673                SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1674            }
1675
1676            _ => default(),
1677        }
1678    }
1679}
1680
1681impl<'tcx> RegionVariableOrigin<'tcx> {
1682    pub fn span(&self) -> Span {
1683        match *self {
1684            RegionVariableOrigin::Misc(a)
1685            | RegionVariableOrigin::PatternRegion(a)
1686            | RegionVariableOrigin::BorrowRegion(a)
1687            | RegionVariableOrigin::Autoref(a)
1688            | RegionVariableOrigin::Coercion(a)
1689            | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1690            | RegionVariableOrigin::BoundRegion(a, ..)
1691            | RegionVariableOrigin::UpvarRegion(_, a) => a,
1692            RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable used with `span`"))bug!("NLL variable used with `span`"),
1693        }
1694    }
1695}
1696
1697impl<'tcx> InferCtxt<'tcx> {
1698    /// Given a [`hir::Block`], get the span of its last expression or
1699    /// statement, peeling off any inner blocks.
1700    pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1701        let block = block.innermost_block();
1702        if let Some(expr) = &block.expr {
1703            expr.span
1704        } else if let Some(stmt) = block.stmts.last() {
1705            // possibly incorrect trailing `;` in the else arm
1706            stmt.span
1707        } else {
1708            // empty block; point at its entirety
1709            block.span
1710        }
1711    }
1712
1713    /// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1714    /// of its last expression or statement, peeling off any inner blocks.
1715    pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1716        match self.tcx.hir_node(hir_id) {
1717            hir::Node::Block(blk)
1718            | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1719                self.find_block_span(blk)
1720            }
1721            hir::Node::Expr(e) => e.span,
1722            _ => DUMMY_SP,
1723        }
1724    }
1725}