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::snapshot_vec as sv;
16use rustc_data_structures::undo_log::{Rollback, UndoLogs};
17use rustc_data_structures::unify::{self as ut, UnifyKey, UnifyValue};
18use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
19use rustc_hir::def_id::{DefId, LocalDefId};
20use rustc_hir::{self as hir, HirId};
21use rustc_index::IndexVec;
22use rustc_macros::extension;
23pub use rustc_macros::{TypeFoldable, TypeVisitable};
24use rustc_middle::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, OpaqueTypeKey, ProvisionalHiddenType,
32    PseudoCanonicalInput, Term, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable,
33    TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
34};
35use rustc_span::{DUMMY_SP, Span, Symbol, bug};
36use rustc_type_ir::{CanonicalizerState, MayBeErased};
37use snapshot::undo_log::InferCtxtUndoLogs;
38use tracing::{debug, instrument};
39use ty::solve::TyOrConstInferVar;
40use type_variable::TypeVariableOrigin;
41
42use crate::infer::snapshot::undo_log::UndoLog;
43use crate::infer::type_variable::{FloatVariableOrigin, TypeVariableValue};
44use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
45use crate::traits::{
46    self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
47    TraitEngine,
48};
49
50pub mod at;
51pub mod canonical;
52mod context;
53mod free_regions;
54mod freshen;
55mod lexical_region_resolve;
56mod opaque_types;
57pub mod outlives;
58mod projection;
59pub mod region_constraints;
60pub mod relate;
61pub mod resolve;
62pub(crate) mod snapshot;
63mod solver_region_constraints;
64mod type_variable;
65mod unify_key;
66
67pub use solver_region_constraints::SolverRegionConstraint;
68use solver_region_constraints::SolverRegionConstraintStorage;
69
70/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
71/// around `PredicateObligations<'tcx>`, but it has one important property:
72/// because `InferOk` is marked with `#[must_use]`, if you have a method
73/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
74/// `infcx.f()?;` you'll get a warning about the obligations being discarded
75/// without use, which is probably unintentional and has been a source of bugs
76/// in the past.
77#[must_use]
78#[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)]
79pub struct InferOk<'tcx, T> {
80    pub value: T,
81    pub obligations: PredicateObligations<'tcx>,
82}
83pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
84
85pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
86
87pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
88    ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
89>;
90
91/// This type contains all the things within [`InferCtxt`] that sit within a
92/// [`RefCell`] and are involved with taking/rolling back snapshots. Snapshot
93/// operations are hot enough that we want only one call to
94/// [`RefCell::borrow_mut`] per call to [`InferCtxt::start_snapshot`] and
95///  [`InferCtxt::rollback_to`].
96#[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)]
97pub struct InferCtxtInner<'tcx> {
98    undo_log: InferCtxtUndoLogs<'tcx>,
99
100    /// Cache for projections.
101    ///
102    /// This cache is snapshotted along with the infcx.
103    projection_cache: traits::ProjectionCacheStorage<'tcx>,
104
105    /// Primary map of inference variables to the types that they currently
106    /// represent.
107    ///
108    /// We instantiate [`UnificationTable`] with `bounds<Ty>` because the types
109    /// that might instantiate a general type variable have an order,
110    /// represented by its upper and lower bounds.
111    type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
112
113    /// Map from const parameter variable to the kind of const it represents.
114    const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
115
116    /// Map from integral variable to the kind of integer it represents.
117    int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
118
119    /// Map from floating variable to the kind of float it represents.
120    float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
121
122    /// Map from floating variable to the origin span it came from, and the HirId that should be
123    /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
124    /// so can be removed once the `f32` fallback is removed.
125    float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
126
127    /// Tracks the set of region variables and the constraints between them.
128    ///
129    /// This is initially `Some(_)` but when
130    /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
131    /// -- further attempts to perform unification, etc., may fail if new
132    /// region constraints would've been added.
133    region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
134
135    /// Used by the next solver when `-Zassumptions-on-binders` is set.
136    solver_region_constraint_storage: SolverRegionConstraintStorage<'tcx>,
137
138    /// A set of constraints that regionck must validate.
139    ///
140    /// Each constraint has the form `T:'a`, meaning "some type `T` must
141    /// outlive the lifetime 'a". These constraints derive from
142    /// instantiated type parameters. So if you had a struct defined
143    /// like the following:
144    /// ```ignore (illustrative)
145    /// struct Foo<T: 'static> { ... }
146    /// ```
147    /// In some expression `let x = Foo { ... }`, it will
148    /// instantiate the type parameter `T` with a fresh type `$0`. At
149    /// the same time, it will record a region obligation of
150    /// `$0: 'static`. This will get checked later by regionck. (We
151    /// can't generally check these things right away because we have
152    /// to wait until types are resolved.)
153    region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
154
155    /// The outlives bounds that we assume must hold about placeholders that
156    /// come from instantiating the binder of coroutine-witnesses. These bounds
157    /// are deduced from the well-formedness of the witness's types, and are
158    /// necessary because of the way we anonymize the regions in a coroutine,
159    /// which may cause types to no longer be considered well-formed.
160    region_assumptions: Vec<ty::ArgOutlivesClause<'tcx>>,
161
162    /// `-Znext-solver`: Successfully proven goals during HIR typeck which
163    /// reference inference variables and get reproven in case MIR type check
164    /// fails to prove something.
165    ///
166    /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
167    hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
168
169    /// Caches for opaque type inference.
170    opaque_type_storage: OpaqueTypeStorage<'tcx>,
171}
172
173impl<'tcx> InferCtxtInner<'tcx> {
174    fn new() -> InferCtxtInner<'tcx> {
175        InferCtxtInner {
176            undo_log: InferCtxtUndoLogs::default(),
177
178            projection_cache: Default::default(),
179            type_variable_storage: Default::default(),
180            const_unification_storage: Default::default(),
181            int_unification_storage: Default::default(),
182            float_unification_storage: Default::default(),
183            float_origin_origin_storage: Default::default(),
184            region_constraint_storage: Some(Default::default()),
185            solver_region_constraint_storage: SolverRegionConstraintStorage::new(),
186            region_obligations: Default::default(),
187            region_assumptions: Default::default(),
188            hir_typeck_potentially_region_dependent_goals: Default::default(),
189            opaque_type_storage: Default::default(),
190        }
191    }
192
193    #[inline]
194    pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
195        &self.region_obligations
196    }
197
198    #[inline]
199    pub fn region_assumptions(&self) -> &[ty::ArgOutlivesClause<'tcx>] {
200        &self.region_assumptions
201    }
202
203    #[inline]
204    pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
205        self.projection_cache.with_log(&mut self.undo_log)
206    }
207
208    #[inline]
209    fn try_type_variables_probe_ref(&self, vid: ty::TyVid) -> Option<&TypeVariableValue<'tcx>> {
210        // Uses a read-only view of the unification table, this way we don't
211        // need an undo log.
212        self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
213    }
214
215    #[inline]
216    fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
217        self.type_variable_storage.with_log(&mut self.undo_log)
218    }
219
220    #[inline]
221    pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
222        self.opaque_type_storage.with_log(&mut self.undo_log)
223    }
224
225    #[inline]
226    fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
227        self.int_unification_storage.with_log(&mut self.undo_log)
228    }
229
230    #[inline]
231    fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
232        self.float_unification_storage.with_log(&mut self.undo_log)
233    }
234
235    #[inline]
236    fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
237        self.const_unification_storage.with_log(&mut self.undo_log)
238    }
239
240    #[inline]
241    pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
242        self.region_constraint_storage
243            .as_mut()
244            .expect("region constraints already solved")
245            .with_log(&mut self.undo_log)
246    }
247}
248
249pub struct InferCtxt<'tcx> {
250    pub tcx: TyCtxt<'tcx>,
251
252    /// The mode of this inference context, see the struct documentation
253    /// for more details.
254    typing_mode: TypingMode<'tcx>,
255
256    /// Whether this inference context should care about region obligations in
257    /// the root universe. Most notably, this is used during HIR typeck as region
258    /// solving is left to borrowck instead.
259    ///
260    /// This is used in the old solver to enable the generation of regions constraints.
261    /// In the new solver its only used inside the InferCtxt's `Drop` implementation:
262    /// if we're considering regions, and new opaques are registered, we panic.
263    pub considering_regions: bool,
264    /// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
265    /// need to make sure we don't rely on region identity in the trait solver or when
266    /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
267    /// free region with a unique inference variable. If HIR typeck ends up depending on two
268    /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
269    /// resulting in an ICE.
270    ///
271    /// The trait solver sometimes depends on regions being identical. As a concrete example
272    /// the trait solver ignores other candidates if one candidate exists without any constraints.
273    /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
274    /// occurrence of `'a` with a unique region the goal now equates these regions. See
275    /// the tests in trait-system-refactor-initiative#27 for concrete examples.
276    ///
277    /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
278    /// This is still insufficient as inference variables may *hide* region variables, so e.g.
279    /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
280    /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
281    /// stash all successfully proven goals which reference inference variables and then reprove
282    /// them after writeback.
283    pub in_hir_typeck: bool,
284
285    /// If set, this flag causes us to skip the 'leak check' during
286    /// higher-ranked subtyping operations. This flag is a temporary one used
287    /// to manage the removal of the leak-check: for the time being, we still run the
288    /// leak-check, but we issue warnings.
289    skip_leak_check: bool,
290
291    pub inner: RefCell<InferCtxtInner<'tcx>>,
292
293    /// Once region inference is done, the values for each variable.
294    lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
295
296    /// Caches the results of trait selection. This cache is used
297    /// for things that depends on inference variables or placeholders.
298    pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
299
300    /// Caches the results of trait evaluation. This cache is used
301    /// for things that depends on inference variables or placeholders.
302    pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
303
304    /// The set of predicates on which errors have been reported, to
305    /// avoid reporting the same error twice.
306    pub reported_trait_errors:
307        RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
308
309    pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
310
311    /// When an error occurs, we want to avoid reporting "derived"
312    /// errors that are due to this original failure. We have this
313    /// flag that one can set whenever one creates a type-error that
314    /// is due to an error in a prior pass.
315    ///
316    /// Don't read this flag directly, call `is_tainted_by_errors()`
317    /// and `set_tainted_by_errors()`.
318    tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
319
320    /// What is the innermost universe we have created? Starts out as
321    /// `UniverseIndex::root()` but grows from there as we enter
322    /// universal quantifiers.
323    ///
324    /// N.B., at present, we exclude the universal quantifiers on the
325    /// item we are type-checking, and just consider those names as
326    /// part of the root universe. So this would only get incremented
327    /// when we enter into a higher-ranked (`for<..>`) type or trait
328    /// bound.
329    universe: Cell<ty::UniverseIndex>,
330
331    /// List of assumed wellformed types which we can derive implied
332    /// bounds on a `for<...>` from. Only used unstabley and by the
333    /// new solver.
334    //
335    // FIXME(-Zassumptions-on-binders): This and `universe` should probably be
336    // in `InferCtxtInner` so they can participate in rollbacks and whatnot
337    placeholder_assumptions_for_next_solver: RefCell<
338        FxIndexMap<
339            ty::UniverseIndex,
340            Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
341        >,
342    >,
343
344    next_trait_solver: bool,
345
346    /// We have a `recursion_depth_exceeding_limit` FCW to mitigate breakages
347    /// caused by enabling the next solver globally. But the next solver is
348    /// already used by default in some places so we know they won't have
349    /// additional breakages. We also don't want spurious result in coherence
350    /// checking so we disable the FCW there as well.
351    enable_next_solver_overflow_fcw: Cell<bool>,
352
353    pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
354
355    /// State reused by each new canonicalizer, and then cleared (but not deallocated) once the
356    /// canonicalizer is finished. A performance win, because it avoids reallocating new
357    /// vecs/hashmaps for every canonicalizer.
358    pub canonicalizer_state: RefCell<CanonicalizerState<TyCtxt<'tcx>>>,
359}
360
361impl<'tcx> Drop for InferCtxt<'tcx> {
362    fn drop(&mut self) {
363        let mut inner = self.inner.borrow_mut();
364        let opaque_type_storage = &mut inner.opaque_type_storage;
365
366        // No need for the drop bomb when we're in `TypingMode::PostTypeckUntilBorrowck`, and the `InferCtxt`
367        // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
368        // in relation to regions. In some places *after* typeck that aren't borrowck, we use
369        // `TypingMode::PostTypeckUntilBorrowck` to prevent defining opaque types and we simply don't care about regions.
370        match self.typing_mode_raw() {
371            TypingMode::Coherence
372            | TypingMode::Typeck { .. }
373            | TypingMode::PostBorrowck { .. }
374            | TypingMode::Reflection
375            | TypingMode::PostAnalysis
376            | TypingMode::Codegen => {}
377            // In erased mode, the opaque type storage is always empty
378            TypingMode::ErasedNotCoherence(..) => {}
379            TypingMode::PostTypeckUntilBorrowck { .. } => {
380                if !self.considering_regions {
381                    return;
382                }
383            }
384        }
385
386        if !opaque_type_storage.is_empty() {
387            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:?}")));
388        }
389    }
390}
391
392/// See the `error_reporting` module for more details.
393#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for ValuePairs<'tcx> { }
#[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::marker::StructuralPartialEq for ValuePairs<'tcx> { }
#[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)]
394pub enum ValuePairs<'tcx> {
395    Regions(ExpectedFound<ty::Region<'tcx>>),
396    Terms(ExpectedFound<ty::Term<'tcx>>),
397    Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
398    TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
399    PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
400    ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
401    ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
402}
403
404impl<'tcx> ValuePairs<'tcx> {
405    pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
406        if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
407            && let Some(expected) = expected.as_type()
408            && let Some(found) = found.as_type()
409        {
410            Some((expected, found))
411        } else {
412            None
413        }
414    }
415}
416
417/// The trace designates the path through inference that we took to
418/// encounter an error or subtyping constraint.
419///
420/// See the `error_reporting` module for more details.
421#[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)]
422pub struct TypeTrace<'tcx> {
423    pub cause: ObligationCause<'tcx>,
424    pub values: ValuePairs<'tcx>,
425}
426
427/// The origin of a `r1 <= r2` constraint.
428///
429/// See `error_reporting` module for more details
430#[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)]
431pub enum SubregionOrigin<'tcx> {
432    /// Arose from a subtyping relation
433    Subtype(Box<TypeTrace<'tcx>>),
434
435    /// When casting `&'a T` to an `&'b Trait` object,
436    /// relating `'a` to `'b`.
437    RelateObjectBound(Span),
438
439    /// Some type parameter was instantiated with the given type,
440    /// and that type must outlive some region.
441    RelateParamBound(Span, Ty<'tcx>, Option<Span>),
442
443    /// The given region parameter was instantiated with a region
444    /// that must outlive some other region.
445    RelateRegionParamBound(Span, Option<Ty<'tcx>>),
446
447    /// Creating a pointer `b` to contents of another reference.
448    Reborrow(Span),
449
450    /// (&'a &'b T) where a >= b
451    ReferenceOutlivesReferent(Ty<'tcx>, Span),
452
453    /// Comparing the signature and requirements of an impl method against
454    /// the containing trait.
455    CompareImplItemObligation {
456        span: Span,
457        impl_item_def_id: LocalDefId,
458        trait_item_def_id: DefId,
459    },
460
461    /// Checking that the bounds of a trait's associated type hold for a given impl.
462    CheckAssociatedTypeBounds {
463        parent: Box<SubregionOrigin<'tcx>>,
464        impl_item_def_id: LocalDefId,
465        trait_item_def_id: DefId,
466    },
467
468    AscribeUserTypeProvePredicate(Span),
469
470    // FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
471    // proper diagnostics for solver region constraints.
472    SolverRegionConstraint(Span),
473}
474
475// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
476#[cfg(target_pointer_width = "64")]
477const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
478
479impl<'tcx> SubregionOrigin<'tcx> {
480    pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
481        match self {
482            Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
483            Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
484            Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
485            _ => ConstraintCategory::BoringNoLocation,
486        }
487    }
488}
489
490/// Times when we replace bound regions with existentials:
491#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BoundRegionConversionTime { }
#[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)]
492pub enum BoundRegionConversionTime {
493    /// when a fn is called
494    FnCall,
495
496    /// when two higher-ranked types are compared
497    HigherRankedType,
498
499    /// when projecting an associated type
500    AssocTypeProjection(DefId),
501}
502
503/// Reasons to create a region inference variable.
504///
505/// See `error_reporting` module for more details.
506#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for RegionVariableOrigin<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for RegionVariableOrigin<'tcx> {
}
#[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)]
507pub enum RegionVariableOrigin<'tcx> {
508    /// Region variables created for ill-categorized reasons.
509    ///
510    /// They mostly indicate places in need of refactoring.
511    Misc(Span),
512
513    /// Regions created by a `&P` or `[...]` pattern.
514    PatternRegion(Span),
515
516    /// Regions created by `&` operator.
517    BorrowRegion(Span),
518
519    /// Regions created as part of an autoref of a method receiver.
520    Autoref(Span),
521
522    /// Regions created as part of an automatic coercion.
523    Coercion(Span),
524
525    /// Region variables created as the values for early-bound regions.
526    ///
527    /// FIXME(@lcnr): This should also store a `DefId`, similar to
528    /// `TypeVariableOrigin`.
529    RegionParameterDefinition(Span, Symbol),
530
531    /// Region variables created when instantiating a binder with
532    /// existential variables, e.g. when calling a function or method.
533    BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
534
535    UpvarRegion(ty::UpvarId, Span),
536
537    /// This origin is used for the inference variables that we create
538    /// during NLL region processing.
539    Nll(NllRegionVariableOrigin<'tcx>),
540}
541
542#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for NllRegionVariableOrigin<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for
    NllRegionVariableOrigin<'tcx> {
}
#[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)]
543pub enum NllRegionVariableOrigin<'tcx> {
544    /// During NLL region processing, we create variables for free
545    /// regions that we encounter in the function signature and
546    /// elsewhere. This origin indices we've got one of those.
547    FreeRegion,
548
549    /// "Universal" instantiation of a higher-ranked region (e.g.,
550    /// from a `for<'a> T` binder). Meant to represent "any region".
551    Placeholder(ty::PlaceholderRegion<'tcx>),
552
553    Existential {
554        name: Option<Symbol>,
555    },
556}
557
558#[derive(#[automatically_derived]
impl ::core::marker::Copy for FixupError { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for FixupError { }
#[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)]
559pub struct FixupError {
560    unresolved: TyOrConstInferVar,
561}
562
563impl fmt::Display for FixupError {
564    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
565        match self.unresolved {
566            TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
567                f,
568                "cannot determine the type of this integer; \
569                 add a suffix to specify the type explicitly"
570            ),
571            TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
572                f,
573                "cannot determine the type of this number; \
574                 add a suffix to specify the type explicitly"
575            ),
576            TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
577            TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
578        }
579    }
580}
581
582/// See the `region_obligations` field for more information.
583#[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)]
584pub struct TypeOutlivesConstraint<'tcx> {
585    pub sub_region: ty::Region<'tcx>,
586    pub sup_type: Ty<'tcx>,
587    pub origin: SubregionOrigin<'tcx>,
588}
589
590/// Used to configure inference contexts before their creation.
591pub struct InferCtxtBuilder<'tcx> {
592    tcx: TyCtxt<'tcx>,
593    considering_regions: bool,
594    in_hir_typeck: bool,
595    skip_leak_check: bool,
596    /// Whether we should use the new trait solver in the local inference context,
597    /// which affects things like which solver is used in `predicate_may_hold`.
598    next_trait_solver: bool,
599    enable_next_solver_overflow_fcw: bool,
600}
601
602pub trait TyCtxtInferExt<'tcx> {
    fn infer_ctxt(self)
    -> InferCtxtBuilder<'tcx>;
}
impl<'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(),
            enable_next_solver_overflow_fcw: true,
        }
    }
}#[extension(pub trait TyCtxtInferExt<'tcx>)]
603impl<'tcx> TyCtxt<'tcx> {
604    fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
605        InferCtxtBuilder {
606            tcx: self,
607            considering_regions: true,
608            in_hir_typeck: false,
609            skip_leak_check: false,
610            next_trait_solver: self.next_trait_solver_globally(),
611            enable_next_solver_overflow_fcw: true,
612        }
613    }
614}
615
616impl<'tcx> InferCtxtBuilder<'tcx> {
617    pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
618        self.next_trait_solver = next_trait_solver;
619        self
620    }
621
622    pub fn enable_next_solver_overflow_fcw(
623        mut self,
624        enable_next_solver_overflow_fcw: bool,
625    ) -> Self {
626        self.enable_next_solver_overflow_fcw = enable_next_solver_overflow_fcw;
627        self
628    }
629
630    pub fn ignoring_regions(mut self) -> Self {
631        self.considering_regions = false;
632        self
633    }
634
635    pub fn in_hir_typeck(mut self) -> Self {
636        self.in_hir_typeck = true;
637        self
638    }
639
640    pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
641        self.skip_leak_check = skip_leak_check;
642        self
643    }
644
645    /// Given a canonical value `C` as a starting point, create an
646    /// inference context that contains each of the bound values
647    /// within instantiated as a fresh variable. The `f` closure is
648    /// invoked with the new infcx, along with the instantiated value
649    /// `V` and a instantiation `S`. This instantiation `S` maps from
650    /// the bound values in `C` to their instantiated values in `V`
651    /// (in other words, `S(C) = V`).
652    pub fn build_with_canonical<T>(
653        mut self,
654        span: Span,
655        input: &CanonicalQueryInput<'tcx, T>,
656    ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
657    where
658        T: TypeFoldable<TyCtxt<'tcx>>,
659    {
660        let infcx = self.build(input.typing_mode.0);
661        let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
662        (infcx, value, args)
663    }
664
665    pub fn build_with_typing_env(
666        mut self,
667        typing_env: TypingEnv<'tcx>,
668    ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
669        (self.build(typing_env.typing_mode()), typing_env.param_env)
670    }
671
672    pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
673        let InferCtxtBuilder {
674            tcx,
675            considering_regions,
676            in_hir_typeck,
677            skip_leak_check,
678            next_trait_solver,
679            enable_next_solver_overflow_fcw,
680        } = *self;
681        InferCtxt {
682            tcx,
683            typing_mode,
684            considering_regions,
685            in_hir_typeck,
686            skip_leak_check,
687            inner: RefCell::new(InferCtxtInner::new()),
688            lexical_region_resolutions: RefCell::new(None),
689            selection_cache: Default::default(),
690            evaluation_cache: Default::default(),
691            reported_trait_errors: Default::default(),
692            reported_signature_mismatch: Default::default(),
693            tainted_by_errors: Cell::new(None),
694            universe: Cell::new(ty::UniverseIndex::ROOT),
695            placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
696            next_trait_solver,
697            enable_next_solver_overflow_fcw: Cell::new(enable_next_solver_overflow_fcw),
698            obligation_inspector: Cell::new(None),
699            canonicalizer_state: Default::default(),
700        }
701    }
702}
703
704impl<'tcx, T> InferOk<'tcx, T> {
705    /// Extracts `value`, registering any obligations into `fulfill_cx`.
706    pub fn into_value_registering_obligations<E: 'tcx>(
707        self,
708        infcx: &InferCtxt<'tcx>,
709        fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
710    ) -> T {
711        let InferOk { value, obligations } = self;
712        fulfill_cx.register_predicate_obligations(infcx, obligations);
713        value
714    }
715}
716
717impl<'tcx> InferOk<'tcx, ()> {
718    pub fn into_obligations(self) -> PredicateObligations<'tcx> {
719        self.obligations
720    }
721}
722
723impl<'tcx> InferCtxt<'tcx> {
724    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
725        self.tcx.dcx().into_taintable(&self.tainted_by_errors)
726    }
727
728    pub fn next_trait_solver(&self) -> bool {
729        self.next_trait_solver
730    }
731
732    /// This method is deliberately called `..._raw`,
733    /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
734    /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
735    /// more information.
736    ///
737    /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
738    /// works as a kind of store for for example type unification information.
739    /// `InferCtxt` is also often used outside the trait solver during typeck.
740    /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
741    /// To make sure these two uses are never confused, we want to statically encode this information.
742    ///
743    /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
744    /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
745    /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
746    /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
747    /// match on the variant and can safely ignore it.
748    ///
749    /// Prefer non-raw apis if available. e.g.,
750    /// - On the `FnCtxt`
751    /// - on the `SelectionCtxt`
752    #[inline(always)]
753    pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
754        self.typing_mode
755    }
756
757    #[inline(always)]
758    pub fn disable_trait_solver_fast_paths(&self) -> bool {
759        self.tcx.disable_trait_solver_fast_paths()
760    }
761
762    /// Returns the origin of the type variable identified by `vid`.
763    ///
764    /// No attempt is made to resolve `vid` to its root variable.
765    pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
766        self.inner.borrow_mut().type_variables().var_origin(vid)
767    }
768
769    /// Returns the origin of the float type variable identified by `vid`.
770    ///
771    /// No attempt is made to resolve `vid` to its root variable.
772    pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
773        self.inner.borrow_mut().float_origin_origin_storage[vid]
774    }
775
776    /// Returns the origin of the const variable identified by `vid`
777    // FIXME: We should store origins separately from the unification table
778    // so this doesn't need to be optional.
779    pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
780        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
781            ConstVariableValue::Known { .. } => None,
782            ConstVariableValue::Unknown { origin, .. } => Some(origin),
783        }
784    }
785
786    pub fn unresolved_root_variables(&self) -> (Vec<TyVid>, Vec<ty::IntVid>, Vec<ty::FloatVid>) {
787        let mut inner = self.inner.borrow_mut();
788
789        let ty = inner.type_variables().unresolved_root_variables();
790
791        let int = unresolved_root_variables_of(
792            inner.int_unification_table(),
793            ty::IntVarValue::is_unknown,
794        );
795
796        let float = unresolved_root_variables_of(
797            inner.float_unification_table(),
798            ty::FloatVarValue::is_unknown,
799        );
800
801        (ty, int, float)
802    }
803
804    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(804u32),
                                    ::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")]
