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::combine::PredicateEmittingRelation;
14use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
15use rustc_data_structures::undo_log::{Rollback, UndoLogs};
16use rustc_data_structures::unify as ut;
17use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
18use rustc_hir::def_id::{DefId, LocalDefId};
19use rustc_hir::{self as hir, HirId};
20use rustc_index::IndexVec;
21use rustc_macros::extension;
22pub use rustc_macros::{TypeFoldable, TypeVisitable};
23use rustc_middle::bug;
24use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
25use rustc_middle::mir::ConstraintCategory;
26use rustc_middle::traits::select;
27use rustc_middle::traits::solve::Goal;
28use rustc_middle::ty::error::{ExpectedFound, TypeError};
29use rustc_middle::ty::{
30    self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
31    GenericArgsRef, GenericParamDefKind, InferConst, IntVid, OpaqueTypeKey, ProvisionalHiddenType,
32    PseudoCanonicalInput, Term, TermKind, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder,
33    TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
34};
35use rustc_span::{DUMMY_SP, Span, Symbol};
36use rustc_type_ir::MayBeErased;
37use snapshot::undo_log::InferCtxtUndoLogs;
38use tracing::{debug, instrument};
39use type_variable::TypeVariableOrigin;
40
41use crate::infer::snapshot::undo_log::UndoLog;
42use crate::infer::type_variable::FloatVariableOrigin;
43use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
44use crate::traits::{
45    self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
46    TraitEngine,
47};
48
49pub mod at;
50pub mod canonical;
51mod context;
52mod free_regions;
53mod freshen;
54mod lexical_region_resolve;
55mod opaque_types;
56pub mod outlives;
57mod projection;
58pub mod region_constraints;
59pub mod relate;
60pub mod resolve;
61pub(crate) mod snapshot;
62mod type_variable;
63mod unify_key;
64
65/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
66/// around `PredicateObligations<'tcx>`, but it has one important property:
67/// because `InferOk` is marked with `#[must_use]`, if you have a method
68/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
69/// `infcx.f()?;` you'll get a warning about the obligations being discarded
70/// without use, which is probably unintentional and has been a source of bugs
71/// in the past.
72#[must_use]
73#[derive(#[automatically_derived]
impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug for InferOk<'tcx, T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "InferOk",
            "value", &self.value, "obligations", &&self.obligations)
    }
}Debug)]
74pub struct InferOk<'tcx, T> {
75    pub value: T,
76    pub obligations: PredicateObligations<'tcx>,
77}
78pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
79
80pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
81
82pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
83    ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
84>;
85
86/// This type contains all the things within `InferCtxt` that sit within a
87/// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
88/// operations are hot enough that we want only one call to `borrow_mut` per
89/// call to `start_snapshot` and `rollback_to`.
90#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for InferCtxtInner<'tcx> {
    #[inline]
    fn clone(&self) -> InferCtxtInner<'tcx> {
        InferCtxtInner {
            undo_log: ::core::clone::Clone::clone(&self.undo_log),
            projection_cache: ::core::clone::Clone::clone(&self.projection_cache),
            type_variable_storage: ::core::clone::Clone::clone(&self.type_variable_storage),
            const_unification_storage: ::core::clone::Clone::clone(&self.const_unification_storage),
            int_unification_storage: ::core::clone::Clone::clone(&self.int_unification_storage),
            float_unification_storage: ::core::clone::Clone::clone(&self.float_unification_storage),
            float_origin_origin_storage: ::core::clone::Clone::clone(&self.float_origin_origin_storage),
            region_constraint_storage: ::core::clone::Clone::clone(&self.region_constraint_storage),
            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)]
