rustc_infer/infer/
mod.rs

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