Skip to main content

rustc_infer/infer/
mod.rs

1use std::cell::{Cell, RefCell};
2use std::fmt;
3use std::range::RangeInclusive;
4
5pub use at::DefineOpaqueTypes;
6use free_regions::RegionRelations;
7pub use freshen::TypeFreshener;
8use lexical_region_resolve::LexicalRegionResolutions;
9pub use lexical_region_resolve::RegionResolutionError;
10pub use opaque_types::{OpaqueTypeStorage, OpaqueTypeStorageEntries, OpaqueTypeTable};
11use region_constraints::{
12    GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
13};
14pub use relate::combine::PredicateEmittingRelation;
15use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
16use rustc_data_structures::snapshot_vec as sv;
17use rustc_data_structures::undo_log::{Rollback, UndoLogs};
18use rustc_data_structures::unify::{self as ut, UnifyKey, UnifyValue};
19use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
20use rustc_hir::def_id::{DefId, LocalDefId};
21use rustc_hir::{self as hir, HirId};
22use rustc_index::IndexVec;
23use rustc_macros::extension;
24pub use rustc_macros::{TypeFoldable, TypeVisitable};
25use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
26use rustc_middle::mir::ConstraintCategory;
27use rustc_middle::traits::select;
28use rustc_middle::traits::solve::Goal;
29use rustc_middle::ty::error::{ExpectedFound, TypeError};
30use rustc_middle::ty::{
31    self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
32    GenericArgsRef, GenericParamDefKind, InferConst, OpaqueTypeKey, ProvisionalHiddenType,
33    PseudoCanonicalInput, Term, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable,
34    TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
35};
36use rustc_span::{DUMMY_SP, Span, Symbol, bug};
37use rustc_type_ir::{CanonicalizerState, MayBeErased};
38use snapshot::undo_log::InferCtxtUndoLogs;
39use tracing::{debug, instrument};
40use ty::solve::TyOrConstInferVar;
41use type_variable::TypeVariableOrigin;
42
43use crate::infer::snapshot::undo_log::UndoLog;
44use crate::infer::type_variable::{FloatVariableOrigin, TypeVariableValue};
45use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
46use crate::traits::{
47    self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
48    TraitEngine,
49};
50
51pub mod at;
52pub mod canonical;
53mod context;
54mod free_regions;
55mod freshen;
56mod lexical_region_resolve;
57mod opaque_types;
58pub mod outlives;
59mod projection;
60pub mod region_constraints;
61pub mod relate;
62pub mod resolve;
63pub(crate) mod snapshot;
64mod type_variable;
65mod unify_key;
66
67pub use region_constraints::SolverRegionConstraint;
68
69/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
70/// around `PredicateObligations<'tcx>`, but it has one important property:
71/// because `InferOk` is marked with `#[must_use]`, if you have a method
72/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
73/// `infcx.f()?;` you'll get a warning about the obligations being discarded
74/// without use, which is probably unintentional and has been a source of bugs
75/// in the past.
76#[must_use]
77#[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)]
78pub struct InferOk<'tcx, T> {
79    pub value: T,
80    pub obligations: PredicateObligations<'tcx>,
81}
82pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
83
84pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
85
86pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
87    ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
88>;
89
90/// This type contains all the things within [`InferCtxt`] that sit within a
91/// [`RefCell`] and are involved with taking/rolling back snapshots. Snapshot
92/// operations are hot enough that we want only one call to
93/// [`RefCell::borrow_mut`] per call to [`InferCtxt::start_snapshot`] and
94///  [`InferCtxt::rollback_to`].
95#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
    InferCtxtInner<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        InferCtxtInner {
            undo_log: ::core::clone::Clone::clone(&self.undo_log),
            projection_cache: ::core::clone::Clone::clone(&self.projection_cache),
            type_variable_storage: ::core::clone::Clone::clone(&self.type_variable_storage),
            const_unification_storage: ::core::clone::Clone::clone(&self.const_unification_storage),
            int_unification_storage: ::core::clone::Clone::clone(&self.int_unification_storage),
            float_unification_storage: ::core::clone::Clone::clone(&self.float_unification_storage),
            float_origin_origin_storage: ::core::clone::Clone::clone(&self.float_origin_origin_storage),
            region_constraint_storage: ::core::clone::Clone::clone(&self.region_constraint_storage),
            region_obligations: ::core::clone::Clone::clone(&self.region_obligations),
            region_assumptions: ::core::clone::Clone::clone(&self.region_assumptions),
            hir_typeck_potentially_region_dependent_goals: ::core::clone::Clone::clone(&self.hir_typeck_potentially_region_dependent_goals),
            opaque_type_storage: ::core::clone::Clone::clone(&self.opaque_type_storage),
        }
    }
}Clone)]
96pub struct InferCtxtInner<'tcx> {
97    undo_log: InferCtxtUndoLogs<'tcx>,
98
99    /// Cache for projections.
100    ///
101    /// This cache is snapshotted along with the infcx.
102    projection_cache: traits::ProjectionCacheStorage<'tcx>,
103
104    /// Primary map of inference variables to the types that they currently
105    /// represent.
106    ///
107    /// We instantiate [`UnificationTable`] with `bounds<Ty>` because the types
108    /// that might instantiate a general type variable have an order,
109    /// represented by its upper and lower bounds.
110    type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
111
112    /// Map from const parameter variable to the kind of const it represents.
113    const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
114
115    /// Map from integral variable to the kind of integer it represents.
116    int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
117
118    /// Map from floating variable to the kind of float it represents.
119    float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
120
121    /// Map from floating variable to the origin span it came from, and the HirId that should be
122    /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
123    /// so can be removed once the `f32` fallback is removed.
124    float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
125
126    /// Tracks the set of region variables and the constraints between them.
127    ///
128    /// This is initially `Some(_)` but when
129    /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
130    /// -- further attempts to perform unification, etc., may fail if new
131    /// region constraints would've been added.
132    region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
133
134    /// A set of constraints that regionck must validate.
135    ///
136    /// Each constraint has the form `T:'a`, meaning "some type `T` must
137    /// outlive the lifetime 'a". These constraints derive from
138    /// instantiated type parameters. So if you had a struct defined
139    /// like the following:
140    /// ```ignore (illustrative)
141    /// struct Foo<T: 'static> { ... }
142    /// ```
143    /// In some expression `let x = Foo { ... }`, it will
144    /// instantiate the type parameter `T` with a fresh type `$0`. At
145    /// the same time, it will record a region obligation of
146    /// `$0: 'static`. This will get checked later by regionck. (We
147    /// can't generally check these things right away because we have
148    /// to wait until types are resolved.)
149    region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
150
151    /// The outlives bounds that we assume must hold about placeholders that
152    /// come from instantiating the binder of coroutine-witnesses. These bounds
153    /// are deduced from the well-formedness of the witness's types, and are
154    /// necessary because of the way we anonymize the regions in a coroutine,
155    /// which may cause types to no longer be considered well-formed.
156    region_assumptions: Vec<ty::ArgOutlivesClause<'tcx>>,
157
158    /// `-Znext-solver`: Successfully proven goals during HIR typeck which
159    /// reference inference variables and get reproven in case MIR type check
160    /// fails to prove something.
161    ///
162    /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
163    hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
164
165    /// Caches for opaque type inference.
166    opaque_type_storage: OpaqueTypeStorage<'tcx>,
167}
168
169impl<'tcx> InferCtxtInner<'tcx> {
170    fn new() -> InferCtxtInner<'tcx> {
171        InferCtxtInner {
172            undo_log: InferCtxtUndoLogs::default(),
173
174            projection_cache: Default::default(),
175            type_variable_storage: Default::default(),
176            const_unification_storage: Default::default(),
177            int_unification_storage: Default::default(),
178            float_unification_storage: Default::default(),
179            float_origin_origin_storage: Default::default(),
180            region_constraint_storage: Some(Default::default()),
181            region_obligations: Default::default(),
182            region_assumptions: Default::default(),
183            hir_typeck_potentially_region_dependent_goals: Default::default(),
184            opaque_type_storage: Default::default(),
185        }
186    }
187
188    #[inline]
189    pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
190        &self.region_obligations
191    }
192
193    #[inline]
194    pub fn region_assumptions(&self) -> &[ty::ArgOutlivesClause<'tcx>] {
195        &self.region_assumptions
196    }
197
198    #[inline]
199    pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
200        self.projection_cache.with_log(&mut self.undo_log)
201    }
202
203    #[inline]
204    fn try_type_variables_probe_ref(&self, vid: ty::TyVid) -> Option<&TypeVariableValue<'tcx>> {
205        // Uses a read-only view of the unification table, this way we don't
206        // need an undo log.
207        self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
208    }
209
210    #[inline]
211    fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
212        self.type_variable_storage.with_log(&mut self.undo_log)
213    }
214
215    #[inline]
216    pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
217        self.opaque_type_storage.with_log(&mut self.undo_log)
218    }
219
220    #[inline]
221    fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
222        self.int_unification_storage.with_log(&mut self.undo_log)
223    }
224
225    #[inline]
226    fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
227        self.float_unification_storage.with_log(&mut self.undo_log)
228    }
229
230    #[inline]
231    fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
232        self.const_unification_storage.with_log(&mut self.undo_log)
233    }
234
235    #[inline]
236    pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
237        self.region_constraint_storage
238            .as_mut()
239            .expect("region constraints already solved")
240            .with_log(&mut self.undo_log)
241    }
242}
243
244pub struct InferCtxt<'tcx> {
245    pub tcx: TyCtxt<'tcx>,
246
247    /// The mode of this inference context, see the struct documentation
248    /// for more details.
249    typing_mode: TypingMode<'tcx>,
250
251    /// Whether this inference context should care about region obligations in
252    /// the root universe. Most notably, this is used during HIR typeck as region
253    /// solving is left to borrowck instead.
254    ///
255    /// This is used in the old solver to enable the generation of regions constraints.
256    /// In the new solver its only used inside the InferCtxt's `Drop` implementation:
257    /// if we're considering regions, and new opaques are registered, we panic.
258    pub considering_regions: bool,
259    /// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
260    /// need to make sure we don't rely on region identity in the trait solver or when
261    /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
262    /// free region with a unique inference variable. If HIR typeck ends up depending on two
263    /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
264    /// resulting in an ICE.
265    ///
266    /// The trait solver sometimes depends on regions being identical. As a concrete example
267    /// the trait solver ignores other candidates if one candidate exists without any constraints.
268    /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
269    /// occurrence of `'a` with a unique region the goal now equates these regions. See
270    /// the tests in trait-system-refactor-initiative#27 for concrete examples.
271    ///
272    /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
273    /// This is still insufficient as inference variables may *hide* region variables, so e.g.
274    /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
275    /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
276    /// stash all successfully proven goals which reference inference variables and then reprove
277    /// them after writeback.
278    pub in_hir_typeck: bool,
279
280    /// If set, this flag causes us to skip the 'leak check' during
281    /// higher-ranked subtyping operations. This flag is a temporary one used
282    /// to manage the removal of the leak-check: for the time being, we still run the
283    /// leak-check, but we issue warnings.
284    skip_leak_check: bool,
285
286    pub inner: RefCell<InferCtxtInner<'tcx>>,
287
288    /// Once region inference is done, the values for each variable.
289    lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
290
291    /// Caches the results of trait selection. This cache is used
292    /// for things that depends on inference variables or placeholders.
293    pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
294
295    /// Caches the results of trait evaluation. This cache is used
296    /// for things that depends on inference variables or placeholders.
297    pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
298
299    /// The set of predicates on which errors have been reported, to
300    /// avoid reporting the same error twice.
301    pub reported_trait_errors:
302        RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
303
304    /// A set of predicates *on a specific* HIR node (the originating expression and its enclosing
305    /// statement), to avoid reporting multiple errors pointing at different sub-expressions in the
306    /// same method chain.
307    pub reported_hir_errors: RefCell<FxIndexMap<HirId, FxHashSet<ty::Predicate<'tcx>>>>,
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<ty::UniverseIndex, rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
339    >,
340
341    next_trait_solver: bool,
342
343    /// We have a `recursion_depth_exceeding_limit` FCW to mitigate breakages
344    /// caused by enabling the next solver globally. But the next solver is
345    /// already used by default in some places so we know they won't have
346    /// additional breakages. We also don't want spurious result in coherence
347    /// checking so we disable the FCW there as well.
348    enable_next_solver_overflow_fcw: Cell<bool>,
349
350    pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
351
352    /// State reused by each new canonicalizer, and then cleared (but not deallocated) once the
353    /// canonicalizer is finished. A performance win, because it avoids reallocating new
354    /// vecs/hashmaps for every canonicalizer.
355    pub canonicalizer_state: RefCell<CanonicalizerState<TyCtxt<'tcx>>>,
356}
357
358impl<'tcx> Drop for InferCtxt<'tcx> {
359    fn drop(&mut self) {
360        let mut inner = self.inner.borrow_mut();
361        let opaque_type_storage = &mut inner.opaque_type_storage;
362
363        // No need for the drop bomb when we're in `TypingMode::PostTypeckThroughBorrowck`, and the `InferCtxt`
364        // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
365        // in relation to regions. In some places *after* typeck that aren't borrowck, we use
366        // `TypingMode::PostTypeckThroughBorrowck` to prevent defining opaque types and we simply don't care about regions.
367        match self.typing_mode_raw() {
368            TypingMode::Coherence
369            | TypingMode::Typeck { .. }
370            | TypingMode::PostBorrowck { .. }
371            | TypingMode::Reflection
372            | TypingMode::PostAnalysis
373            | TypingMode::Codegen => {}
374            // In erased mode, the opaque type storage is always empty
375            TypingMode::ErasedNotCoherence(..) => {}
376            TypingMode::PostTypeckThroughBorrowck { .. } => {
377                if !self.considering_regions {
378                    return;
379                }
380            }
381        }
382
383        if !opaque_type_storage.is_empty() {
384            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:?}")));
385        }
386    }
387}
388
389/// See the `error_reporting` module for more details.
390#[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) -> Self {
        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 {
            Self::Regions(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Regions", &__self_0),
            Self::Terms(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Terms",
                    &__self_0),
            Self::Aliases(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Aliases", &__self_0),
            Self::TraitRefs(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TraitRefs", &__self_0),
            Self::PolySigs(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "PolySigs", &__self_0),
            Self::ExistentialTraitRef(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ExistentialTraitRef", &__self_0),
            Self::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: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Regions(__self_0), Self::Regions(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Terms(__self_0), Self::Terms(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Aliases(__self_0), Self::Aliases(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::TraitRefs(__self_0), Self::TraitRefs(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::PolySigs(__self_0), Self::PolySigs(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::ExistentialTraitRef(__self_0),
                    Self::ExistentialTraitRef(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::ExistentialProjection(__self_0),
                    Self::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)]
391pub enum ValuePairs<'tcx> {
392    Regions(ExpectedFound<ty::Region<'tcx>>),
393    Terms(ExpectedFound<ty::Term<'tcx>>),
394    Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
395    TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
396    PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
397    ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
398    ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
399}
400
401impl<'tcx> ValuePairs<'tcx> {
402    pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
403        if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
404            && let Some(expected) = expected.as_type()
405            && let Some(found) = found.as_type()
406        {
407            Some((expected, found))
408        } else {
409            None
410        }
411    }
412}
413
414/// The trace designates the path through inference that we took to
415/// encounter an error or subtyping constraint.
416///
417/// See the `error_reporting` module for more details.
418#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for TypeTrace<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        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)]
419pub struct TypeTrace<'tcx> {
420    pub cause: ObligationCause<'tcx>,
421    pub values: ValuePairs<'tcx>,
422}
423
424/// The origin of a `r1 <= r2` constraint.
425///
426/// See `error_reporting` module for more details
427#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
    SubregionOrigin<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Subtype(__self_0) =>
                SubregionOrigin::Subtype(::core::clone::Clone::clone(__self_0)),
            Self::RelateObjectBound(__self_0) =>
                SubregionOrigin::RelateObjectBound(::core::clone::Clone::clone(__self_0)),
            Self::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)),
            Self::RelateRegionParamBound(__self_0, __self_1) =>
                SubregionOrigin::RelateRegionParamBound(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            Self::Reborrow(__self_0) =>
                SubregionOrigin::Reborrow(::core::clone::Clone::clone(__self_0)),
            Self::ReferenceOutlivesReferent(__self_0, __self_1) =>
                SubregionOrigin::ReferenceOutlivesReferent(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            Self::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),
                },
            Self::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),
                },
            Self::AscribeUserTypeProvePredicate(__self_0, __self_1) =>
                SubregionOrigin::AscribeUserTypeProvePredicate(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            Self::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 {
            Self::Subtype(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Subtype", &__self_0),
            Self::RelateObjectBound(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "RelateObjectBound", &__self_0),
            Self::RelateParamBound(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "RelateParamBound", __self_0, __self_1, &__self_2),
            Self::RelateRegionParamBound(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "RelateRegionParamBound", __self_0, &__self_1),
            Self::Reborrow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Reborrow", &__self_0),
            Self::ReferenceOutlivesReferent(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "ReferenceOutlivesReferent", __self_0, &__self_1),
            Self::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),
            Self::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),
            Self::AscribeUserTypeProvePredicate(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AscribeUserTypeProvePredicate", __self_0, &__self_1),
            Self::SolverRegionConstraint(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "SolverRegionConstraint", &__self_0),
        }
    }
}Debug)]
428pub enum SubregionOrigin<'tcx> {
429    /// Arose from a subtyping relation
430    Subtype(Box<TypeTrace<'tcx>>),
431
432    /// When casting `&'a T` to an `&'b Trait` object,
433    /// relating `'a` to `'b`.
434    RelateObjectBound(Span),
435
436    /// Some type parameter was instantiated with the given type,
437    /// and that type must outlive some region.
438    RelateParamBound(Span, Ty<'tcx>, Option<Span>),
439
440    /// The given region parameter was instantiated with a region
441    /// that must outlive some other region.
442    RelateRegionParamBound(Span, Option<Ty<'tcx>>),
443
444    /// Creating a pointer `b` to contents of another reference.
445    Reborrow(Span),
446
447    /// (&'a &'b T) where a >= b
448    ReferenceOutlivesReferent(Ty<'tcx>, Span),
449
450    /// Comparing the signature and requirements of an impl method against
451    /// the containing trait.
452    CompareImplItemObligation {
453        span: Span,
454        impl_item_def_id: LocalDefId,
455        trait_item_def_id: DefId,
456    },
457
458    /// Checking that the bounds of a trait's associated type hold for a given impl.
459    CheckAssociatedTypeBounds {
460        parent: Box<SubregionOrigin<'tcx>>,
461        impl_item_def_id: LocalDefId,
462        trait_item_def_id: DefId,
463    },
464
465    AscribeUserTypeProvePredicate(Span, DefId),
466
467    // FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
468    // proper diagnostics for solver region constraints.
469    SolverRegionConstraint(Span),
470}
471
472// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
473#[cfg(target_pointer_width = "64")]
474const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
475
476impl<'tcx> SubregionOrigin<'tcx> {
477    pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
478        match self {
479            Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
480            Self::AscribeUserTypeProvePredicate(span, def_id) => {
481                ConstraintCategory::Predicate(*span, *def_id)
482            }
483            Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
484            _ => ConstraintCategory::BoringNoLocation,
485        }
486    }
487}
488
489/// Times when we replace bound regions with existentials:
490#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for BoundRegionConversionTime {
}
#[automatically_derived]impl ::core::clone::Clone for
    BoundRegionConversionTime {
    #[inline]
    fn clone(&self) -> Self {
        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 {
            Self::FnCall => ::core::fmt::Formatter::write_str(f, "FnCall"),
            Self::HigherRankedType =>
                ::core::fmt::Formatter::write_str(f, "HigherRankedType"),
            Self::AssocTypeProjection(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AssocTypeProjection", &__self_0),
        }
    }
}Debug)]
491pub enum BoundRegionConversionTime {
492    /// when a fn is called
493    FnCall,
494
495    /// when two higher-ranked types are compared
496    HigherRankedType,
497
498    /// when projecting an associated type
499    AssocTypeProjection(DefId),
500}
501
502/// Reasons to create a region inference variable.
503///
504/// See `error_reporting` module for more details.
505#[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) -> Self {
        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 {
            Self::Misc(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Misc",
                    &__self_0),
            Self::PatternRegion(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "PatternRegion", &__self_0),
            Self::BorrowRegion(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "BorrowRegion", &__self_0),
            Self::Autoref(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Autoref", &__self_0),
            Self::Coercion(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Coercion", &__self_0),
            Self::RegionParameterDefinition(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "RegionParameterDefinition", __self_0, &__self_1),
            Self::BoundRegion(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "BoundRegion", __self_0, __self_1, &__self_2),
            Self::UpvarRegion(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "UpvarRegion", __self_0, &__self_1),
            Self::Nll(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Nll",
                    &__self_0),
        }
    }
}Debug)]
506pub enum RegionVariableOrigin<'tcx> {
507    /// Region variables created for ill-categorized reasons.
508    ///
509    /// They mostly indicate places in need of refactoring.
510    Misc(Span),
511
512    /// Regions created by a `&P` or `[...]` pattern.
513    PatternRegion(Span),
514
515    /// Regions created by `&` operator.
516    BorrowRegion(Span),
517
518    /// Regions created as part of an autoref of a method receiver.
519    Autoref(Span),
520
521    /// Regions created as part of an automatic coercion.
522    Coercion(Span),
523
524    /// Region variables created as the values for early-bound regions.
525    ///
526    /// FIXME(@lcnr): This should also store a `DefId`, similar to
527    /// `TypeVariableOrigin`.
528    RegionParameterDefinition(Span, Symbol),
529
530    /// Region variables created when instantiating a binder with
531    /// existential variables, e.g. when calling a function or method.
532    BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
533
534    UpvarRegion(ty::UpvarId, Span),
535
536    /// This origin is used for the inference variables that we create
537    /// during NLL region processing.
538    Nll(NllRegionVariableOrigin<'tcx>),
539}
540
541#[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) -> Self {
        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 {
            Self::FreeRegion =>
                ::core::fmt::Formatter::write_str(f, "FreeRegion"),
            Self::Placeholder(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Placeholder", &__self_0),
            Self::Existential { name: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Existential", "name", &__self_0),
        }
    }
}Debug)]
542pub enum NllRegionVariableOrigin<'tcx> {
543    /// During NLL region processing, we create variables for free
544    /// regions that we encounter in the function signature and
545    /// elsewhere. This origin indices we've got one of those.
546    FreeRegion,
547
548    /// "Universal" instantiation of a higher-ranked region (e.g.,
549    /// from a `for<'a> T` binder). Meant to represent "any region".
550    Placeholder(ty::PlaceholderRegion<'tcx>),
551
552    Existential {
553        name: Option<Symbol>,
554    },
555}
556
557#[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) -> Self {
        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)]
