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    GenericParamDefKind, InferConst, OpaqueTypeKey, ProvisionalHiddenType, PseudoCanonicalInput,
33    Term, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
34    TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
35};
36use rustc_span::{DUMMY_SP, Span, Symbol, bug};
37use rustc_type_ir::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]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "InferOk value obligations", &self.value, &&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]
    #[rustc_trivial_field_reads]
    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
353impl<'tcx> Drop for InferCtxt<'tcx> {
354    fn drop(&mut self) {
355        let mut inner = self.inner.borrow_mut();
356        let opaque_type_storage = &mut inner.opaque_type_storage;
357
358        // No need for the drop bomb when we're in `TypingMode::PostTypeckThroughBorrowck`, and the `InferCtxt`
359        // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
360        // in relation to regions. In some places *after* typeck that aren't borrowck, we use
361        // `TypingMode::PostTypeckThroughBorrowck` to prevent defining opaque types and we simply don't care about regions.
362        match self.typing_mode_raw() {
363            TypingMode::Coherence
364            | TypingMode::Typeck { .. }
365            | TypingMode::PostBorrowck { .. }
366            | TypingMode::Reflection
367            | TypingMode::PostAnalysis
368            | TypingMode::Codegen => {}
369            // In erased mode, the opaque type storage is always empty
370            TypingMode::ErasedNotCoherence(..) => {}
371            TypingMode::PostTypeckThroughBorrowck { .. } => {
372                if !self.considering_regions {
373                    return;
374                }
375            }
376        }
377
378        if !opaque_type_storage.is_empty() {
379            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:?}")));
380        }
381    }
382}
383
384/// See the `error_reporting` module for more details.
385#[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]
    #[rustc_trivial_field_reads]
    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]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Regions(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Regions", &__self_0),
            Self::Terms(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Terms",
                    &__self_0),
            Self::Aliases(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Aliases", &__self_0),
            Self::TraitRefs(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TraitRefs", &__self_0),
            Self::PolySigs(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "PolySigs", &__self_0),
            Self::ExistentialTraitRef(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ExistentialTraitRef", &__self_0),
            Self::ExistentialProjection(__self_0) =>
                ::core::fmt::Formatter::debug_struct_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)]
386pub enum ValuePairs<'tcx> {
387    Regions(ExpectedFound<ty::Region<'tcx>>),
388    Terms(ExpectedFound<ty::Term<'tcx>>),
389    Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
390    TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
391    PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
392    ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
393    ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
394}
395
396impl<'tcx> ValuePairs<'tcx> {
397    pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
398        if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
399            && let Some(expected) = expected.as_type()
400            && let Some(found) = found.as_type()
401        {
402            Some((expected, found))
403        } else {
404            None
405        }
406    }
407}
408
409/// The trace designates the path through inference that we took to
410/// encounter an error or subtyping constraint.
411///
412/// See the `error_reporting` module for more details.
413#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for TypeTrace<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    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]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "TypeTrace cause values", &self.cause, &&self.values)
    }
}Debug)]
414pub struct TypeTrace<'tcx> {
415    pub cause: ObligationCause<'tcx>,
416    pub values: ValuePairs<'tcx>,
417}
418
419/// The origin of a `r1 <= r2` constraint.
420///
421/// See `error_reporting` module for more details
422#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
    SubregionOrigin<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    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]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Subtype(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Subtype", &__self_0),
            Self::RelateObjectBound(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "RelateObjectBound", &__self_0),
            Self::RelateParamBound(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "RelateParamBound", __self_0, __self_1, &__self_2),
            Self::RelateRegionParamBound(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "RelateRegionParamBound", __self_0, &__self_1),
            Self::Reborrow(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Reborrow", &__self_0),
            Self::ReferenceOutlivesReferent(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_struct_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 impl_item_def_id trait_item_def_id",
                    __self_0, __self_1, &__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 impl_item_def_id trait_item_def_id",
                    __self_0, __self_1, &__self_2),
            Self::AscribeUserTypeProvePredicate(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "AscribeUserTypeProvePredicate", __self_0, &__self_1),
            Self::SolverRegionConstraint(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "SolverRegionConstraint", &__self_0),
        }
    }
}Debug)]
423pub enum SubregionOrigin<'tcx> {
424    /// Arose from a subtyping relation
425    Subtype(Box<TypeTrace<'tcx>>),
426
427    /// When casting `&'a T` to an `&'b Trait` object,
428    /// relating `'a` to `'b`.
429    RelateObjectBound(Span),
430
431    /// Some type parameter was instantiated with the given type,
432    /// and that type must outlive some region.
433    RelateParamBound(Span, Ty<'tcx>, Option<Span>),
434
435    /// The given region parameter was instantiated with a region
436    /// that must outlive some other region.
437    RelateRegionParamBound(Span, Option<Ty<'tcx>>),
438
439    /// Creating a pointer `b` to contents of another reference.
440    Reborrow(Span),
441
442    /// (&'a &'b T) where a >= b
443    ReferenceOutlivesReferent(Ty<'tcx>, Span),
444
445    /// Comparing the signature and requirements of an impl method against
446    /// the containing trait.
447    CompareImplItemObligation {
448        span: Span,
449        impl_item_def_id: LocalDefId,
450        trait_item_def_id: DefId,
451    },
452
453    /// Checking that the bounds of a trait's associated type hold for a given impl.
454    CheckAssociatedTypeBounds {
455        parent: Box<SubregionOrigin<'tcx>>,
456        impl_item_def_id: LocalDefId,
457        trait_item_def_id: DefId,
458    },
459
460    AscribeUserTypeProvePredicate(Span, DefId),
461
462    // FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
463    // proper diagnostics for solver region constraints.
464    SolverRegionConstraint(Span),
465}
466
467// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
468#[cfg(target_pointer_width = "64")]
469const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
470
471impl<'tcx> SubregionOrigin<'tcx> {
472    pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
473        match self {
474            Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
475            Self::AscribeUserTypeProvePredicate(span, def_id) => {
476                ConstraintCategory::Predicate(*span, *def_id)
477            }
478            Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
479            _ => ConstraintCategory::BoringNoLocation,
480        }
481    }
482}
483
484/// Times when we replace bound regions with existentials:
485#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for BoundRegionConversionTime {
}
#[automatically_derived]impl ::core::clone::Clone for
    BoundRegionConversionTime {
    #[inline]
    #[rustc_trivial_field_reads]
    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]
    #[rustc_trivial_field_reads]
    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_struct_field1_finish(f,
                    "AssocTypeProjection", &__self_0),
        }
    }
}Debug)]
486pub enum BoundRegionConversionTime {
487    /// when a fn is called
488    FnCall,
489
490    /// when two higher-ranked types are compared
491    HigherRankedType,
492
493    /// when projecting an associated type
494    AssocTypeProjection(DefId),
495}
496
497/// Reasons to create a region inference variable.
498///
499/// See `error_reporting` module for more details.
500#[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]
    #[rustc_trivial_field_reads]
    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]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Misc(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Misc",
                    &__self_0),
            Self::PatternRegion(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "PatternRegion", &__self_0),
            Self::BorrowRegion(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "BorrowRegion", &__self_0),
            Self::Autoref(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Autoref", &__self_0),
            Self::Coercion(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Coercion", &__self_0),
            Self::RegionParameterDefinition(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "RegionParameterDefinition", __self_0, &__self_1),
            Self::BoundRegion(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "BoundRegion", __self_0, __self_1, &__self_2),
            Self::UpvarRegion(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "UpvarRegion", __self_0, &__self_1),
            Self::Nll(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Nll",
                    &__self_0),
        }
    }
}Debug)]
501pub enum RegionVariableOrigin<'tcx> {
502    /// Region variables created for ill-categorized reasons.
503    ///
504    /// They mostly indicate places in need of refactoring.
505    Misc(Span),
506
507    /// Regions created by a `&P` or `[...]` pattern.
508    PatternRegion(Span),
509
510    /// Regions created by `&` operator.
511    BorrowRegion(Span),
512
513    /// Regions created as part of an autoref of a method receiver.
514    Autoref(Span),
515
516    /// Regions created as part of an automatic coercion.
517    Coercion(Span),
518
519    /// Region variables created as the values for early-bound regions.
520    ///
521    /// FIXME(@lcnr): This should also store a `DefId`, similar to
522    /// `TypeVariableOrigin`.
523    RegionParameterDefinition(Span, Symbol),
524
525    /// Region variables created when instantiating a binder with
526    /// existential variables, e.g. when calling a function or method.
527    BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
528
529    UpvarRegion(ty::UpvarId, Span),
530
531    /// This origin is used for the inference variables that we create
532    /// during NLL region processing.
533    Nll(NllRegionVariableOrigin<'tcx>),
534}
535
536#[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]
    #[rustc_trivial_field_reads]
    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]
    #[rustc_trivial_field_reads]
    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_struct_field1_finish(f,
                    "Placeholder", &__self_0),
            Self::Existential { name: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Existential name", &__self_0),
        }
    }
}Debug)]
537pub enum NllRegionVariableOrigin<'tcx> {
538    /// During NLL region processing, we create variables for free
539    /// regions that we encounter in the function signature and
540    /// elsewhere. This origin indices we've got one of those.
541    FreeRegion,
542
543    /// "Universal" instantiation of a higher-ranked region (e.g.,
544    /// from a `for<'a> T` binder). Meant to represent "any region".
545    Placeholder(ty::PlaceholderRegion<'tcx>),
546
547    Existential {
548        name: Option<Symbol>,
549    },
550}
551
552#[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]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<TyOrConstInferVar>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for FixupError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "FixupError unresolved", &&self.unresolved)
    }
}Debug)]
553pub struct FixupError {
554    unresolved: TyOrConstInferVar,
555}
556
557impl fmt::Display for FixupError {
558    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559        match self.unresolved {
560            TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
561                f,
562                "cannot determine the type of this integer; \
563                 add a suffix to specify the type explicitly"
564            ),
565            TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
566                f,
567                "cannot determine the type of this number; \
568                 add a suffix to specify the type explicitly"
569            ),
570            TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
571            TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
572        }
573    }
574}
575
576/// See the `region_obligations` field for more information.
577#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
    TypeOutlivesConstraint<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    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]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "TypeOutlivesConstraint sub_region sup_type origin",
            &self.sub_region, &self.sup_type, &&self.origin)
    }
}Debug)]
578pub struct TypeOutlivesConstraint<'tcx> {
579    pub sub_region: ty::Region<'tcx>,
580    pub sup_type: Ty<'tcx>,
581    pub origin: SubregionOrigin<'tcx>,
582}
583
584/// Used to configure inference contexts before their creation.
585pub struct InferCtxtBuilder<'tcx> {
586    tcx: TyCtxt<'tcx>,
587    considering_regions: bool,
588    in_hir_typeck: bool,
589    skip_leak_check: bool,
590    /// Whether we should use the new trait solver in the local inference context,
591    /// which affects things like which solver is used in `predicate_may_hold`.
592    next_trait_solver: bool,
593    enable_next_solver_overflow_fcw: bool,
594}
595
596pub 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>)]
597impl<'tcx> TyCtxt<'tcx> {
598    fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
599        InferCtxtBuilder {
600            tcx: self,
601            considering_regions: true,
602            in_hir_typeck: false,
603            skip_leak_check: false,
604            next_trait_solver: self.next_trait_solver_globally(),
605            enable_next_solver_overflow_fcw: true,
606        }
607    }
608}
609
610impl<'tcx> InferCtxtBuilder<'tcx> {
611    pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
612        self.next_trait_solver = next_trait_solver;
613        self
614    }
615
616    pub fn enable_next_solver_overflow_fcw(
617        mut self,
618        enable_next_solver_overflow_fcw: bool,
619    ) -> Self {
620        self.enable_next_solver_overflow_fcw = enable_next_solver_overflow_fcw;
621        self
622    }
623
624    pub fn ignoring_regions(mut self) -> Self {
625        self.considering_regions = false;
626        self
627    }
628
629    pub fn in_hir_typeck(mut self) -> Self {
630        self.in_hir_typeck = true;
631        self
632    }
633
634    pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
635        self.skip_leak_check = skip_leak_check;
636        self
637    }
638
639    /// Given a canonical value `C` as a starting point, create an
640    /// inference context that contains each of the bound values
641    /// within instantiated as a fresh variable. The `f` closure is
642    /// invoked with the new infcx, along with the instantiated value
643    /// `V` and a instantiation `S`. This instantiation `S` maps from
644    /// the bound values in `C` to their instantiated values in `V`
645    /// (in other words, `S(C) = V`).
646    pub fn build_with_canonical<T>(
647        mut self,
648        span: Span,
649        input: &CanonicalQueryInput<'tcx, T>,
650    ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
651    where
652        T: TypeFoldable<TyCtxt<'tcx>>,
653    {
654        let infcx = self.build(input.typing_mode.0);
655        let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
656        (infcx, value, args)
657    }
658
659    pub fn build_with_typing_env(
660        mut self,
661        typing_env: TypingEnv<'tcx>,
662    ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
663        (self.build(typing_env.typing_mode()), typing_env.param_env)
664    }
665
666    pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
667        let InferCtxtBuilder {
668            tcx,
669            considering_regions,
670            in_hir_typeck,
671            skip_leak_check,
672            next_trait_solver,
673            enable_next_solver_overflow_fcw,
674        } = *self;
675        InferCtxt {
676            tcx,
677            typing_mode,
678            considering_regions,
679            in_hir_typeck,
680            skip_leak_check,
681            inner: RefCell::new(InferCtxtInner::new()),
682            lexical_region_resolutions: RefCell::new(None),
683            selection_cache: Default::default(),
684            evaluation_cache: Default::default(),
685            reported_trait_errors: Default::default(),
686            reported_hir_errors: Default::default(),
687            reported_signature_mismatch: Default::default(),
688            tainted_by_errors: Cell::new(None),
689            universe: Cell::new(ty::UniverseIndex::ROOT),
690            placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
691            next_trait_solver,
692            enable_next_solver_overflow_fcw: Cell::new(enable_next_solver_overflow_fcw),
693            obligation_inspector: Cell::new(None),
694        }
695    }
696}
697
698impl<'tcx, T> InferOk<'tcx, T> {
699    /// Extracts `value`, registering any obligations into `fulfill_cx`.
700    pub fn into_value_registering_obligations<E: 'tcx>(
701        self,
702        infcx: &InferCtxt<'tcx>,
703        fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
704    ) -> T {
705        let InferOk { value, obligations } = self;
706        fulfill_cx.register_predicate_obligations(infcx, obligations);
707        value
708    }
709}
710
711impl<'tcx> InferOk<'tcx, ()> {
712    pub fn into_obligations(self) -> PredicateObligations<'tcx> {
713        self.obligations
714    }
715}
716
717impl<'tcx> InferCtxt<'tcx> {
718    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
719        self.tcx.dcx().into_taintable(&self.tainted_by_errors)
720    }
721
722    pub fn next_trait_solver(&self) -> bool {
723        self.next_trait_solver
724    }
725
726    /// This method is deliberately called `..._raw`,
727    /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
728    /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
729    /// more information.
730    ///
731    /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
732    /// works as a kind of store for for example type unification information.
733    /// `InferCtxt` is also often used outside the trait solver during typeck.
734    /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
735    /// To make sure these two uses are never confused, we want to statically encode this information.
736    ///
737    /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
738    /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
739    /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
740    /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
741    /// match on the variant and can safely ignore it.
742    ///
743    /// Prefer non-raw apis if available. e.g.,
744    /// - On the `FnCtxt`
745    /// - on the `SelectionCtxt`
746    #[inline(always)]
747    pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
748        self.typing_mode
749    }
750
751    #[inline(always)]
752    pub fn disable_trait_solver_fast_paths(&self) -> bool {
753        self.tcx.disable_trait_solver_fast_paths()
754    }
755
756    /// Returns the origin of the type variable identified by `vid`.
757    ///
758    /// No attempt is made to resolve `vid` to its root variable.
759    pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
760        self.inner.borrow_mut().type_variables().var_origin(vid)
761    }
762
763    /// Returns the origin of the float type variable identified by `vid`.
764    ///
765    /// No attempt is made to resolve `vid` to its root variable.
766    pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
767        self.inner.borrow_mut().float_origin_origin_storage[vid]
768    }
769
770    /// Returns the origin of the const variable identified by `vid`
771    // FIXME: We should store origins separately from the unification table
772    // so this doesn't need to be optional.
773    pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
774        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
775            ConstVariableValue::Known { .. } => None,
776            ConstVariableValue::Unknown { origin, .. } => Some(origin),
777        }
778    }
779
780    pub fn unresolved_root_variables(&self) -> (Vec<TyVid>, Vec<ty::IntVid>, Vec<ty::FloatVid>) {
781        let mut inner = self.inner.borrow_mut();
782
783        let ty = inner.type_variables().unresolved_root_variables();
784
785        let int = unresolved_root_variables_of(
786            inner.int_unification_table(),
787            ty::IntVarValue::is_unknown,
788        );
789
790        let float = unresolved_root_variables_of(
791            inner.float_unification_table(),
792            ty::FloatVarValue::is_unknown,
793        );
794
795        (ty, int, float)
796    }
797
798    {}
#[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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(798u32),
                                    ::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")]