805    pub fn sub_regions(
806        &self,
807        origin: SubregionOrigin<'tcx>,
808        a: ty::Region<'tcx>,
809        b: ty::Region<'tcx>,
810        vis: ty::VisibleForLeakCheck,
811    ) {
812        self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
813    }
814
815    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(815u32),
                                    ::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")]
816    pub fn equate_regions(
817        &self,
818        origin: SubregionOrigin<'tcx>,
819        a: ty::Region<'tcx>,
820        b: ty::Region<'tcx>,
821        vis: ty::VisibleForLeakCheck,
822    ) {
823        self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
824    }
825
826    /// Processes a `Coerce` predicate from the fulfillment context.
827    /// This is NOT the preferred way to handle coercion, which is to
828    /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
829    ///
830    /// This method here is actually a fallback that winds up being
831    /// invoked when `FnCtxt::coerce` encounters unresolved type variables
832    /// and records a coercion predicate. Presently, this method is equivalent
833    /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
834    /// actually requiring `a <: b`. This is of course a valid coercion,
835    /// but it's not as flexible as `FnCtxt::coerce` would be.
836    ///
837    /// (We may refactor this in the future, but there are a number of
838    /// practical obstacles. Among other things, `FnCtxt::coerce` presently
839    /// records adjustments that are required on the HIR in order to perform
840    /// the coercion, and we don't currently have a way to manage that.)
841    pub fn coerce_predicate(
842        &self,
843        cause: &ObligationCause<'tcx>,
844        param_env: ty::ParamEnv<'tcx>,
845        predicate: ty::PolyCoercePredicate<'tcx>,
846    ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
847        let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
848            a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
849            a: p.a,
850            b: p.b,
851        });
852        self.subtype_predicate(cause, param_env, subtype_predicate)
853    }
854
855    pub fn subtype_predicate(
856        &self,
857        cause: &ObligationCause<'tcx>,
858        param_env: ty::ParamEnv<'tcx>,
859        predicate: ty::PolySubtypePredicate<'tcx>,
860    ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
861        // Check for two unresolved inference variables, in which case we can
862        // make no progress. This is partly a micro-optimization, but it's
863        // also an opportunity to "sub-unify" the variables. This isn't
864        // *necessary* to prevent cycles, because they would eventually be sub-unified
865        // anyhow during generalization, but it helps with diagnostics (we can detect
866        // earlier that they are sub-unified).
867        //
868        // Note that we can just skip the binders here because
869        // type variables can't (at present, at
870        // least) capture any of the things bound by this binder.
871        //
872        // Note that this sub here is not just for diagnostics - it has semantic
873        // effects as well.
874        let r_a = self.shallow_resolve(predicate.skip_binder().a);
875        let r_b = self.shallow_resolve(predicate.skip_binder().b);
876        match (r_a.kind(), r_b.kind()) {
877            (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
878                self.sub_unify_ty_vids_raw(a_vid, b_vid);
879                return Err((a_vid, b_vid));
880            }
881            _ => {}
882        }
883
884        self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
885            if a_is_expected {
886                Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
887            } else {
888                Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
889            }
890        })
891    }
892
893    /// Number of type variables created so far.
894    pub fn num_ty_vars(&self) -> usize {
895        self.inner.borrow_mut().type_variables().num_vars()
896    }
897
898    pub fn next_ty_vid(&self, span: Span) -> TyVid {
899        self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
900    }
901
902    pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
903        self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
904    }
905
906    pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
907        let origin = TypeVariableOrigin { span, param_def_id: None };
908        self.inner.borrow_mut().type_variables().new_var(universe, origin)
909    }
910
911    pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
912        self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
913    }
914
915    pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
916        let vid = self.next_ty_vid_with_origin(origin);
917        Ty::new_var(self.tcx, vid)
918    }
919
920    pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
921        let vid = self.next_ty_vid_in_universe(span, universe);
922        Ty::new_var(self.tcx, vid)
923    }
924
925    pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
926        self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
927    }
928
929    pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
930        let vid = self
931            .inner
932            .borrow_mut()
933            .const_unification_table()
934            .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
935            .vid;
936        ty::Const::new_var(self.tcx, vid)
937    }
938
939    pub fn next_const_var_in_universe(
940        &self,
941        span: Span,
942        universe: ty::UniverseIndex,
943    ) -> ty::Const<'tcx> {
944        let origin = ConstVariableOrigin { span, param_def_id: None };
945        let vid = self
946            .inner
947            .borrow_mut()
948            .const_unification_table()
949            .new_key(ConstVariableValue::Unknown { origin, universe })
950            .vid;
951        ty::Const::new_var(self.tcx, vid)
952    }
953
954    pub fn next_int_var(&self) -> Ty<'tcx> {
955        let next_int_var_id =
956            self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
957        Ty::new_int_var(self.tcx, next_int_var_id)
958    }
959
960    pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
961        let mut inner = self.inner.borrow_mut();
962        let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
963        let origin = FloatVariableOrigin { span, lint_id };
964        let span_index = inner.float_origin_origin_storage.push(origin);
965        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);
966        Ty::new_float_var(self.tcx, next_float_var_id)
967    }
968
969    /// Creates a fresh region variable with the next available index.
970    /// The variable will be created in the maximum universe created
971    /// thus far, allowing it to name any region created thus far.
972    pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
973        self.next_region_var_in_universe(origin, self.universe())
974    }
975
976    /// Creates a fresh region variable with the next available index
977    /// in the given universe; typically, you can use
978    /// `next_region_var` and just use the maximal universe.
979    pub fn next_region_var_in_universe(
980        &self,
981        origin: RegionVariableOrigin<'tcx>,
982        universe: ty::UniverseIndex,
983    ) -> ty::Region<'tcx> {
984        let region_var =
985            self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
986        ty::Region::new_var(self.tcx, region_var)
987    }
988
989    pub fn next_term_var_of_alias_kind(
990        &self,
991        alias_term: ty::AliasTerm<'tcx>,
992        span: Span,
993    ) -> ty::Term<'tcx> {
994        match alias_term.kind {
995            ty::AliasTermKind::ProjectionTy { .. }
996            | ty::AliasTermKind::InherentTy { .. }
997            | ty::AliasTermKind::OpaqueTy { .. }
998            | ty::AliasTermKind::FreeTy { .. } => self.next_ty_var(span).into(),
999            ty::AliasTermKind::FreeConst { .. }
1000            | ty::AliasTermKind::InherentConstSelf { .. }
1001            | ty::AliasTermKind::InherentConstImpl { .. }
1002            | ty::AliasTermKind::AnonConst { .. }
1003            | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_var(span).into(),
1004        }
1005    }
1006
1007    /// Return the universe that the region `r` was created in. For
1008    /// most regions (e.g., `'static`, named regions from the user,
1009    /// etc) this is the root universe U0. For inference variables or
1010    /// placeholders, however, it will return the universe which they
1011    /// are associated.
1012    pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1013        self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1014    }
1015
1016    /// Number of region variables created so far.
1017    pub fn num_region_vars(&self) -> usize {
1018        self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1019    }
1020
1021    /// Just a convenient wrapper of `next_region_var` for using during NLL.
1022    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1022u32),
                                    ::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")]