558pub struct FixupError {
559    unresolved: TyOrConstInferVar,
560}
561
562impl fmt::Display for FixupError {
563    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
564        match self.unresolved {
565            TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
566                f,
567                "cannot determine the type of this integer; \
568                 add a suffix to specify the type explicitly"
569            ),
570            TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
571                f,
572                "cannot determine the type of this number; \
573                 add a suffix to specify the type explicitly"
574            ),
575            TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
576            TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
577        }
578    }
579}
580
581/// See the `region_obligations` field for more information.
582#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
    TypeOutlivesConstraint<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        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)]
583pub struct TypeOutlivesConstraint<'tcx> {
584    pub sub_region: ty::Region<'tcx>,
585    pub sup_type: Ty<'tcx>,
586    pub origin: SubregionOrigin<'tcx>,
587}
588
589/// Used to configure inference contexts before their creation.
590pub struct InferCtxtBuilder<'tcx> {
591    tcx: TyCtxt<'tcx>,
592    considering_regions: bool,
593    in_hir_typeck: bool,
594    skip_leak_check: bool,
595    /// Whether we should use the new trait solver in the local inference context,
596    /// which affects things like which solver is used in `predicate_may_hold`.
597    next_trait_solver: bool,
598    enable_next_solver_overflow_fcw: bool,
599}
600
601pub 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>)]
602impl<'tcx> TyCtxt<'tcx> {
603    fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
604        InferCtxtBuilder {
605            tcx: self,
606            considering_regions: true,
607            in_hir_typeck: false,
608            skip_leak_check: false,
609            next_trait_solver: self.next_trait_solver_globally(),
610            enable_next_solver_overflow_fcw: true,
611        }
612    }
613}
614
615impl<'tcx> InferCtxtBuilder<'tcx> {
616    pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
617        self.next_trait_solver = next_trait_solver;
618        self
619    }
620
621    pub fn enable_next_solver_overflow_fcw(
622        mut self,
623        enable_next_solver_overflow_fcw: bool,
624    ) -> Self {
625        self.enable_next_solver_overflow_fcw = enable_next_solver_overflow_fcw;
626        self
627    }
628
629    pub fn ignoring_regions(mut self) -> Self {
630        self.considering_regions = false;
631        self
632    }
633
634    pub fn in_hir_typeck(mut self) -> Self {
635        self.in_hir_typeck = true;
636        self
637    }
638
639    pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
640        self.skip_leak_check = skip_leak_check;
641        self
642    }
643
644    /// Given a canonical value `C` as a starting point, create an
645    /// inference context that contains each of the bound values
646    /// within instantiated as a fresh variable. The `f` closure is
647    /// invoked with the new infcx, along with the instantiated value
648    /// `V` and a instantiation `S`. This instantiation `S` maps from
649    /// the bound values in `C` to their instantiated values in `V`
650    /// (in other words, `S(C) = V`).
651    pub fn build_with_canonical<T>(
652        mut self,
653        span: Span,
654        input: &CanonicalQueryInput<'tcx, T>,
655    ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
656    where
657        T: TypeFoldable<TyCtxt<'tcx>>,
658    {
659        let infcx = self.build(input.typing_mode.0);
660        let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
661        (infcx, value, args)
662    }
663
664    pub fn build_with_typing_env(
665        mut self,
666        typing_env: TypingEnv<'tcx>,
667    ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
668        (self.build(typing_env.typing_mode()), typing_env.param_env)
669    }
670
671    pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
672        let InferCtxtBuilder {
673            tcx,
674            considering_regions,
675            in_hir_typeck,
676            skip_leak_check,
677            next_trait_solver,
678            enable_next_solver_overflow_fcw,
679        } = *self;
680        InferCtxt {
681            tcx,
682            typing_mode,
683            considering_regions,
684            in_hir_typeck,
685            skip_leak_check,
686            inner: RefCell::new(InferCtxtInner::new()),
687            lexical_region_resolutions: RefCell::new(None),
688            selection_cache: Default::default(),
689            evaluation_cache: Default::default(),
690            reported_trait_errors: Default::default(),
691            reported_hir_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/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/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/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/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.sup_raw(cause, param_env, 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/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/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/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/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    #[inline(always)]
1038    pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1039        match param.kind {
1040            GenericParamDefKind::Lifetime => {
1041                // Create a region inference variable for the given
1042                // region parameter definition.
1043                self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1044                    span, param.name,
1045                ))
1046                .into()
1047            }
1048            GenericParamDefKind::Type { .. } => {
1049                // Create a type inference variable for the given
1050                // type parameter definition. The generic parameters are
1051                // for actual parameters that may be referred to by
1052                // the default of this type parameter, if it exists.
1053                // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1054                // used in a path such as `Foo::<T, U>::new()` will
1055                // use an inference variable for `C` with `[T, U]`
1056                // as the generic parameters for the default, `(T, U)`.
1057                let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1058                    self.universe(),
1059                    TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1060                );
1061
1062                Ty::new_var(self.tcx, ty_var_id).into()
1063            }
1064            GenericParamDefKind::Const { .. } => {
1065                let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1066                let const_var_id = self
1067                    .inner
1068                    .borrow_mut()
1069                    .const_unification_table()
1070                    .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1071                    .vid;
1072                ty::Const::new_var(self.tcx, const_var_id).into()
1073            }
1074        }
1075    }
1076
1077    /// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1078    /// each type/region parameter to a fresh inference variable.
1079    pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
1080        GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1081    }
1082
1083    /// Returns `true` if errors have been reported since this infcx was
1084    /// created. This is sometimes used as a heuristic to skip
1085    /// reporting errors that often occur as a result of earlier
1086    /// errors, but where it's hard to be 100% sure (e.g., unresolved
1087    /// inference variables, regionck errors).
1088    #[must_use = "this method does not have any side effects"]
1089    pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1090        self.tainted_by_errors.get()
1091    }
1092
1093    /// Set the "tainted by errors" flag to true. We call this when we
1094    /// observe an error from a prior pass.
1095    pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1096        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs:1096",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1096u32),
                        ::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)");