799    pub fn sub_regions(
800        &self,
801        origin: SubregionOrigin<'tcx>,
802        a: ty::Region<'tcx>,
803        b: ty::Region<'tcx>,
804        vis: ty::VisibleForLeakCheck,
805    ) {
806        self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
807    }
808
809    {}
#[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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(809u32),
                                    ::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")]
810    pub fn equate_regions(
811        &self,
812        origin: SubregionOrigin<'tcx>,
813        a: ty::Region<'tcx>,
814        b: ty::Region<'tcx>,
815        vis: ty::VisibleForLeakCheck,
816    ) {
817        self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
818    }
819
820    /// Processes a `Coerce` predicate from the fulfillment context.
821    /// This is NOT the preferred way to handle coercion, which is to
822    /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
823    ///
824    /// This method here is actually a fallback that winds up being
825    /// invoked when `FnCtxt::coerce` encounters unresolved type variables
826    /// and records a coercion predicate. Presently, this method is equivalent
827    /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
828    /// actually requiring `a <: b`. This is of course a valid coercion,
829    /// but it's not as flexible as `FnCtxt::coerce` would be.
830    ///
831    /// (We may refactor this in the future, but there are a number of
832    /// practical obstacles. Among other things, `FnCtxt::coerce` presently
833    /// records adjustments that are required on the HIR in order to perform
834    /// the coercion, and we don't currently have a way to manage that.)
835    pub fn coerce_predicate(
836        &self,
837        cause: &ObligationCause<'tcx>,
838        param_env: ty::ParamEnv<'tcx>,
839        predicate: ty::PolyCoercePredicate<'tcx>,
840    ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
841        let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
842            a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
843            a: p.a,
844            b: p.b,
845        });
846        self.subtype_predicate(cause, param_env, subtype_predicate)
847    }
848
849    pub fn subtype_predicate(
850        &self,
851        cause: &ObligationCause<'tcx>,
852        param_env: ty::ParamEnv<'tcx>,
853        predicate: ty::PolySubtypePredicate<'tcx>,
854    ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
855        // Check for two unresolved inference variables, in which case we can
856        // make no progress. This is partly a micro-optimization, but it's
857        // also an opportunity to "sub-unify" the variables. This isn't
858        // *necessary* to prevent cycles, because they would eventually be sub-unified
859        // anyhow during generalization, but it helps with diagnostics (we can detect
860        // earlier that they are sub-unified).
861        //
862        // Note that we can just skip the binders here because
863        // type variables can't (at present, at
864        // least) capture any of the things bound by this binder.
865        //
866        // Note that this sub here is not just for diagnostics - it has semantic
867        // effects as well.
868        let r_a = self.shallow_resolve(predicate.skip_binder().a);
869        let r_b = self.shallow_resolve(predicate.skip_binder().b);
870        match (r_a.kind(), r_b.kind()) {
871            (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
872                self.sub_unify_ty_vids_raw(a_vid, b_vid);
873                return Err((a_vid, b_vid));
874            }
875            _ => {}
876        }
877
878        self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
879            if a_is_expected {
880                Ok(self.sub_raw(cause, param_env, DefineOpaqueTypes::Yes, a, b))
881            } else {
882                Ok(self.sup_raw(cause, param_env, DefineOpaqueTypes::Yes, b, a))
883            }
884        })
885    }
886
887    /// Number of type variables created so far.
888    pub fn num_ty_vars(&self) -> usize {
889        self.inner.borrow_mut().type_variables().num_vars()
890    }
891
892    pub fn next_ty_vid(&self, span: Span) -> TyVid {
893        self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
894    }
895
896    pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
897        self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
898    }
899
900    pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
901        let origin = TypeVariableOrigin { span, param_def_id: None };
902        self.inner.borrow_mut().type_variables().new_var(universe, origin)
903    }
904
905    pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
906        self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
907    }
908
909    pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
910        let vid = self.next_ty_vid_with_origin(origin);
911        Ty::new_var(self.tcx, vid)
912    }
913
914    pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
915        let vid = self.next_ty_vid_in_universe(span, universe);
916        Ty::new_var(self.tcx, vid)
917    }
918
919    pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
920        self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
921    }
922
923    pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
924        let vid = self
925            .inner
926            .borrow_mut()
927            .const_unification_table()
928            .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
929            .vid;
930        ty::Const::new_var(self.tcx, vid)
931    }
932
933    pub fn next_const_var_in_universe(
934        &self,
935        span: Span,
936        universe: ty::UniverseIndex,
937    ) -> ty::Const<'tcx> {
938        let origin = ConstVariableOrigin { span, param_def_id: None };
939        let vid = self
940            .inner
941            .borrow_mut()
942            .const_unification_table()
943            .new_key(ConstVariableValue::Unknown { origin, universe })
944            .vid;
945        ty::Const::new_var(self.tcx, vid)
946    }
947
948    pub fn next_int_var(&self) -> Ty<'tcx> {
949        let next_int_var_id =
950            self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
951        Ty::new_int_var(self.tcx, next_int_var_id)
952    }
953
954    pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
955        let mut inner = self.inner.borrow_mut();
956        let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
957        let origin = FloatVariableOrigin { span, lint_id };
958        let span_index = inner.float_origin_origin_storage.push(origin);
959        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);
960        Ty::new_float_var(self.tcx, next_float_var_id)
961    }
962
963    /// Creates a fresh region variable with the next available index.
964    /// The variable will be created in the maximum universe created
965    /// thus far, allowing it to name any region created thus far.
966    pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
967        self.next_region_var_in_universe(origin, self.universe())
968    }
969
970    /// Creates a fresh region variable with the next available index
971    /// in the given universe; typically, you can use
972    /// `next_region_var` and just use the maximal universe.
973    pub fn next_region_var_in_universe(
974        &self,
975        origin: RegionVariableOrigin<'tcx>,
976        universe: ty::UniverseIndex,
977    ) -> ty::Region<'tcx> {
978        let region_var =
979            self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
980        ty::Region::new_var(self.tcx, region_var)
981    }
982
983    pub fn next_term_var_of_alias_kind(
984        &self,
985        alias_term: ty::AliasTerm<'tcx>,
986        span: Span,
987    ) -> ty::Term<'tcx> {
988        match alias_term.kind {
989            ty::AliasTermKind::ProjectionTy { .. }
990            | ty::AliasTermKind::InherentTy { .. }
991            | ty::AliasTermKind::OpaqueTy { .. }
992            | ty::AliasTermKind::FreeTy { .. } => self.next_ty_var(span).into(),
993            ty::AliasTermKind::FreeConst { .. }
994            | ty::AliasTermKind::InherentConstSelf { .. }
995            | ty::AliasTermKind::InherentConstImpl { .. }
996            | ty::AliasTermKind::AnonConst { .. }
997            | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_var(span).into(),
998        }
999    }
1000
1001    /// Return the universe that the region `r` was created in. For
1002    /// most regions (e.g., `'static`, named regions from the user,
1003    /// etc) this is the root universe U0. For inference variables or
1004    /// placeholders, however, it will return the universe which they
1005    /// are associated.
1006    pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1007        self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1008    }
1009
1010    /// Number of region variables created so far.
1011    pub fn num_region_vars(&self) -> usize {
1012        self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1013    }
1014
1015    /// Just a convenient wrapper of `next_region_var` for using during NLL.
1016    {}
#[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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1016u32),
                                    ::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")]