1023    pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
1024        self.next_region_var(RegionVariableOrigin::Nll(origin))
1025    }
1026
1027    /// Just a convenient wrapper of `next_region_var` for using during NLL.
1028    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1028u32),
                                    ::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")]
1029    pub fn next_nll_region_var_in_universe(
1030        &self,
1031        origin: NllRegionVariableOrigin<'tcx>,
1032        universe: ty::UniverseIndex,
1033    ) -> ty::Region<'tcx> {
1034        self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1035    }
1036
1037    pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1038        match param.kind {
1039            GenericParamDefKind::Lifetime => {
1040                // Create a region inference variable for the given
1041                // region parameter definition.
1042                self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1043                    span, param.name,
1044                ))
1045                .into()
1046            }
1047            GenericParamDefKind::Type { .. } => {
1048                // Create a type inference variable for the given
1049                // type parameter definition. The generic parameters are
1050                // for actual parameters that may be referred to by
1051                // the default of this type parameter, if it exists.
1052                // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1053                // used in a path such as `Foo::<T, U>::new()` will
1054                // use an inference variable for `C` with `[T, U]`
1055                // as the generic parameters for the default, `(T, U)`.
1056                let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1057                    self.universe(),
1058                    TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1059                );
1060
1061                Ty::new_var(self.tcx, ty_var_id).into()
1062            }
1063            GenericParamDefKind::Const { .. } => {
1064                let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1065                let const_var_id = self
1066                    .inner
1067                    .borrow_mut()
1068                    .const_unification_table()
1069                    .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1070                    .vid;
1071                ty::Const::new_var(self.tcx, const_var_id).into()
1072            }
1073        }
1074    }
1075
1076    /// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1077    /// each type/region parameter to a fresh inference variable.
1078    pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
1079        GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1080    }
1081
1082    /// Returns `true` if errors have been reported since this infcx was
1083    /// created. This is sometimes used as a heuristic to skip
1084    /// reporting errors that often occur as a result of earlier
1085    /// errors, but where it's hard to be 100% sure (e.g., unresolved
1086    /// inference variables, regionck errors).
1087    #[must_use = "this method does not have any side effects"]
1088    pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1089        self.tainted_by_errors.get()
1090    }
1091
1092    /// Set the "tainted by errors" flag to true. We call this when we
1093    /// observe an error from a prior pass.
1094    pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1095        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs:1095",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1095u32),
                        ::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)");
