1 pub use self::freshen::TypeFreshener;
2 pub use self::lexical_region_resolve::RegionResolutionError;
3 pub use self::LateBoundRegionConversionTime::*;
4 pub use self::RegionVariableOrigin::*;
5 pub use self::SubregionOrigin::*;
6 pub use self::ValuePairs::*;
8 use self::opaque_types::OpaqueTypeStorage;
9 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
11 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine, TraitEngineExt};
13 use rustc_data_structures::fx::FxIndexMap;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_data_structures::sync::Lrc;
16 use rustc_data_structures::undo_log::Rollback;
17 use rustc_data_structures::unify as ut;
18 use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed};
19 use rustc_hir::def_id::{DefId, LocalDefId};
20 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
21 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
22 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
23 use rustc_middle::mir::interpret::{ErrorHandled, EvalToValTreeResult};
24 use rustc_middle::mir::ConstraintCategory;
25 use rustc_middle::traits::select;
26 use rustc_middle::ty::error::{ExpectedFound, TypeError};
27 use rustc_middle::ty::fold::BoundVarReplacerDelegate;
28 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
29 use rustc_middle::ty::relate::RelateResult;
30 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
31 use rustc_middle::ty::visit::TypeVisitable;
32 pub use rustc_middle::ty::IntVarValue;
33 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
34 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
35 use rustc_span::symbol::Symbol;
38 use std::cell::{Cell, RefCell};
41 use self::combine::CombineFields;
42 use self::error_reporting::TypeErrCtxt;
43 use self::free_regions::RegionRelations;
44 use self::lexical_region_resolve::LexicalRegionResolutions;
45 use self::outlives::env::OutlivesEnvironment;
46 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
47 use self::region_constraints::{
48 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
50 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
56 pub mod error_reporting;
63 mod lexical_region_resolve;
69 pub mod region_constraints;
72 pub mod type_variable;
77 pub struct InferOk<'tcx, T> {
79 pub obligations: PredicateObligations<'tcx>,
81 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
83 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
84 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
86 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
87 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
90 /// This type contains all the things within `InferCtxt` that sit within a
91 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
92 /// operations are hot enough that we want only one call to `borrow_mut` per
93 /// call to `start_snapshot` and `rollback_to`.
95 pub struct InferCtxtInner<'tcx> {
96 /// Cache for projections. This cache is snapshotted along with the infcx.
98 /// Public so that `traits::project` can use it.
99 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
101 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
102 /// that might instantiate a general type variable have an order,
103 /// represented by its upper and lower bounds.
104 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
106 /// Map from const parameter variable to the kind of const it represents.
107 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
109 /// Map from integral variable to the kind of integer it represents.
110 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
112 /// Map from floating variable to the kind of float it represents.
113 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
115 /// Tracks the set of region variables and the constraints between them.
116 /// This is initially `Some(_)` but when
117 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
118 /// -- further attempts to perform unification, etc., may fail if new
119 /// region constraints would've been added.
120 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
122 /// A set of constraints that regionck must validate. Each
123 /// constraint has the form `T:'a`, meaning "some type `T` must
124 /// outlive the lifetime 'a". These constraints derive from
125 /// instantiated type parameters. So if you had a struct defined
127 /// ```ignore (illustrative)
128 /// struct Foo<T:'static> { ... }
130 /// then in some expression `let x = Foo { ... }` it will
131 /// instantiate the type parameter `T` with a fresh type `$0`. At
132 /// the same time, it will record a region obligation of
133 /// `$0:'static`. This will get checked later by regionck. (We
134 /// can't generally check these things right away because we have
135 /// to wait until types are resolved.)
137 /// These are stored in a map keyed to the id of the innermost
138 /// enclosing fn body / static initializer expression. This is
139 /// because the location where the obligation was incurred can be
140 /// relevant with respect to which sublifetime assumptions are in
141 /// place. The reason that we store under the fn-id, and not
142 /// something more fine-grained, is so that it is easier for
143 /// regionck to be sure that it has found *all* the region
144 /// obligations (otherwise, it's easy to fail to walk to a
145 /// particular node-id).
147 /// Before running `resolve_regions_and_report_errors`, the creator
148 /// of the inference context is expected to invoke
149 /// [`InferCtxt::process_registered_region_obligations`]
150 /// for each body-id in this map, which will process the
151 /// obligations within. This is expected to be done 'late enough'
152 /// that all type inference variables have been bound and so forth.
153 region_obligations: Vec<RegionObligation<'tcx>>,
155 undo_log: InferCtxtUndoLogs<'tcx>,
157 /// Caches for opaque type inference.
158 pub opaque_type_storage: OpaqueTypeStorage<'tcx>,
161 impl<'tcx> InferCtxtInner<'tcx> {
162 fn new() -> InferCtxtInner<'tcx> {
164 projection_cache: Default::default(),
165 type_variable_storage: type_variable::TypeVariableStorage::new(),
166 undo_log: InferCtxtUndoLogs::default(),
167 const_unification_storage: ut::UnificationTableStorage::new(),
168 int_unification_storage: ut::UnificationTableStorage::new(),
169 float_unification_storage: ut::UnificationTableStorage::new(),
170 region_constraint_storage: Some(RegionConstraintStorage::new()),
171 region_obligations: vec![],
172 opaque_type_storage: Default::default(),
177 pub fn region_obligations(&self) -> &[RegionObligation<'tcx>] {
178 &self.region_obligations
182 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
183 self.projection_cache.with_log(&mut self.undo_log)
187 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
188 self.type_variable_storage.with_log(&mut self.undo_log)
192 pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
193 self.opaque_type_storage.with_log(&mut self.undo_log)
197 fn int_unification_table(
199 ) -> ut::UnificationTable<
202 &mut ut::UnificationStorage<ty::IntVid>,
203 &mut InferCtxtUndoLogs<'tcx>,
206 self.int_unification_storage.with_log(&mut self.undo_log)
210 fn float_unification_table(
212 ) -> ut::UnificationTable<
215 &mut ut::UnificationStorage<ty::FloatVid>,
216 &mut InferCtxtUndoLogs<'tcx>,
219 self.float_unification_storage.with_log(&mut self.undo_log)
223 fn const_unification_table(
225 ) -> ut::UnificationTable<
228 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
229 &mut InferCtxtUndoLogs<'tcx>,
232 self.const_unification_storage.with_log(&mut self.undo_log)
236 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
237 self.region_constraint_storage
239 .expect("region constraints already solved")
240 .with_log(&mut self.undo_log)
244 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
245 pub enum DefiningAnchor {
246 /// `DefId` of the item.
248 /// When opaque types are not resolved, we `Bubble` up, meaning
249 /// return the opaque/hidden type pair from query, for caller of query to handle it.
251 /// Used to catch type mismatch errors when handling opaque types.
255 pub struct InferCtxt<'tcx> {
256 pub tcx: TyCtxt<'tcx>,
258 /// The `DefId` of the item in whose context we are performing inference or typeck.
259 /// It is used to check whether an opaque type use is a defining use.
261 /// If it is `DefiningAnchor::Bubble`, we can't resolve opaque types here and need to bubble up
262 /// the obligation. This frequently happens for
263 /// short lived InferCtxt within queries. The opaque type obligations are forwarded
264 /// to the outside until the end up in an `InferCtxt` for typeck or borrowck.
266 /// It is default value is `DefiningAnchor::Error`, this way it is easier to catch errors that
267 /// might come up during inference or typeck.
268 pub defining_use_anchor: DefiningAnchor,
270 /// Whether this inference context should care about region obligations in
271 /// the root universe. Most notably, this is used during hir typeck as region
272 /// solving is left to borrowck instead.
273 pub considering_regions: bool,
275 pub inner: RefCell<InferCtxtInner<'tcx>>,
277 /// If set, this flag causes us to skip the 'leak check' during
278 /// higher-ranked subtyping operations. This flag is a temporary one used
279 /// to manage the removal of the leak-check: for the time being, we still run the
280 /// leak-check, but we issue warnings. This flag can only be set to true
281 /// when entering a snapshot.
282 skip_leak_check: Cell<bool>,
284 /// Once region inference is done, the values for each variable.
285 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
287 /// Caches the results of trait selection. This cache is used
288 /// for things that have to do with the parameters in scope.
289 pub selection_cache: select::SelectionCache<'tcx>,
291 /// Caches the results of trait evaluation.
292 pub evaluation_cache: select::EvaluationCache<'tcx>,
294 /// the set of predicates on which errors have been reported, to
295 /// avoid reporting the same error twice.
296 pub reported_trait_errors: RefCell<FxIndexMap<Span, Vec<ty::Predicate<'tcx>>>>,
298 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
300 /// When an error occurs, we want to avoid reporting "derived"
301 /// errors that are due to this original failure. Normally, we
302 /// handle this with the `err_count_on_creation` count, which
303 /// basically just tracks how many errors were reported when we
304 /// started type-checking a fn and checks to see if any new errors
305 /// have been reported since then. Not great, but it works.
307 /// However, when errors originated in other passes -- notably
308 /// resolve -- this heuristic breaks down. Therefore, we have this
309 /// auxiliary flag that one can set whenever one creates a
310 /// type-error that is due to an error in a prior pass.
312 /// Don't read this flag directly, call `is_tainted_by_errors()`
313 /// and `set_tainted_by_errors()`.
314 tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
316 /// Track how many errors were reported when this infcx is created.
317 /// If the number of errors increases, that's also a sign (line
318 /// `tainted_by_errors`) to avoid reporting certain kinds of errors.
319 // FIXME(matthewjasper) Merge into `tainted_by_errors`
320 err_count_on_creation: usize,
322 /// This flag is true while there is an active snapshot.
323 in_snapshot: Cell<bool>,
325 /// What is the innermost universe we have created? Starts out as
326 /// `UniverseIndex::root()` but grows from there as we enter
327 /// universal quantifiers.
329 /// N.B., at present, we exclude the universal quantifiers on the
330 /// item we are type-checking, and just consider those names as
331 /// part of the root universe. So this would only get incremented
332 /// when we enter into a higher-ranked (`for<..>`) type or trait
334 universe: Cell<ty::UniverseIndex>,
336 normalize_fn_sig_for_diagnostic:
337 Option<Lrc<dyn Fn(&InferCtxt<'tcx>, ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx>>>,
339 /// During coherence we have to assume that other crates may add
340 /// additional impls which we currently don't know about.
342 /// To deal with this evaluation should be conservative
343 /// and consider the possibility of impls from outside this crate.
344 /// This comes up primarily when resolving ambiguity. Imagine
345 /// there is some trait reference `$0: Bar` where `$0` is an
346 /// inference variable. If `intercrate` is true, then we can never
347 /// say for sure that this reference is not implemented, even if
348 /// there are *no impls at all for `Bar`*, because `$0` could be
349 /// bound to some type that in a downstream crate that implements
352 /// Outside of coherence we set this to false because we are only
353 /// interested in types that the user could actually have written.
354 /// In other words, we consider `$0: Bar` to be unimplemented if
355 /// there is no type that the user could *actually name* that
356 /// would satisfy it. This avoids crippling inference, basically.
357 pub intercrate: bool,
360 /// See the `error_reporting` module for more details.
361 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
362 pub enum ValuePairs<'tcx> {
363 Regions(ExpectedFound<ty::Region<'tcx>>),
364 Terms(ExpectedFound<ty::Term<'tcx>>),
365 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
366 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
369 impl<'tcx> ValuePairs<'tcx> {
370 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
371 if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
372 && let Some(expected) = expected.ty()
373 && let Some(found) = found.ty()
375 Some((expected, found))
382 /// The trace designates the path through inference that we took to
383 /// encounter an error or subtyping constraint.
385 /// See the `error_reporting` module for more details.
386 #[derive(Clone, Debug)]
387 pub struct TypeTrace<'tcx> {
388 pub cause: ObligationCause<'tcx>,
389 pub values: ValuePairs<'tcx>,
392 /// The origin of a `r1 <= r2` constraint.
394 /// See `error_reporting` module for more details
395 #[derive(Clone, Debug)]
396 pub enum SubregionOrigin<'tcx> {
397 /// Arose from a subtyping relation
398 Subtype(Box<TypeTrace<'tcx>>),
400 /// When casting `&'a T` to an `&'b Trait` object,
401 /// relating `'a` to `'b`
402 RelateObjectBound(Span),
404 /// Some type parameter was instantiated with the given type,
405 /// and that type must outlive some region.
406 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
408 /// The given region parameter was instantiated with a region
409 /// that must outlive some other region.
410 RelateRegionParamBound(Span),
412 /// Creating a pointer `b` to contents of another reference
415 /// Creating a pointer `b` to contents of an upvar
416 ReborrowUpvar(Span, ty::UpvarId),
418 /// Data with type `Ty<'tcx>` was borrowed
419 DataBorrowed(Ty<'tcx>, Span),
421 /// (&'a &'b T) where a >= b
422 ReferenceOutlivesReferent(Ty<'tcx>, Span),
424 /// Comparing the signature and requirements of an impl method against
425 /// the containing trait.
426 CompareImplItemObligation {
428 impl_item_def_id: LocalDefId,
429 trait_item_def_id: DefId,
432 /// Checking that the bounds of a trait's associated type hold for a given impl
433 CheckAssociatedTypeBounds {
434 parent: Box<SubregionOrigin<'tcx>>,
435 impl_item_def_id: LocalDefId,
436 trait_item_def_id: DefId,
439 AscribeUserTypeProvePredicate(Span),
442 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
443 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
444 static_assert_size!(SubregionOrigin<'_>, 32);
446 impl<'tcx> SubregionOrigin<'tcx> {
447 pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
449 Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
450 Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
451 _ => ConstraintCategory::BoringNoLocation,
456 /// Times when we replace late-bound regions with variables:
457 #[derive(Clone, Copy, Debug)]
458 pub enum LateBoundRegionConversionTime {
459 /// when a fn is called
462 /// when two higher-ranked types are compared
465 /// when projecting an associated type
466 AssocTypeProjection(DefId),
469 /// Reasons to create a region inference variable
471 /// See `error_reporting` module for more details
472 #[derive(Copy, Clone, Debug)]
473 pub enum RegionVariableOrigin {
474 /// Region variables created for ill-categorized reasons,
475 /// mostly indicates places in need of refactoring
478 /// Regions created by a `&P` or `[...]` pattern
481 /// Regions created by `&` operator
484 /// Regions created as part of an autoref of a method receiver
487 /// Regions created as part of an automatic coercion
490 /// Region variables created as the values for early-bound regions
491 EarlyBoundRegion(Span, Symbol),
493 /// Region variables created for bound regions
494 /// in a function or method that is called
495 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
497 UpvarRegion(ty::UpvarId, Span),
499 /// This origin is used for the inference variables that we create
500 /// during NLL region processing.
501 Nll(NllRegionVariableOrigin),
504 #[derive(Copy, Clone, Debug)]
505 pub enum NllRegionVariableOrigin {
506 /// During NLL region processing, we create variables for free
507 /// regions that we encounter in the function signature and
508 /// elsewhere. This origin indices we've got one of those.
511 /// "Universal" instantiation of a higher-ranked region (e.g.,
512 /// from a `for<'a> T` binder). Meant to represent "any region".
513 Placeholder(ty::PlaceholderRegion),
516 /// If this is true, then this variable was created to represent a lifetime
517 /// bound in a `for` binder. For example, it might have been created to
518 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
519 /// Such variables are created when we are trying to figure out if there
520 /// is any valid instantiation of `'a` that could fit into some scenario.
522 /// This is used to inform error reporting: in the case that we are trying to
523 /// determine whether there is any valid instantiation of a `'a` variable that meets
524 /// some constraint C, we want to blame the "source" of that `for` type,
525 /// rather than blaming the source of the constraint C.
530 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
531 #[derive(Copy, Clone, Debug)]
532 pub enum FixupError<'tcx> {
533 UnresolvedIntTy(IntVid),
534 UnresolvedFloatTy(FloatVid),
536 UnresolvedConst(ConstVid<'tcx>),
539 /// See the `region_obligations` field for more information.
540 #[derive(Clone, Debug)]
541 pub struct RegionObligation<'tcx> {
542 pub sub_region: ty::Region<'tcx>,
543 pub sup_type: Ty<'tcx>,
544 pub origin: SubregionOrigin<'tcx>,
547 impl<'tcx> fmt::Display for FixupError<'tcx> {
548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549 use self::FixupError::*;
552 UnresolvedIntTy(_) => write!(
554 "cannot determine the type of this integer; \
555 add a suffix to specify the type explicitly"
557 UnresolvedFloatTy(_) => write!(
559 "cannot determine the type of this number; \
560 add a suffix to specify the type explicitly"
562 UnresolvedTy(_) => write!(f, "unconstrained type"),
563 UnresolvedConst(_) => write!(f, "unconstrained const value"),
568 /// Used to configure inference contexts before their creation
569 pub struct InferCtxtBuilder<'tcx> {
571 defining_use_anchor: DefiningAnchor,
572 considering_regions: bool,
573 /// Whether we are in coherence mode.
575 normalize_fn_sig_for_diagnostic:
576 Option<Lrc<dyn Fn(&InferCtxt<'tcx>, ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx>>>,
579 pub trait TyCtxtInferExt<'tcx> {
580 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
583 impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
584 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
587 defining_use_anchor: DefiningAnchor::Error,
588 considering_regions: true,
589 normalize_fn_sig_for_diagnostic: None,
595 impl<'tcx> InferCtxtBuilder<'tcx> {
596 /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
597 /// you need to call this function. Otherwise the opaque type will be treated opaquely.
599 /// It is only meant to be called in two places, for typeck
600 /// (via `Inherited::build`) and for the inference context used
602 pub fn with_opaque_type_inference(mut self, defining_use_anchor: DefiningAnchor) -> Self {
603 self.defining_use_anchor = defining_use_anchor;
607 pub fn intercrate(mut self) -> Self {
608 self.intercrate = true;
612 pub fn ignoring_regions(mut self) -> Self {
613 self.considering_regions = false;
617 pub fn with_normalize_fn_sig_for_diagnostic(
619 fun: Lrc<dyn Fn(&InferCtxt<'tcx>, ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx>>,
621 self.normalize_fn_sig_for_diagnostic = Some(fun);
625 /// Given a canonical value `C` as a starting point, create an
626 /// inference context that contains each of the bound values
627 /// within instantiated as a fresh variable. The `f` closure is
628 /// invoked with the new infcx, along with the instantiated value
629 /// `V` and a substitution `S`. This substitution `S` maps from
630 /// the bound values in `C` to their instantiated values in `V`
631 /// (in other words, `S(C) = V`).
632 pub fn build_with_canonical<T>(
635 canonical: &Canonical<'tcx, T>,
636 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
638 T: TypeFoldable<'tcx>,
640 let infcx = self.build();
641 let (value, subst) = infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
642 (infcx, value, subst)
645 pub fn build(&mut self) -> InferCtxt<'tcx> {
646 let InferCtxtBuilder {
650 ref normalize_fn_sig_for_diagnostic,
657 inner: RefCell::new(InferCtxtInner::new()),
658 lexical_region_resolutions: RefCell::new(None),
659 selection_cache: Default::default(),
660 evaluation_cache: Default::default(),
661 reported_trait_errors: Default::default(),
662 reported_closure_mismatch: Default::default(),
663 tainted_by_errors: Cell::new(None),
664 err_count_on_creation: tcx.sess.err_count(),
665 in_snapshot: Cell::new(false),
666 skip_leak_check: Cell::new(false),
667 universe: Cell::new(ty::UniverseIndex::ROOT),
668 normalize_fn_sig_for_diagnostic: normalize_fn_sig_for_diagnostic
676 impl<'tcx, T> InferOk<'tcx, T> {
677 pub fn unit(self) -> InferOk<'tcx, ()> {
678 InferOk { value: (), obligations: self.obligations }
681 /// Extracts `value`, registering any obligations into `fulfill_cx`.
682 pub fn into_value_registering_obligations(
684 infcx: &InferCtxt<'tcx>,
685 fulfill_cx: &mut dyn TraitEngine<'tcx>,
687 let InferOk { value, obligations } = self;
688 fulfill_cx.register_predicate_obligations(infcx, obligations);
693 impl<'tcx> InferOk<'tcx, ()> {
694 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
699 #[must_use = "once you start a snapshot, you should always consume it"]
700 pub struct CombinedSnapshot<'tcx> {
701 undo_snapshot: Snapshot<'tcx>,
702 region_constraints_snapshot: RegionSnapshot,
703 universe: ty::UniverseIndex,
704 was_in_snapshot: bool,
707 impl<'tcx> InferCtxt<'tcx> {
708 /// Creates a `TypeErrCtxt` for emitting various inference errors.
709 /// During typeck, use `FnCtxt::err_ctxt` instead.
710 pub fn err_ctxt(&self) -> TypeErrCtxt<'_, 'tcx> {
711 TypeErrCtxt { infcx: self, typeck_results: None, fallback_has_occurred: false }
714 pub fn is_in_snapshot(&self) -> bool {
715 self.in_snapshot.get()
718 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
719 t.fold_with(&mut self.freshener())
722 /// Returns the origin of the type variable identified by `vid`, or `None`
723 /// if this is not a type variable.
725 /// No attempt is made to resolve `ty`.
726 pub fn type_var_origin(&self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
728 ty::Infer(ty::TyVar(vid)) => {
729 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
735 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
736 freshen::TypeFreshener::new(self, false)
739 /// Like `freshener`, but does not replace `'static` regions.
740 pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
741 freshen::TypeFreshener::new(self, true)
744 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
745 let mut inner = self.inner.borrow_mut();
746 let mut vars: Vec<Ty<'_>> = inner
748 .unsolved_variables()
750 .map(|t| self.tcx.mk_ty_var(t))
753 (0..inner.int_unification_table().len())
754 .map(|i| ty::IntVid { index: i as u32 })
755 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
756 .map(|v| self.tcx.mk_int_var(v)),
759 (0..inner.float_unification_table().len())
760 .map(|i| ty::FloatVid { index: i as u32 })
761 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
762 .map(|v| self.tcx.mk_float_var(v)),
767 fn combine_fields<'a>(
769 trace: TypeTrace<'tcx>,
770 param_env: ty::ParamEnv<'tcx>,
771 define_opaque_types: bool,
772 ) -> CombineFields<'a, 'tcx> {
778 obligations: PredicateObligations::new(),
783 fn start_snapshot(&self) -> CombinedSnapshot<'tcx> {
784 debug!("start_snapshot()");
786 let in_snapshot = self.in_snapshot.replace(true);
788 let mut inner = self.inner.borrow_mut();
791 undo_snapshot: inner.undo_log.start_snapshot(),
792 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
793 universe: self.universe(),
794 was_in_snapshot: in_snapshot,
798 #[instrument(skip(self, snapshot), level = "debug")]
799 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'tcx>) {
800 let CombinedSnapshot {
802 region_constraints_snapshot,
807 self.in_snapshot.set(was_in_snapshot);
808 self.universe.set(universe);
810 let mut inner = self.inner.borrow_mut();
811 inner.rollback_to(undo_snapshot);
812 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
815 #[instrument(skip(self, snapshot), level = "debug")]
816 fn commit_from(&self, snapshot: CombinedSnapshot<'tcx>) {
817 let CombinedSnapshot {
819 region_constraints_snapshot: _,
824 self.in_snapshot.set(was_in_snapshot);
826 self.inner.borrow_mut().commit(undo_snapshot);
829 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
830 #[instrument(skip(self, f), level = "debug")]
831 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
833 F: FnOnce(&CombinedSnapshot<'tcx>) -> Result<T, E>,
835 let snapshot = self.start_snapshot();
836 let r = f(&snapshot);
837 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
840 self.commit_from(snapshot);
843 self.rollback_to("commit_if_ok -- error", snapshot);
849 /// Execute `f` then unroll any bindings it creates.
850 #[instrument(skip(self, f), level = "debug")]
851 pub fn probe<R, F>(&self, f: F) -> R
853 F: FnOnce(&CombinedSnapshot<'tcx>) -> R,
855 let snapshot = self.start_snapshot();
856 let r = f(&snapshot);
857 self.rollback_to("probe", snapshot);
861 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
862 #[instrument(skip(self, f), level = "debug")]
863 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
865 F: FnOnce(&CombinedSnapshot<'tcx>) -> R,
867 let snapshot = self.start_snapshot();
868 let was_skip_leak_check = self.skip_leak_check.get();
870 self.skip_leak_check.set(true);
872 let r = f(&snapshot);
873 self.rollback_to("probe", snapshot);
874 self.skip_leak_check.set(was_skip_leak_check);
878 /// Scan the constraints produced since `snapshot` began and returns:
880 /// - `None` -- if none of them involve "region outlives" constraints
881 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
882 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
883 pub fn region_constraints_added_in_snapshot(
885 snapshot: &CombinedSnapshot<'tcx>,
889 .unwrap_region_constraints()
890 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
893 pub fn opaque_types_added_in_snapshot(&self, snapshot: &CombinedSnapshot<'tcx>) -> bool {
894 self.inner.borrow().undo_log.opaque_types_in_snapshot(&snapshot.undo_snapshot)
897 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
898 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
901 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
903 T: at::ToTrace<'tcx>,
905 let origin = &ObligationCause::dummy();
907 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
908 // Ignore obligations, since we are unrolling
909 // everything anyway.
914 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
916 T: at::ToTrace<'tcx>,
918 let origin = &ObligationCause::dummy();
920 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
921 // Ignore obligations, since we are unrolling
922 // everything anyway.
927 #[instrument(skip(self), level = "debug")]
930 origin: SubregionOrigin<'tcx>,
934 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
937 /// Require that the region `r` be equal to one of the regions in
938 /// the set `regions`.
939 #[instrument(skip(self), level = "debug")]
940 pub fn member_constraint(
942 key: ty::OpaqueTypeKey<'tcx>,
943 definition_span: Span,
945 region: ty::Region<'tcx>,
946 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
948 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
957 /// Processes a `Coerce` predicate from the fulfillment context.
958 /// This is NOT the preferred way to handle coercion, which is to
959 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
961 /// This method here is actually a fallback that winds up being
962 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
963 /// and records a coercion predicate. Presently, this method is equivalent
964 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
965 /// actually requiring `a <: b`. This is of course a valid coercion,
966 /// but it's not as flexible as `FnCtxt::coerce` would be.
968 /// (We may refactor this in the future, but there are a number of
969 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
970 /// records adjustments that are required on the HIR in order to perform
971 /// the coercion, and we don't currently have a way to manage that.)
972 pub fn coerce_predicate(
974 cause: &ObligationCause<'tcx>,
975 param_env: ty::ParamEnv<'tcx>,
976 predicate: ty::PolyCoercePredicate<'tcx>,
977 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
978 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
979 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
983 self.subtype_predicate(cause, param_env, subtype_predicate)
986 pub fn subtype_predicate(
988 cause: &ObligationCause<'tcx>,
989 param_env: ty::ParamEnv<'tcx>,
990 predicate: ty::PolySubtypePredicate<'tcx>,
991 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
992 // Check for two unresolved inference variables, in which case we can
993 // make no progress. This is partly a micro-optimization, but it's
994 // also an opportunity to "sub-unify" the variables. This isn't
995 // *necessary* to prevent cycles, because they would eventually be sub-unified
996 // anyhow during generalization, but it helps with diagnostics (we can detect
997 // earlier that they are sub-unified).
999 // Note that we can just skip the binders here because
1000 // type variables can't (at present, at
1001 // least) capture any of the things bound by this binder.
1003 // Note that this sub here is not just for diagnostics - it has semantic
1005 let r_a = self.shallow_resolve(predicate.skip_binder().a);
1006 let r_b = self.shallow_resolve(predicate.skip_binder().b);
1007 match (r_a.kind(), r_b.kind()) {
1008 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
1009 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
1010 return Err((a_vid, b_vid));
1015 Ok(self.commit_if_ok(|_snapshot| {
1016 let ty::SubtypePredicate { a_is_expected, a, b } =
1017 self.replace_bound_vars_with_placeholders(predicate);
1019 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1025 pub fn region_outlives_predicate(
1027 cause: &traits::ObligationCause<'tcx>,
1028 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1030 let ty::OutlivesPredicate(r_a, r_b) = self.replace_bound_vars_with_placeholders(predicate);
1032 SubregionOrigin::from_obligation_cause(cause, || RelateRegionParamBound(cause.span));
1033 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1036 /// Number of type variables created so far.
1037 pub fn num_ty_vars(&self) -> usize {
1038 self.inner.borrow_mut().type_variables().num_vars()
1041 pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1042 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1045 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1046 self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1049 pub fn next_ty_var_id_in_universe(
1051 origin: TypeVariableOrigin,
1052 universe: ty::UniverseIndex,
1054 self.inner.borrow_mut().type_variables().new_var(universe, origin)
1057 pub fn next_ty_var_in_universe(
1059 origin: TypeVariableOrigin,
1060 universe: ty::UniverseIndex,
1062 let vid = self.next_ty_var_id_in_universe(origin, universe);
1063 self.tcx.mk_ty_var(vid)
1066 pub fn next_const_var(&self, ty: Ty<'tcx>, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
1067 self.tcx.mk_const(self.next_const_var_id(origin), ty)
1070 pub fn next_const_var_in_universe(
1073 origin: ConstVariableOrigin,
1074 universe: ty::UniverseIndex,
1075 ) -> ty::Const<'tcx> {
1079 .const_unification_table()
1080 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1081 self.tcx.mk_const(vid, ty)
1084 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1085 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1087 val: ConstVariableValue::Unknown { universe: self.universe() },
1091 fn next_int_var_id(&self) -> IntVid {
1092 self.inner.borrow_mut().int_unification_table().new_key(None)
1095 pub fn next_int_var(&self) -> Ty<'tcx> {
1096 self.tcx.mk_int_var(self.next_int_var_id())
1099 fn next_float_var_id(&self) -> FloatVid {
1100 self.inner.borrow_mut().float_unification_table().new_key(None)
1103 pub fn next_float_var(&self) -> Ty<'tcx> {
1104 self.tcx.mk_float_var(self.next_float_var_id())
1107 /// Creates a fresh region variable with the next available index.
1108 /// The variable will be created in the maximum universe created
1109 /// thus far, allowing it to name any region created thus far.
1110 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1111 self.next_region_var_in_universe(origin, self.universe())
1114 /// Creates a fresh region variable with the next available index
1115 /// in the given universe; typically, you can use
1116 /// `next_region_var` and just use the maximal universe.
1117 pub fn next_region_var_in_universe(
1119 origin: RegionVariableOrigin,
1120 universe: ty::UniverseIndex,
1121 ) -> ty::Region<'tcx> {
1123 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1124 self.tcx.mk_region(ty::ReVar(region_var))
1127 /// Return the universe that the region `r` was created in. For
1128 /// most regions (e.g., `'static`, named regions from the user,
1129 /// etc) this is the root universe U0. For inference variables or
1130 /// placeholders, however, it will return the universe which they
1132 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1133 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1136 /// Number of region variables created so far.
1137 pub fn num_region_vars(&self) -> usize {
1138 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1141 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1142 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1143 self.next_region_var(RegionVariableOrigin::Nll(origin))
1146 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1147 pub fn next_nll_region_var_in_universe(
1149 origin: NllRegionVariableOrigin,
1150 universe: ty::UniverseIndex,
1151 ) -> ty::Region<'tcx> {
1152 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1155 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1157 GenericParamDefKind::Lifetime => {
1158 // Create a region inference variable for the given
1159 // region parameter definition.
1160 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1162 GenericParamDefKind::Type { .. } => {
1163 // Create a type inference variable for the given
1164 // type parameter definition. The substitutions are
1165 // for actual parameters that may be referred to by
1166 // the default of this type parameter, if it exists.
1167 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1168 // used in a path such as `Foo::<T, U>::new()` will
1169 // use an inference variable for `C` with `[T, U]`
1170 // as the substitutions for the default, `(T, U)`.
1171 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1173 TypeVariableOrigin {
1174 kind: TypeVariableOriginKind::TypeParameterDefinition(
1182 self.tcx.mk_ty_var(ty_var_id).into()
1184 GenericParamDefKind::Const { .. } => {
1185 let origin = ConstVariableOrigin {
1186 kind: ConstVariableOriginKind::ConstParameterDefinition(
1193 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1195 val: ConstVariableValue::Unknown { universe: self.universe() },
1197 self.tcx.mk_const(const_var_id, self.tcx.type_of(param.def_id)).into()
1202 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1203 /// type/region parameter to a fresh inference variable.
1204 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1205 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1208 /// Returns `true` if errors have been reported since this infcx was
1209 /// created. This is sometimes used as a heuristic to skip
1210 /// reporting errors that often occur as a result of earlier
1211 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1212 /// inference variables, regionck errors).
1213 #[must_use = "this method does not have any side effects"]
1214 pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1216 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1217 tainted_by_errors={})",
1218 self.tcx.sess.err_count(),
1219 self.err_count_on_creation,
1220 self.tainted_by_errors.get().is_some()
1223 if let Some(e) = self.tainted_by_errors.get() {
1227 if self.tcx.sess.err_count() > self.err_count_on_creation {
1228 // errors reported since this infcx was made
1229 let e = self.tcx.sess.has_errors().unwrap();
1230 self.set_tainted_by_errors(e);
1237 /// Set the "tainted by errors" flag to true. We call this when we
1238 /// observe an error from a prior pass.
1239 pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1240 debug!("set_tainted_by_errors(ErrorGuaranteed)");
1241 self.tainted_by_errors.set(Some(e));
1244 pub fn skip_region_resolution(&self) {
1245 let (var_infos, _) = {
1246 let mut inner = self.inner.borrow_mut();
1247 let inner = &mut *inner;
1248 // Note: `inner.region_obligations` may not be empty, because we
1249 // didn't necessarily call `process_registered_region_obligations`.
1250 // This is okay, because that doesn't introduce new vars.
1252 .region_constraint_storage
1254 .expect("regions already resolved")
1255 .with_log(&mut inner.undo_log)
1256 .into_infos_and_data()
1259 let lexical_region_resolutions = LexicalRegionResolutions {
1260 values: rustc_index::vec::IndexVec::from_elem_n(
1261 crate::infer::lexical_region_resolve::VarValue::Value(self.tcx.lifetimes.re_erased),
1266 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1267 assert!(old_value.is_none());
1270 /// Process the region constraints and return any errors that
1271 /// result. After this, no more unification operations should be
1272 /// done -- or the compiler will panic -- but it is legal to use
1273 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1274 pub fn resolve_regions(
1276 outlives_env: &OutlivesEnvironment<'tcx>,
1277 ) -> Vec<RegionResolutionError<'tcx>> {
1278 let (var_infos, data) = {
1279 let mut inner = self.inner.borrow_mut();
1280 let inner = &mut *inner;
1282 self.tainted_by_errors().is_some() || inner.region_obligations.is_empty(),
1283 "region_obligations not empty: {:#?}",
1284 inner.region_obligations
1287 .region_constraint_storage
1289 .expect("regions already resolved")
1290 .with_log(&mut inner.undo_log)
1291 .into_infos_and_data()
1294 let region_rels = &RegionRelations::new(self.tcx, outlives_env.free_region_map());
1296 let (lexical_region_resolutions, errors) =
1297 lexical_region_resolve::resolve(outlives_env.param_env, region_rels, var_infos, data);
1299 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1300 assert!(old_value.is_none());
1304 /// Obtains (and clears) the current set of region
1305 /// constraints. The inference context is still usable: further
1306 /// unifications will simply add new constraints.
1308 /// This method is not meant to be used with normal lexical region
1309 /// resolution. Rather, it is used in the NLL mode as a kind of
1310 /// interim hack: basically we run normal type-check and generate
1311 /// region constraints as normal, but then we take them and
1312 /// translate them into the form that the NLL solver
1313 /// understands. See the NLL module for mode details.
1314 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1316 self.inner.borrow().region_obligations.is_empty(),
1317 "region_obligations not empty: {:#?}",
1318 self.inner.borrow().region_obligations
1321 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1324 /// Gives temporary access to the region constraint data.
1325 pub fn with_region_constraints<R>(
1327 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1329 let mut inner = self.inner.borrow_mut();
1330 op(inner.unwrap_region_constraints().data())
1333 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1334 let mut inner = self.inner.borrow_mut();
1335 let inner = &mut *inner;
1337 .region_constraint_storage
1339 .expect("regions already resolved")
1340 .with_log(&mut inner.undo_log)
1344 /// Takes ownership of the list of variable regions. This implies
1345 /// that all the region constraints have already been taken, and
1346 /// hence that `resolve_regions_and_report_errors` can never be
1347 /// called. This is used only during NLL processing to "hand off" ownership
1348 /// of the set of region variables into the NLL region context.
1349 pub fn take_region_var_origins(&self) -> VarInfos {
1350 let mut inner = self.inner.borrow_mut();
1351 let (var_infos, data) = inner
1352 .region_constraint_storage
1354 .expect("regions already resolved")
1355 .with_log(&mut inner.undo_log)
1356 .into_infos_and_data();
1357 assert!(data.is_empty());
1361 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1362 self.resolve_vars_if_possible(t).to_string()
1365 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1366 /// universe index of `TyVar(vid)`.
1367 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1368 use self::type_variable::TypeVariableValue;
1370 match self.inner.borrow_mut().type_variables().probe(vid) {
1371 TypeVariableValue::Known { value } => Ok(value),
1372 TypeVariableValue::Unknown { universe } => Err(universe),
1376 /// Resolve any type variables found in `value` -- but only one
1377 /// level. So, if the variable `?X` is bound to some type
1378 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1379 /// itself be bound to a type).
1381 /// Useful when you only need to inspect the outermost level of
1382 /// the type and don't care about nested types (or perhaps you
1383 /// will be resolving them as well, e.g. in a loop).
1384 pub fn shallow_resolve<T>(&self, value: T) -> T
1386 T: TypeFoldable<'tcx>,
1388 value.fold_with(&mut ShallowResolver { infcx: self })
1391 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1392 self.inner.borrow_mut().type_variables().root_var(var)
1395 /// Where possible, replaces type/const variables in
1396 /// `value` with their final value. Note that region variables
1397 /// are unaffected. If a type/const variable has not been unified, it
1398 /// is left as is. This is an idempotent operation that does
1399 /// not affect inference state in any way and so you can do it
1401 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1403 T: TypeFoldable<'tcx>,
1405 if !value.needs_infer() {
1406 return value; // Avoid duplicated subst-folding.
1408 let mut r = resolve::OpportunisticVarResolver::new(self);
1409 value.fold_with(&mut r)
1412 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1414 T: TypeFoldable<'tcx>,
1416 if !value.needs_infer() {
1417 return value; // Avoid duplicated subst-folding.
1419 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1420 value.fold_with(&mut r)
1423 /// Returns the first unresolved type or const variable contained in `T`.
1424 pub fn first_unresolved_const_or_ty_var<T>(
1427 ) -> Option<(ty::Term<'tcx>, Option<Span>)>
1429 T: TypeVisitable<'tcx>,
1431 value.visit_with(&mut resolve::UnresolvedTypeOrConstFinder::new(self)).break_value()
1434 pub fn probe_const_var(
1436 vid: ty::ConstVid<'tcx>,
1437 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1438 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1439 ConstVariableValue::Known { value } => Ok(value),
1440 ConstVariableValue::Unknown { universe } => Err(universe),
1444 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1446 * Attempts to resolve all type/region/const variables in
1447 * `value`. Region inference must have been run already (e.g.,
1448 * by calling `resolve_regions_and_report_errors`). If some
1449 * variable was never unified, an `Err` results.
1451 * This method is idempotent, but it not typically not invoked
1452 * except during the writeback phase.
1455 let value = resolve::fully_resolve(self, value);
1457 value.as_ref().map_or(true, |value| !value.needs_infer()),
1458 "`{value:?}` is not fully resolved"
1463 pub fn replace_bound_vars_with_fresh_vars<T>(
1466 lbrct: LateBoundRegionConversionTime,
1467 value: ty::Binder<'tcx, T>,
1470 T: TypeFoldable<'tcx> + Copy,
1472 if let Some(inner) = value.no_bound_vars() {
1476 struct ToFreshVars<'a, 'tcx> {
1477 infcx: &'a InferCtxt<'tcx>,
1479 lbrct: LateBoundRegionConversionTime,
1480 map: FxHashMap<ty::BoundVar, ty::GenericArg<'tcx>>,
1483 impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'_, 'tcx> {
1484 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1487 .or_insert_with(|| {
1489 .next_region_var(LateBoundRegion(self.span, br.kind, self.lbrct))
1494 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1497 .or_insert_with(|| {
1499 .next_ty_var(TypeVariableOrigin {
1500 kind: TypeVariableOriginKind::MiscVariable,
1507 fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> {
1510 .or_insert_with(|| {
1514 ConstVariableOrigin {
1515 kind: ConstVariableOriginKind::MiscVariable,
1524 let delegate = ToFreshVars { infcx: self, span, lbrct, map: Default::default() };
1525 self.tcx.replace_bound_vars_uncached(value, delegate)
1528 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1529 pub fn verify_generic_bound(
1531 origin: SubregionOrigin<'tcx>,
1532 kind: GenericKind<'tcx>,
1533 a: ty::Region<'tcx>,
1534 bound: VerifyBound<'tcx>,
1536 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1540 .unwrap_region_constraints()
1541 .verify_generic_bound(origin, kind, a, bound);
1544 /// Obtains the latest type of the given closure; this may be a
1545 /// closure in the current function, in which case its
1546 /// `ClosureKind` may not yet be known.
1547 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1548 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1549 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1550 closure_kind_ty.to_opt_closure_kind()
1553 /// Clears the selection, evaluation, and projection caches. This is useful when
1554 /// repeatedly attempting to select an `Obligation` while changing only
1555 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1556 pub fn clear_caches(&self) {
1557 self.selection_cache.clear();
1558 self.evaluation_cache.clear();
1559 self.inner.borrow_mut().projection_cache().clear();
1562 pub fn universe(&self) -> ty::UniverseIndex {
1566 /// Creates and return a fresh universe that extends all previous
1567 /// universes. Updates `self.universe` to that new universe.
1568 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1569 let u = self.universe.get().next_universe();
1570 self.universe.set(u);
1574 pub fn try_const_eval_resolve(
1576 param_env: ty::ParamEnv<'tcx>,
1577 unevaluated: ty::UnevaluatedConst<'tcx>,
1580 ) -> Result<ty::Const<'tcx>, ErrorHandled> {
1581 match self.const_eval_resolve(param_env, unevaluated, span) {
1582 Ok(Some(val)) => Ok(self.tcx.mk_const(val, ty)),
1585 let def_id = unevaluated.def.did;
1587 tcx.def_span(def_id),
1588 "unable to construct a constant value for the unevaluated constant {:?}",
1592 Err(err) => Err(err),
1596 /// Resolves and evaluates a constant.
1598 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1599 /// substitutions and environment are used to resolve the constant. Alternatively if the
1600 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1601 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1602 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1603 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1606 /// This handles inferences variables within both `param_env` and `substs` by
1607 /// performing the operation on their respective canonical forms.
1608 #[instrument(skip(self), level = "debug")]
1609 pub fn const_eval_resolve(
1611 mut param_env: ty::ParamEnv<'tcx>,
1612 unevaluated: ty::UnevaluatedConst<'tcx>,
1614 ) -> EvalToValTreeResult<'tcx> {
1615 let mut substs = self.resolve_vars_if_possible(unevaluated.substs);
1618 // Postpone the evaluation of constants whose substs depend on inference
1621 if substs.has_non_region_infer() {
1622 if let Some(ct) = tcx.bound_abstract_const(unevaluated.def)? {
1623 let ct = tcx.expand_abstract_consts(ct.subst(tcx, substs));
1624 if let Err(e) = ct.error_reported() {
1625 return Err(ErrorHandled::Reported(e));
1626 } else if ct.has_non_region_infer() || ct.has_non_region_param() {
1627 return Err(ErrorHandled::TooGeneric);
1629 substs = replace_param_and_infer_substs_with_placeholder(tcx, substs);
1632 substs = InternalSubsts::identity_for_item(tcx, unevaluated.def.did);
1633 param_env = tcx.param_env(unevaluated.def.did);
1637 let param_env_erased = tcx.erase_regions(param_env);
1638 let substs_erased = tcx.erase_regions(substs);
1639 debug!(?param_env_erased);
1640 debug!(?substs_erased);
1642 let unevaluated = ty::UnevaluatedConst { def: unevaluated.def, substs: substs_erased };
1644 // The return value is the evaluated value which doesn't contain any reference to inference
1645 // variables, thus we don't need to substitute back the original values.
1646 tcx.const_eval_resolve_for_typeck(param_env_erased, unevaluated, span)
1649 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1650 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1651 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1653 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1654 /// inlined, despite being large, because it has only two call sites that
1655 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1656 /// inference variables), and it handles both `Ty` and `ty::Const` without
1657 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1659 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1661 TyOrConstInferVar::Ty(v) => {
1662 use self::type_variable::TypeVariableValue;
1664 // If `inlined_probe` returns a `Known` value, it never equals
1665 // `ty::Infer(ty::TyVar(v))`.
1666 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1667 TypeVariableValue::Unknown { .. } => false,
1668 TypeVariableValue::Known { .. } => true,
1672 TyOrConstInferVar::TyInt(v) => {
1673 // If `inlined_probe_value` returns a value it's always a
1674 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1676 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1679 TyOrConstInferVar::TyFloat(v) => {
1680 // If `probe_value` returns a value it's always a
1681 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1683 // Not `inlined_probe_value(v)` because this call site is colder.
1684 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1687 TyOrConstInferVar::Const(v) => {
1688 // If `probe_value` returns a `Known` value, it never equals
1689 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1691 // Not `inlined_probe_value(v)` because this call site is colder.
1692 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1693 ConstVariableValue::Unknown { .. } => false,
1694 ConstVariableValue::Known { .. } => true,
1701 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
1702 /// Process the region constraints and report any errors that
1703 /// result. After this, no more unification operations should be
1704 /// done -- or the compiler will panic -- but it is legal to use
1705 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1707 /// Make sure to call [`InferCtxt::process_registered_region_obligations`]
1708 /// first, or preferably use [`InferCtxt::check_region_obligations_and_report_errors`]
1709 /// to do both of these operations together.
1710 pub fn resolve_regions_and_report_errors(
1712 generic_param_scope: LocalDefId,
1713 outlives_env: &OutlivesEnvironment<'tcx>,
1715 let errors = self.resolve_regions(outlives_env);
1717 if let None = self.tainted_by_errors() {
1718 // As a heuristic, just skip reporting region errors
1719 // altogether if other errors have been reported while
1720 // this infcx was in use. This is totally hokey but
1721 // otherwise we have a hard time separating legit region
1722 // errors from silly ones.
1723 self.report_region_errors(generic_param_scope, &errors);
1727 // [Note-Type-error-reporting]
1728 // An invariant is that anytime the expected or actual type is Error (the special
1729 // error type, meaning that an error occurred when typechecking this expression),
1730 // this is a derived error. The error cascaded from another error (that was already
1731 // reported), so it's not useful to display it to the user.
1732 // The following methods implement this logic.
1733 // They check if either the actual or expected type is Error, and don't print the error
1734 // in this case. The typechecker should only ever report type errors involving mismatched
1735 // types using one of these methods, and should not call span_err directly for such
1738 pub fn type_error_struct_with_diag<M>(
1742 actual_ty: Ty<'tcx>,
1743 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>
1745 M: FnOnce(String) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1747 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1748 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1750 let mut err = mk_diag(self.ty_to_string(actual_ty));
1752 // Don't report an error if actual type is `Error`.
1753 if actual_ty.references_error() {
1754 err.downgrade_to_delayed_bug();
1760 pub fn report_mismatched_types(
1762 cause: &ObligationCause<'tcx>,
1765 err: TypeError<'tcx>,
1766 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1767 self.report_and_explain_type_error(TypeTrace::types(cause, true, expected, actual), err)
1770 pub fn report_mismatched_consts(
1772 cause: &ObligationCause<'tcx>,
1773 expected: ty::Const<'tcx>,
1774 actual: ty::Const<'tcx>,
1775 err: TypeError<'tcx>,
1776 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1777 self.report_and_explain_type_error(TypeTrace::consts(cause, true, expected, actual), err)
1781 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1782 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1783 #[derive(Copy, Clone, Debug)]
1784 pub enum TyOrConstInferVar<'tcx> {
1785 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1787 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1789 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1792 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1793 Const(ConstVid<'tcx>),
1796 impl<'tcx> TyOrConstInferVar<'tcx> {
1797 /// Tries to extract an inference variable from a type or a constant, returns `None`
1798 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1799 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1800 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1801 match arg.unpack() {
1802 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1803 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1804 GenericArgKind::Lifetime(_) => None,
1808 /// Tries to extract an inference variable from a type, returns `None`
1809 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1810 fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1812 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1813 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1814 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1819 /// Tries to extract an inference variable from a constant, returns `None`
1820 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1821 fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1823 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1829 /// Replace `{integer}` with `i32` and `{float}` with `f64`.
1830 /// Used only for diagnostics.
1831 struct InferenceLiteralEraser<'tcx> {
1835 impl<'tcx> TypeFolder<'tcx> for InferenceLiteralEraser<'tcx> {
1836 fn tcx(&self) -> TyCtxt<'tcx> {
1840 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1842 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1843 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1844 _ => ty.super_fold_with(self),
1849 struct ShallowResolver<'a, 'tcx> {
1850 infcx: &'a InferCtxt<'tcx>,
1853 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1854 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1858 /// If `ty` is a type variable of some kind, resolve it one level
1859 /// (but do not resolve types found in the result). If `typ` is
1860 /// not a type variable, just return it unmodified.
1861 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1863 ty::Infer(ty::TyVar(v)) => {
1864 // Not entirely obvious: if `typ` is a type variable,
1865 // it can be resolved to an int/float variable, which
1866 // can then be recursively resolved, hence the
1867 // recursion. Note though that we prevent type
1868 // variables from unifying to other type variables
1869 // directly (though they may be embedded
1870 // structurally), and we prevent cycles in any case,
1871 // so this recursion should always be of very limited
1874 // Note: if these two lines are combined into one we get
1875 // dynamic borrow errors on `self.inner`.
1876 let known = self.infcx.inner.borrow_mut().type_variables().probe(v).known();
1877 known.map_or(ty, |t| self.fold_ty(t))
1880 ty::Infer(ty::IntVar(v)) => self
1884 .int_unification_table()
1886 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1888 ty::Infer(ty::FloatVar(v)) => self
1892 .float_unification_table()
1894 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1900 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1901 if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
1905 .const_unification_table()
1916 impl<'tcx> TypeTrace<'tcx> {
1917 pub fn span(&self) -> Span {
1922 cause: &ObligationCause<'tcx>,
1923 a_is_expected: bool,
1926 ) -> TypeTrace<'tcx> {
1928 cause: cause.clone(),
1929 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1933 pub fn poly_trait_refs(
1934 cause: &ObligationCause<'tcx>,
1935 a_is_expected: bool,
1936 a: ty::PolyTraitRef<'tcx>,
1937 b: ty::PolyTraitRef<'tcx>,
1938 ) -> TypeTrace<'tcx> {
1940 cause: cause.clone(),
1941 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1946 cause: &ObligationCause<'tcx>,
1947 a_is_expected: bool,
1950 ) -> TypeTrace<'tcx> {
1952 cause: cause.clone(),
1953 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1958 impl<'tcx> SubregionOrigin<'tcx> {
1959 pub fn span(&self) -> Span {
1961 Subtype(ref a) => a.span(),
1962 RelateObjectBound(a) => a,
1963 RelateParamBound(a, ..) => a,
1964 RelateRegionParamBound(a) => a,
1966 ReborrowUpvar(a, _) => a,
1967 DataBorrowed(_, a) => a,
1968 ReferenceOutlivesReferent(_, a) => a,
1969 CompareImplItemObligation { span, .. } => span,
1970 AscribeUserTypeProvePredicate(span) => span,
1971 CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1975 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1977 F: FnOnce() -> Self,
1979 match *cause.code() {
1980 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1981 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1984 traits::ObligationCauseCode::CompareImplItemObligation {
1988 } => SubregionOrigin::CompareImplItemObligation {
1994 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1997 } => SubregionOrigin::CheckAssociatedTypeBounds {
2000 parent: Box::new(default()),
2003 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
2004 SubregionOrigin::AscribeUserTypeProvePredicate(span)
2012 impl RegionVariableOrigin {
2013 pub fn span(&self) -> Span {
2020 | EarlyBoundRegion(a, ..)
2021 | LateBoundRegion(a, ..)
2022 | UpvarRegion(_, a) => a,
2023 Nll(..) => bug!("NLL variable used with `span`"),
2028 /// Replaces substs that reference param or infer variables with suitable
2029 /// placeholders. This function is meant to remove these param and infer
2030 /// substs when they're not actually needed to evaluate a constant.
2031 fn replace_param_and_infer_substs_with_placeholder<'tcx>(
2033 substs: SubstsRef<'tcx>,
2034 ) -> SubstsRef<'tcx> {
2035 tcx.mk_substs(substs.iter().enumerate().map(|(idx, arg)| {
2036 match arg.unpack() {
2037 GenericArgKind::Type(_) if arg.has_non_region_param() || arg.has_non_region_infer() => {
2038 tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
2039 universe: ty::UniverseIndex::ROOT,
2040 name: ty::BoundVar::from_usize(idx),
2044 GenericArgKind::Const(ct) if ct.has_non_region_infer() || ct.has_non_region_param() => {
2046 // If the type references param or infer, replace that too...
2047 if ty.has_non_region_param() || ty.has_non_region_infer() {
2048 bug!("const `{ct}`'s type should not reference params or types");
2051 ty::PlaceholderConst {
2052 universe: ty::UniverseIndex::ROOT,
2053 name: ty::BoundVar::from_usize(idx),