1017    pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
1018        self.next_region_var(RegionVariableOrigin::Nll(origin))
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_in_universe",
                                    "rustc_infer::infer", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/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()
                                                    },
                                                    {
                                                        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")]
1023    pub fn next_nll_region_var_in_universe(
1024        &self,
1025        origin: NllRegionVariableOrigin<'tcx>,
1026        universe: ty::UniverseIndex,
1027    ) -> ty::Region<'tcx> {
1028        self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1029    }
1030
1031    #[inline(always)]
1032    pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1033        match param.kind {
1034            GenericParamDefKind::Lifetime => {
1035                // Create a region inference variable for the given
1036                // region parameter definition.
1037                self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1038                    span, param.name,
1039                ))
1040                .into()
1041            }
1042            GenericParamDefKind::Type { .. } => {
1043                // Create a type inference variable for the given
1044                // type parameter definition. The generic parameters are
1045                // for actual parameters that may be referred to by
1046                // the default of this type parameter, if it exists.
1047                // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1048                // used in a path such as `Foo::<T, U>::new()` will
1049                // use an inference variable for `C` with `[T, U]`
1050                // as the generic parameters for the default, `(T, U)`.
1051                let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1052                    self.universe(),
1053                    TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1054                );
1055
1056                Ty::new_var(self.tcx, ty_var_id).into()
1057            }
1058            GenericParamDefKind::Const { .. } => {
1059                let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1060                let const_var_id = self
1061                    .inner
1062                    .borrow_mut()
1063                    .const_unification_table()
1064                    .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1065                    .vid;
1066                ty::Const::new_var(self.tcx, const_var_id).into()
1067            }
1068        }
1069    }
1070
1071    /// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1072    /// each type/region parameter to a fresh inference variable.
1073    pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgs<'tcx> {
1074        GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1075    }
1076
1077    /// Returns `true` if errors have been reported since this infcx was
1078    /// created. This is sometimes used as a heuristic to skip
1079    /// reporting errors that often occur as a result of earlier
1080    /// errors, but where it's hard to be 100% sure (e.g., unresolved
1081    /// inference variables, regionck errors).
1082    #[must_use = "this method does not have any side effects"]
1083    pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1084        self.tainted_by_errors.get()
1085    }
1086
1087    /// Set the "tainted by errors" flag to true. We call this when we
1088    /// observe an error from a prior pass.
1089    pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1090        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs:1090",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1090u32),
                        ::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)");