1096        self.tainted_by_errors.set(Some(e));
1097    }
1098
1099    pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1100        let mut inner = self.inner.borrow_mut();
1101        let inner = &mut *inner;
1102        inner.unwrap_region_constraints().var_origin(vid)
1103    }
1104
1105    /// Clone the list of variable regions. This is used only during NLL processing
1106    /// to put the set of region variables into the NLL region context.
1107    pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1108        let inner = self.inner.borrow();
1109        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));
1110        let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1111        if !storage.data.is_empty() {
    { ::core::panicking::panic_fmt(format_args!("{0:#?}", storage.data)); }
};assert!(storage.data.is_empty(), "{:#?}", storage.data);
1112        // We clone instead of taking because borrowck still wants to use the
1113        // inference context after calling this for diagnostics and the new
1114        // trait solver.
1115        storage.var_infos.clone()
1116    }
1117
1118    pub fn has_opaque_types_in_storage(&self) -> bool {
1119        !self.inner.borrow().opaque_type_storage.is_empty()
1120    }
1121
1122    {}
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("take_opaque_types",
                                "rustc_infer::infer", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(1122u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                ::tracing_core::field::FieldSet::new(&[],
                                    ::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,
                    &{ meta.fields().value_set_all(&[]) })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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:
                                Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs:1122",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1122u32),
                        ::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("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
1123    pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1124        self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1125    }
1126
1127    {}
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("clone_opaque_types",
                                "rustc_infer::infer", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(1127u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                ::tracing_core::field::FieldSet::new(&[],
                                    ::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,
                    &{ meta.fields().value_set_all(&[]) })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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:
                                Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs:1127",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1127u32),
                        ::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("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
1128    pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1129        self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1130    }
1131
1132    pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1133        if !self.next_trait_solver() {
1134            return false;
1135        }
1136
1137        let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1138        let inner = &mut *self.inner.borrow_mut();
1139        let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1140        inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1141            if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1142                let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1143                if opaque_sub_vid == ty_sub_vid {
1144                    return true;
1145                }
1146            }
1147
1148            false
1149        })
1150    }
1151
1152    /// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1153    ///
1154    /// This only checks for a subtype relation, it does not require equality.
1155    pub fn opaques_with_sub_unified_hidden_type(
1156        &self,
1157        ty_vid: TyVid,
1158    ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1159        // Avoid accidentally allowing more code to compile with the old solver.
1160        if !self.next_trait_solver() {
1161            return ::alloc::vec::Vec::new()vec![];
1162        }
1163
1164        let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1165        let inner = &mut *self.inner.borrow_mut();
1166        // This is iffy, can't call `type_variables()` as we're already
1167        // borrowing the `opaque_type_storage` here.
1168        let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1169        inner
1170            .opaque_type_storage
1171            .iter_opaque_types()
1172            .filter_map(|(key, hidden_ty)| {
1173                if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1174                    let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1175                    if opaque_sub_vid == ty_sub_vid {
1176                        return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1177                            self.tcx,
1178                            key.def_id.into(),
1179                            key.args,
1180                        ));
1181                    }
1182                }
1183
1184                None
1185            })
1186            .collect()
1187    }
1188
1189    #[inline(always)]
1190    pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1191        if true {
    if !!self.next_trait_solver() {
        ::core::panicking::panic("assertion failed: !self.next_trait_solver()")
    };
};debug_assert!(!self.next_trait_solver());
1192        match self.typing_mode_raw().assert_not_erased() {
1193            TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1194            | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types } => {
1195                id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1196            }
1197            // FIXME(#132279): This function is quite weird in post-analysis
1198            // and post-borrowck analysis mode. We may need to modify its uses
1199            // to support PostBorrowck in the old solver as well.
1200            TypingMode::Coherence
1201            | TypingMode::Reflection
1202            | TypingMode::PostBorrowck { .. }
1203            | TypingMode::PostAnalysis
1204            | TypingMode::Codegen => false,
1205        }
1206    }
1207
1208    pub fn push_hir_typeck_potentially_region_dependent_goal(
1209        &self,
1210        goal: PredicateObligation<'tcx>,
1211    ) {
1212        let mut inner = self.inner.borrow_mut();
1213        inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1214        inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1215    }
1216
1217    pub fn take_hir_typeck_potentially_region_dependent_goals(
1218        &self,
1219    ) -> Vec<PredicateObligation<'tcx>> {
1220        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");
1221        std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1222    }
1223
1224    pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1225        self.deeply_resolve_ignoring_regions(t).to_string()
1226    }
1227
1228    /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1229    /// universe index of `TyVar(vid)`.
1230    pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1231        use self::type_variable::TypeVariableValue;
1232
1233        match self.inner.borrow_mut().type_variables().probe(vid) {
1234            TypeVariableValue::Known { value } => Ok(value),
1235            TypeVariableValue::Unknown { universe } => Err(universe),
1236        }
1237    }
1238
1239    /// If `vid` resolves to a type, return that type. Otherwise return the root variable id for `vid`.
1240    pub fn shallow_resolve_ty_var_or_get_root(&self, vid: TyVid) -> Result<Ty<'tcx>, TyVid> {
1241        let (root, value) = self.inner.borrow_mut().type_variables().probe_with_root_vid(vid);
1242
1243        match value {
1244            TypeVariableValue::Known { value } => Ok(value),
1245            TypeVariableValue::Unknown { universe: _ } => Err(root),
1246        }
1247    }
1248
1249    /// Resolve a type variable. Resolving means the following:
1250    ///
1251    /// - If a `Ty` is a rigid type (like, an integer, or some ADT), do nothing.
1252    /// - If a `Ty` is a type infer variable, but has been equated with an actual type,
1253    ///   return that type.
1254    /// - If a `Ty` is an int or float infer variable, and has been equated with an integer
1255    ///   or floating point type, return that type.
1256    /// - If a `Ty` is any kind of infer variable that has been equated, but not yet with a rigid
1257    ///   type, then this set of equated variables forms an equivalence class. One of the variables
1258    ///   in that equivalent class is said to be the root variable, and resolving makes sure to
1259    ///   consistently return this root variable. This is beneficial for caching.
1260    ///   This behavior, of returning roots, changed in <https://github.com/rust-lang/rust/pull/158447>.
1261    ///
1262    /// Otherwise, resolving simply does nothing.
1263    ///
1264    /// The "shallow" part of the name refers to the fact that types may themselves contain more
1265    /// type variables. e.g. The field types of a struct. `shallow_resolve` does not recurse into
1266    /// these nested variables. If that's what you want, use [`deeply_resolve_ignoring_regions`](Self::deeply_resolve_ignoring_regions),
1267    /// or better [`deeply_resolve_via_unification_table`](rustc_type_ir::InferCtxtLike::deeply_resolve_via_unification_table), if you can, which *does* resolve regions.
1268    pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1269        if let ty::Infer(v) = *ty.kind() {
1270            match v {
1271                ty::TyVar(v) => {
1272                    // Not entirely obvious: if `typ` is a type variable,
1273                    // it can be resolved to an int/float variable, which
1274                    // can then be recursively resolved, hence the
1275                    // recursion. Note though that we prevent type
1276                    // variables from unifying to other type variables
1277                    // directly (though they may be embedded
1278                    // structurally), and we prevent cycles in any case,
1279                    // so this recursion should always be of very limited
1280                    // depth.
1281                    //
1282                    // Note: if these two lines are combined into one we get
1283                    // dynamic borrow errors on `self.inner`.
1284                    let (root_vid, value) =
1285                        self.inner.borrow_mut().type_variables().probe_with_root_vid(v);
1286                    value.known().map_or_else(
1287                        || if root_vid == v { ty } else { Ty::new_var(self.tcx, root_vid) },
1288                        |t| self.shallow_resolve(t),
1289                    )
1290                }
1291
1292                ty::IntVar(v) => {
1293                    let (root, value) =
1294                        self.inner.borrow_mut().int_unification_table().inlined_probe_key_value(v);
1295                    match value {
1296                        ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1297                        ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1298                        ty::IntVarValue::Unknown => {
1299                            if root == v {
1300                                ty
1301                            } else {
1302                                Ty::new_int_var(self.tcx, root)
1303                            }
1304                        }
1305                    }
1306                }
1307
1308                ty::FloatVar(v) => {
1309                    let (root, value) = self
1310                        .inner
1311                        .borrow_mut()
1312                        .float_unification_table()
1313                        .inlined_probe_key_value(v);
1314                    match value {
1315                        ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1316                        ty::FloatVarValue::Unknown => {
1317                            if root == v {
1318                                ty
1319                            } else {
1320                                Ty::new_float_var(self.tcx, root)
1321                            }
1322                        }
1323                    }
1324                }
1325
1326                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1327            }
1328        } else {
1329            ty
1330        }
1331    }
1332
1333    /// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1334    /// It's the same, but for consts.
1335    pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1336        match ct.kind() {
1337            ty::ConstKind::Infer(infer_ct) => match infer_ct {
1338                InferConst::Var(vid) => {
1339                    let (root, value) = self
1340                        .inner
1341                        .borrow_mut()
1342                        .const_unification_table()
1343                        .inlined_probe_key_value(vid);
1344                    value.known().unwrap_or_else(|| {
1345                        if root.vid == vid { ct } else { ty::Const::new_var(self.tcx, root.vid) }
1346                    })
1347                }
1348                InferConst::Fresh(_) => ct,
1349            },
1350
1351            ty::ConstKind::Param(_)
1352            | ty::ConstKind::Bound(_, _)
1353            | ty::ConstKind::Placeholder(_)
1354            | ty::ConstKind::Alias(_, _)
1355            | ty::ConstKind::Value(_)
1356            | ty::ConstKind::Error(_)
1357            | ty::ConstKind::Expr(_) => ct,
1358        }
1359    }
1360
1361    /// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1362    /// It's the same, but for terms (types or consts).
1363    pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1364        match term.kind() {
1365            ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1366            ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1367        }
1368    }
1369
1370    pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1371        self.inner.borrow_mut().type_variables().root_var(var)
1372    }
1373
1374    /// If `ty` is an unresolved type variable, returns its root vid.
1375    pub fn root_vid(&self, ty: Ty<'tcx>) -> Option<ty::TyVid> {
1376        let (root, value) =
1377            self.inner.borrow_mut().type_variables().inlined_probe_with_vid(ty.ty_vid()?);
1378        value.is_unknown().then_some(root)
1379    }
1380
1381    pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1382        self.inner.borrow_mut().type_variables().sub_unify(a, b);
1383    }
1384
1385    pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1386        self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1387    }
1388
1389    pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1390        self.inner.borrow_mut().float_unification_table().find(var)
1391    }
1392
1393    pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1394        self.inner.borrow_mut().const_unification_table().find(var).vid
1395    }
1396
1397    /// Resolves a const var to a rigid const, if it was constrained to one,
1398    /// or else the root const var in the unification table.
1399    pub fn shallow_resolve_const_var(&self, vid: ty::ConstVid) -> ty::Const<'tcx> {
1400        match self.try_resolve_const_var(vid) {
1401            Ok(ct) => ct,
1402            Err(_) => ty::Const::new_var(self.tcx, self.root_const_var(vid)),
1403        }
1404    }
1405
1406    /// Resolves a type var to a rigid type, if it was constrained to one,
1407    /// or else the root type var in the unification table.
1408    pub fn shallow_resolve_ty_var(&self, vid: ty::TyVid) -> Ty<'tcx> {
1409        match self.try_resolve_ty_var(vid) {
1410            Ok(ty) => ty,
1411            Err(_) => Ty::new_var(self.tcx, self.root_var(vid)),
1412        }
1413    }
1414
1415    /// Resolves an int var to a rigid int type, if it was constrained to one,
1416    /// or else the root int var in the unification table.
1417    pub fn shallow_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1418        let mut inner = self.inner.borrow_mut();
1419        let value = inner.int_unification_table().probe_value(vid);
1420        match value {
1421            ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1422            ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1423            ty::IntVarValue::Unknown => {
1424                Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1425            }
1426        }
1427    }
1428
1429    /// Resolves a float var to a rigid type, if it was constrained to one,
1430    /// or else the root float var in the unification table.
1431    pub fn shallow_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1432        let mut inner = self.inner.borrow_mut();
1433        let value = inner.float_unification_table().probe_value(vid);
1434        match value {
1435            ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1436            ty::FloatVarValue::Unknown => {
1437                Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1438            }
1439        }
1440    }
1441
1442    /// If a type/const variable has not (yet) been unified, it is left as is.
1443    ///
1444    /// This is an idempotent operation that does not affect inference state in any way,
1445    /// which means it's safe to call this function at will.
1446    ///
1447    /// Region variables are unaffected.
1448    pub fn deeply_resolve_ignoring_regions<T>(&self, value: T) -> T
1449    where
1450        T: TypeFoldable<TyCtxt<'tcx>>,
1451    {
1452        if let Err(guar) = value.error_reported() {
1453            self.set_tainted_by_errors(guar);
1454        }
1455        if !value.has_non_region_infer() {
1456            return value;
1457        }
1458        let mut r = resolve::DeepResolverIgnoringRegions::new(self);
1459        value.fold_with(&mut r)
1460    }
1461
1462    /// Where possible, replaces type/const/region variables in `value` with their final value.
1463    /// If a type/const/region variable has not (yet) been unified, it is left as is.
1464    ///
1465    /// This is an idempotent operation that does not affect inference state in any way,
1466    /// which means it's safe to call this function at will.
1467    pub fn deeply_resolve_via_unification_table<T>(&self, value: T) -> T
1468    where
1469        T: TypeFoldable<TyCtxt<'tcx>>,
1470    {
1471        use rustc_middle::ty::InferCtxtLike;
1472        #[allow(rustc::usage_of_type_ir_traits)]
1473        InferCtxtLike::deeply_resolve_via_unification_table(self, value)
1474    }
1475
1476    pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1477    where
1478        T: TypeFoldable<TyCtxt<'tcx>>,
1479    {
1480        if !value.has_infer() {
1481            return value; // Avoid duplicated type-folding.
1482        }
1483        let mut r = InferenceLiteralEraser { tcx: self.tcx };
1484        value.fold_with(&mut r)
1485    }
1486
1487    pub fn try_resolve_const_var(
1488        &self,
1489        vid: ty::ConstVid,
1490    ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1491        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1492            ConstVariableValue::Known { value } => Ok(value),
1493            ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1494        }
1495    }
1496
1497    /// Attempts to resolve all type/region/const variables in
1498    /// `value`. Region inference must have been run already (e.g.,
1499    /// by calling `resolve_regions_and_report_errors`). If some
1500    /// variable was never unified, an `Err` results.
1501    ///
1502    /// This method is idempotent, but it not typically not invoked
1503    /// except during the writeback phase.
1504    pub fn deeply_resolve_via_region_graph<T: TypeFoldable<TyCtxt<'tcx>>>(
1505        &self,
1506        value: T,
1507    ) -> FixupResult<T> {
1508        match resolve::deeply_resolve_via_region_graph(self, value) {
1509            Ok(value) => {
1510                if value.has_non_region_infer() {
1511                    bug_impl(None, format_args!("`{0:?}` is not fully resolved", value),
    Location::caller());bug!("`{value:?}` is not fully resolved");
1512                }
1513                if value.has_infer_regions() {
1514                    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"));
1515                    Ok(fold_regions(self.tcx, value, |re, _| {
1516                        if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1517                    }))
1518                } else {
1519                    Ok(value)
1520                }
1521            }
1522            Err(e) => Err(e),
1523        }
1524    }
1525
1526    // Instantiates the bound variables in a given binder with fresh inference
1527    // variables in the current universe.
1528    //
1529    // Use this method if you'd like to find some generic parameters of the binder's
1530    // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1531    // that corresponds to your use case, consider whether or not you should
1532    // use [`InferCtxt::enter_forall`] instead.
1533    pub fn instantiate_binder_with_fresh_vars<T>(
1534        &self,
1535        span: Span,
1536        lbrct: BoundRegionConversionTime,
1537        value: ty::Binder<'tcx, T>,
1538    ) -> T
1539    where
1540        T: TypeFoldable<TyCtxt<'tcx>>,
1541    {
1542        if let Some(_) = value.as_ref().no_bound_vars() {
1543            return value.skip_binder();
1544        }
1545
1546        let bound_vars = value.bound_vars();
1547        let mut args = Vec::with_capacity(bound_vars.len());
1548
1549        for bound_var_kind in bound_vars {
1550            let arg: ty::GenericArg<'_> = match bound_var_kind {
1551                ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1552                ty::BoundVariableKind::Region(br) => {
1553                    self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1554                }
1555                ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1556            };
1557            args.push(arg);
1558        }
1559
1560        struct ToFreshVars<'tcx> {
1561            args: Vec<ty::GenericArg<'tcx>>,
1562        }
1563
1564        impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1565            fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1566                self.args[br.var.index()].expect_region()
1567            }
1568            fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1569                self.args[bt.var.index()].expect_ty()
1570            }
1571            fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1572                self.args[bc.var.index()].expect_const()
1573            }
1574        }
1575        let delegate = ToFreshVars { args };
1576        self.tcx.replace_bound_vars_uncached(value, delegate)
1577    }
1578
1579    pub fn insert_placeholder_assumptions(
1580        &self,
1581        u: ty::UniverseIndex,
1582        assumptions: Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
1583    ) {
1584        if let Some(assumptions) = &assumptions {
1585            if !!assumptions.type_outlives.has_escaping_bound_vars() {
    {
        ::core::panicking::panic_fmt(format_args!("assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {0:?}",
                assumptions.type_outlives));
    }
};assert!(
1586                !assumptions.type_outlives.has_escaping_bound_vars(),
1587                "assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1588                assumptions.type_outlives
1589            );
1590            if !assumptions.region_outlives.base_edges().all(|r|
                !r.has_escaping_bound_vars()) {
    {
        ::core::panicking::panic_fmt(format_args!("assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {0:?}",
                assumptions.region_outlives));
    }
};assert!(
1591                assumptions.region_outlives.base_edges().all(|r| !r.has_escaping_bound_vars()),
1592                "assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1593                assumptions.region_outlives
1594            );
1595        }
1596        self.placeholder_assumptions_for_next_solver.borrow_mut().insert(u, assumptions);
1597    }
1598
1599    pub fn get_placeholder_assumptions(
1600        &self,
1601        u: ty::UniverseIndex,
1602    ) -> Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>> {
1603        self.placeholder_assumptions_for_next_solver.borrow().get(&u).unwrap().as_ref().cloned()
1604    }
1605
1606    pub fn get_solver_region_constraint(&self) -> SolverRegionConstraint<'tcx> {
1607        self.inner.borrow().solver_region_constraint_storage.get_constraint()
1608    }
1609
1610    pub fn overwrite_solver_region_constraint(&self, constraint: SolverRegionConstraint<'tcx>) {
1611        if !!constraint.has_escaping_bound_vars() {
    {
        ::core::panicking::panic_fmt(format_args!("solver region constraint has escaping bound vars, which is indicative of a bug in how constraints are handled: {0:?}",
                constraint));
    }
};assert!(
1612            !constraint.has_escaping_bound_vars(),
1613            "solver region constraint has escaping bound vars, which is indicative of a bug in how constraints are handled: {constraint:?}",
1614        );
1615        let mut inner = self.inner.borrow_mut();
1616        let old_constraint = inner.solver_region_constraint_storage.get_constraint();
1617        inner.undo_log.push(UndoLog::OverwriteSolverRegionConstraint { old_constraint });
1618        inner.solver_region_constraint_storage.overwrite(constraint);
1619    }
1620
1621    /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1622    pub(crate) fn verify_generic_bound(
1623        &self,
1624        origin: SubregionOrigin<'tcx>,
1625        kind: GenericKind<'tcx>,
1626        a: ty::Region<'tcx>,
1627        bound: VerifyBound<'tcx>,
1628    ) {
1629        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs:1629",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1629u32),
                        ::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);