1097        self.tainted_by_errors.set(Some(e));
1098    }
1099
1100    pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1101        let mut inner = self.inner.borrow_mut();
1102        let inner = &mut *inner;
1103        inner.unwrap_region_constraints().var_origin(vid)
1104    }
1105
1106    /// Clone the list of variable regions. This is used only during NLL processing
1107    /// to put the set of region variables into the NLL region context.
1108    pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1109        let inner = self.inner.borrow();
1110        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));
1111        let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1112        // FIXME(-Zassumptions-on-binders): Handle solver_data
1113        if !storage.legacy_data.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("{0:#?}",
                storage.legacy_data));
    }
};assert!(storage.legacy_data.is_empty(), "{:#?}", storage.legacy_data);
1114        // We clone instead of taking because borrowck still wants to use the
1115        // inference context after calling this for diagnostics and the new
1116        // trait solver.
1117        storage.var_infos.clone()
1118    }
1119
1120    pub fn has_opaque_types_in_storage(&self) -> bool {
1121        !self.inner.borrow().opaque_type_storage.is_empty()
1122    }
1123
1124    {}
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/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(1124u32),
                                ::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/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs:1124",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1124u32),
                        ::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)]
1125    pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1126        self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1127    }
1128
1129    {}
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/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(1129u32),
                                ::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/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs:1129",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1129u32),
                        ::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)]
