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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin,
                a, b, vis);
        }
    }
}#[instrument(skip(self), level = "debug")]
775    pub fn sub_regions(
776        &self,
777        origin: SubregionOrigin<'tcx>,
778        a: ty::Region<'tcx>,
779        b: ty::Region<'tcx>,
780        vis: ty::VisibleForLeakCheck,
781    ) {
782        self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
783    }
784
785    #[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(785u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&["origin", "a", "b",
                                                    "vis"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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