rustc_infer/infer/
mod.rs

1use std::cell::{Cell, RefCell};
2use std::fmt;
3
4pub use at::DefineOpaqueTypes;
5use free_regions::RegionRelations;
6pub use freshen::TypeFreshener;
7use lexical_region_resolve::LexicalRegionResolutions;
8pub use lexical_region_resolve::RegionResolutionError;
9pub use opaque_types::{OpaqueTypeStorage, OpaqueTypeStorageEntries, OpaqueTypeTable};
10use region_constraints::{
11    GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
12};
13pub use relate::StructurallyRelateAliases;
14pub use relate::combine::PredicateEmittingRelation;
15use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
16use rustc_data_structures::undo_log::{Rollback, UndoLogs};
17use rustc_data_structures::unify as ut;
18use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
19use rustc_hir as hir;
20use rustc_hir::def_id::{DefId, LocalDefId};
21use rustc_macros::extension;
22pub use rustc_macros::{TypeFoldable, TypeVisitable};
23use rustc_middle::bug;
24use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
25use rustc_middle::mir::ConstraintCategory;
26use rustc_middle::traits::select;
27use rustc_middle::traits::solve::Goal;
28use rustc_middle::ty::error::{ExpectedFound, TypeError};
29use rustc_middle::ty::{
30    self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
31    GenericArgsRef, GenericParamDefKind, InferConst, IntVid, OpaqueHiddenType, OpaqueTypeKey,
32    PseudoCanonicalInput, Term, TermKind, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder,
33    TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
34};
35use rustc_span::{DUMMY_SP, Span, Symbol};
36use snapshot::undo_log::InferCtxtUndoLogs;
37use tracing::{debug, instrument};
38use type_variable::TypeVariableOrigin;
39
40use crate::infer::region_constraints::UndoLog;
41use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
42use crate::traits::{
43    self, ObligationCause, ObligationInspector, PredicateObligations, TraitEngine,
44};
45
46pub mod at;
47pub mod canonical;
48mod context;
49mod free_regions;
50mod freshen;
51mod lexical_region_resolve;
52mod opaque_types;
53pub mod outlives;
54mod projection;
55pub mod region_constraints;
56pub mod relate;
57pub mod resolve;
58pub(crate) mod snapshot;
59mod type_variable;
60mod unify_key;
61
62/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
63/// around `PredicateObligations<'tcx>`, but it has one important property:
64/// because `InferOk` is marked with `#[must_use]`, if you have a method
65/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
66/// `infcx.f()?;` you'll get a warning about the obligations being discarded
67/// without use, which is probably unintentional and has been a source of bugs
68/// in the past.
69#[must_use]
70#[derive(Debug)]
71pub struct InferOk<'tcx, T> {
72    pub value: T,
73    pub obligations: PredicateObligations<'tcx>,
74}
75pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
76
77pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
78
79pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
80    ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
81>;
82
83/// This type contains all the things within `InferCtxt` that sit within a
84/// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
85/// operations are hot enough that we want only one call to `borrow_mut` per
86/// call to `start_snapshot` and `rollback_to`.
87#[derive(Clone)]
88pub struct InferCtxtInner<'tcx> {
89    undo_log: InferCtxtUndoLogs<'tcx>,
90
91    /// Cache for projections.
92    ///
93    /// This cache is snapshotted along with the infcx.
94    projection_cache: traits::ProjectionCacheStorage<'tcx>,
95
96    /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
97    /// that might instantiate a general type variable have an order,
98    /// represented by its upper and lower bounds.
99    type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
100
101    /// Map from const parameter variable to the kind of const it represents.
102    const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
103
104    /// Map from integral variable to the kind of integer it represents.
105    int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
106
107    /// Map from floating variable to the kind of float it represents.
108    float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
109
110    /// Tracks the set of region variables and the constraints between them.
111    ///
112    /// This is initially `Some(_)` but when
113    /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
114    /// -- further attempts to perform unification, etc., may fail if new
115    /// region constraints would've been added.
116    region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
117
118    /// A set of constraints that regionck must validate.
119    ///
120    /// Each constraint has the form `T:'a`, meaning "some type `T` must
121    /// outlive the lifetime 'a". These constraints derive from
122    /// instantiated type parameters. So if you had a struct defined
123    /// like the following:
124    /// ```ignore (illustrative)
125    /// struct Foo<T: 'static> { ... }
126    /// ```
127    /// In some expression `let x = Foo { ... }`, it will
128    /// instantiate the type parameter `T` with a fresh type `$0`. At
129    /// the same time, it will record a region obligation of
130    /// `$0: 'static`. This will get checked later by regionck. (We
131    /// can't generally check these things right away because we have
132    /// to wait until types are resolved.)
133    ///
134    /// These are stored in a map keyed to the id of the innermost
135    /// enclosing fn body / static initializer expression. This is
136    /// because the location where the obligation was incurred can be
137    /// relevant with respect to which sublifetime assumptions are in
138    /// place. The reason that we store under the fn-id, and not
139    /// something more fine-grained, is so that it is easier for
140    /// regionck to be sure that it has found *all* the region
141    /// obligations (otherwise, it's easy to fail to walk to a
142    /// particular node-id).
143    ///
144    /// Before running `resolve_regions_and_report_errors`, the creator
145    /// of the inference context is expected to invoke
146    /// [`InferCtxt::process_registered_region_obligations`]
147    /// for each body-id in this map, which will process the
148    /// obligations within. This is expected to be done 'late enough'
149    /// that all type inference variables have been bound and so forth.
150    region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
151
152    /// The outlives bounds that we assume must hold about placeholders that
153    /// come from instantiating the binder of coroutine-witnesses. These bounds
154    /// are deduced from the well-formedness of the witness's types, and are
155    /// necessary because of the way we anonymize the regions in a coroutine,
156    /// which may cause types to no longer be considered well-formed.
157    region_assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
158
159    /// Caches for opaque type inference.
160    opaque_type_storage: OpaqueTypeStorage<'tcx>,
161}
162
163impl<'tcx> InferCtxtInner<'tcx> {
164    fn new() -> InferCtxtInner<'tcx> {
165        InferCtxtInner {
166            undo_log: InferCtxtUndoLogs::default(),
167
168            projection_cache: Default::default(),
169            type_variable_storage: Default::default(),
170            const_unification_storage: Default::default(),
171            int_unification_storage: Default::default(),
172            float_unification_storage: Default::default(),
173            region_constraint_storage: Some(Default::default()),
174            region_obligations: Default::default(),
175            region_assumptions: Default::default(),
176            opaque_type_storage: Default::default(),
177        }
178    }
179
180    #[inline]
181    pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
182        &self.region_obligations
183    }
184
185    #[inline]
186    pub fn region_assumptions(&self) -> &[ty::ArgOutlivesPredicate<'tcx>] {
187        &self.region_assumptions
188    }
189
190    #[inline]
191    pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
192        self.projection_cache.with_log(&mut self.undo_log)
193    }
194
195    #[inline]
196    fn try_type_variables_probe_ref(
197        &self,
198        vid: ty::TyVid,
199    ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
200        // Uses a read-only view of the unification table, this way we don't
201        // need an undo log.
202        self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
203    }
204
205    #[inline]
206    fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
207        self.type_variable_storage.with_log(&mut self.undo_log)
208    }
209
210    #[inline]
211    pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
212        self.opaque_type_storage.with_log(&mut self.undo_log)
213    }
214
215    #[inline]
216    fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
217        self.int_unification_storage.with_log(&mut self.undo_log)
218    }
219
220    #[inline]
221    fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
222        self.float_unification_storage.with_log(&mut self.undo_log)
223    }
224
225    #[inline]
226    fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
227        self.const_unification_storage.with_log(&mut self.undo_log)
228    }
229
230    #[inline]
231    pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
232        self.region_constraint_storage
233            .as_mut()
234            .expect("region constraints already solved")
235            .with_log(&mut self.undo_log)
236    }
237}
238
239pub struct InferCtxt<'tcx> {
240    pub tcx: TyCtxt<'tcx>,
241
242    /// The mode of this inference context, see the struct documentation
243    /// for more details.
244    typing_mode: TypingMode<'tcx>,
245
246    /// Whether this inference context should care about region obligations in
247    /// the root universe. Most notably, this is used during hir typeck as region
248    /// solving is left to borrowck instead.
249    pub considering_regions: bool,
250
251    /// If set, this flag causes us to skip the 'leak check' during
252    /// higher-ranked subtyping operations. This flag is a temporary one used
253    /// to manage the removal of the leak-check: for the time being, we still run the
254    /// leak-check, but we issue warnings.
255    skip_leak_check: bool,
256
257    pub inner: RefCell<InferCtxtInner<'tcx>>,
258
259    /// Once region inference is done, the values for each variable.
260    lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
261
262    /// Caches the results of trait selection. This cache is used
263    /// for things that depends on inference variables or placeholders.
264    pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
265
266    /// Caches the results of trait evaluation. This cache is used
267    /// for things that depends on inference variables or placeholders.
268    pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
269
270    /// The set of predicates on which errors have been reported, to
271    /// avoid reporting the same error twice.
272    pub reported_trait_errors:
273        RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
274
275    pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
276
277    /// When an error occurs, we want to avoid reporting "derived"
278    /// errors that are due to this original failure. We have this
279    /// flag that one can set whenever one creates a type-error that
280    /// is due to an error in a prior pass.
281    ///
282    /// Don't read this flag directly, call `is_tainted_by_errors()`
283    /// and `set_tainted_by_errors()`.
284    tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
285
286    /// What is the innermost universe we have created? Starts out as
287    /// `UniverseIndex::root()` but grows from there as we enter
288    /// universal quantifiers.
289    ///
290    /// N.B., at present, we exclude the universal quantifiers on the
291    /// item we are type-checking, and just consider those names as
292    /// part of the root universe. So this would only get incremented
293    /// when we enter into a higher-ranked (`for<..>`) type or trait
294    /// bound.
295    universe: Cell<ty::UniverseIndex>,
296
297    next_trait_solver: bool,
298
299    pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
300}
301
302/// See the `error_reporting` module for more details.
303#[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
304pub enum ValuePairs<'tcx> {
305    Regions(ExpectedFound<ty::Region<'tcx>>),
306    Terms(ExpectedFound<ty::Term<'tcx>>),
307    Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
308    TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
309    PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
310    ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
311    ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
312}
313
314impl<'tcx> ValuePairs<'tcx> {
315    pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
316        if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
317            && let Some(expected) = expected.as_type()
318            && let Some(found) = found.as_type()
319        {
320            Some((expected, found))
321        } else {
322            None
323        }
324    }
325}
326
327/// The trace designates the path through inference that we took to
328/// encounter an error or subtyping constraint.
329///
330/// See the `error_reporting` module for more details.
331#[derive(Clone, Debug)]
332pub struct TypeTrace<'tcx> {
333    pub cause: ObligationCause<'tcx>,
334    pub values: ValuePairs<'tcx>,
335}
336
337/// The origin of a `r1 <= r2` constraint.
338///
339/// See `error_reporting` module for more details
340#[derive(Clone, Debug)]
341pub enum SubregionOrigin<'tcx> {
342    /// Arose from a subtyping relation
343    Subtype(Box<TypeTrace<'tcx>>),
344
345    /// When casting `&'a T` to an `&'b Trait` object,
346    /// relating `'a` to `'b`.
347    RelateObjectBound(Span),
348
349    /// Some type parameter was instantiated with the given type,
350    /// and that type must outlive some region.
351    RelateParamBound(Span, Ty<'tcx>, Option<Span>),
352
353    /// The given region parameter was instantiated with a region
354    /// that must outlive some other region.
355    RelateRegionParamBound(Span, Option<Ty<'tcx>>),
356
357    /// Creating a pointer `b` to contents of another reference.
358    Reborrow(Span),
359
360    /// (&'a &'b T) where a >= b
361    ReferenceOutlivesReferent(Ty<'tcx>, Span),
362
363    /// Comparing the signature and requirements of an impl method against
364    /// the containing trait.
365    CompareImplItemObligation {
366        span: Span,
367        impl_item_def_id: LocalDefId,
368        trait_item_def_id: DefId,
369    },
370
371    /// Checking that the bounds of a trait's associated type hold for a given impl.
372    CheckAssociatedTypeBounds {
373        parent: Box<SubregionOrigin<'tcx>>,
374        impl_item_def_id: LocalDefId,
375        trait_item_def_id: DefId,
376    },
377
378    AscribeUserTypeProvePredicate(Span),
379}
380
381// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
382#[cfg(target_pointer_width = "64")]
383rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
384
385impl<'tcx> SubregionOrigin<'tcx> {
386    pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
387        match self {
388            Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
389            Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
390            _ => ConstraintCategory::BoringNoLocation,
391        }
392    }
393}
394
395/// Times when we replace bound regions with existentials:
396#[derive(Clone, Copy, Debug)]
397pub enum BoundRegionConversionTime {
398    /// when a fn is called
399    FnCall,
400
401    /// when two higher-ranked types are compared
402    HigherRankedType,
403
404    /// when projecting an associated type
405    AssocTypeProjection(DefId),
406}
407
408/// Reasons to create a region inference variable.
409///
410/// See `error_reporting` module for more details.
411#[derive(Copy, Clone, Debug)]
412pub enum RegionVariableOrigin {
413    /// Region variables created for ill-categorized reasons.
414    ///
415    /// They mostly indicate places in need of refactoring.
416    Misc(Span),
417
418    /// Regions created by a `&P` or `[...]` pattern.
419    PatternRegion(Span),
420
421    /// Regions created by `&` operator.
422    BorrowRegion(Span),
423
424    /// Regions created as part of an autoref of a method receiver.
425    Autoref(Span),
426
427    /// Regions created as part of an automatic coercion.
428    Coercion(Span),
429
430    /// Region variables created as the values for early-bound regions.
431    ///
432    /// FIXME(@lcnr): This should also store a `DefId`, similar to
433    /// `TypeVariableOrigin`.
434    RegionParameterDefinition(Span, Symbol),
435
436    /// Region variables created when instantiating a binder with
437    /// existential variables, e.g. when calling a function or method.
438    BoundRegion(Span, ty::BoundRegionKind, BoundRegionConversionTime),
439
440    UpvarRegion(ty::UpvarId, Span),
441
442    /// This origin is used for the inference variables that we create
443    /// during NLL region processing.
444    Nll(NllRegionVariableOrigin),
445}
446
447#[derive(Copy, Clone, Debug)]
448pub enum NllRegionVariableOrigin {
449    /// During NLL region processing, we create variables for free
450    /// regions that we encounter in the function signature and
451    /// elsewhere. This origin indices we've got one of those.
452    FreeRegion,
453
454    /// "Universal" instantiation of a higher-ranked region (e.g.,
455    /// from a `for<'a> T` binder). Meant to represent "any region".
456    Placeholder(ty::PlaceholderRegion),
457
458    Existential {
459        /// If this is true, then this variable was created to represent a lifetime
460        /// bound in a `for` binder. For example, it might have been created to
461        /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
462        /// Such variables are created when we are trying to figure out if there
463        /// is any valid instantiation of `'a` that could fit into some scenario.
464        ///
465        /// This is used to inform error reporting: in the case that we are trying to
466        /// determine whether there is any valid instantiation of a `'a` variable that meets
467        /// some constraint C, we want to blame the "source" of that `for` type,
468        /// rather than blaming the source of the constraint C.
469        from_forall: bool,
470    },
471}
472
473#[derive(Copy, Clone, Debug)]
474pub struct FixupError {
475    unresolved: TyOrConstInferVar,
476}
477
478impl fmt::Display for FixupError {
479    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480        match self.unresolved {
481            TyOrConstInferVar::TyInt(_) => write!(
482                f,
483                "cannot determine the type of this integer; \
484                 add a suffix to specify the type explicitly"
485            ),
486            TyOrConstInferVar::TyFloat(_) => write!(
487                f,
488                "cannot determine the type of this number; \
489                 add a suffix to specify the type explicitly"
490            ),
491            TyOrConstInferVar::Ty(_) => write!(f, "unconstrained type"),
492            TyOrConstInferVar::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 TypeOutlivesConstraint<'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    /// Number of type variables created so far.
750    pub fn num_ty_vars(&self) -> usize {
751        self.inner.borrow_mut().type_variables().num_vars()
752    }
753
754    pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
755        self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
756    }
757
758    pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
759        let vid = self.inner.borrow_mut().type_variables().new_var(self.universe(), origin);
760        Ty::new_var(self.tcx, vid)
761    }
762
763    pub fn next_ty_var_id_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
764        let origin = TypeVariableOrigin { span, param_def_id: None };
765        self.inner.borrow_mut().type_variables().new_var(universe, origin)
766    }
767
768    pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
769        let vid = self.next_ty_var_id_in_universe(span, universe);
770        Ty::new_var(self.tcx, vid)
771    }
772
773    pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
774        self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
775    }
776
777    pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
778        let vid = self
779            .inner
780            .borrow_mut()
781            .const_unification_table()
782            .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
783            .vid;
784        ty::Const::new_var(self.tcx, vid)
785    }
786
787    pub fn next_const_var_in_universe(
788        &self,
789        span: Span,
790        universe: ty::UniverseIndex,
791    ) -> ty::Const<'tcx> {
792        let origin = ConstVariableOrigin { span, param_def_id: None };
793        let vid = self
794            .inner
795            .borrow_mut()
796            .const_unification_table()
797            .new_key(ConstVariableValue::Unknown { origin, universe })
798            .vid;
799        ty::Const::new_var(self.tcx, vid)
800    }
801
802    pub fn next_int_var(&self) -> Ty<'tcx> {
803        let next_int_var_id =
804            self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
805        Ty::new_int_var(self.tcx, next_int_var_id)
806    }
807
808    pub fn next_float_var(&self) -> Ty<'tcx> {
809        let next_float_var_id =
810            self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown);
811        Ty::new_float_var(self.tcx, next_float_var_id)
812    }
813
814    /// Creates a fresh region variable with the next available index.
815    /// The variable will be created in the maximum universe created
816    /// thus far, allowing it to name any region created thus far.
817    pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
818        self.next_region_var_in_universe(origin, self.universe())
819    }
820
821    /// Creates a fresh region variable with the next available index
822    /// in the given universe; typically, you can use
823    /// `next_region_var` and just use the maximal universe.
824    pub fn next_region_var_in_universe(
825        &self,
826        origin: RegionVariableOrigin,
827        universe: ty::UniverseIndex,
828    ) -> ty::Region<'tcx> {
829        let region_var =
830            self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
831        ty::Region::new_var(self.tcx, region_var)
832    }
833
834    pub fn next_term_var_of_kind(&self, term: ty::Term<'tcx>, span: Span) -> ty::Term<'tcx> {
835        match term.kind() {
836            ty::TermKind::Ty(_) => self.next_ty_var(span).into(),
837            ty::TermKind::Const(_) => self.next_const_var(span).into(),
838        }
839    }
840
841    /// Return the universe that the region `r` was created in. For
842    /// most regions (e.g., `'static`, named regions from the user,
843    /// etc) this is the root universe U0. For inference variables or
844    /// placeholders, however, it will return the universe which they
845    /// are associated.
846    pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
847        self.inner.borrow_mut().unwrap_region_constraints().universe(r)
848    }
849
850    /// Number of region variables created so far.
851    pub fn num_region_vars(&self) -> usize {
852        self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
853    }
854
855    /// Just a convenient wrapper of `next_region_var` for using during NLL.
856    #[instrument(skip(self), level = "debug")]
857    pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
858        self.next_region_var(RegionVariableOrigin::Nll(origin))
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_in_universe(
864        &self,
865        origin: NllRegionVariableOrigin,
866        universe: ty::UniverseIndex,
867    ) -> ty::Region<'tcx> {
868        self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
869    }
870
871    pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
872        match param.kind {
873            GenericParamDefKind::Lifetime => {
874                // Create a region inference variable for the given
875                // region parameter definition.
876                self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
877                    span, param.name,
878                ))
879                .into()
880            }
881            GenericParamDefKind::Type { .. } => {
882                // Create a type inference variable for the given
883                // type parameter definition. The generic parameters are
884                // for actual parameters that may be referred to by
885                // the default of this type parameter, if it exists.
886                // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
887                // used in a path such as `Foo::<T, U>::new()` will
888                // use an inference variable for `C` with `[T, U]`
889                // as the generic parameters for the default, `(T, U)`.
890                let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
891                    self.universe(),
892                    TypeVariableOrigin { param_def_id: Some(param.def_id), span },
893                );
894
895                Ty::new_var(self.tcx, ty_var_id).into()
896            }
897            GenericParamDefKind::Const { .. } => {
898                let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
899                let const_var_id = self
900                    .inner
901                    .borrow_mut()
902                    .const_unification_table()
903                    .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
904                    .vid;
905                ty::Const::new_var(self.tcx, const_var_id).into()
906            }
907        }
908    }
909
910    /// Given a set of generics defined on a type or impl, returns the generic parameters mapping
911    /// each type/region parameter to a fresh inference variable.
912    pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
913        GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
914    }
915
916    /// Returns `true` if errors have been reported since this infcx was
917    /// created. This is sometimes used as a heuristic to skip
918    /// reporting errors that often occur as a result of earlier
919    /// errors, but where it's hard to be 100% sure (e.g., unresolved
920    /// inference variables, regionck errors).
921    #[must_use = "this method does not have any side effects"]
922    pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
923        self.tainted_by_errors.get()
924    }
925
926    /// Set the "tainted by errors" flag to true. We call this when we
927    /// observe an error from a prior pass.
928    pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
929        debug!("set_tainted_by_errors(ErrorGuaranteed)");
930        self.tainted_by_errors.set(Some(e));
931    }
932
933    pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
934        let mut inner = self.inner.borrow_mut();
935        let inner = &mut *inner;
936        inner.unwrap_region_constraints().var_origin(vid)
937    }
938
939    /// Clone the list of variable regions. This is used only during NLL processing
940    /// to put the set of region variables into the NLL region context.
941    pub fn get_region_var_infos(&self) -> VarInfos {
942        let inner = self.inner.borrow();
943        assert!(!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log));
944        let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
945        assert!(storage.data.is_empty(), "{:#?}", storage.data);
946        // We clone instead of taking because borrowck still wants to use the
947        // inference context after calling this for diagnostics and the new
948        // trait solver.
949        storage.var_infos.clone()
950    }
951
952    #[instrument(level = "debug", skip(self), ret)]
953    pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
954        self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
955    }
956
957    #[instrument(level = "debug", skip(self), ret)]
958    pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
959        self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
960    }
961
962    #[inline(always)]
963    pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
964        debug_assert!(!self.next_trait_solver());
965        match self.typing_mode() {
966            TypingMode::Analysis {
967                defining_opaque_types_and_generators: defining_opaque_types,
968            }
969            | TypingMode::Borrowck { 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 shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1061        match term.kind() {
1062            ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1063            ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1064        }
1065    }
1066
1067    pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1068        self.inner.borrow_mut().type_variables().root_var(var)
1069    }
1070
1071    pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1072        self.inner.borrow_mut().const_unification_table().find(var).vid
1073    }
1074
1075    /// Resolves an int var to a rigid int type, if it was constrained to one,
1076    /// or else the root int var in the unification table.
1077    pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1078        let mut inner = self.inner.borrow_mut();
1079        let value = inner.int_unification_table().probe_value(vid);
1080        match value {
1081            ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1082            ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1083            ty::IntVarValue::Unknown => {
1084                Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1085            }
1086        }
1087    }
1088
1089    /// Resolves a float var to a rigid int type, if it was constrained to one,
1090    /// or else the root float var in the unification table.
1091    pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1092        let mut inner = self.inner.borrow_mut();
1093        let value = inner.float_unification_table().probe_value(vid);
1094        match value {
1095            ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1096            ty::FloatVarValue::Unknown => {
1097                Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1098            }
1099        }
1100    }
1101
1102    /// Where possible, replaces type/const variables in
1103    /// `value` with their final value. Note that region variables
1104    /// are unaffected. If a type/const variable has not been unified, it
1105    /// is left as is. This is an idempotent operation that does
1106    /// not affect inference state in any way and so you can do it
1107    /// at will.
1108    pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1109    where
1110        T: TypeFoldable<TyCtxt<'tcx>>,
1111    {
1112        if let Err(guar) = value.error_reported() {
1113            self.set_tainted_by_errors(guar);
1114        }
1115        if !value.has_non_region_infer() {
1116            return value;
1117        }
1118        let mut r = resolve::OpportunisticVarResolver::new(self);
1119        value.fold_with(&mut r)
1120    }
1121
1122    pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1123    where
1124        T: TypeFoldable<TyCtxt<'tcx>>,
1125    {
1126        if !value.has_infer() {
1127            return value; // Avoid duplicated type-folding.
1128        }
1129        let mut r = InferenceLiteralEraser { tcx: self.tcx };
1130        value.fold_with(&mut r)
1131    }
1132
1133    pub fn probe_const_var(&self, vid: ty::ConstVid) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1134        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1135            ConstVariableValue::Known { value } => Ok(value),
1136            ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1137        }
1138    }
1139
1140    /// Attempts to resolve all type/region/const variables in
1141    /// `value`. Region inference must have been run already (e.g.,
1142    /// by calling `resolve_regions_and_report_errors`). If some
1143    /// variable was never unified, an `Err` results.
1144    ///
1145    /// This method is idempotent, but it not typically not invoked
1146    /// except during the writeback phase.
1147    pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1148        match resolve::fully_resolve(self, value) {
1149            Ok(value) => {
1150                if value.has_non_region_infer() {
1151                    bug!("`{value:?}` is not fully resolved");
1152                }
1153                if value.has_infer_regions() {
1154                    let guar = self.dcx().delayed_bug(format!("`{value:?}` is not fully resolved"));
1155                    Ok(fold_regions(self.tcx, value, |re, _| {
1156                        if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1157                    }))
1158                } else {
1159                    Ok(value)
1160                }
1161            }
1162            Err(e) => Err(e),
1163        }
1164    }
1165
1166    // Instantiates the bound variables in a given binder with fresh inference
1167    // variables in the current universe.
1168    //
1169    // Use this method if you'd like to find some generic parameters of the binder's
1170    // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1171    // that corresponds to your use case, consider whether or not you should
1172    // use [`InferCtxt::enter_forall`] instead.
1173    pub fn instantiate_binder_with_fresh_vars<T>(
1174        &self,
1175        span: Span,
1176        lbrct: BoundRegionConversionTime,
1177        value: ty::Binder<'tcx, T>,
1178    ) -> T
1179    where
1180        T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1181    {
1182        if let Some(inner) = value.no_bound_vars() {
1183            return inner;
1184        }
1185
1186        let bound_vars = value.bound_vars();
1187        let mut args = Vec::with_capacity(bound_vars.len());
1188
1189        for bound_var_kind in bound_vars {
1190            let arg: ty::GenericArg<'_> = match bound_var_kind {
1191                ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1192                ty::BoundVariableKind::Region(br) => {
1193                    self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1194                }
1195                ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1196            };
1197            args.push(arg);
1198        }
1199
1200        struct ToFreshVars<'tcx> {
1201            args: Vec<ty::GenericArg<'tcx>>,
1202        }
1203
1204        impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1205            fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1206                self.args[br.var.index()].expect_region()
1207            }
1208            fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1209                self.args[bt.var.index()].expect_ty()
1210            }
1211            fn replace_const(&mut self, bv: ty::BoundVar) -> ty::Const<'tcx> {
1212                self.args[bv.index()].expect_const()
1213            }
1214        }
1215        let delegate = ToFreshVars { args };
1216        self.tcx.replace_bound_vars_uncached(value, delegate)
1217    }
1218
1219    /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1220    pub(crate) fn verify_generic_bound(
1221        &self,
1222        origin: SubregionOrigin<'tcx>,
1223        kind: GenericKind<'tcx>,
1224        a: ty::Region<'tcx>,
1225        bound: VerifyBound<'tcx>,
1226    ) {
1227        debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1228
1229        self.inner
1230            .borrow_mut()
1231            .unwrap_region_constraints()
1232            .verify_generic_bound(origin, kind, a, bound);
1233    }
1234
1235    /// Obtains the latest type of the given closure; this may be a
1236    /// closure in the current function, in which case its
1237    /// `ClosureKind` may not yet be known.
1238    pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1239        let unresolved_kind_ty = match *closure_ty.kind() {
1240            ty::Closure(_, args) => args.as_closure().kind_ty(),
1241            ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1242            _ => bug!("unexpected type {closure_ty}"),
1243        };
1244        let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1245        closure_kind_ty.to_opt_closure_kind()
1246    }
1247
1248    pub fn universe(&self) -> ty::UniverseIndex {
1249        self.universe.get()
1250    }
1251
1252    /// Creates and return a fresh universe that extends all previous
1253    /// universes. Updates `self.universe` to that new universe.
1254    pub fn create_next_universe(&self) -> ty::UniverseIndex {
1255        let u = self.universe.get().next_universe();
1256        debug!("create_next_universe {u:?}");
1257        self.universe.set(u);
1258        u
1259    }
1260
1261    /// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1262    /// which contains the necessary information to use the trait system without
1263    /// using canonicalization or carrying this inference context around.
1264    pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1265        let typing_mode = match self.typing_mode() {
1266            // FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1267            // to handle them without proper canonicalization. This means we may cause cycle
1268            // errors and fail to reveal opaques while inside of bodies. We should rename this
1269            // function and require explicit comments on all use-sites in the future.
1270            ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1271            | ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1272                TypingMode::non_body_analysis()
1273            }
1274            mode @ (ty::TypingMode::Coherence
1275            | ty::TypingMode::PostBorrowckAnalysis { .. }
1276            | ty::TypingMode::PostAnalysis) => mode,
1277        };
1278        ty::TypingEnv { typing_mode, param_env }
1279    }
1280
1281    /// Similar to [`Self::canonicalize_query`], except that it returns
1282    /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1283    /// `param_env` to not contain any inference variables or placeholders.
1284    pub fn pseudo_canonicalize_query<V>(
1285        &self,
1286        param_env: ty::ParamEnv<'tcx>,
1287        value: V,
1288    ) -> PseudoCanonicalInput<'tcx, V>
1289    where
1290        V: TypeVisitable<TyCtxt<'tcx>>,
1291    {
1292        debug_assert!(!value.has_infer());
1293        debug_assert!(!value.has_placeholders());
1294        debug_assert!(!param_env.has_infer());
1295        debug_assert!(!param_env.has_placeholders());
1296        self.typing_env(param_env).as_query_input(value)
1297    }
1298
1299    /// The returned function is used in a fast path. If it returns `true` the variable is
1300    /// unchanged, `false` indicates that the status is unknown.
1301    #[inline]
1302    pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1303        // This hoists the borrow/release out of the loop body.
1304        let inner = self.inner.try_borrow();
1305
1306        move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1307            (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1308                use self::type_variable::TypeVariableValue;
1309
1310                matches!(
1311                    inner.try_type_variables_probe_ref(ty_var),
1312                    Some(TypeVariableValue::Unknown { .. })
1313                )
1314            }
1315            _ => false,
1316        }
1317    }
1318
1319    /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1320    ///   * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1321    ///   * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1322    ///
1323    /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1324    /// inlined, despite being large, because it has only two call sites that
1325    /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1326    /// inference variables), and it handles both `Ty` and `ty::Const` without
1327    /// having to resort to storing full `GenericArg`s in `stalled_on`.
1328    #[inline(always)]
1329    pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1330        match infer_var {
1331            TyOrConstInferVar::Ty(v) => {
1332                use self::type_variable::TypeVariableValue;
1333
1334                // If `inlined_probe` returns a `Known` value, it never equals
1335                // `ty::Infer(ty::TyVar(v))`.
1336                match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1337                    TypeVariableValue::Unknown { .. } => false,
1338                    TypeVariableValue::Known { .. } => true,
1339                }
1340            }
1341
1342            TyOrConstInferVar::TyInt(v) => {
1343                // If `inlined_probe_value` returns a value it's always a
1344                // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1345                // `ty::Infer(_)`.
1346                self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1347            }
1348
1349            TyOrConstInferVar::TyFloat(v) => {
1350                // If `probe_value` returns a value it's always a
1351                // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1352                //
1353                // Not `inlined_probe_value(v)` because this call site is colder.
1354                self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1355            }
1356
1357            TyOrConstInferVar::Const(v) => {
1358                // If `probe_value` returns a `Known` value, it never equals
1359                // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1360                //
1361                // Not `inlined_probe_value(v)` because this call site is colder.
1362                match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1363                    ConstVariableValue::Unknown { .. } => false,
1364                    ConstVariableValue::Known { .. } => true,
1365                }
1366            }
1367        }
1368    }
1369
1370    /// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1371    pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1372        debug_assert!(
1373            self.obligation_inspector.get().is_none(),
1374            "shouldn't override a set obligation inspector"
1375        );
1376        self.obligation_inspector.set(Some(inspector));
1377    }
1378}
1379
1380/// Helper for [InferCtxt::ty_or_const_infer_var_changed] (see comment on that), currently
1381/// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1382#[derive(Copy, Clone, Debug)]
1383pub enum TyOrConstInferVar {
1384    /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1385    Ty(TyVid),
1386    /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1387    TyInt(IntVid),
1388    /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1389    TyFloat(FloatVid),
1390
1391    /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1392    Const(ConstVid),
1393}
1394
1395impl<'tcx> TyOrConstInferVar {
1396    /// Tries to extract an inference variable from a type or a constant, returns `None`
1397    /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1398    /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1399    pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1400        match arg.kind() {
1401            GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1402            GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1403            GenericArgKind::Lifetime(_) => None,
1404        }
1405    }
1406
1407    /// Tries to extract an inference variable from a type or a constant, returns `None`
1408    /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1409    /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1410    pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1411        match term.kind() {
1412            TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1413            TermKind::Const(ct) => Self::maybe_from_const(ct),
1414        }
1415    }
1416
1417    /// Tries to extract an inference variable from a type, returns `None`
1418    /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1419    fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1420        match *ty.kind() {
1421            ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1422            ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1423            ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1424            _ => None,
1425        }
1426    }
1427
1428    /// Tries to extract an inference variable from a constant, returns `None`
1429    /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1430    fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1431        match ct.kind() {
1432            ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1433            _ => None,
1434        }
1435    }
1436}
1437
1438/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1439/// Used only for diagnostics.
1440struct InferenceLiteralEraser<'tcx> {
1441    tcx: TyCtxt<'tcx>,
1442}
1443
1444impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1445    fn cx(&self) -> TyCtxt<'tcx> {
1446        self.tcx
1447    }
1448
1449    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1450        match ty.kind() {
1451            ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1452            ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1453            _ => ty.super_fold_with(self),
1454        }
1455    }
1456}
1457
1458impl<'tcx> TypeTrace<'tcx> {
1459    pub fn span(&self) -> Span {
1460        self.cause.span
1461    }
1462
1463    pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1464        TypeTrace {
1465            cause: cause.clone(),
1466            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1467        }
1468    }
1469
1470    pub fn trait_refs(
1471        cause: &ObligationCause<'tcx>,
1472        a: ty::TraitRef<'tcx>,
1473        b: ty::TraitRef<'tcx>,
1474    ) -> TypeTrace<'tcx> {
1475        TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1476    }
1477
1478    pub fn consts(
1479        cause: &ObligationCause<'tcx>,
1480        a: ty::Const<'tcx>,
1481        b: ty::Const<'tcx>,
1482    ) -> TypeTrace<'tcx> {
1483        TypeTrace {
1484            cause: cause.clone(),
1485            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1486        }
1487    }
1488}
1489
1490impl<'tcx> SubregionOrigin<'tcx> {
1491    pub fn span(&self) -> Span {
1492        match *self {
1493            SubregionOrigin::Subtype(ref a) => a.span(),
1494            SubregionOrigin::RelateObjectBound(a) => a,
1495            SubregionOrigin::RelateParamBound(a, ..) => a,
1496            SubregionOrigin::RelateRegionParamBound(a, _) => a,
1497            SubregionOrigin::Reborrow(a) => a,
1498            SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1499            SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1500            SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1501            SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1502        }
1503    }
1504
1505    pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1506    where
1507        F: FnOnce() -> Self,
1508    {
1509        match *cause.code() {
1510            traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1511                SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1512            }
1513
1514            traits::ObligationCauseCode::CompareImplItem {
1515                impl_item_def_id,
1516                trait_item_def_id,
1517                kind: _,
1518            } => SubregionOrigin::CompareImplItemObligation {
1519                span: cause.span,
1520                impl_item_def_id,
1521                trait_item_def_id,
1522            },
1523
1524            traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1525                impl_item_def_id,
1526                trait_item_def_id,
1527            } => SubregionOrigin::CheckAssociatedTypeBounds {
1528                impl_item_def_id,
1529                trait_item_def_id,
1530                parent: Box::new(default()),
1531            },
1532
1533            traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1534                SubregionOrigin::AscribeUserTypeProvePredicate(span)
1535            }
1536
1537            traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1538                SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1539            }
1540
1541            _ => default(),
1542        }
1543    }
1544}
1545
1546impl RegionVariableOrigin {
1547    pub fn span(&self) -> Span {
1548        match *self {
1549            RegionVariableOrigin::Misc(a)
1550            | RegionVariableOrigin::PatternRegion(a)
1551            | RegionVariableOrigin::BorrowRegion(a)
1552            | RegionVariableOrigin::Autoref(a)
1553            | RegionVariableOrigin::Coercion(a)
1554            | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1555            | RegionVariableOrigin::BoundRegion(a, ..)
1556            | RegionVariableOrigin::UpvarRegion(_, a) => a,
1557            RegionVariableOrigin::Nll(..) => bug!("NLL variable used with `span`"),
1558        }
1559    }
1560}
1561
1562impl<'tcx> InferCtxt<'tcx> {
1563    /// Given a [`hir::Block`], get the span of its last expression or
1564    /// statement, peeling off any inner blocks.
1565    pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1566        let block = block.innermost_block();
1567        if let Some(expr) = &block.expr {
1568            expr.span
1569        } else if let Some(stmt) = block.stmts.last() {
1570            // possibly incorrect trailing `;` in the else arm
1571            stmt.span
1572        } else {
1573            // empty block; point at its entirety
1574            block.span
1575        }
1576    }
1577
1578    /// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1579    /// of its last expression or statement, peeling off any inner blocks.
1580    pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1581        match self.tcx.hir_node(hir_id) {
1582            hir::Node::Block(blk)
1583            | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1584                self.find_block_span(blk)
1585            }
1586            hir::Node::Expr(e) => e.span,
1587            _ => DUMMY_SP,
1588        }
1589    }
1590}