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