91pub struct InferCtxtInner<'tcx> {
92    undo_log: InferCtxtUndoLogs<'tcx>,
93
94    /// Cache for projections.
95    ///
96    /// This cache is snapshotted along with the infcx.
97    projection_cache: traits::ProjectionCacheStorage<'tcx>,
98
99    /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
100    /// that might instantiate a general type variable have an order,
101    /// represented by its upper and lower bounds.
102    type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
103
104    /// Map from const parameter variable to the kind of const it represents.
105    const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
106
107    /// Map from integral variable to the kind of integer it represents.
108    int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
109
110    /// Map from floating variable to the kind of float it represents.
111    float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
112
113    /// Map from floating variable to the origin span it came from, and the HirId that should be
114    /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
115    /// so can be removed once the `f32` fallback is removed.
116    float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
117
118    /// Tracks the set of region variables and the constraints between them.
119    ///
120    /// This is initially `Some(_)` but when
121    /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
122    /// -- further attempts to perform unification, etc., may fail if new
123    /// region constraints would've been added.
124    region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
125
126    /// Used by the next solver when `-Zassumptions-on-binders` is set.
127    solver_region_constraint_storage: SolverRegionConstraintStorage<'tcx>,
128
129    /// A set of constraints that regionck must validate.
130    ///
131    /// Each constraint has the form `T:'a`, meaning "some type `T` must
132    /// outlive the lifetime 'a". These constraints derive from
133    /// instantiated type parameters. So if you had a struct defined
134    /// like the following:
135    /// ```ignore (illustrative)
136    /// struct Foo<T: 'static> { ... }
137    /// ```
138    /// In some expression `let x = Foo { ... }`, it will
139    /// instantiate the type parameter `T` with a fresh type `$0`. At
140    /// the same time, it will record a region obligation of
141    /// `$0: 'static`. This will get checked later by regionck. (We
142    /// can't generally check these things right away because we have
143    /// to wait until types are resolved.)
144    region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
145
146    /// The outlives bounds that we assume must hold about placeholders that
147    /// come from instantiating the binder of coroutine-witnesses. These bounds
148    /// are deduced from the well-formedness of the witness's types, and are
149    /// necessary because of the way we anonymize the regions in a coroutine,
150    /// which may cause types to no longer be considered well-formed.
151    region_assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
152
153    /// `-Znext-solver`: Successfully proven goals during HIR typeck which
154    /// reference inference variables and get reproven in case MIR type check
155    /// fails to prove something.
156    ///
157    /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
158    hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
159
160    /// Caches for opaque type inference.
161    opaque_type_storage: OpaqueTypeStorage<'tcx>,
162}
163
164impl<'tcx> InferCtxtInner<'tcx> {
165    fn new() -> InferCtxtInner<'tcx> {
166        InferCtxtInner {
167            undo_log: InferCtxtUndoLogs::default(),
168
169            projection_cache: Default::default(),
170            type_variable_storage: Default::default(),
171            const_unification_storage: Default::default(),
172            int_unification_storage: Default::default(),
173            float_unification_storage: Default::default(),
174            float_origin_origin_storage: Default::default(),
175            region_constraint_storage: Some(Default::default()),
176            solver_region_constraint_storage: SolverRegionConstraintStorage::new(),
177            region_obligations: Default::default(),
178            region_assumptions: Default::default(),
179            hir_typeck_potentially_region_dependent_goals: Default::default(),
180            opaque_type_storage: Default::default(),
181        }
182    }
183
184    #[inline]
185    pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
186        &self.region_obligations
187    }
188
189    #[inline]
190    pub fn region_assumptions(&self) -> &[ty::ArgOutlivesPredicate<'tcx>] {
191        &self.region_assumptions
192    }
193
194    #[inline]
195    pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
196        self.projection_cache.with_log(&mut self.undo_log)
197    }
198
199    #[inline]
200    fn try_type_variables_probe_ref(
201        &self,
202        vid: ty::TyVid,
203    ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
204        // Uses a read-only view of the unification table, this way we don't
205        // need an undo log.
206        self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
207    }
208
209    #[inline]
210    fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
211        self.type_variable_storage.with_log(&mut self.undo_log)
212    }
213
214    #[inline]
215    pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
216        self.opaque_type_storage.with_log(&mut self.undo_log)
217    }
218
219    #[inline]
220    fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
221        self.int_unification_storage.with_log(&mut self.undo_log)
222    }
223
224    #[inline]
225    fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
226        self.float_unification_storage.with_log(&mut self.undo_log)
227    }
228
229    #[inline]
230    fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
231        self.const_unification_storage.with_log(&mut self.undo_log)
232    }
233
234    #[inline]
235    pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
236        self.region_constraint_storage
237            .as_mut()
238            .expect("region constraints already solved")
239            .with_log(&mut self.undo_log)
240    }
241}
242
243pub struct InferCtxt<'tcx> {
244    pub tcx: TyCtxt<'tcx>,
245
246    /// The mode of this inference context, see the struct documentation
247    /// for more details.
248    typing_mode: TypingMode<'tcx>,
249
250    /// Whether this inference context should care about region obligations in
251    /// the root universe. Most notably, this is used during HIR typeck as region
252    /// solving is left to borrowck instead.
253    ///
254    /// This is used in the old solver to enable the generation of regions constraints.
255    /// In the new solver its only used inside the InferCtxt's `Drop` implementation:
256    /// if we're considering regions, and new opaques are registered, we panic.
257    pub considering_regions: bool,
258    /// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
259    /// need to make sure we don't rely on region identity in the trait solver or when
260    /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
261    /// free region with a unique inference variable. If HIR typeck ends up depending on two
262    /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
263    /// resulting in an ICE.
264    ///
265    /// The trait solver sometimes depends on regions being identical. As a concrete example
266    /// the trait solver ignores other candidates if one candidate exists without any constraints.
267    /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
268    /// occurrence of `'a` with a unique region the goal now equates these regions. See
269    /// the tests in trait-system-refactor-initiative#27 for concrete examples.
270    ///
271    /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
272    /// This is still insufficient as inference variables may *hide* region variables, so e.g.
273    /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
274    /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
275    /// stash all successfully proven goals which reference inference variables and then reprove
276    /// them after writeback.
277    pub in_hir_typeck: bool,
278
279    /// If set, this flag causes us to skip the 'leak check' during
280    /// higher-ranked subtyping operations. This flag is a temporary one used
281    /// to manage the removal of the leak-check: for the time being, we still run the
282    /// leak-check, but we issue warnings.
283    skip_leak_check: bool,
284
285    pub inner: RefCell<InferCtxtInner<'tcx>>,
286
287    /// Once region inference is done, the values for each variable.
288    lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
289
290    /// Caches the results of trait selection. This cache is used
291    /// for things that depends on inference variables or placeholders.
292    pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
293
294    /// Caches the results of trait evaluation. This cache is used
295    /// for things that depends on inference variables or placeholders.
296    pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
297
298    /// The set of predicates on which errors have been reported, to
299    /// avoid reporting the same error twice.
300    pub reported_trait_errors:
301        RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
302
303    pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
304
305    /// When an error occurs, we want to avoid reporting "derived"
306    /// errors that are due to this original failure. We have this
307    /// flag that one can set whenever one creates a type-error that
308    /// is due to an error in a prior pass.
309    ///
310    /// Don't read this flag directly, call `is_tainted_by_errors()`
311    /// and `set_tainted_by_errors()`.
312    tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
313
314    /// What is the innermost universe we have created? Starts out as
315    /// `UniverseIndex::root()` but grows from there as we enter
316    /// universal quantifiers.
317    ///
318    /// N.B., at present, we exclude the universal quantifiers on the
319    /// item we are type-checking, and just consider those names as
320    /// part of the root universe. So this would only get incremented
321    /// when we enter into a higher-ranked (`for<..>`) type or trait
322    /// bound.
323    universe: Cell<ty::UniverseIndex>,
324
325    /// List of assumed wellformed types which we can derive implied
326    /// bounds on a `for<...>` from. Only used unstabley and by the
327    /// new solver.
328    //
329    // FIXME(-Zassumptions-on-binders): This and `universe` should probably be
330    // in `InferCtxtInner` so they can participate in rollbacks and whatnot
331    placeholder_assumptions_for_next_solver: RefCell<
332        FxIndexMap<
333            ty::UniverseIndex,
334            Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
335        >,
336    >,
337
338    next_trait_solver: bool,
339
340    pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
341}
342
343impl<'tcx> Drop for InferCtxt<'tcx> {
344    fn drop(&mut self) {
345        let mut inner = self.inner.borrow_mut();
346        let opaque_type_storage = &mut inner.opaque_type_storage;
347
348        // No need for the drop bomb when we're in `TypingMode::PostTypeckUntilBorrowck`, and the `InferCtxt`
349        // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
350        // in relation to regions. In some places *after* typeck that aren't borrowck, like in lints we use
351        // `TypingMode::PostTypeckUntilBorrowck` to prevent defining opaque types and we simply don't care about regions.
352        match self.typing_mode_raw() {
353            TypingMode::Coherence
354            | TypingMode::Typeck { .. }
355            | TypingMode::PostBorrowck { .. }
356            | TypingMode::PostAnalysis
357            | TypingMode::Codegen => {}
358            // In erased mode, the opaque type storage is always empty
359            TypingMode::ErasedNotCoherence(..) => {}
360            TypingMode::PostTypeckUntilBorrowck { .. } => {
361                if !self.considering_regions {
362                    return;
363                }
364            }
365        }
366
367        if !opaque_type_storage.is_empty() {
368            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:?}")));
369        }
370    }
371}
372
373/// See the `error_reporting` module for more details.
374#[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)]
375pub enum ValuePairs<'tcx> {
376    Regions(ExpectedFound<ty::Region<'tcx>>),
377    Terms(ExpectedFound<ty::Term<'tcx>>),
378    Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
379    TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
380    PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
381    ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
382    ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
383}
384
385impl<'tcx> ValuePairs<'tcx> {
386    pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
387        if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
388            && let Some(expected) = expected.as_type()
389            && let Some(found) = found.as_type()
390        {
391            Some((expected, found))
392        } else {
393            None
394        }
395    }
396}
397
398/// The trace designates the path through inference that we took to
399/// encounter an error or subtyping constraint.
400///
401/// See the `error_reporting` module for more details.
402#[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)]
403pub struct TypeTrace<'tcx> {
404    pub cause: ObligationCause<'tcx>,
405    pub values: ValuePairs<'tcx>,
406}
407
408/// The origin of a `r1 <= r2` constraint.
409///
410/// See `error_reporting` module for more details
411#[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)]
412pub enum SubregionOrigin<'tcx> {
413    /// Arose from a subtyping relation
414    Subtype(Box<TypeTrace<'tcx>>),
415
416    /// When casting `&'a T` to an `&'b Trait` object,
417    /// relating `'a` to `'b`.
418    RelateObjectBound(Span),
419
420    /// Some type parameter was instantiated with the given type,
421    /// and that type must outlive some region.
422    RelateParamBound(Span, Ty<'tcx>, Option<Span>),
423
424    /// The given region parameter was instantiated with a region
425    /// that must outlive some other region.
426    RelateRegionParamBound(Span, Option<Ty<'tcx>>),
427
428    /// Creating a pointer `b` to contents of another reference.
429    Reborrow(Span),
430
431    /// (&'a &'b T) where a >= b
432    ReferenceOutlivesReferent(Ty<'tcx>, Span),
433
434    /// Comparing the signature and requirements of an impl method against
435    /// the containing trait.
436    CompareImplItemObligation {
437        span: Span,
438        impl_item_def_id: LocalDefId,
439        trait_item_def_id: DefId,
440    },
441
442    /// Checking that the bounds of a trait's associated type hold for a given impl.
443    CheckAssociatedTypeBounds {
444        parent: Box<SubregionOrigin<'tcx>>,
445        impl_item_def_id: LocalDefId,
446        trait_item_def_id: DefId,
447    },
448
449    AscribeUserTypeProvePredicate(Span),
450
451    // FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
452    // proper diagnostics for solver region constraints.
453    SolverRegionConstraint(Span),
454}
455
456// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
457#[cfg(target_pointer_width = "64")]
458const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
459
460impl<'tcx> SubregionOrigin<'tcx> {
461    pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
462        match self {
463            Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
464            Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
465            Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
466            _ => ConstraintCategory::BoringNoLocation,
467        }
468    }
469}
470
471/// Times when we replace bound regions with existentials:
472#[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)]
473pub enum BoundRegionConversionTime {
474    /// when a fn is called
475    FnCall,
476
477    /// when two higher-ranked types are compared
478    HigherRankedType,
479
480    /// when projecting an associated type
481    AssocTypeProjection(DefId),
482}
483
484/// Reasons to create a region inference variable.
485///
486/// See `error_reporting` module for more details.
487#[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)]
488pub enum RegionVariableOrigin<'tcx> {
489    /// Region variables created for ill-categorized reasons.
490    ///
491    /// They mostly indicate places in need of refactoring.
492    Misc(Span),
493
494    /// Regions created by a `&P` or `[...]` pattern.
495    PatternRegion(Span),
496
497    /// Regions created by `&` operator.
498    BorrowRegion(Span),
499
500    /// Regions created as part of an autoref of a method receiver.
501    Autoref(Span),
502
503    /// Regions created as part of an automatic coercion.
504    Coercion(Span),
505
506    /// Region variables created as the values for early-bound regions.
507    ///
508    /// FIXME(@lcnr): This should also store a `DefId`, similar to
509    /// `TypeVariableOrigin`.
510    RegionParameterDefinition(Span, Symbol),
511
512    /// Region variables created when instantiating a binder with
513    /// existential variables, e.g. when calling a function or method.
514    BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
515
516    UpvarRegion(ty::UpvarId, Span),
517
518    /// This origin is used for the inference variables that we create
519    /// during NLL region processing.
520    Nll(NllRegionVariableOrigin<'tcx>),
521}
522
523#[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)]
524pub enum NllRegionVariableOrigin<'tcx> {
525    /// During NLL region processing, we create variables for free
526    /// regions that we encounter in the function signature and
527    /// elsewhere. This origin indices we've got one of those.
528    FreeRegion,
529
530    /// "Universal" instantiation of a higher-ranked region (e.g.,
531    /// from a `for<'a> T` binder). Meant to represent "any region".
532    Placeholder(ty::PlaceholderRegion<'tcx>),
533
534    Existential {
535        name: Option<Symbol>,
536    },
537}
538
539#[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)]
540pub struct FixupError {
541    unresolved: TyOrConstInferVar,
542}
543
544impl fmt::Display for FixupError {
545    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546        match self.unresolved {
547            TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
548                f,
549                "cannot determine the type of this integer; \
550                 add a suffix to specify the type explicitly"
551            ),
552            TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
553                f,
554                "cannot determine the type of this number; \
555                 add a suffix to specify the type explicitly"
556            ),
557            TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
558            TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
559        }
560    }
561}
562
563/// See the `region_obligations` field for more information.
564#[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)]
565pub struct TypeOutlivesConstraint<'tcx> {
566    pub sub_region: ty::Region<'tcx>,
567    pub sup_type: Ty<'tcx>,
568    pub origin: SubregionOrigin<'tcx>,
569}
570
571/// Used to configure inference contexts before their creation.
572pub struct InferCtxtBuilder<'tcx> {
573    tcx: TyCtxt<'tcx>,
574    considering_regions: bool,
575    in_hir_typeck: bool,
576    skip_leak_check: bool,
577    /// Whether we should use the new trait solver in the local inference context,
578    /// which affects things like which solver is used in `predicate_may_hold`.
579    next_trait_solver: bool,
580}
581
582impl<'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>)]
583impl<'tcx> TyCtxt<'tcx> {
584    fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
585        InferCtxtBuilder {
586            tcx: self,
587            considering_regions: true,
588            in_hir_typeck: false,
589            skip_leak_check: false,
590            next_trait_solver: self.next_trait_solver_globally(),
591        }
592    }
593}
594
595impl<'tcx> InferCtxtBuilder<'tcx> {
596    pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
597        self.next_trait_solver = next_trait_solver;
598        self
599    }
600
601    pub fn ignoring_regions(mut self) -> Self {
602        self.considering_regions = false;
603        self
604    }
605
606    pub fn in_hir_typeck(mut self) -> Self {
607        self.in_hir_typeck = true;
608        self
609    }
610
611    pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
612        self.skip_leak_check = skip_leak_check;
613        self
614    }
615
616    /// Given a canonical value `C` as a starting point, create an
617    /// inference context that contains each of the bound values
618    /// within instantiated as a fresh variable. The `f` closure is
619    /// invoked with the new infcx, along with the instantiated value
620    /// `V` and a instantiation `S`. This instantiation `S` maps from
621    /// the bound values in `C` to their instantiated values in `V`
622    /// (in other words, `S(C) = V`).
623    pub fn build_with_canonical<T>(
624        mut self,
625        span: Span,
626        input: &CanonicalQueryInput<'tcx, T>,
627    ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
628    where
629        T: TypeFoldable<TyCtxt<'tcx>>,
630    {
631        let infcx = self.build(input.typing_mode.0);
632        let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
633        (infcx, value, args)
634    }
635
636    pub fn build_with_typing_env(
637        mut self,
638        typing_env: TypingEnv<'tcx>,
639    ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
640        (self.build(typing_env.typing_mode()), typing_env.param_env)
641    }
642
643    pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
644        let InferCtxtBuilder {
645            tcx,
646            considering_regions,
647            in_hir_typeck,
648            skip_leak_check,
649            next_trait_solver,
650        } = *self;
651        InferCtxt {
652            tcx,
653            typing_mode,
654            considering_regions,
655            in_hir_typeck,
656            skip_leak_check,
657            inner: RefCell::new(InferCtxtInner::new()),
658            lexical_region_resolutions: RefCell::new(None),
659            selection_cache: Default::default(),
660            evaluation_cache: Default::default(),
661            reported_trait_errors: Default::default(),
662            reported_signature_mismatch: Default::default(),
663            tainted_by_errors: Cell::new(None),
664            universe: Cell::new(ty::UniverseIndex::ROOT),
665            placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
666            next_trait_solver,
667            obligation_inspector: Cell::new(None),
668        }
669    }
670}
671
672impl<'tcx, T> InferOk<'tcx, T> {
673    /// Extracts `value`, registering any obligations into `fulfill_cx`.
674    pub fn into_value_registering_obligations<E: 'tcx>(
675        self,
676        infcx: &InferCtxt<'tcx>,
677        fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
678    ) -> T {
679        let InferOk { value, obligations } = self;
680        fulfill_cx.register_predicate_obligations(infcx, obligations);
681        value
682    }
683}
684
685impl<'tcx> InferOk<'tcx, ()> {
686    pub fn into_obligations(self) -> PredicateObligations<'tcx> {
687        self.obligations
688    }
689}
690
691impl<'tcx> InferCtxt<'tcx> {
692    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
693        self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
694    }
695
696    pub fn next_trait_solver(&self) -> bool {
697        self.next_trait_solver
698    }
699
700    /// This method is deliberately called `..._raw`,
701    /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
702    /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
703    /// more information.
704    ///
705    /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
706    /// works as a kind of store for for example type unification information.
707    /// `InferCtxt` is also often used outside the trait solver during typeck.
708    /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
709    /// To make sure these two uses are never confused, we want to statically encode this information.
710    ///
711    /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
712    /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
713    /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
714    /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
715    /// match on the variant and can safely ignore it.
716    ///
717    /// Prefer non-raw apis if available. e.g.,
718    /// - On the `FnCtxt`
719    /// - on the `SelectionCtxt`
720    #[inline(always)]
721    pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
722        self.typing_mode
723    }
724
725    #[inline(always)]
726    pub fn disable_trait_solver_fast_paths(&self) -> bool {
727        self.tcx.disable_trait_solver_fast_paths()
728    }
729
730    /// Returns the origin of the type variable identified by `vid`.
731    ///
732    /// No attempt is made to resolve `vid` to its root variable.
733    pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
734        self.inner.borrow_mut().type_variables().var_origin(vid)
735    }
736
737    /// Returns the origin of the float type variable identified by `vid`.
738    ///
739    /// No attempt is made to resolve `vid` to its root variable.
740    pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
741        self.inner.borrow_mut().float_origin_origin_storage[vid]
742    }
743
744    /// Returns the origin of the const variable identified by `vid`
745    // FIXME: We should store origins separately from the unification table
746    // so this doesn't need to be optional.
747    pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
748        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
749            ConstVariableValue::Known { .. } => None,
750            ConstVariableValue::Unknown { origin, .. } => Some(origin),
751        }
752    }
753
754    pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
755        let mut inner = self.inner.borrow_mut();
756        let mut vars: Vec<Ty<'_>> = inner
757            .type_variables()
758            .unresolved_variables()
759            .into_iter()
760            .map(|t| Ty::new_var(self.tcx, t))
761            .collect();
762        vars.extend(
763            (0..inner.int_unification_table().len())
764                .map(|i| ty::IntVid::from_usize(i))
765                .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
766                .map(|v| Ty::new_int_var(self.tcx, v)),
767        );
768        vars.extend(
769            (0..inner.float_unification_table().len())
770                .map(|i| ty::FloatVid::from_usize(i))
771                .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
772                .map(|v| Ty::new_float_var(self.tcx, v)),
773        );
774        vars
775    }
776
777    #[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(777u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("origin")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("origin");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("vis")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("vis");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
                                                            as &dyn ::tracing::field::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")]