1130    pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1131        self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1132    }
1133
1134    pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1135        if !self.next_trait_solver() {
1136            return false;
1137        }
1138
1139        let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1140        let inner = &mut *self.inner.borrow_mut();
1141        let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1142        inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1143            if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1144                let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1145                if opaque_sub_vid == ty_sub_vid {
1146                    return true;
1147                }
1148            }
1149
1150            false
1151        })
1152    }
1153
1154    /// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1155    ///
1156    /// This only checks for a subtype relation, it does not require equality.
1157    pub fn opaques_with_sub_unified_hidden_type(
1158        &self,
1159        ty_vid: TyVid,
1160    ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1161        // Avoid accidentally allowing more code to compile with the old solver.
1162        if !self.next_trait_solver() {
1163            return ::alloc::vec::Vec::new()vec![];
1164        }
1165
1166        let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1167        let inner = &mut *self.inner.borrow_mut();
1168        // This is iffy, can't call `type_variables()` as we're already
1169        // borrowing the `opaque_type_storage` here.
1170        let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1171        inner
1172            .opaque_type_storage
1173            .iter_opaque_types()
1174            .filter_map(|(key, hidden_ty)| {
1175                if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1176                    let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1177                    if opaque_sub_vid == ty_sub_vid {
1178                        return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1179                            self.tcx,
1180                            key.def_id.into(),
1181                            key.args,
1182                        ));
1183                    }
1184                }
1185
1186                None
1187            })
1188            .collect()
1189    }
1190
1191    #[inline(always)]
1192    pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1193        if true {
    if !!self.next_trait_solver() {
        ::core::panicking::panic("assertion failed: !self.next_trait_solver()")
    };
};debug_assert!(!self.next_trait_solver());
1194        match self.typing_mode_raw().assert_not_erased() {
1195            TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1196            | TypingMode::PostTypeckThroughBorrowck { defining_opaque_types } => {
1197                id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1198            }
1199            // FIXME(#132279): This function is quite weird in post-analysis
1200            // and post-borrowck analysis mode. We may need to modify its uses
1201            // to support PostBorrowck in the old solver as well.
1202            TypingMode::Coherence
1203            | TypingMode::Reflection
1204            | TypingMode::PostBorrowck { .. }
1205            | TypingMode::PostAnalysis
1206            | TypingMode::Codegen => false,
1207        }
1208    }
1209
1210    pub fn push_hir_typeck_potentially_region_dependent_goal(
1211        &self,
1212        goal: PredicateObligation<'tcx>,
1213    ) {
1214        let mut inner = self.inner.borrow_mut();
1215        inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1216        inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1217    }
1218
1219    pub fn take_hir_typeck_potentially_region_dependent_goals(
1220        &self,
1221    ) -> Vec<PredicateObligation<'tcx>> {
1222        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");
1223        std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1224    }
1225
1226    pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1227        self.deeply_resolve_ignoring_regions(t).to_string()
1228    }
1229
1230    /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1231    /// universe index of `TyVar(vid)`.
1232    pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1233        use self::type_variable::TypeVariableValue;
1234
1235        match self.inner.borrow_mut().type_variables().probe(vid) {
1236            TypeVariableValue::Known { value } => Ok(value),
1237            TypeVariableValue::Unknown { universe } => Err(universe),
1238        }
1239    }
1240
1241    /// If `vid` resolves to a type, return that type. Otherwise return the root variable id for `vid`.
1242    pub fn shallow_resolve_ty_var_or_get_root(&self, vid: TyVid) -> Result<Ty<'tcx>, TyVid> {
1243        let (root, value) = self.inner.borrow_mut().type_variables().probe_with_root_vid(vid);
1244
1245        match value {
1246            TypeVariableValue::Known { value } => Ok(value),
1247            TypeVariableValue::Unknown { universe: _ } => Err(root),
1248        }
1249    }
1250
1251    /// Resolve a type variable. Resolving means the following:
1252    ///
1253    /// - If a `Ty` is a rigid type (like, an integer, or some ADT), do nothing.
1254    /// - If a `Ty` is a type infer variable, but has been equated with an actual type,
1255    ///   return that type.
1256    /// - If a `Ty` is an int or float infer variable, and has been equated with an integer
1257    ///   or floating point type, return that type.
1258    /// - If a `Ty` is any kind of infer variable that has been equated, but not yet with a rigid
1259    ///   type, then this set of equated variables forms an equivalence class. One of the variables
1260    ///   in that equivalent class is said to be the root variable, and resolving makes sure to
1261    ///   consistently return this root variable. This is beneficial for caching.
1262    ///   This behavior, of returning roots, changed in <https://github.com/rust-lang/rust/pull/158447>.
1263    ///
1264    /// Otherwise, resolving simply does nothing.
1265    ///
1266    /// The "shallow" part of the name refers to the fact that types may themselves contain more
1267    /// type variables. e.g. The field types of a struct. `shallow_resolve` does not recurse into
1268    /// these nested variables. If that's what you want, use [`deeply_resolve_ignoring_regions`](Self::deeply_resolve_ignoring_regions),
1269    /// or better [`deeply_resolve_via_unification_table`](rustc_type_ir::InferCtxtLike::deeply_resolve_via_unification_table), if you can, which *does* resolve regions.
1270    pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1271        if let ty::Infer(v) = *ty.kind() {
1272            match v {
1273                ty::TyVar(v) => {
1274                    // Not entirely obvious: if `typ` is a type variable,
1275                    // it can be resolved to an int/float variable, which
1276                    // can then be recursively resolved, hence the
1277                    // recursion. Note though that we prevent type
1278                    // variables from unifying to other type variables
1279                    // directly (though they may be embedded
1280                    // structurally), and we prevent cycles in any case,
1281                    // so this recursion should always be of very limited
1282                    // depth.
1283                    //
1284                    // Note: if these two lines are combined into one we get
1285                    // dynamic borrow errors on `self.inner`.
1286                    let (root_vid, value) =
1287                        self.inner.borrow_mut().type_variables().probe_with_root_vid(v);
1288                    value.known().map_or_else(
1289                        || if root_vid == v { ty } else { Ty::new_var(self.tcx, root_vid) },
1290                        |t| self.shallow_resolve(t),
1291                    )
1292                }
1293
1294                ty::IntVar(v) => {
1295                    let (root, value) =
1296                        self.inner.borrow_mut().int_unification_table().inlined_probe_key_value(v);
1297                    match value {
1298                        ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1299                        ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1300                        ty::IntVarValue::Unknown => {
1301                            if root == v {
1302                                ty
1303                            } else {
1304                                Ty::new_int_var(self.tcx, root)
1305                            }
1306                        }
1307                    }
1308                }
1309
1310                ty::FloatVar(v) => {
1311                    let (root, value) = self
1312                        .inner
1313                        .borrow_mut()
1314                        .float_unification_table()
1315                        .inlined_probe_key_value(v);
1316                    match value {
1317                        ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1318                        ty::FloatVarValue::Unknown => {
1319                            if root == v {
1320                                ty
1321                            } else {
1322                                Ty::new_float_var(self.tcx, root)
1323                            }
1324                        }
1325                    }
1326                }
1327
1328                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1329            }
1330        } else {
1331            ty
1332        }
1333    }
1334
1335    /// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1336    /// It's the same, but for consts.
1337    pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1338        match ct.kind() {
1339            ty::ConstKind::Infer(infer_ct) => match infer_ct {
1340                InferConst::Var(vid) => {
1341                    let (root, value) = self
1342                        .inner
1343                        .borrow_mut()
1344                        .const_unification_table()
1345                        .inlined_probe_key_value(vid);
1346                    value.known().unwrap_or_else(|| {
1347                        if root.vid == vid { ct } else { ty::Const::new_var(self.tcx, root.vid) }
1348                    })
1349                }
1350                InferConst::Fresh(_) => ct,
1351            },
1352
1353            ty::ConstKind::Param(_)
1354            | ty::ConstKind::Bound(_, _)
1355            | ty::ConstKind::Placeholder(_)
1356            | ty::ConstKind::Alias(_, _)
1357            | ty::ConstKind::Value(_)
1358            | ty::ConstKind::Error(_)
1359            | ty::ConstKind::Expr(_) => ct,
1360        }
1361    }
1362
1363    /// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1364    /// It's the same, but for terms (types or consts).
1365    pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1366        match term.kind() {
1367            ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1368            ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1369        }
1370    }
1371
1372    pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1373        self.inner.borrow_mut().type_variables().root_var(var)
1374    }
1375
1376    /// If `ty` is an unresolved type variable, returns its root vid.
1377    pub fn root_vid(&self, ty: Ty<'tcx>) -> Option<ty::TyVid> {
1378        let (root, value) =
1379            self.inner.borrow_mut().type_variables().inlined_probe_with_vid(ty.ty_vid()?);
1380        value.is_unknown().then_some(root)
1381    }
1382
1383    pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1384        self.inner.borrow_mut().type_variables().sub_unify(a, b);
1385    }
1386
1387    pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1388        self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1389    }
1390
1391    pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1392        self.inner.borrow_mut().float_unification_table().find(var)
1393    }
1394
1395    pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1396        self.inner.borrow_mut().const_unification_table().find(var).vid
1397    }
1398
1399    /// Resolves a const var to a rigid const, if it was constrained to one,
1400    /// or else the root const var in the unification table.
1401    pub fn shallow_resolve_const_var(&self, vid: ty::ConstVid) -> ty::Const<'tcx> {
1402        match self.try_resolve_const_var(vid) {
1403            Ok(ct) => ct,
1404            Err(_) => ty::Const::new_var(self.tcx, self.root_const_var(vid)),
1405        }
1406    }
1407
1408    /// Resolves a type var to a rigid type, if it was constrained to one,
1409    /// or else the root type var in the unification table.
1410    pub fn shallow_resolve_ty_var(&self, vid: ty::TyVid) -> Ty<'tcx> {
1411        match self.try_resolve_ty_var(vid) {
1412            Ok(ty) => ty,
1413            Err(_) => Ty::new_var(self.tcx, self.root_var(vid)),
1414        }
1415    }
1416
1417    /// Resolves an int var to a rigid int type, if it was constrained to one,
1418    /// or else the root int var in the unification table.
1419    pub fn shallow_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1420        let mut inner = self.inner.borrow_mut();
1421        let value = inner.int_unification_table().probe_value(vid);
1422        match value {
1423            ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1424            ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1425            ty::IntVarValue::Unknown => {
1426                Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1427            }
1428        }
1429    }
1430
1431    /// Resolves a float var to a rigid type, if it was constrained to one,
1432    /// or else the root float var in the unification table.
1433    pub fn shallow_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1434        let mut inner = self.inner.borrow_mut();
1435        let value = inner.float_unification_table().probe_value(vid);
1436        match value {
1437            ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1438            ty::FloatVarValue::Unknown => {
1439                Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1440            }
1441        }
1442    }
1443
1444    /// If a type/const variable has not (yet) been unified, it is left as is.
1445    ///
1446    /// This is an idempotent operation that does not affect inference state in any way,
1447    /// which means it's safe to call this function at will.
1448    ///
1449    /// Region variables are unaffected.
1450    pub fn deeply_resolve_ignoring_regions<T>(&self, value: T) -> T
1451    where
1452        T: TypeFoldable<TyCtxt<'tcx>>,
1453    {
1454        if let Err(guar) = value.error_reported() {
1455            self.set_tainted_by_errors(guar);
1456        }
1457        if !value.has_non_region_infer() {
1458            return value;
1459        }
1460        let mut r = resolve::DeepResolverIgnoringRegions::new(self);
1461        value.fold_with(&mut r)
1462    }
1463
1464    /// Where possible, replaces type/const/region variables in `value` with their final value.
1465    /// If a type/const/region variable has not (yet) been unified, it is left as is.
1466    ///
1467    /// This is an idempotent operation that does not affect inference state in any way,
1468    /// which means it's safe to call this function at will.
1469    pub fn deeply_resolve_via_unification_table<T>(&self, value: T) -> T
1470    where
1471        T: TypeFoldable<TyCtxt<'tcx>>,
1472    {
1473        use rustc_middle::ty::InferCtxtLike;
1474        #[allow(rustc::usage_of_type_ir_traits)]
1475        InferCtxtLike::deeply_resolve_via_unification_table(self, value)
1476    }
1477
1478    pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1479    where
1480        T: TypeFoldable<TyCtxt<'tcx>>,
1481    {
1482        if !value.has_infer() {
1483            return value; // Avoid duplicated type-folding.
1484        }
1485        let mut r = InferenceLiteralEraser { tcx: self.tcx };
1486        value.fold_with(&mut r)
1487    }
1488
1489    pub fn try_resolve_const_var(
1490        &self,
1491        vid: ty::ConstVid,
1492    ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1493        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1494            ConstVariableValue::Known { value } => Ok(value),
1495            ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1496        }
1497    }
1498
1499    /// Attempts to resolve all type/region/const variables in
1500    /// `value`. Region inference must have been run already (e.g.,
1501    /// by calling `resolve_regions_and_report_errors`). If some
1502    /// variable was never unified, an `Err` results.
1503    ///
1504    /// This method is idempotent, but it not typically not invoked
1505    /// except during the writeback phase.
1506    pub fn deeply_resolve_via_region_graph<T: TypeFoldable<TyCtxt<'tcx>>>(
1507        &self,
1508        value: T,
1509    ) -> FixupResult<T> {
1510        match resolve::deeply_resolve_via_region_graph(self, value) {
1511            Ok(value) => {
1512                if value.has_non_region_infer() {
1513                    ::rustc_span::macros::bug_impl(None,
    format_args!("`{0:?}` is not fully resolved", value), Location::caller());bug!("`{value:?}` is not fully resolved");
1514                }
1515                if value.has_infer_regions() {
1516                    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"));
1517                    Ok(fold_regions(self.tcx, value, |re, _| {
1518                        if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1519                    }))
1520                } else {
1521                    Ok(value)
1522                }
1523            }
1524            Err(e) => Err(e),
1525        }
1526    }
1527
1528    // Instantiates the bound variables in a given binder with fresh inference
1529    // variables in the current universe.
1530    //
1531    // Use this method if you'd like to find some generic parameters of the binder's
1532    // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1533    // that corresponds to your use case, consider whether or not you should
1534    // use [`InferCtxt::enter_forall`] instead.
1535    pub fn instantiate_binder_with_fresh_vars<T>(
1536        &self,
1537        span: Span,
1538        lbrct: BoundRegionConversionTime,
1539        value: ty::Binder<'tcx, T>,
1540    ) -> T
1541    where
1542        T: TypeFoldable<TyCtxt<'tcx>>,
1543    {
1544        if let Some(_) = value.as_ref().no_bound_vars() {
1545            return value.skip_binder();
1546        }
1547
1548        let bound_vars = value.bound_vars();
1549        let mut args = Vec::with_capacity(bound_vars.len());
1550
1551        for bound_var_kind in bound_vars {
1552            let arg: ty::GenericArg<'_> = match bound_var_kind {
1553                ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1554                ty::BoundVariableKind::Region(br) => {
1555                    self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1556                }
1557                ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1558            };
1559            args.push(arg);
1560        }
1561
1562        struct ToFreshVars<'tcx> {
1563            args: Vec<ty::GenericArg<'tcx>>,
1564        }
1565
1566        impl<'tcx> BoundVarReplacerDelegate<TyCtxt<'tcx>> for ToFreshVars<'tcx> {
1567            fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1568                self.args[br.var.index()].expect_region()
1569            }
1570            fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1571                self.args[bt.var.index()].expect_ty()
1572            }
1573            fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1574                self.args[bc.var.index()].expect_const()
1575            }
1576        }
1577        let delegate = ToFreshVars { args };
1578        self.tcx.replace_bound_vars_uncached(value, delegate)
1579    }
1580
1581    pub fn insert_placeholder_assumptions(
1582        &self,
1583        u: ty::UniverseIndex,
1584        assumptions: rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>,
1585    ) {
1586        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!(
1587            !assumptions.type_outlives.has_escaping_bound_vars(),
1588            "assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1589            assumptions.type_outlives
1590        );
1591        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!(
1592            assumptions.region_outlives.base_edges().all(|r| !r.has_escaping_bound_vars()),
1593            "assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1594            assumptions.region_outlives
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    ) -> rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>> {
1603        self.placeholder_assumptions_for_next_solver.borrow().get(&u).unwrap().clone()
1604    }
1605
1606    pub fn has_placeholder_assumptions(&self, range: RangeInclusive<ty::UniverseIndex>) -> bool {
1607        let assumptions = self.placeholder_assumptions_for_next_solver.borrow();
1608        // Walk around that `Step` trait is nightly only.
1609        (range.start.index()..=range.last.index())
1610            .map(ty::UniverseIndex::from_usize)
1611            .all(|u| assumptions.get(&u).is_some())
1612    }
1613
1614    pub fn get_solver_region_constraint(&self) -> SolverRegionConstraint<'tcx> {
1615        self.inner.borrow().region_constraint_storage.as_ref().unwrap().solver_data.get_constraint()
1616    }
1617
1618    pub fn overwrite_solver_region_constraint(&self, constraint: SolverRegionConstraint<'tcx>) {
1619        self.inner.borrow_mut().unwrap_region_constraints().overwrite_solver_constraint(constraint);
1620    }
1621
1622    /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1623    pub(crate) fn verify_generic_bound(
1624        &self,
1625        origin: SubregionOrigin<'tcx>,
1626        kind: GenericKind<'tcx>,
1627        a: ty::Region<'tcx>,
1628        bound: VerifyBound<'tcx>,
1629    ) {
1630        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs:1630",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1630u32),
                        ::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);
