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