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