778    pub fn sub_regions(
779        &self,
780        origin: SubregionOrigin<'tcx>,
781        a: ty::Region<'tcx>,
782        b: ty::Region<'tcx>,
783        vis: ty::VisibleForLeakCheck,
784    ) {
785        self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
786    }
787
788    #[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(788u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("origin")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("origin");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("vis")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("vis");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
                                                            as &dyn ::tracing::field::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")]
789    pub fn equate_regions(
790        &self,
791        origin: SubregionOrigin<'tcx>,
792        a: ty::Region<'tcx>,
793        b: ty::Region<'tcx>,
794        vis: ty::VisibleForLeakCheck,
795    ) {
796        self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
797    }
798
799    /// Processes a `Coerce` predicate from the fulfillment context.
800    /// This is NOT the preferred way to handle coercion, which is to
801    /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
802    ///
803    /// This method here is actually a fallback that winds up being
804    /// invoked when `FnCtxt::coerce` encounters unresolved type variables
805    /// and records a coercion predicate. Presently, this method is equivalent
806    /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
807    /// actually requiring `a <: b`. This is of course a valid coercion,
808    /// but it's not as flexible as `FnCtxt::coerce` would be.
809    ///
810    /// (We may refactor this in the future, but there are a number of
811    /// practical obstacles. Among other things, `FnCtxt::coerce` presently
812    /// records adjustments that are required on the HIR in order to perform
813    /// the coercion, and we don't currently have a way to manage that.)
814    pub fn coerce_predicate(
815        &self,
816        cause: &ObligationCause<'tcx>,
817        param_env: ty::ParamEnv<'tcx>,
818        predicate: ty::PolyCoercePredicate<'tcx>,
819    ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
820        let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
821            a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
822            a: p.a,
823            b: p.b,
824        });
825        self.subtype_predicate(cause, param_env, subtype_predicate)
826    }
827
828    pub fn subtype_predicate(
829        &self,
830        cause: &ObligationCause<'tcx>,
831        param_env: ty::ParamEnv<'tcx>,
832        predicate: ty::PolySubtypePredicate<'tcx>,
833    ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
834        // Check for two unresolved inference variables, in which case we can
835        // make no progress. This is partly a micro-optimization, but it's
836        // also an opportunity to "sub-unify" the variables. This isn't
837        // *necessary* to prevent cycles, because they would eventually be sub-unified
838        // anyhow during generalization, but it helps with diagnostics (we can detect
839        // earlier that they are sub-unified).
840        //
841        // Note that we can just skip the binders here because
842        // type variables can't (at present, at
843        // least) capture any of the things bound by this binder.
844        //
845        // Note that this sub here is not just for diagnostics - it has semantic
846        // effects as well.
847        let r_a = self.shallow_resolve(predicate.skip_binder().a);
848        let r_b = self.shallow_resolve(predicate.skip_binder().b);
849        match (r_a.kind(), r_b.kind()) {
850            (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
851                self.sub_unify_ty_vids_raw(a_vid, b_vid);
852                return Err((a_vid, b_vid));
853            }
854            _ => {}
855        }
856
857        self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
858            if a_is_expected {
859                Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
860            } else {
861                Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
862            }
863        })
864    }
865
866    /// Number of type variables created so far.
867    pub fn num_ty_vars(&self) -> usize {
868        self.inner.borrow_mut().type_variables().num_vars()
869    }
870
871    pub fn next_ty_vid(&self, span: Span) -> TyVid {
872        self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
873    }
874
875    pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
876        self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
877    }
878
879    pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
880        let origin = TypeVariableOrigin { span, param_def_id: None };
881        self.inner.borrow_mut().type_variables().new_var(universe, origin)
882    }
883
884    pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
885        self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
886    }
887
888    pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
889        let vid = self.next_ty_vid_with_origin(origin);
890        Ty::new_var(self.tcx, vid)
891    }
892
893    pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
894        let vid = self.next_ty_vid_in_universe(span, universe);
895        Ty::new_var(self.tcx, vid)
896    }
897
898    pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
899        self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
900    }
901
902    pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
903        let vid = self
904            .inner
905            .borrow_mut()
906            .const_unification_table()
907            .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
908            .vid;
909        ty::Const::new_var(self.tcx, vid)
910    }
911
912    pub fn next_const_var_in_universe(
913        &self,
914        span: Span,
915        universe: ty::UniverseIndex,
916    ) -> ty::Const<'tcx> {
917        let origin = ConstVariableOrigin { span, param_def_id: None };
918        let vid = self
919            .inner
920            .borrow_mut()
921            .const_unification_table()
922            .new_key(ConstVariableValue::Unknown { origin, universe })
923            .vid;
924        ty::Const::new_var(self.tcx, vid)
925    }
926
927    pub fn next_int_var(&self) -> Ty<'tcx> {
928        let next_int_var_id =
929            self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
930        Ty::new_int_var(self.tcx, next_int_var_id)
931    }
932
933    pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
934        let mut inner = self.inner.borrow_mut();
935        let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
936        let origin = FloatVariableOrigin { span, lint_id };
937        let span_index = inner.float_origin_origin_storage.push(origin);
938        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);
939        Ty::new_float_var(self.tcx, next_float_var_id)
940    }
941
942    /// Creates a fresh region variable with the next available index.
943    /// The variable will be created in the maximum universe created
944    /// thus far, allowing it to name any region created thus far.
945    pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
946        self.next_region_var_in_universe(origin, self.universe())
947    }
948
949    /// Creates a fresh region variable with the next available index
950    /// in the given universe; typically, you can use
951    /// `next_region_var` and just use the maximal universe.
952    pub fn next_region_var_in_universe(
953        &self,
954        origin: RegionVariableOrigin<'tcx>,
955        universe: ty::UniverseIndex,
956    ) -> ty::Region<'tcx> {
957        let region_var =
958            self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
959        ty::Region::new_var(self.tcx, region_var)
960    }
961
962    pub fn next_term_var_of_alias_kind(
963        &self,
964        alias_term: ty::AliasTerm<'tcx>,
965        span: Span,
966    ) -> ty::Term<'tcx> {
967        match alias_term.kind {
968            ty::AliasTermKind::ProjectionTy { .. }
969            | ty::AliasTermKind::InherentTy { .. }
970            | ty::AliasTermKind::OpaqueTy { .. }
971            | ty::AliasTermKind::FreeTy { .. } => self.next_ty_var(span).into(),
972            ty::AliasTermKind::FreeConst { .. }
973            | ty::AliasTermKind::InherentConst { .. }
974            | ty::AliasTermKind::AnonConst { .. }
975            | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_var(span).into(),
976        }
977    }
978
979    /// Return the universe that the region `r` was created in. For
980    /// most regions (e.g., `'static`, named regions from the user,
981    /// etc) this is the root universe U0. For inference variables or
982    /// placeholders, however, it will return the universe which they
983    /// are associated.
984    pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
985        self.inner.borrow_mut().unwrap_region_constraints().universe(r)
986    }
987
988    /// Number of region variables created so far.
989    pub fn num_region_vars(&self) -> usize {
990        self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
991    }
992
993    /// Just a convenient wrapper of `next_region_var` for using during NLL.
994    #[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(994u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("origin")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("origin");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn ::tracing::field::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")]
995    pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
996        self.next_region_var(RegionVariableOrigin::Nll(origin))
997    }
998
999    /// Just a convenient wrapper of `next_region_var` for using during NLL.
1000    #[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(1000u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("origin")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("origin");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("universe")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("universe");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&universe)
                                                            as &dyn ::tracing::field::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")]
