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