1091        self.tainted_by_errors.set(Some(e));
1092    }
1093
1094    pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1095        let mut inner = self.inner.borrow_mut();
1096        let inner = &mut *inner;
1097        inner.unwrap_region_constraints().var_origin(vid)
1098    }
1099
1100    /// Clone the list of variable regions. This is used only during NLL processing
1101    /// to put the set of region variables into the NLL region context.
1102    pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1103        let inner = self.inner.borrow();
1104        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));
1105        let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1106        // FIXME(-Zassumptions-on-binders): Handle solver_data
1107        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);
1108        // We clone instead of taking because borrowck still wants to use the
1109        // inference context after calling this for diagnostics and the new
1110        // trait solver.
1111        storage.var_infos.clone()
1112    }
1113
1114    pub fn has_opaque_types_in_storage(&self) -> bool {
1115        !self.inner.borrow().opaque_type_storage.is_empty()
1116    }
1117
1118    {}
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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(1118u32),
                                ::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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs:1118",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1118u32),
                        ::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)]
1119    pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1120        self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1121    }
1122
1123    {}
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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(1123u32),
                                ::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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs:1123",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1123u32),
                        ::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)]
1124    pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1125        self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1126    }
1127
1128    pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1129        if !self.next_trait_solver() {
1130            return false;
1131        }
1132
1133        let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1134        let inner = &mut *self.inner.borrow_mut();
1135        let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1136        inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1137            if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1138                let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1139                if opaque_sub_vid == ty_sub_vid {
1140                    return true;
1141                }
1142            }
1143
1144            false
1145        })
1146    }
1147
1148    /// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1149    ///
1150    /// This only checks for a subtype relation, it does not require equality.
1151    pub fn opaques_with_sub_unified_hidden_type(
1152        &self,
1153        ty_vid: TyVid,
1154    ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1155        // Avoid accidentally allowing more code to compile with the old solver.
1156        if !self.next_trait_solver() {
1157            return ::alloc::vec::Vec::new()vec![];
1158        }
1159
1160        let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1161        let inner = &mut *self.inner.borrow_mut();
1162        // This is iffy, can't call `type_variables()` as we're already
1163        // borrowing the `opaque_type_storage` here.
1164        let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1165        inner
1166            .opaque_type_storage
1167            .iter_opaque_types()
1168            .filter_map(|(key, hidden_ty)| {
1169                if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1170                    let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1171                    if opaque_sub_vid == ty_sub_vid {
1172                        return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1173                            self.tcx,
1174                            key.def_id.into(),
1175                            key.args,
1176                        ));
1177                    }
1178                }
1179
1180                None
1181            })
1182            .collect()
1183    }
1184
1185    #[inline(always)]
1186    pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1187        if true {
    if !!self.next_trait_solver() {
        ::core::panicking::panic("assertion failed: !self.next_trait_solver()")
    };
};debug_assert!(!self.next_trait_solver());
1188        match self.typing_mode_raw().assert_not_erased() {
1189            TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1190            | TypingMode::PostTypeckThroughBorrowck { defining_opaque_types } => {
1191                id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1192            }
1193            // FIXME(#132279): This function is quite weird in post-analysis
1194            // and post-borrowck analysis mode. We may need to modify its uses
1195            // to support PostBorrowck in the old solver as well.
1196            TypingMode::Coherence
1197            | TypingMode::Reflection
1198            | TypingMode::PostBorrowck { .. }
1199            | TypingMode::PostAnalysis
1200            | TypingMode::Codegen => false,
1201        }
1202    }
1203
1204    pub fn push_hir_typeck_potentially_region_dependent_goal(
1205        &self,
1206        goal: PredicateObligation<'tcx>,
1207    ) {
1208        let mut inner = self.inner.borrow_mut();
1209        inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1210        inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1211    }
1212
1213    pub fn take_hir_typeck_potentially_region_dependent_goals(
1214        &self,
1215    ) -> Vec<PredicateObligation<'tcx>> {
1216        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");
1217        std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1218    }
1219
1220    pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1221        self.deeply_resolve_ignoring_regions(t).to_string()
1222    }
1223
1224    /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1225    /// universe index of `TyVar(vid)`.
1226    pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1227        use self::type_variable::TypeVariableValue;
1228
1229        match self.inner.borrow_mut().type_variables().probe(vid) {
1230            TypeVariableValue::Known { value } => Ok(value),
1231            TypeVariableValue::Unknown { universe } => Err(universe),
1232        }
1233    }
1234
1235    /// If `vid` resolves to a type, return that type. Otherwise return the root variable id for `vid`.
1236    pub fn shallow_resolve_ty_var_or_get_root(&self, vid: TyVid) -> Result<Ty<'tcx>, TyVid> {
1237        let (root, value) = self.inner.borrow_mut().type_variables().probe_with_root_vid(vid);
1238
1239        match value {
1240            TypeVariableValue::Known { value } => Ok(value),
1241            TypeVariableValue::Unknown { universe: _ } => Err(root),
1242        }
1243    }
1244
1245    /// Resolve a type variable. Resolving means the following:
1246    ///
1247    /// - If a `Ty` is a rigid type (like, an integer, or some ADT), do nothing.
1248    /// - If a `Ty` is a type infer variable, but has been equated with an actual type,
1249    ///   return that type.
1250    /// - If a `Ty` is an int or float infer variable, and has been equated with an integer
1251    ///   or floating point type, return that type.
1252    /// - If a `Ty` is any kind of infer variable that has been equated, but not yet with a rigid
1253    ///   type, then this set of equated variables forms an equivalence class. One of the variables
1254    ///   in that equivalent class is said to be the root variable, and resolving makes sure to
1255    ///   consistently return this root variable. This is beneficial for caching.
1256    ///   This behavior, of returning roots, changed in <https://github.com/rust-lang/rust/pull/158447>.
1257    ///
1258    /// Otherwise, resolving simply does nothing.
1259    ///
1260    /// The "shallow" part of the name refers to the fact that types may themselves contain more
1261    /// type variables. e.g. The field types of a struct. `shallow_resolve` does not recurse into
1262    /// these nested variables. If that's what you want, use [`deeply_resolve_ignoring_regions`](Self::deeply_resolve_ignoring_regions),
1263    /// or better [`deeply_resolve_via_unification_table`](rustc_type_ir::InferCtxtLike::deeply_resolve_via_unification_table), if you can, which *does* resolve regions.
1264    pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1265        if let ty::Infer(v) = *ty.kind() {
1266            match v {
1267                ty::TyVar(v) => {
1268                    // Not entirely obvious: if `typ` is a type variable,
1269                    // it can be resolved to an int/float variable, which
1270                    // can then be recursively resolved, hence the
1271                    // recursion. Note though that we prevent type
1272                    // variables from unifying to other type variables
1273                    // directly (though they may be embedded
1274                    // structurally), and we prevent cycles in any case,
1275                    // so this recursion should always be of very limited
1276                    // depth.
1277                    //
1278                    // Note: if these two lines are combined into one we get
1279                    // dynamic borrow errors on `self.inner`.
1280                    let (root_vid, value) =
1281                        self.inner.borrow_mut().type_variables().probe_with_root_vid(v);
1282                    value.known().map_or_else(
1283                        || if root_vid == v { ty } else { Ty::new_var(self.tcx, root_vid) },
1284                        |t| self.shallow_resolve(t),
1285                    )
1286                }
1287
1288                ty::IntVar(v) => {
1289                    let (root, value) =
1290                        self.inner.borrow_mut().int_unification_table().inlined_probe_key_value(v);
1291                    match value {
1292                        ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1293                        ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1294                        ty::IntVarValue::Unknown => {
1295                            if root == v {
1296                                ty
1297                            } else {
1298                                Ty::new_int_var(self.tcx, root)
1299                            }
1300                        }
1301                    }
1302                }
1303
1304                ty::FloatVar(v) => {
1305                    let (root, value) = self
1306                        .inner
1307                        .borrow_mut()
1308                        .float_unification_table()
1309                        .inlined_probe_key_value(v);
1310                    match value {
1311                        ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1312                        ty::FloatVarValue::Unknown => {
1313                            if root == v {
1314                                ty
1315                            } else {
1316                                Ty::new_float_var(self.tcx, root)
1317                            }
1318                        }
1319                    }
1320                }
1321
1322                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1323            }
1324        } else {
1325            ty
1326        }
1327    }
1328
1329    /// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1330    /// It's the same, but for consts.
1331    pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1332        match ct.kind() {
1333            ty::ConstKind::Infer(infer_ct) => match infer_ct {
1334                InferConst::Var(vid) => {
1335                    let (root, value) = self
1336                        .inner
1337                        .borrow_mut()
1338                        .const_unification_table()
1339                        .inlined_probe_key_value(vid);
1340                    value.known().unwrap_or_else(|| {
1341                        if root.vid == vid { ct } else { ty::Const::new_var(self.tcx, root.vid) }
1342                    })
1343                }
1344                InferConst::Fresh(_) => ct,
1345            },
1346
1347            ty::ConstKind::Param(_)
1348            | ty::ConstKind::Bound(_, _)
1349            | ty::ConstKind::Placeholder(_)
1350            | ty::ConstKind::Alias(_, _)
1351            | ty::ConstKind::Value(_)
1352            | ty::ConstKind::Error(_)
1353            | ty::ConstKind::Expr(_) => ct,
1354        }
1355    }
1356
1357    /// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1358    /// It's the same, but for terms (types or consts).
1359    pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1360        match term.kind() {
1361            ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1362            ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1363        }
1364    }
1365
1366    pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1367        self.inner.borrow_mut().type_variables().root_var(var)
1368    }
1369
1370    /// If `ty` is an unresolved type variable, returns its root vid.
1371    pub fn root_vid(&self, ty: Ty<'tcx>) -> Option<ty::TyVid> {
1372        let (root, value) =
1373            self.inner.borrow_mut().type_variables().inlined_probe_with_vid(ty.ty_vid()?);
1374        value.is_unknown().then_some(root)
1375    }
1376
1377    pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1378        self.inner.borrow_mut().type_variables().sub_unify(a, b);
1379    }
1380
1381    pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1382        self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1383    }
1384
1385    pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1386        self.inner.borrow_mut().float_unification_table().find(var)
1387    }
1388
1389    pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1390        self.inner.borrow_mut().const_unification_table().find(var).vid
1391    }
1392
1393    /// Resolves a const var to a rigid const, if it was constrained to one,
1394    /// or else the root const var in the unification table.
1395    pub fn shallow_resolve_const_var(&self, vid: ty::ConstVid) -> ty::Const<'tcx> {
1396        match self.try_resolve_const_var(vid) {
1397            Ok(ct) => ct,
1398            Err(_) => ty::Const::new_var(self.tcx, self.root_const_var(vid)),
1399        }
1400    }
1401
1402    /// Resolves a type var to a rigid type, if it was constrained to one,
1403    /// or else the root type var in the unification table.
1404    pub fn shallow_resolve_ty_var(&self, vid: ty::TyVid) -> Ty<'tcx> {
1405        match self.try_resolve_ty_var(vid) {
1406            Ok(ty) => ty,
1407            Err(_) => Ty::new_var(self.tcx, self.root_var(vid)),
1408        }
1409    }
1410
1411    /// Resolves an int var to a rigid int type, if it was constrained to one,
1412    /// or else the root int var in the unification table.
1413    pub fn shallow_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1414        let mut inner = self.inner.borrow_mut();
1415        let value = inner.int_unification_table().probe_value(vid);
1416        match value {
1417            ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1418            ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1419            ty::IntVarValue::Unknown => {
1420                Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1421            }
1422        }
1423    }
1424
1425    /// Resolves a float var to a rigid type, if it was constrained to one,
1426    /// or else the root float var in the unification table.
1427    pub fn shallow_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1428        let mut inner = self.inner.borrow_mut();
1429        let value = inner.float_unification_table().probe_value(vid);
1430        match value {
1431            ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1432            ty::FloatVarValue::Unknown => {
1433                Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1434            }
1435        }
1436    }
1437
1438    /// If a type/const variable has not (yet) been unified, it is left as is.
1439    ///
1440    /// This is an idempotent operation that does not affect inference state in any way,
1441    /// which means it's safe to call this function at will.
1442    ///
1443    /// Region variables are unaffected.
1444    pub fn deeply_resolve_ignoring_regions<T>(&self, value: T) -> T
1445    where
1446        T: TypeFoldable<TyCtxt<'tcx>>,
1447    {
1448        if let Err(guar) = value.error_reported() {
1449            self.set_tainted_by_errors(guar);
1450        }
1451        if !value.has_non_region_infer() {
1452            return value;
1453        }
1454        let mut r = resolve::DeepResolverIgnoringRegions::new(self);
1455        value.fold_with(&mut r)
1456    }
1457
1458    /// Where possible, replaces type/const/region variables in `value` with their final value.
1459    /// If a type/const/region variable has not (yet) been unified, it is left as is.
1460    ///
1461    /// This is an idempotent operation that does not affect inference state in any way,
1462    /// which means it's safe to call this function at will.
1463    pub fn deeply_resolve_via_unification_table<T>(&self, value: T) -> T
1464    where
1465        T: TypeFoldable<TyCtxt<'tcx>>,
1466    {
1467        use rustc_middle::ty::InferCtxtLike;
1468        #[allow(rustc::usage_of_type_ir_traits)]
1469        InferCtxtLike::deeply_resolve_via_unification_table(self, value)
1470    }
1471
1472    pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1473    where
1474        T: TypeFoldable<TyCtxt<'tcx>>,
1475    {
1476        if !value.has_infer() {
1477            return value; // Avoid duplicated type-folding.
1478        }
1479        let mut r = InferenceLiteralEraser { tcx: self.tcx };
1480        value.fold_with(&mut r)
1481    }
1482
1483    pub fn try_resolve_const_var(
1484        &self,
1485        vid: ty::ConstVid,
1486    ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1487        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1488            ConstVariableValue::Known { value } => Ok(value),
1489            ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1490        }
1491    }
1492
1493    /// Attempts to resolve all type/region/const variables in
1494    /// `value`. Region inference must have been run already (e.g.,
1495    /// by calling `resolve_regions_and_report_errors`). If some
1496    /// variable was never unified, an `Err` results.
1497    ///
1498    /// This method is idempotent, but it not typically not invoked
1499    /// except during the writeback phase.
1500    pub fn deeply_resolve_via_region_graph<T: TypeFoldable<TyCtxt<'tcx>>>(
1501        &self,
1502        value: T,
1503    ) -> FixupResult<T> {
1504        match resolve::deeply_resolve_via_region_graph(self, value) {
1505            Ok(value) => {
1506                if value.has_non_region_infer() {
1507                    ::rustc_span::macros::bug_impl(None,
    format_args!("`{0:?}` is not fully resolved", value), Location::caller());bug!("`{value:?}` is not fully resolved");
1508                }
1509                if value.has_infer_regions() {
1510                    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"));
1511                    Ok(fold_regions(self.tcx, value, |re, _| {
1512                        if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1513                    }))
1514                } else {
1515                    Ok(value)
1516                }
1517            }
1518            Err(e) => Err(e),
1519        }
1520    }
1521
1522    // Instantiates the bound variables in a given binder with fresh inference
1523    // variables in the current universe.
1524    //
1525    // Use this method if you'd like to find some generic parameters of the binder's
1526    // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1527    // that corresponds to your use case, consider whether or not you should
1528    // use [`InferCtxt::enter_forall`] instead.
1529    pub fn instantiate_binder_with_fresh_vars<T>(
1530        &self,
1531        span: Span,
1532        lbrct: BoundRegionConversionTime,
1533        value: ty::Binder<'tcx, T>,
1534    ) -> T
1535    where
1536        T: TypeFoldable<TyCtxt<'tcx>>,
1537    {
1538        if let Some(_) = value.as_ref().no_bound_vars() {
1539            return value.skip_binder();
1540        }
1541
1542        let bound_vars = value.bound_vars();
1543        let mut args = Vec::with_capacity(bound_vars.len());
1544
1545        for bound_var_kind in bound_vars {
1546            let arg: ty::GenericArg<'_> = match bound_var_kind {
1547                ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1548                ty::BoundVariableKind::Region(br) => {
1549                    self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1550                }
1551                ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1552            };
1553            args.push(arg);
1554        }
1555
1556        struct ToFreshVars<'tcx> {
1557            args: Vec<ty::GenericArg<'tcx>>,
1558        }
1559
1560        impl<'tcx> BoundVarReplacerDelegate<TyCtxt<'tcx>> for ToFreshVars<'tcx> {
1561            fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1562                self.args[br.var.index()].expect_region()
1563            }
1564            fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1565                self.args[bt.var.index()].expect_ty()
1566            }
1567            fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1568                self.args[bc.var.index()].expect_const()
1569            }
1570        }
1571        let delegate = ToFreshVars { args };
1572        self.tcx.replace_bound_vars_uncached(value, delegate)
1573    }
1574
1575    pub fn insert_placeholder_assumptions(
1576        &self,
1577        u: ty::UniverseIndex,
1578        assumptions: rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>,
1579    ) {
1580        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!(
1581            !assumptions.type_outlives.has_escaping_bound_vars(),
1582            "assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1583            assumptions.type_outlives
1584        );
1585        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!(
1586            assumptions.region_outlives.base_edges().all(|r| !r.has_escaping_bound_vars()),
1587            "assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1588            assumptions.region_outlives
1589        );
1590        self.placeholder_assumptions_for_next_solver.borrow_mut().insert(u, assumptions);
1591    }
1592
1593    pub fn get_placeholder_assumptions(
1594        &self,
1595        u: ty::UniverseIndex,
1596    ) -> rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>> {
1597        self.placeholder_assumptions_for_next_solver.borrow().get(&u).unwrap().clone()
1598    }
1599
1600    pub fn has_placeholder_assumptions(&self, range: RangeInclusive<ty::UniverseIndex>) -> bool {
1601        let assumptions = self.placeholder_assumptions_for_next_solver.borrow();
1602        // Walk around that `Step` trait is nightly only.
1603        (range.start.index()..=range.last.index())
1604            .map(ty::UniverseIndex::from_usize)
1605            .all(|u| assumptions.get(&u).is_some())
1606    }
1607
1608    pub fn get_solver_region_constraint(&self) -> SolverRegionConstraint<'tcx> {
1609        self.inner.borrow().region_constraint_storage.as_ref().unwrap().solver_data.get_constraint()
1610    }
1611
1612    pub fn overwrite_solver_region_constraint(&self, constraint: SolverRegionConstraint<'tcx>) {
1613        self.inner.borrow_mut().unwrap_region_constraints().overwrite_solver_constraint(constraint);
1614    }
1615
1616    /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1617    pub(crate) fn verify_generic_bound(
1618        &self,
1619        origin: SubregionOrigin<'tcx>,
1620        kind: GenericKind<'tcx>,
1621        a: ty::Region<'tcx>,
1622        bound: VerifyBound<'tcx>,
1623    ) {
1624        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs:1624",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1624u32),
                        ::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);