1001    pub fn next_nll_region_var_in_universe(
1002        &self,
1003        origin: NllRegionVariableOrigin<'tcx>,
1004        universe: ty::UniverseIndex,
1005    ) -> ty::Region<'tcx> {
1006        self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1007    }
1008
1009    pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1010        match param.kind {
1011            GenericParamDefKind::Lifetime => {
1012                // Create a region inference variable for the given
1013                // region parameter definition.
1014                self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1015                    span, param.name,
1016                ))
1017                .into()
1018            }
1019            GenericParamDefKind::Type { .. } => {
1020                // Create a type inference variable for the given
1021                // type parameter definition. The generic parameters are
1022                // for actual parameters that may be referred to by
1023                // the default of this type parameter, if it exists.
1024                // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1025                // used in a path such as `Foo::<T, U>::new()` will
1026                // use an inference variable for `C` with `[T, U]`
1027                // as the generic parameters for the default, `(T, U)`.
1028                let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1029                    self.universe(),
1030                    TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1031                );
1032
1033                Ty::new_var(self.tcx, ty_var_id).into()
1034            }
1035            GenericParamDefKind::Const { .. } => {
1036                let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1037                let const_var_id = self
1038                    .inner
1039                    .borrow_mut()
1040                    .const_unification_table()
1041                    .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1042                    .vid;
1043                ty::Const::new_var(self.tcx, const_var_id).into()
1044            }
1045        }
1046    }
1047
1048    /// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1049    /// each type/region parameter to a fresh inference variable.
1050    pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
1051        GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1052    }
1053
1054    /// Returns `true` if errors have been reported since this infcx was
1055    /// created. This is sometimes used as a heuristic to skip
1056    /// reporting errors that often occur as a result of earlier
1057    /// errors, but where it's hard to be 100% sure (e.g., unresolved
1058    /// inference variables, regionck errors).
1059    #[must_use = "this method does not have any side effects"]
1060    pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1061        self.tainted_by_errors.get()
1062    }
1063
1064    /// Set the "tainted by errors" flag to true. We call this when we
1065    /// observe an error from a prior pass.
1066    pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1067        {
    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:1067",
                        "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(1067u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("set_tainted_by_errors(ErrorGuaranteed)")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("set_tainted_by_errors(ErrorGuaranteed)");
1068        self.tainted_by_errors.set(Some(e));
1069    }
1070
1071    pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1072        let mut inner = self.inner.borrow_mut();
1073        let inner = &mut *inner;
1074        inner.unwrap_region_constraints().var_origin(vid)
1075    }
1076
1077    /// Clone the list of variable regions. This is used only during NLL processing
1078    /// to put the set of region variables into the NLL region context.
1079    pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1080        let inner = self.inner.borrow();
1081        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));
1082        let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1083        if !storage.data.is_empty() {
    { ::core::panicking::panic_fmt(format_args!("{0:#?}", storage.data)); }
};assert!(storage.data.is_empty(), "{:#?}", storage.data);
1084        // We clone instead of taking because borrowck still wants to use the
1085        // inference context after calling this for diagnostics and the new
1086        // trait solver.
1087        storage.var_infos.clone()
1088    }
1089
1090    pub fn has_opaque_types_in_storage(&self) -> bool {
1091        !self.inner.borrow().opaque_type_storage.is_empty()
1092    }
1093
1094    x;#[instrument(level = "debug", skip(self), ret)]
1095    pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1096        self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1097    }
1098
1099    x;#[instrument(level = "debug", skip(self), ret)]
1100    pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1101        self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1102    }
1103
1104    pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1105        if !self.next_trait_solver() {
1106            return false;
1107        }
1108
1109        let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1110        let inner = &mut *self.inner.borrow_mut();
1111        let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1112        inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1113            if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1114                let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1115                if opaque_sub_vid == ty_sub_vid {
1116                    return true;
1117                }
1118            }
1119
1120            false
1121        })
1122    }
1123
1124    /// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1125    ///
1126    /// This only checks for a subtype relation, it does not require equality.
1127    pub fn opaques_with_sub_unified_hidden_type(
1128        &self,
1129        ty_vid: TyVid,
1130    ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1131        // Avoid accidentally allowing more code to compile with the old solver.
1132        if !self.next_trait_solver() {
1133            return ::alloc::vec::Vec::new()vec![];
1134        }
1135
1136        let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1137        let inner = &mut *self.inner.borrow_mut();
1138        // This is iffy, can't call `type_variables()` as we're already
1139        // borrowing the `opaque_type_storage` here.
1140        let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1141        inner
1142            .opaque_type_storage
1143            .iter_opaque_types()
1144            .filter_map(|(key, hidden_ty)| {
1145                if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1146                    let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1147                    if opaque_sub_vid == ty_sub_vid {
1148                        return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1149                            self.tcx,
1150                            key.def_id.into(),
1151                            key.args,
1152                        ));
1153                    }
1154                }
1155
1156                None
1157            })
1158            .collect()
1159    }
1160
1161    #[inline(always)]
1162    pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1163        if true {
    if !!self.next_trait_solver() {
        ::core::panicking::panic("assertion failed: !self.next_trait_solver()")
    };
};debug_assert!(!self.next_trait_solver());
1164        match self.typing_mode_raw().assert_not_erased() {
1165            TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1166            | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types } => {
1167                id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1168            }
1169            // FIXME(#132279): This function is quite weird in post-analysis
1170            // and post-borrowck analysis mode. We may need to modify its uses
1171            // to support PostBorrowck in the old solver as well.
1172            TypingMode::Coherence
1173            | TypingMode::PostBorrowck { .. }
1174            | TypingMode::PostAnalysis
1175            | TypingMode::Codegen => false,
1176        }
1177    }
1178
1179    pub fn push_hir_typeck_potentially_region_dependent_goal(
1180        &self,
1181        goal: PredicateObligation<'tcx>,
1182    ) {
1183        let mut inner = self.inner.borrow_mut();
1184        inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1185        inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1186    }
1187
1188    pub fn take_hir_typeck_potentially_region_dependent_goals(
1189        &self,
1190    ) -> Vec<PredicateObligation<'tcx>> {
1191        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");
1192        std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1193    }
1194
1195    pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1196        self.resolve_vars_if_possible(t).to_string()
1197    }
1198
1199    /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1200    /// universe index of `TyVar(vid)`.
1201    pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1202        use self::type_variable::TypeVariableValue;
1203
1204        match self.inner.borrow_mut().type_variables().probe(vid) {
1205            TypeVariableValue::Known { value } => Ok(value),
1206            TypeVariableValue::Unknown { universe } => Err(universe),
1207        }
1208    }
1209
1210    pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1211        if let ty::Infer(v) = *ty.kind() {
1212            match v {
1213                ty::TyVar(v) => {
1214                    // Not entirely obvious: if `typ` is a type variable,
1215                    // it can be resolved to an int/float variable, which
1216                    // can then be recursively resolved, hence the
1217                    // recursion. Note though that we prevent type
1218                    // variables from unifying to other type variables
1219                    // directly (though they may be embedded
1220                    // structurally), and we prevent cycles in any case,
1221                    // so this recursion should always be of very limited
1222                    // depth.
1223                    //
1224                    // Note: if these two lines are combined into one we get
1225                    // dynamic borrow errors on `self.inner`.
1226                    let known = self.inner.borrow_mut().type_variables().probe(v).known();
1227                    known.map_or(ty, |t| self.shallow_resolve(t))
1228                }
1229
1230                ty::IntVar(v) => {
1231                    match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1232                        ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1233                        ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1234                        ty::IntVarValue::Unknown => ty,
1235                    }
1236                }
1237
1238                ty::FloatVar(v) => {
1239                    match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1240                        ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1241                        ty::FloatVarValue::Unknown => ty,
1242                    }
1243                }
1244
1245                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1246            }
1247        } else {
1248            ty
1249        }
1250    }
1251
1252    pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1253        match ct.kind() {
1254            ty::ConstKind::Infer(infer_ct) => match infer_ct {
1255                InferConst::Var(vid) => self
1256                    .inner
1257                    .borrow_mut()
1258                    .const_unification_table()
1259                    .probe_value(vid)
1260                    .known()
1261                    .unwrap_or(ct),
1262                InferConst::Fresh(_) => ct,
1263            },
1264
1265            ty::ConstKind::Param(_)
1266            | ty::ConstKind::Bound(_, _)
1267            | ty::ConstKind::Placeholder(_)
1268            | ty::ConstKind::Alias(_, _)
1269            | ty::ConstKind::Value(_)
1270            | ty::ConstKind::Error(_)
1271            | ty::ConstKind::Expr(_) => ct,
1272        }
1273    }
1274
1275    pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1276        match term.kind() {
1277            ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1278            ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1279        }
1280    }
1281
1282    pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1283        self.inner.borrow_mut().type_variables().root_var(var)
1284    }
1285
1286    pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1287        self.inner.borrow_mut().type_variables().sub_unify(a, b);
1288    }
1289
1290    pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1291        self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1292    }
1293
1294    pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1295        self.inner.borrow_mut().float_unification_table().find(var)
1296    }
1297
1298    pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1299        self.inner.borrow_mut().const_unification_table().find(var).vid
1300    }
1301
1302    /// Resolves an int var to a rigid int type, if it was constrained to one,
1303    /// or else the root int var in the unification table.
1304    pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1305        let mut inner = self.inner.borrow_mut();
1306        let value = inner.int_unification_table().probe_value(vid);
1307        match value {
1308            ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1309            ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1310            ty::IntVarValue::Unknown => {
1311                Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1312            }
1313        }
1314    }
1315
1316    /// Resolves a float var to a rigid int type, if it was constrained to one,
1317    /// or else the root float var in the unification table.
1318    pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1319        let mut inner = self.inner.borrow_mut();
1320        let value = inner.float_unification_table().probe_value(vid);
1321        match value {
1322            ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1323            ty::FloatVarValue::Unknown => {
1324                Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1325            }
1326        }
1327    }
1328
1329    /// Where possible, replaces type/const variables in
1330    /// `value` with their final value. Note that region variables
1331    /// are unaffected. If a type/const variable has not been unified, it
1332    /// is left as is. This is an idempotent operation that does
1333    /// not affect inference state in any way and so you can do it
1334    /// at will.
1335    pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1336    where
1337        T: TypeFoldable<TyCtxt<'tcx>>,
1338    {
1339        if let Err(guar) = value.error_reported() {
1340            self.set_tainted_by_errors(guar);
1341        }
1342        if !value.has_non_region_infer() {
1343            return value;
1344        }
1345        let mut r = resolve::OpportunisticVarResolver::new(self);
1346        value.fold_with(&mut r)
1347    }
1348
1349    pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1350    where
1351        T: TypeFoldable<TyCtxt<'tcx>>,
1352    {
1353        if !value.has_infer() {
1354            return value; // Avoid duplicated type-folding.
1355        }
1356        let mut r = InferenceLiteralEraser { tcx: self.tcx };
1357        value.fold_with(&mut r)
1358    }
1359
1360    pub fn try_resolve_const_var(
1361        &self,
1362        vid: ty::ConstVid,
1363    ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1364        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1365            ConstVariableValue::Known { value } => Ok(value),
1366            ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1367        }
1368    }
1369
1370    /// Attempts to resolve all type/region/const variables in
1371    /// `value`. Region inference must have been run already (e.g.,
1372    /// by calling `resolve_regions_and_report_errors`). If some
1373    /// variable was never unified, an `Err` results.
1374    ///
1375    /// This method is idempotent, but it not typically not invoked
1376    /// except during the writeback phase.
1377    pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1378        match resolve::fully_resolve(self, value) {
1379            Ok(value) => {
1380                if value.has_non_region_infer() {
1381                    ::rustc_middle::util::bug::bug_fmt(format_args!("`{0:?}` is not fully resolved",
        value));bug!("`{value:?}` is not fully resolved");
1382                }
1383                if value.has_infer_regions() {
1384                    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"));
1385                    Ok(fold_regions(self.tcx, value, |re, _| {
1386                        if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1387                    }))
1388                } else {
1389                    Ok(value)
1390                }
1391            }
1392            Err(e) => Err(e),
1393        }
1394    }
1395
1396    // Instantiates the bound variables in a given binder with fresh inference
1397    // variables in the current universe.
1398    //
1399    // Use this method if you'd like to find some generic parameters of the binder's
1400    // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1401    // that corresponds to your use case, consider whether or not you should
1402    // use [`InferCtxt::enter_forall`] instead.
1403    pub fn instantiate_binder_with_fresh_vars<T>(
1404        &self,
1405        span: Span,
1406        lbrct: BoundRegionConversionTime,
1407        value: ty::Binder<'tcx, T>,
1408    ) -> T
1409    where
1410        T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1411    {
1412        if let Some(inner) = value.no_bound_vars() {
1413            return inner;
1414        }
1415
1416        let bound_vars = value.bound_vars();
1417        let mut args = Vec::with_capacity(bound_vars.len());
1418
1419        for bound_var_kind in bound_vars {
1420            let arg: ty::GenericArg<'_> = match bound_var_kind {
1421                ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1422                ty::BoundVariableKind::Region(br) => {
1423                    self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1424                }
1425                ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1426            };
1427            args.push(arg);
1428        }
1429
1430        struct ToFreshVars<'tcx> {
1431            args: Vec<ty::GenericArg<'tcx>>,
1432        }
1433
1434        impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1435            fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1436                self.args[br.var.index()].expect_region()
1437            }
1438            fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1439                self.args[bt.var.index()].expect_ty()
1440            }
1441            fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1442                self.args[bc.var.index()].expect_const()
1443            }
1444        }
1445        let delegate = ToFreshVars { args };
1446        self.tcx.replace_bound_vars_uncached(value, delegate)
1447    }
1448
1449    /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1450    pub(crate) fn verify_generic_bound(
1451        &self,
1452        origin: SubregionOrigin<'tcx>,
1453        kind: GenericKind<'tcx>,
1454        a: ty::Region<'tcx>,
1455        bound: VerifyBound<'tcx>,
1456    ) {
1457        {
    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:1457",
                        "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(1457u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("verify_generic_bound({0:?}, {1:?} <: {2:?})",
                                                    kind, a, bound) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1458
1459        self.inner
1460            .borrow_mut()
1461            .unwrap_region_constraints()
1462            .verify_generic_bound(origin, kind, a, bound);
1463    }
1464
1465    /// Obtains the latest type of the given closure; this may be a
1466    /// closure in the current function, in which case its
1467    /// `ClosureKind` may not yet be known.
1468    pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1469        let unresolved_kind_ty = match *closure_ty.kind() {
1470            ty::Closure(_, args) => args.as_closure().kind_ty(),
1471            ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1472            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0}",
        closure_ty))bug!("unexpected type {closure_ty}"),