1631
1632        self.inner
1633            .borrow_mut()
1634            .unwrap_region_constraints()
1635            .verify_generic_bound(origin, kind, a, bound);
1636    }
1637
1638    /// Obtains the latest type of the given closure; this may be a
1639    /// closure in the current function, in which case its
1640    /// `ClosureKind` may not yet be known.
1641    pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1642        let unresolved_kind_ty = match *closure_ty.kind() {
1643            ty::Closure(_, args) => args.as_closure().kind_ty(),
1644            ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1645            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected type {0}", closure_ty), Location::caller())bug!("unexpected type {closure_ty}"),
1646        };
1647        let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1648        closure_kind_ty.to_opt_closure_kind()
1649    }
1650
1651    pub fn universe(&self) -> ty::UniverseIndex {
1652        self.universe.get()
1653    }
1654
1655    /// Creates and return a fresh universe that extends all previous
1656    /// universes. Updates `self.universe` to that new universe.
1657    pub fn create_next_universe(&self) -> ty::UniverseIndex {
1658        let u = self.universe.get().next_universe();
1659        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs:1659",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1659u32),
                        ::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:?}");
1660        self.universe.set(u);
1661        u
1662    }
1663
1664    /// We need to disable the fcw if we're already in a fcw emitting to avoid
1665    /// indefinite triggering.
1666    pub fn with_disabled_next_solver_overflow_fcw<F, R>(&self, mut f: F) -> R
1667    where
1668        F: FnMut() -> R,
1669    {
1670        let prev = self.enable_next_solver_overflow_fcw.replace(false);
1671        let ret = f();
1672        self.enable_next_solver_overflow_fcw.set(prev);
1673        ret
1674    }
1675
1676    /// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1677    /// which contains the necessary information to use the trait system without
1678    /// using canonicalization or carrying this inference context around.
1679    pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1680        let typing_mode = match self.typing_mode_raw() {
1681            // FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1682            // to handle them without proper canonicalization. This means we may cause cycle
1683            // errors and fail to reveal opaques while inside of bodies. We should rename this
1684            // function and require explicit comments on all use-sites in the future.
1685            ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1686            | ty::TypingMode::PostTypeckThroughBorrowck { defining_opaque_types: _ } => {
1687                TypingMode::non_body_analysis()
1688            }
1689            mode @ (ty::TypingMode::Coherence
1690            | ty::TypingMode::PostBorrowck { .. }
1691            | ty::TypingMode::PostAnalysis
1692            | ty::TypingMode::Reflection
1693            | ty::TypingMode::Codegen) => mode,
1694            ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::unreachable_default_msg()unreachable!(),
1695        };
1696        ty::TypingEnv::new(param_env, typing_mode)
1697    }
1698
1699    /// Similar to [`Self::canonicalize_query`], except that it returns
1700    /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1701    /// `param_env` to not contain any inference variables or placeholders.
1702    pub fn pseudo_canonicalize_query<V>(
1703        &self,
1704        param_env: ty::ParamEnv<'tcx>,
1705        value: V,
1706    ) -> PseudoCanonicalInput<'tcx, V>
1707    where
1708        V: TypeVisitable<TyCtxt<'tcx>>,
1709    {
1710        if true {
    if !!value.has_infer() {
        ::core::panicking::panic("assertion failed: !value.has_infer()")
    };
};debug_assert!(!value.has_infer());
1711        if true {
    if !!value.has_placeholders() {
        ::core::panicking::panic("assertion failed: !value.has_placeholders()")
    };
};debug_assert!(!value.has_placeholders());
1712        if true {
    if !!param_env.has_infer() {
        ::core::panicking::panic("assertion failed: !param_env.has_infer()")
    };
};debug_assert!(!param_env.has_infer());
1713        if true {
    if !!param_env.has_placeholders() {
        ::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
    };
};debug_assert!(!param_env.has_placeholders());
1714        self.typing_env(param_env).as_query_input(value)
1715    }
1716
1717    /// The returned function is used in a fast path. If it returns `true` the variable is
1718    /// unchanged, `false` indicates that the status is unknown.
1719    #[inline]
1720    pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1721        // This hoists the borrow/release out of the loop body.
1722        let inner = self.inner.try_borrow();
1723
1724        move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1725            (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1726                use self::type_variable::TypeVariableValue;
1727
1728                #[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
    {
    Some(TypeVariableValue::Unknown { .. }) => true,
    _ => false,
}matches!(
1729                    inner.try_type_variables_probe_ref(ty_var),
1730                    Some(TypeVariableValue::Unknown { .. })
1731                )
1732            }
1733            _ => false,
1734        }
1735    }
1736
1737    /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1738    ///   * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1739    ///   * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1740    ///
1741    /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1742    /// inlined, despite being large, because it has only two call sites that
1743    /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1744    /// inference variables), and it handles both `Ty` and `ty::Const` without
1745    /// having to resort to storing full `GenericArg`s in `stalled_on`.
1746    #[inline(always)]
1747    pub fn ty_or_const_infer_var_changed(&self, var: TyOrConstInferVar) -> bool {
1748        match var {
1749            TyOrConstInferVar::Ty(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().try_type_variables_probe_ref(vid)
    {
    Some(TypeVariableValue::Unknown { .. }) => true,
    _ => false,
}matches!(
1750                self.inner.borrow().try_type_variables_probe_ref(vid),
1751                Some(TypeVariableValue::Unknown { .. })
1752            ),
1753            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!(
1754                self.inner.borrow().int_unification_storage.try_probe_value(vid),
1755                Some(ty::IntVarValue::Unknown)
1756            ),
1757            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!(
1758                self.inner.borrow().float_unification_storage.try_probe_value(vid),
1759                Some(ty::FloatVarValue::Unknown)
1760            ),
1761            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!(
1762                self.inner.borrow().const_unification_storage.try_probe_value(vid),
1763                Some(ConstVariableValue::Unknown { .. })
1764            ),
1765        }
1766    }
1767
1768    /// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1769    pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1770        if true {
    if !self.obligation_inspector.get().is_none() {
        {
            ::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
        }
    };
};debug_assert!(
1771            self.obligation_inspector.get().is_none(),
1772            "shouldn't override a set obligation inspector"
1773        );
1774        self.obligation_inspector.set(Some(inspector));
1775    }
1776}
1777
1778/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1779/// Used only for diagnostics.
1780struct InferenceLiteralEraser<'tcx> {
1781    tcx: TyCtxt<'tcx>,
1782}
1783
1784impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1785    fn cx(&self) -> TyCtxt<'tcx> {
1786        self.tcx
1787    }
1788
1789    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1790        match ty.kind() {
1791            ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1792            ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1793            _ => ty.super_fold_with(self),
1794        }
1795    }
1796}
1797
1798impl<'tcx> TypeTrace<'tcx> {
1799    pub fn span(&self) -> Span {
1800        self.cause.span
1801    }
1802
1803    pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1804        TypeTrace {
1805            cause: cause.clone(),
1806            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1807        }
1808    }
1809
1810    pub fn trait_refs(
1811        cause: &ObligationCause<'tcx>,
1812        a: ty::TraitRef<'tcx>,
1813        b: ty::TraitRef<'tcx>,
1814    ) -> TypeTrace<'tcx> {
1815        TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1816    }
1817
1818    pub fn consts(
1819        cause: &ObligationCause<'tcx>,
1820        a: ty::Const<'tcx>,
1821        b: ty::Const<'tcx>,
1822    ) -> TypeTrace<'tcx> {
1823        TypeTrace {
1824            cause: cause.clone(),
1825            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1826        }
1827    }
1828}
1829
1830impl<'tcx> SubregionOrigin<'tcx> {
1831    pub fn span(&self) -> Span {
1832        match *self {
1833            SubregionOrigin::Subtype(ref a) => a.span(),
1834            SubregionOrigin::RelateObjectBound(a) => a,
1835            SubregionOrigin::RelateParamBound(a, ..) => a,
1836            SubregionOrigin::RelateRegionParamBound(a, _) => a,
1837            SubregionOrigin::Reborrow(a) => a,
1838            SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1839            SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1840            SubregionOrigin::AscribeUserTypeProvePredicate(span, _) => span,
1841            SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1842            SubregionOrigin::SolverRegionConstraint(a) => a,
1843        }
1844    }
1845
1846    pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1847    where
1848        F: FnOnce() -> Self,
1849    {
1850        match *cause.code() {
1851            traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1852                SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1853            }
1854
1855            traits::ObligationCauseCode::CompareImplItem {
1856                impl_item_def_id,
1857                trait_item_def_id,
1858                kind: _,
1859            } => SubregionOrigin::CompareImplItemObligation {
1860                span: cause.span,
1861                impl_item_def_id,
1862                trait_item_def_id,
1863            },
1864
1865            traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1866                impl_item_def_id,
1867                trait_item_def_id,
1868            } => SubregionOrigin::CheckAssociatedTypeBounds {
1869                impl_item_def_id,
1870                trait_item_def_id,
1871                parent: Box::new(default()),
1872            },
1873
1874            traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span, def_id) => {
1875                SubregionOrigin::AscribeUserTypeProvePredicate(span, def_id)
1876            }
1877
1878            traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1879                SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1880            }
1881
1882            _ => default(),
1883        }
1884    }
1885}
1886
1887impl<'tcx> RegionVariableOrigin<'tcx> {
1888    pub fn span(&self) -> Span {
1889        match *self {
1890            RegionVariableOrigin::Misc(a)
1891            | RegionVariableOrigin::PatternRegion(a)
1892            | RegionVariableOrigin::BorrowRegion(a)
1893            | RegionVariableOrigin::Autoref(a)
1894            | RegionVariableOrigin::Coercion(a)
1895            | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1896            | RegionVariableOrigin::BoundRegion(a, ..)
1897            | RegionVariableOrigin::UpvarRegion(_, a) => a,
1898            RegionVariableOrigin::Nll(..) => ::rustc_span::macros::bug_impl(None,
    format_args!("NLL variable used with `span`"), Location::caller())bug!("NLL variable used with `span`"),
1899        }
1900    }
1901}
1902
1903impl<'tcx> InferCtxt<'tcx> {
1904    /// Given a [`hir::Block`], get the span of its last expression or
1905    /// statement, peeling off any inner blocks.
1906    pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1907        let block = block.innermost_block();
1908        if let Some(expr) = &block.expr {
1909            expr.span
1910        } else if let Some(stmt) = block.stmts.last() {
1911            // possibly incorrect trailing `;` in the else arm
1912            stmt.span
1913        } else {
1914            // empty block; point at its entirety
1915            block.span
1916        }
1917    }
1918
1919    /// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1920    /// of its last expression or statement, peeling off any inner blocks.
1921    pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1922        match self.tcx.hir_node(hir_id) {
1923            hir::Node::Block(blk)
1924            | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1925                self.find_block_span(blk)
1926            }
1927            hir::Node::Expr(e) => e.span,
1928            _ => DUMMY_SP,
1929        }
1930    }
1931}
1932
1933/// Returns unresolved root variables from `table`, according to `is_unresolved`.
1934fn unresolved_root_variables_of<V: UnifyKey>(
1935    mut table: UnificationTable<'_, '_, V>,
1936    is_unresolved: impl Fn(V::Value) -> bool,
1937) -> Vec<V>
1938where
1939    V: Eq,
1940    V::Value: UnifyValue,
1941    for<'a> UndoLog<'a>: From<sv::UndoLog<ut::Delegate<V>>>,
1942{
1943    (0..table.len() as u32)
1944        .map(V::from_index)
1945        .filter(|&vid| {
1946            // NB: as of writing this `ena` doesn't provide a non-inlined `probe_key_value`...
1947            let (root, value) = table.inlined_probe_key_value(vid);
1948            root == vid && is_unresolved(value)
1949        })
1950        .collect()
1951}