1625
1626        self.inner
1627            .borrow_mut()
1628            .unwrap_region_constraints()
1629            .verify_generic_bound(origin, kind, a, bound);
1630    }
1631
1632    /// Obtains the latest type of the given closure; this may be a
1633    /// closure in the current function, in which case its
1634    /// `ClosureKind` may not yet be known.
1635    pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1636        let unresolved_kind_ty = match *closure_ty.kind() {
1637            ty::Closure(_, args) => args.as_closure().kind_ty(),
1638            ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1639            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected type {0}", closure_ty), Location::caller())bug!("unexpected type {closure_ty}"),
1640        };
1641        let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1642        closure_kind_ty.to_opt_closure_kind()
1643    }
1644
1645    pub fn universe(&self) -> ty::UniverseIndex {
1646        self.universe.get()
1647    }
1648
1649    /// Creates and return a fresh universe that extends all previous
1650    /// universes. Updates `self.universe` to that new universe.
1651    pub fn create_next_universe(&self) -> ty::UniverseIndex {
1652        let u = self.universe.get().next_universe();
1653        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs:1653",
                        "rustc_infer::infer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1653u32),
                        ::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:?}");
1654        self.universe.set(u);
1655        u
1656    }
1657
1658    /// We need to disable the fcw if we're already in a fcw emitting to avoid
1659    /// indefinite triggering.
1660    pub fn with_disabled_next_solver_overflow_fcw<F, R>(&self, mut f: F) -> R
1661    where
1662        F: FnMut() -> R,
1663    {
1664        let prev = self.enable_next_solver_overflow_fcw.replace(false);
1665        let ret = f();
1666        self.enable_next_solver_overflow_fcw.set(prev);
1667        ret
1668    }
1669
1670    /// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1671    /// which contains the necessary information to use the trait system without
1672    /// using canonicalization or carrying this inference context around.
1673    pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1674        let typing_mode = match self.typing_mode_raw() {
1675            // FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1676            // to handle them without proper canonicalization. This means we may cause cycle
1677            // errors and fail to reveal opaques while inside of bodies. We should rename this
1678            // function and require explicit comments on all use-sites in the future.
1679            ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1680            | ty::TypingMode::PostTypeckThroughBorrowck { defining_opaque_types: _ } => {
1681                TypingMode::non_body_analysis()
1682            }
1683            mode @ (ty::TypingMode::Coherence
1684            | ty::TypingMode::PostBorrowck { .. }
1685            | ty::TypingMode::PostAnalysis
1686            | ty::TypingMode::Reflection
1687            | ty::TypingMode::Codegen) => mode,
1688            ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::unreachable_default_msg()unreachable!(),
1689        };
1690        ty::TypingEnv::new(param_env, typing_mode)
1691    }
1692
1693    /// Similar to [`Self::canonicalize_query`], except that it returns
1694    /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1695    /// `param_env` to not contain any inference variables or placeholders.
1696    pub fn pseudo_canonicalize_query<V>(
1697        &self,
1698        param_env: ty::ParamEnv<'tcx>,
1699        value: V,
1700    ) -> PseudoCanonicalInput<'tcx, V>
1701    where
1702        V: TypeVisitable<TyCtxt<'tcx>>,
1703    {
1704        if true {
    if !!value.has_infer() {
        ::core::panicking::panic("assertion failed: !value.has_infer()")
    };
};debug_assert!(!value.has_infer());
1705        if true {
    if !!value.has_placeholders() {
        ::core::panicking::panic("assertion failed: !value.has_placeholders()")
    };
};debug_assert!(!value.has_placeholders());
1706        if true {
    if !!param_env.has_infer() {
        ::core::panicking::panic("assertion failed: !param_env.has_infer()")
    };
};debug_assert!(!param_env.has_infer());
1707        if true {
    if !!param_env.has_placeholders() {
        ::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
    };
};debug_assert!(!param_env.has_placeholders());
1708        self.typing_env(param_env).as_query_input(value)
1709    }
1710
1711    /// The returned function is used in a fast path. If it returns `true` the variable is
1712    /// unchanged, `false` indicates that the status is unknown.
1713    #[inline]
1714    pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1715        // This hoists the borrow/release out of the loop body.
1716        let inner = self.inner.try_borrow();
1717
1718        move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1719            (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1720                use self::type_variable::TypeVariableValue;
1721
1722                #[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
    {
    Some(TypeVariableValue::Unknown { .. }) => true,
    _ => false,
}matches!(
1723                    inner.try_type_variables_probe_ref(ty_var),
1724                    Some(TypeVariableValue::Unknown { .. })
1725                )
1726            }
1727            _ => false,
1728        }
1729    }
1730
1731    /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1732    ///   * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1733    ///   * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1734    ///
1735    /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1736    /// inlined, despite being large, because it has only two call sites that
1737    /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1738    /// inference variables), and it handles both `Ty` and `ty::Const` without
1739    /// having to resort to storing full `GenericArg`s in `stalled_on`.
1740    #[inline(always)]
1741    pub fn ty_or_const_infer_var_changed(&self, var: TyOrConstInferVar) -> bool {
1742        match var {
1743            TyOrConstInferVar::Ty(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().try_type_variables_probe_ref(vid)
    {
    Some(TypeVariableValue::Unknown { .. }) => true,
    _ => false,
}matches!(
1744                self.inner.borrow().try_type_variables_probe_ref(vid),
1745                Some(TypeVariableValue::Unknown { .. })
1746            ),
1747            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!(
1748                self.inner.borrow().int_unification_storage.try_probe_value(vid),
1749                Some(ty::IntVarValue::Unknown)
1750            ),
1751            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!(
1752                self.inner.borrow().float_unification_storage.try_probe_value(vid),
1753                Some(ty::FloatVarValue::Unknown)
1754            ),
1755            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!(
1756                self.inner.borrow().const_unification_storage.try_probe_value(vid),
1757                Some(ConstVariableValue::Unknown { .. })
1758            ),
1759        }
1760    }
1761
1762    /// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1763    pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1764        if true {
    if !self.obligation_inspector.get().is_none() {
        {
            ::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
        }
    };
};debug_assert!(
1765            self.obligation_inspector.get().is_none(),
1766            "shouldn't override a set obligation inspector"
1767        );
1768        self.obligation_inspector.set(Some(inspector));
1769    }
1770}
1771
1772/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1773/// Used only for diagnostics.
1774struct InferenceLiteralEraser<'tcx> {
1775    tcx: TyCtxt<'tcx>,
1776}
1777
1778impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1779    fn cx(&self) -> TyCtxt<'tcx> {
1780        self.tcx
1781    }
1782
1783    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1784        match ty.kind() {
1785            ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1786            ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1787            _ => ty.super_fold_with(self),
1788        }
1789    }
1790}
1791
1792impl<'tcx> TypeTrace<'tcx> {
1793    pub fn span(&self) -> Span {
1794        self.cause.span
1795    }
1796
1797    pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1798        TypeTrace {
1799            cause: cause.clone(),
1800            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1801        }
1802    }
1803
1804    pub fn trait_refs(
1805        cause: &ObligationCause<'tcx>,
1806        a: ty::TraitRef<'tcx>,
1807        b: ty::TraitRef<'tcx>,
1808    ) -> TypeTrace<'tcx> {
1809        TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1810    }
1811
1812    pub fn consts(
1813        cause: &ObligationCause<'tcx>,
1814        a: ty::Const<'tcx>,
1815        b: ty::Const<'tcx>,
1816    ) -> TypeTrace<'tcx> {
1817        TypeTrace {
1818            cause: cause.clone(),
1819            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1820        }
1821    }
1822}
1823
1824impl<'tcx> SubregionOrigin<'tcx> {
1825    pub fn span(&self) -> Span {
1826        match *self {
1827            SubregionOrigin::Subtype(ref a) => a.span(),
1828            SubregionOrigin::RelateObjectBound(a) => a,
1829            SubregionOrigin::RelateParamBound(a, ..) => a,
1830            SubregionOrigin::RelateRegionParamBound(a, _) => a,
1831            SubregionOrigin::Reborrow(a) => a,
1832            SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1833            SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1834            SubregionOrigin::AscribeUserTypeProvePredicate(span, _) => span,
1835            SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1836            SubregionOrigin::SolverRegionConstraint(a) => a,
1837        }
1838    }
1839
1840    pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1841    where
1842        F: FnOnce() -> Self,
1843    {
1844        match *cause.code() {
1845            traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1846                SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1847            }
1848
1849            traits::ObligationCauseCode::CompareImplItem {
1850                impl_item_def_id,
1851                trait_item_def_id,
1852                kind: _,
1853            } => SubregionOrigin::CompareImplItemObligation {
1854                span: cause.span,
1855                impl_item_def_id,
1856                trait_item_def_id,
1857            },
1858
1859            traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1860                impl_item_def_id,
1861                trait_item_def_id,
1862            } => SubregionOrigin::CheckAssociatedTypeBounds {
1863                impl_item_def_id,
1864                trait_item_def_id,
1865                parent: Box::new(default()),
1866            },
1867
1868            traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span, def_id) => {
1869                SubregionOrigin::AscribeUserTypeProvePredicate(span, def_id)
1870            }
1871
1872            traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1873                SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1874            }
1875
1876            _ => default(),
1877        }
1878    }
1879}
1880
1881impl<'tcx> RegionVariableOrigin<'tcx> {
1882    pub fn span(&self) -> Span {
1883        match *self {
1884            RegionVariableOrigin::Misc(a)
1885            | RegionVariableOrigin::PatternRegion(a)
1886            | RegionVariableOrigin::BorrowRegion(a)
1887            | RegionVariableOrigin::Autoref(a)
1888            | RegionVariableOrigin::Coercion(a)
1889            | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1890            | RegionVariableOrigin::BoundRegion(a, ..)
1891            | RegionVariableOrigin::UpvarRegion(_, a) => a,
1892            RegionVariableOrigin::Nll(..) => ::rustc_span::macros::bug_impl(None,
    format_args!("NLL variable used with `span`"), Location::caller())bug!("NLL variable used with `span`"),
1893        }
1894    }
1895}
1896
1897impl<'tcx> InferCtxt<'tcx> {
1898    /// Given a [`hir::Block`], get the span of its last expression or
1899    /// statement, peeling off any inner blocks.
1900    pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1901        let block = block.innermost_block();
1902        if let Some(expr) = &block.expr {
1903            expr.span
1904        } else if let Some(stmt) = block.stmts.last() {
1905            // possibly incorrect trailing `;` in the else arm
1906            stmt.span
1907        } else {
1908            // empty block; point at its entirety
1909            block.span
1910        }
1911    }
1912
1913    /// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1914    /// of its last expression or statement, peeling off any inner blocks.
1915    pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1916        match self.tcx.hir_node(hir_id) {
1917            hir::Node::Block(blk)
1918            | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1919                self.find_block_span(blk)
1920            }
1921            hir::Node::Expr(e) => e.span,
1922            _ => DUMMY_SP,
1923        }
1924    }
1925}
1926
1927/// Returns unresolved root variables from `table`, according to `is_unresolved`.
1928fn unresolved_root_variables_of<V: UnifyKey>(
1929    mut table: UnificationTable<'_, '_, V>,
1930    is_unresolved: impl Fn(V::Value) -> bool,
1931) -> Vec<V>
1932where
1933    V: Eq,
1934    V::Value: UnifyValue,
1935    for<'a> UndoLog<'a>: From<sv::UndoLog<ut::Delegate<V>>>,
1936{
1937    (0..table.len() as u32)
1938        .map(V::from_index)
1939        .filter(|&vid| {
1940            // NB: as of writing this `ena` doesn't provide a non-inlined `probe_key_value`...
1941            let (root, value) = table.inlined_probe_key_value(vid);
1942            root == vid && is_unresolved(value)
1943        })
1944        .collect()
1945}