1473        };
1474        let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1475        closure_kind_ty.to_opt_closure_kind()
1476    }
1477
1478    pub fn universe(&self) -> ty::UniverseIndex {
1479        self.universe.get()
1480    }
1481
1482    /// Creates and return a fresh universe that extends all previous
1483    /// universes. Updates `self.universe` to that new universe.
1484    pub fn create_next_universe(&self) -> ty::UniverseIndex {
1485        let u = self.universe.get().next_universe();
1486        {
    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:1486",
                        "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(1486u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("create_next_universe {0:?}",
                                                    u) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("create_next_universe {u:?}");
1487        self.universe.set(u);
1488        u
1489    }
1490
1491    /// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1492    /// which contains the necessary information to use the trait system without
1493    /// using canonicalization or carrying this inference context around.
1494    pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1495        let typing_mode = match self.typing_mode_raw() {
1496            // FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1497            // to handle them without proper canonicalization. This means we may cause cycle
1498            // errors and fail to reveal opaques while inside of bodies. We should rename this
1499            // function and require explicit comments on all use-sites in the future.
1500            ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1501            | ty::TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ } => {
1502                TypingMode::non_body_analysis()
1503            }
1504            mode @ (ty::TypingMode::Coherence
1505            | ty::TypingMode::PostBorrowck { .. }
1506            | ty::TypingMode::PostAnalysis
1507            | ty::TypingMode::Codegen) => mode,
1508            ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1509        };
1510        ty::TypingEnv::new(param_env, typing_mode)
1511    }
1512
1513    /// Similar to [`Self::canonicalize_query`], except that it returns
1514    /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1515    /// `param_env` to not contain any inference variables or placeholders.
1516    pub fn pseudo_canonicalize_query<V>(
1517        &self,
1518        param_env: ty::ParamEnv<'tcx>,
1519        value: V,
1520    ) -> PseudoCanonicalInput<'tcx, V>
1521    where
1522        V: TypeVisitable<TyCtxt<'tcx>>,
1523    {
1524        if true {
    if !!value.has_infer() {
        ::core::panicking::panic("assertion failed: !value.has_infer()")
    };
};debug_assert!(!value.has_infer());
1525        if true {
    if !!value.has_placeholders() {
        ::core::panicking::panic("assertion failed: !value.has_placeholders()")
    };
};debug_assert!(!value.has_placeholders());
1526        if true {
    if !!param_env.has_infer() {
        ::core::panicking::panic("assertion failed: !param_env.has_infer()")
    };
};debug_assert!(!param_env.has_infer());
1527        if true {
    if !!param_env.has_placeholders() {
        ::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
    };
};debug_assert!(!param_env.has_placeholders());
1528        self.typing_env(param_env).as_query_input(value)
1529    }
1530
1531    /// The returned function is used in a fast path. If it returns `true` the variable is
1532    /// unchanged, `false` indicates that the status is unknown.
1533    #[inline]
1534    pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1535        // This hoists the borrow/release out of the loop body.
1536        let inner = self.inner.try_borrow();
1537
1538        move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1539            (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1540                use self::type_variable::TypeVariableValue;
1541
1542                #[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
    {
    Some(TypeVariableValue::Unknown { .. }) => true,
    _ => false,
}matches!(
1543                    inner.try_type_variables_probe_ref(ty_var),
1544                    Some(TypeVariableValue::Unknown { .. })
1545                )
1546            }
1547            _ => false,
1548        }
1549    }
1550
1551    /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1552    ///   * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1553    ///   * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1554    ///
1555    /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1556    /// inlined, despite being large, because it has only two call sites that
1557    /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1558    /// inference variables), and it handles both `Ty` and `ty::Const` without
1559    /// having to resort to storing full `GenericArg`s in `stalled_on`.
1560    #[inline(always)]
1561    pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1562        match infer_var {
1563            TyOrConstInferVar::Ty(v) => {
1564                use self::type_variable::TypeVariableValue;
1565
1566                // If `inlined_probe` returns a `Known` value, it never equals
1567                // `ty::Infer(ty::TyVar(v))`.
1568                match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1569                    TypeVariableValue::Unknown { .. } => false,
1570                    TypeVariableValue::Known { .. } => true,
1571                }
1572            }
1573
1574            TyOrConstInferVar::TyInt(v) => {
1575                // If `inlined_probe_value` returns a value it's always a
1576                // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1577                // `ty::Infer(_)`.
1578                self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1579            }
1580
1581            TyOrConstInferVar::TyFloat(v) => {
1582                // If `probe_value` returns a value it's always a
1583                // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1584                //
1585                // Not `inlined_probe_value(v)` because this call site is colder.
1586                self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1587            }
1588
1589            TyOrConstInferVar::Const(v) => {
1590                // If `probe_value` returns a `Known` value, it never equals
1591                // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1592                //
1593                // Not `inlined_probe_value(v)` because this call site is colder.
1594                match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1595                    ConstVariableValue::Unknown { .. } => false,
1596                    ConstVariableValue::Known { .. } => true,
1597                }
1598            }
1599        }
1600    }
1601
1602    /// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1603    pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1604        if true {
    if !self.obligation_inspector.get().is_none() {
        {
            ::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
        }
    };
};debug_assert!(
1605            self.obligation_inspector.get().is_none(),
1606            "shouldn't override a set obligation inspector"
1607        );
1608        self.obligation_inspector.set(Some(inspector));
1609    }
1610}
1611
1612/// Helper for [InferCtxt::ty_or_const_infer_var_changed] (see comment on that), currently
1613/// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1614#[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)]
1615pub enum TyOrConstInferVar {
1616    /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1617    Ty(TyVid),
1618    /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1619    TyInt(IntVid),
1620    /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1621    TyFloat(FloatVid),
1622
1623    /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1624    Const(ConstVid),
1625}
1626
1627impl<'tcx> TyOrConstInferVar {
1628    /// Tries to extract an inference variable from a type or a constant, returns `None`
1629    /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1630    /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1631    pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1632        match arg.kind() {
1633            GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1634            GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1635            GenericArgKind::Lifetime(_) => None,
1636        }
1637    }
1638
1639    /// Tries to extract an inference variable from a type or a constant, returns `None`
1640    /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1641    /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1642    pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1643        match term.kind() {
1644            TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1645            TermKind::Const(ct) => Self::maybe_from_const(ct),
1646        }
1647    }
1648
1649    /// Tries to extract an inference variable from a type, returns `None`
1650    /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1651    fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1652        match *ty.kind() {
1653            ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1654            ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1655            ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1656            _ => None,
1657        }
1658    }
1659
1660    /// Tries to extract an inference variable from a constant, returns `None`
1661    /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1662    fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1663        match ct.kind() {
1664            ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1665            _ => None,
1666        }
1667    }
1668}
1669
1670/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1671/// Used only for diagnostics.
1672struct InferenceLiteralEraser<'tcx> {
1673    tcx: TyCtxt<'tcx>,
1674}
1675
1676impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1677    fn cx(&self) -> TyCtxt<'tcx> {
1678        self.tcx
1679    }
1680
1681    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1682        match ty.kind() {
1683            ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1684            ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1685            _ => ty.super_fold_with(self),
1686        }
1687    }
1688}
1689
1690impl<'tcx> TypeTrace<'tcx> {
1691    pub fn span(&self) -> Span {
1692        self.cause.span
1693    }
1694
1695    pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1696        TypeTrace {
1697            cause: cause.clone(),
1698            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1699        }
1700    }
1701
1702    pub fn trait_refs(
1703        cause: &ObligationCause<'tcx>,
1704        a: ty::TraitRef<'tcx>,
1705        b: ty::TraitRef<'tcx>,
1706    ) -> TypeTrace<'tcx> {
1707        TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1708    }
1709
1710    pub fn consts(
1711        cause: &ObligationCause<'tcx>,
1712        a: ty::Const<'tcx>,
1713        b: ty::Const<'tcx>,
1714    ) -> TypeTrace<'tcx> {
1715        TypeTrace {
1716            cause: cause.clone(),
1717            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1718        }
1719    }
1720}
1721
1722impl<'tcx> SubregionOrigin<'tcx> {
1723    pub fn span(&self) -> Span {
1724        match *self {
1725            SubregionOrigin::Subtype(ref a) => a.span(),
1726            SubregionOrigin::RelateObjectBound(a) => a,
1727            SubregionOrigin::RelateParamBound(a, ..) => a,
1728            SubregionOrigin::RelateRegionParamBound(a, _) => a,
1729            SubregionOrigin::Reborrow(a) => a,
1730            SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1731            SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1732            SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1733            SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1734            SubregionOrigin::SolverRegionConstraint(a) => a,
1735        }
1736    }
1737
1738    pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1739    where
1740        F: FnOnce() -> Self,
1741    {
1742        match *cause.code() {
1743            traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1744                SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1745            }
1746
1747            traits::ObligationCauseCode::CompareImplItem {
1748                impl_item_def_id,
1749                trait_item_def_id,
1750                kind: _,
1751            } => SubregionOrigin::CompareImplItemObligation {
1752                span: cause.span,
1753                impl_item_def_id,
1754                trait_item_def_id,
1755            },
1756
1757            traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1758                impl_item_def_id,
1759                trait_item_def_id,
1760            } => SubregionOrigin::CheckAssociatedTypeBounds {
1761                impl_item_def_id,
1762                trait_item_def_id,
1763                parent: Box::new(default()),
1764            },
1765
1766            traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1767                SubregionOrigin::AscribeUserTypeProvePredicate(span)
1768            }
1769
1770            traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1771                SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1772            }
1773
1774            _ => default(),
1775        }
1776    }
1777}
1778
1779impl<'tcx> RegionVariableOrigin<'tcx> {
1780    pub fn span(&self) -> Span {
1781        match *self {
1782            RegionVariableOrigin::Misc(a)
1783            | RegionVariableOrigin::PatternRegion(a)
1784            | RegionVariableOrigin::BorrowRegion(a)
1785            | RegionVariableOrigin::Autoref(a)
1786            | RegionVariableOrigin::Coercion(a)
1787            | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1788            | RegionVariableOrigin::BoundRegion(a, ..)
1789            | RegionVariableOrigin::UpvarRegion(_, a) => a,
1790            RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable used with `span`"))bug!("NLL variable used with `span`"),
1791        }
1792    }
1793}
1794
1795impl<'tcx> InferCtxt<'tcx> {
1796    /// Given a [`hir::Block`], get the span of its last expression or
1797    /// statement, peeling off any inner blocks.
1798    pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1799        let block = block.innermost_block();
1800        if let Some(expr) = &block.expr {
1801            expr.span
1802        } else if let Some(stmt) = block.stmts.last() {
1803            // possibly incorrect trailing `;` in the else arm
1804            stmt.span
1805        } else {
1806            // empty block; point at its entirety
1807            block.span
1808        }
1809    }
1810
1811    /// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1812    /// of its last expression or statement, peeling off any inner blocks.
1813    pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1814        match self.tcx.hir_node(hir_id) {
1815            hir::Node::Block(blk)
1816            | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1817                self.find_block_span(blk)
1818            }
1819            hir::Node::Expr(e) => e.span,
1820            _ => DUMMY_SP,
1821        }
1822    }
1823}
1824
1825type SolverRegionConstraint<'tcx> =
1826    rustc_type_ir::region_constraint::RegionConstraint<TyCtxt<'tcx>>;
1827
1828#[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)]
1829struct SolverRegionConstraintStorage<'tcx>(SolverRegionConstraint<'tcx>);
1830
1831impl<'tcx> SolverRegionConstraintStorage<'tcx> {
1832    fn new() -> Self {
1833        SolverRegionConstraintStorage(SolverRegionConstraint::And(Box::new([])))
1834    }
1835
1836    fn get_constraint(&self) -> SolverRegionConstraint<'tcx> {
1837        self.0.clone()
1838    }
1839
1840    fn pop(&mut self) -> Option<SolverRegionConstraint<'tcx>> {
1841        match &mut self.0 {
1842            SolverRegionConstraint::And(and) => {
1843                let mut and = core::mem::take(and).into_iter().collect::<Vec<_>>();
1844                let popped = and.pop()?;
1845                self.0 = SolverRegionConstraint::And(and.into_boxed_slice());
1846                Some(popped)
1847            }
1848            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1849        }
1850    }
1851
1852    #[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(1852u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("constraint")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("constraint");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint)
                                                            as &dyn ::tracing::field::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")]
1853    fn push(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1854        match &mut self.0 {
1855            SolverRegionConstraint::And(and) => {
1856                let and = core::mem::take(and)
1857                    .into_iter()
1858                    .chain([constraint])
1859                    .collect::<Vec<_>>()
1860                    .into_boxed_slice();
1861                self.0 = SolverRegionConstraint::And(and);
1862            }
1863            _ => unreachable!(),
1864        }
1865    }
1866
1867    #[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(1867u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("constraint")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("constraint");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint)
                                                            as &dyn ::tracing::field::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))]
1868    fn overwrite_solver_region_constraint(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1869        if !constraint.is_and() {
1870            self.0 = SolverRegionConstraint::And(vec![constraint].into_boxed_slice())
1871        } else {
1872            self.0 = constraint;
1873        }
1874    }
1875}