1630
1631        self.inner
1632            .borrow_mut()
1633            .unwrap_region_constraints()
1634            .verify_generic_bound(origin, kind, a, bound);
1635    }
1636
1637    /// Obtains the latest type of the given closure; this may be a
1638    /// closure in the current function, in which case its
1639    /// `ClosureKind` may not yet be known.
1640    pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1641        let unresolved_kind_ty = match *closure_ty.kind() {
1642            ty::Closure(_, args) => args.as_closure().kind_ty(),
1643            ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1644            _ => bug_impl(None, format_args!("unexpected type {0}", closure_ty),
    Location::caller())bug!("unexpected type {closure_ty}"),
1645        };
1646        let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1647        closure_kind_ty.to_opt_closure_kind()
1648    }
1649
1650    pub fn universe(&self) -> ty::UniverseIndex {
1651        self.universe.get()
1652    }
1653
1654    /// Creates and return a fresh universe that extends all previous
1655    /// universes. Updates `self.universe` to that new universe.
1656    pub fn create_next_universe(&self) -> ty::UniverseIndex {
1657        let u = self.universe.get().next_universe();
1658        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs:1658",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1658u32),
                        ::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:?}");
1659        self.universe.set(u);
1660        u
1661    }
1662
1663    /// We need to disable the fcw if we're already in a fcw emitting to avoid
1664    /// indefinite triggering.
1665    pub fn with_disabled_next_solver_overflow_fcw<F, R>(&self, mut f: F) -> R
1666    where
1667        F: FnMut() -> R,
1668    {
1669        let prev = self.enable_next_solver_overflow_fcw.replace(false);
1670        let ret = f();
1671        self.enable_next_solver_overflow_fcw.set(prev);
1672        ret
1673    }
1674
1675    /// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1676    /// which contains the necessary information to use the trait system without
1677    /// using canonicalization or carrying this inference context around.
1678    pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1679        let typing_mode = match self.typing_mode_raw() {
1680            // FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1681            // to handle them without proper canonicalization. This means we may cause cycle
1682            // errors and fail to reveal opaques while inside of bodies. We should rename this
1683            // function and require explicit comments on all use-sites in the future.
1684            ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1685            | ty::TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ } => {
1686                TypingMode::non_body_analysis()
1687            }
1688            mode @ (ty::TypingMode::Coherence
1689            | ty::TypingMode::PostBorrowck { .. }
1690            | ty::TypingMode::PostAnalysis
1691            | ty::TypingMode::Reflection
1692            | ty::TypingMode::Codegen) => mode,
1693            ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1694        };
1695        ty::TypingEnv::new(param_env, typing_mode)
1696    }
1697
1698    /// Similar to [`Self::canonicalize_query`], except that it returns
1699    /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1700    /// `param_env` to not contain any inference variables or placeholders.
1701    pub fn pseudo_canonicalize_query<V>(
1702        &self,
1703        param_env: ty::ParamEnv<'tcx>,
1704        value: V,
1705    ) -> PseudoCanonicalInput<'tcx, V>
1706    where
1707        V: TypeVisitable<TyCtxt<'tcx>>,
1708    {
1709        if true {
    if !!value.has_infer() {
        ::core::panicking::panic("assertion failed: !value.has_infer()")
    };
};debug_assert!(!value.has_infer());
1710        if true {
    if !!value.has_placeholders() {
        ::core::panicking::panic("assertion failed: !value.has_placeholders()")
    };
};debug_assert!(!value.has_placeholders());
1711        if true {
    if !!param_env.has_infer() {
        ::core::panicking::panic("assertion failed: !param_env.has_infer()")
    };
};debug_assert!(!param_env.has_infer());
1712        if true {
    if !!param_env.has_placeholders() {
        ::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
    };
};debug_assert!(!param_env.has_placeholders());
1713        self.typing_env(param_env).as_query_input(value)
1714    }
1715
1716    /// The returned function is used in a fast path. If it returns `true` the variable is
1717    /// unchanged, `false` indicates that the status is unknown.
1718    #[inline]
1719    pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1720        // This hoists the borrow/release out of the loop body.
1721        let inner = self.inner.try_borrow();
1722
1723        move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1724            (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1725                use self::type_variable::TypeVariableValue;
1726
1727                #[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
    {
    Some(TypeVariableValue::Unknown { .. }) => true,
    _ => false,
}matches!(
1728                    inner.try_type_variables_probe_ref(ty_var),
1729                    Some(TypeVariableValue::Unknown { .. })
1730                )
1731            }
1732            _ => false,
1733        }
1734    }
1735
1736    /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1737    ///   * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1738    ///   * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1739    ///
1740    /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1741    /// inlined, despite being large, because it has only two call sites that
1742    /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1743    /// inference variables), and it handles both `Ty` and `ty::Const` without
1744    /// having to resort to storing full `GenericArg`s in `stalled_on`.
1745    #[inline(always)]
1746    pub fn ty_or_const_infer_var_changed(&self, var: TyOrConstInferVar) -> bool {
1747        match var {
1748            TyOrConstInferVar::Ty(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().try_type_variables_probe_ref(vid)
    {
    Some(TypeVariableValue::Unknown { .. }) => true,
    _ => false,
}matches!(
1749                self.inner.borrow().try_type_variables_probe_ref(vid),
1750                Some(TypeVariableValue::Unknown { .. })
1751            ),
1752            TyOrConstInferVar::TyInt(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().int_unification_storage.try_probe_value(vid)
    {
    Some(ty::IntVarValue::Unknown) => true,
    _ => false,
}matches!(
1753                self.inner.borrow().int_unification_storage.try_probe_value(vid),
1754                Some(ty::IntVarValue::Unknown)
1755            ),
1756            TyOrConstInferVar::TyFloat(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().float_unification_storage.try_probe_value(vid)
    {
    Some(ty::FloatVarValue::Unknown) => true,
    _ => false,
}matches!(
1757                self.inner.borrow().float_unification_storage.try_probe_value(vid),
1758                Some(ty::FloatVarValue::Unknown)
1759            ),
1760            TyOrConstInferVar::Const(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().const_unification_storage.try_probe_value(vid)
    {
    Some(ConstVariableValue::Unknown { .. }) => true,
    _ => false,
}matches!(
1761                self.inner.borrow().const_unification_storage.try_probe_value(vid),
1762                Some(ConstVariableValue::Unknown { .. })
1763            ),
1764        }
1765    }
1766
1767    /// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1768    pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1769        if true {
    if !self.obligation_inspector.get().is_none() {
        {
            ::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
        }
    };
};debug_assert!(
1770            self.obligation_inspector.get().is_none(),
1771            "shouldn't override a set obligation inspector"
1772        );
1773        self.obligation_inspector.set(Some(inspector));
1774    }
1775}
1776
1777/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1778/// Used only for diagnostics.
1779struct InferenceLiteralEraser<'tcx> {
1780    tcx: TyCtxt<'tcx>,
1781}
1782
1783impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1784    fn cx(&self) -> TyCtxt<'tcx> {
1785        self.tcx
1786    }
1787
1788    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1789        match ty.kind() {
1790            ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1791            ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1792            _ => ty.super_fold_with(self),
1793        }
1794    }
1795}
1796
1797impl<'tcx> TypeTrace<'tcx> {
1798    pub fn span(&self) -> Span {
1799        self.cause.span
1800    }
1801
1802    pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1803        TypeTrace {
1804            cause: cause.clone(),
1805            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1806        }
1807    }
1808
1809    pub fn trait_refs(
1810        cause: &ObligationCause<'tcx>,
1811        a: ty::TraitRef<'tcx>,
1812        b: ty::TraitRef<'tcx>,
1813    ) -> TypeTrace<'tcx> {
1814        TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1815    }
1816
1817    pub fn consts(
1818        cause: &ObligationCause<'tcx>,
1819        a: ty::Const<'tcx>,
1820        b: ty::Const<'tcx>,
1821    ) -> TypeTrace<'tcx> {
1822        TypeTrace {
1823            cause: cause.clone(),
1824            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1825        }
1826    }
1827}
1828
1829impl<'tcx> SubregionOrigin<'tcx> {
1830    pub fn span(&self) -> Span {
1831        match *self {
1832            SubregionOrigin::Subtype(ref a) => a.span(),
1833            SubregionOrigin::RelateObjectBound(a) => a,
1834            SubregionOrigin::RelateParamBound(a, ..) => a,
1835            SubregionOrigin::RelateRegionParamBound(a, _) => a,
1836            SubregionOrigin::Reborrow(a) => a,
1837            SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1838            SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1839            SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1840            SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1841            SubregionOrigin::SolverRegionConstraint(a) => a,
1842        }
1843    }
1844
1845    pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1846    where
1847        F: FnOnce() -> Self,
1848    {
1849        match *cause.code() {
1850            traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1851                SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1852            }
1853
1854            traits::ObligationCauseCode::CompareImplItem {
1855                impl_item_def_id,
1856                trait_item_def_id,
1857                kind: _,
1858            } => SubregionOrigin::CompareImplItemObligation {
1859                span: cause.span,
1860                impl_item_def_id,
1861                trait_item_def_id,
1862            },
1863
1864            traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1865                impl_item_def_id,
1866                trait_item_def_id,
1867            } => SubregionOrigin::CheckAssociatedTypeBounds {
1868                impl_item_def_id,
1869                trait_item_def_id,
1870                parent: Box::new(default()),
1871            },
1872
1873            traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1874                SubregionOrigin::AscribeUserTypeProvePredicate(span)
1875            }
1876
1877            traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1878                SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1879            }
1880
1881            _ => default(),
1882        }
1883    }
1884}
1885
1886impl<'tcx> RegionVariableOrigin<'tcx> {
1887    pub fn span(&self) -> Span {
1888        match *self {
1889            RegionVariableOrigin::Misc(a)
1890            | RegionVariableOrigin::PatternRegion(a)
1891            | RegionVariableOrigin::BorrowRegion(a)
1892            | RegionVariableOrigin::Autoref(a)
1893            | RegionVariableOrigin::Coercion(a)
1894            | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1895            | RegionVariableOrigin::BoundRegion(a, ..)
1896            | RegionVariableOrigin::UpvarRegion(_, a) => a,
1897            RegionVariableOrigin::Nll(..) => bug_impl(None, format_args!("NLL variable used with `span`"),
    Location::caller())bug!("NLL variable used with `span`"),
1898        }
1899    }
1900}
1901
1902impl<'tcx> InferCtxt<'tcx> {
1903    /// Given a [`hir::Block`], get the span of its last expression or
1904    /// statement, peeling off any inner blocks.
1905    pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1906        let block = block.innermost_block();
1907        if let Some(expr) = &block.expr {
1908            expr.span
1909        } else if let Some(stmt) = block.stmts.last() {
1910            // possibly incorrect trailing `;` in the else arm
1911            stmt.span
1912        } else {
1913            // empty block; point at its entirety
1914            block.span
1915        }
1916    }
1917
1918    /// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1919    /// of its last expression or statement, peeling off any inner blocks.
1920    pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1921        match self.tcx.hir_node(hir_id) {
1922            hir::Node::Block(blk)
1923            | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1924                self.find_block_span(blk)
1925            }
1926            hir::Node::Expr(e) => e.span,
1927            _ => DUMMY_SP,
1928        }
1929    }
1930}
1931
1932/// Returns unresolved root variables from `table`, according to `is_unresolved`.
1933fn unresolved_root_variables_of<V: UnifyKey>(
1934    mut table: UnificationTable<'_, '_, V>,
1935    is_unresolved: impl Fn(V::Value) -> bool,
1936) -> Vec<V>
1937where
1938    V: Eq,
1939    V::Value: UnifyValue,
1940    for<'a> UndoLog<'a>: From<sv::UndoLog<ut::Delegate<V>>>,
1941{
1942    (0..table.len() as u32)
1943        .map(V::from_index)
1944        .filter(|&vid| {
1945            // NB: as of writing this `ena` doesn't provide a non-inlined `probe_key_value`...
1946            let (root, value) = table.inlined_probe_key_value(vid);
1947            root == vid && is_unresolved(value)
1948        })
1949        .collect()
1950}