Skip to main content

rustc_infer/infer/
mod.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match &mut self.0 {
                SolverRegionConstraint::And(and) => {
                    let and =
                        core::mem::take(and).into_iter().chain([constraint]).collect::<Vec<_>>().into_boxed_slice();
                    self.0 = SolverRegionConstraint::And(and);
                }
                _ =>
                    ::core::panicking::panic("internal error: entered unreachable code"),
            }
        }
    }
}#[instrument(level = "debug")]
1878    fn push(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1879        match &mut self.0 {
1880            SolverRegionConstraint::And(and) => {
1881                let and = core::mem::take(and)
1882                    .into_iter()
1883                    .chain([constraint])
1884                    .collect::<Vec<_>>()
1885                    .into_boxed_slice();
1886                self.0 = SolverRegionConstraint::And(and);
1887            }
1888            _ => unreachable!(),
1889        }
1890    }
1891
1892    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("overwrite_solver_region_constraint",
                                    "rustc_infer::infer", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1892u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("constraint")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("constraint");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !constraint.is_and() {
                self.0 =
                    SolverRegionConstraint::And(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                    [constraint])).into_boxed_slice())
            } else { self.0 = constraint; }
        }
    }
}#[instrument(level = "debug", skip(self))]
1893    fn overwrite_solver_region_constraint(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1894        if !constraint.is_and() {
1895            self.0 = SolverRegionConstraint::And(vec![constraint].into_boxed_slice())
1896        } else {
1897            self.0 = constraint;
1898        }
1899    }
1900}
1901
1902/// Returns unresolved root variables from `table`, according to `is_unresolved`.
1903fn unresolved_root_variables_of<V: UnifyKey>(
1904    mut table: UnificationTable<'_, '_, V>,
1905    is_unresolved: impl Fn(V::Value) -> bool,
1906) -> Vec<V>
1907where
1908    V: Eq,
1909    V::Value: UnifyValue,
1910    for<'a> UndoLog<'a>: From<sv::UndoLog<ut::Delegate<V>>>,
1911{
1912    (0..table.len() as u32)
1913        .map(V::from_index)
1914        .filter(|&vid| {
1915            // NB: as of writing this `ena` doesn't provide a non-inlined `probe_key_value`...
1916            let (root, value) = table.inlined_probe_key_value(vid);
1917            root == vid && is_unresolved(value)
1918        })
1919        .collect()
1920}