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 Bound<T> = Option<T>;
84 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
85 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
87 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
88 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
91 /// This type contains all the things within `InferCtxt` that sit within a
92 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
93 /// operations are hot enough that we want only one call to `borrow_mut` per
94 /// call to `start_snapshot` and `rollback_to`.
96 pub struct InferCtxtInner<'tcx> {
97 /// Cache for projections. This cache is snapshotted along with the infcx.
99 /// Public so that `traits::project` can use it.
100 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
102 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
103 /// that might instantiate a general type variable have an order,
104 /// represented by its upper and lower bounds.
105 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
107 /// Map from const parameter variable to the kind of const it represents.
108 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
110 /// Map from integral variable to the kind of integer it represents.
111 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
113 /// Map from floating variable to the kind of float it represents.
114 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
116 /// Tracks the set of region variables and the constraints between them.
117 /// This is initially `Some(_)` but when
118 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
119 /// -- further attempts to perform unification, etc., may fail if new
120 /// region constraints would've been added.
121 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
123 /// A set of constraints that regionck must validate. Each
124 /// constraint has the form `T:'a`, meaning "some type `T` must
125 /// outlive the lifetime 'a". These constraints derive from
126 /// instantiated type parameters. So if you had a struct defined
128 /// ```ignore (illustrative)
129 /// struct Foo<T:'static> { ... }
131 /// then in some expression `let x = Foo { ... }` it will
132 /// instantiate the type parameter `T` with a fresh type `$0`. At
133 /// the same time, it will record a region obligation of
134 /// `$0:'static`. This will get checked later by regionck. (We
135 /// can't generally check these things right away because we have
136 /// to wait until types are resolved.)
138 /// These are stored in a map keyed to the id of the innermost
139 /// enclosing fn body / static initializer expression. This is
140 /// because the location where the obligation was incurred can be
141 /// relevant with respect to which sublifetime assumptions are in
142 /// place. The reason that we store under the fn-id, and not
143 /// something more fine-grained, is so that it is easier for
144 /// regionck to be sure that it has found *all* the region
145 /// obligations (otherwise, it's easy to fail to walk to a
146 /// particular node-id).
148 /// Before running `resolve_regions_and_report_errors`, the creator
149 /// of the inference context is expected to invoke
150 /// [`InferCtxt::process_registered_region_obligations`]
151 /// for each body-id in this map, which will process the
152 /// obligations within. This is expected to be done 'late enough'
153 /// that all type inference variables have been bound and so forth.
154 region_obligations: Vec<RegionObligation<'tcx>>,
156 undo_log: InferCtxtUndoLogs<'tcx>,
158 /// Caches for opaque type inference.
159 pub opaque_type_storage: OpaqueTypeStorage<'tcx>,
162 impl<'tcx> InferCtxtInner<'tcx> {
163 fn new() -> InferCtxtInner<'tcx> {
165 projection_cache: Default::default(),
166 type_variable_storage: type_variable::TypeVariableStorage::new(),
167 undo_log: InferCtxtUndoLogs::default(),
168 const_unification_storage: ut::UnificationTableStorage::new(),
169 int_unification_storage: ut::UnificationTableStorage::new(),
170 float_unification_storage: ut::UnificationTableStorage::new(),
171 region_constraint_storage: Some(RegionConstraintStorage::new()),
172 region_obligations: vec![],
173 opaque_type_storage: Default::default(),
178 pub fn region_obligations(&self) -> &[RegionObligation<'tcx>] {
179 &self.region_obligations
183 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
184 self.projection_cache.with_log(&mut self.undo_log)
188 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
189 self.type_variable_storage.with_log(&mut self.undo_log)
193 pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
194 self.opaque_type_storage.with_log(&mut self.undo_log)
198 fn int_unification_table(
200 ) -> ut::UnificationTable<
203 &mut ut::UnificationStorage<ty::IntVid>,
204 &mut InferCtxtUndoLogs<'tcx>,
207 self.int_unification_storage.with_log(&mut self.undo_log)
211 fn float_unification_table(
213 ) -> ut::UnificationTable<
216 &mut ut::UnificationStorage<ty::FloatVid>,
217 &mut InferCtxtUndoLogs<'tcx>,
220 self.float_unification_storage.with_log(&mut self.undo_log)
224 fn const_unification_table(
226 ) -> ut::UnificationTable<
229 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
230 &mut InferCtxtUndoLogs<'tcx>,
233 self.const_unification_storage.with_log(&mut self.undo_log)
237 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
238 self.region_constraint_storage
240 .expect("region constraints already solved")
241 .with_log(&mut self.undo_log)
245 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
246 pub enum DefiningAnchor {
247 /// `DefId` of the item.
249 /// When opaque types are not resolved, we `Bubble` up, meaning
250 /// return the opaque/hidden type pair from query, for caller of query to handle it.
252 /// Used to catch type mismatch errors when handling opaque types.
256 pub struct InferCtxt<'tcx> {
257 pub tcx: TyCtxt<'tcx>,
259 /// The `DefId` of the item in whose context we are performing inference or typeck.
260 /// It is used to check whether an opaque type use is a defining use.
262 /// If it is `DefiningAnchor::Bubble`, we can't resolve opaque types here and need to bubble up
263 /// the obligation. This frequently happens for
264 /// short lived InferCtxt within queries. The opaque type obligations are forwarded
265 /// to the outside until the end up in an `InferCtxt` for typeck or borrowck.
267 /// It is default value is `DefiningAnchor::Error`, this way it is easier to catch errors that
268 /// might come up during inference or typeck.
269 pub defining_use_anchor: DefiningAnchor,
271 /// Whether this inference context should care about region obligations in
272 /// the root universe. Most notably, this is used during hir typeck as region
273 /// solving is left to borrowck instead.
274 pub considering_regions: bool,
276 pub inner: RefCell<InferCtxtInner<'tcx>>,
278 /// If set, this flag causes us to skip the 'leak check' during
279 /// higher-ranked subtyping operations. This flag is a temporary one used
280 /// to manage the removal of the leak-check: for the time being, we still run the
281 /// leak-check, but we issue warnings. This flag can only be set to true
282 /// when entering a snapshot.
283 skip_leak_check: Cell<bool>,
285 /// Once region inference is done, the values for each variable.
286 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
288 /// Caches the results of trait selection. This cache is used
289 /// for things that have to do with the parameters in scope.
290 pub selection_cache: select::SelectionCache<'tcx>,
292 /// Caches the results of trait evaluation.
293 pub evaluation_cache: select::EvaluationCache<'tcx>,
295 /// the set of predicates on which errors have been reported, to
296 /// avoid reporting the same error twice.
297 pub reported_trait_errors: RefCell<FxIndexMap<Span, Vec<ty::Predicate<'tcx>>>>,
299 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
301 /// When an error occurs, we want to avoid reporting "derived"
302 /// errors that are due to this original failure. Normally, we
303 /// handle this with the `err_count_on_creation` count, which
304 /// basically just tracks how many errors were reported when we
305 /// started type-checking a fn and checks to see if any new errors
306 /// have been reported since then. Not great, but it works.
308 /// However, when errors originated in other passes -- notably
309 /// resolve -- this heuristic breaks down. Therefore, we have this
310 /// auxiliary flag that one can set whenever one creates a
311 /// type-error that is due to an error in a prior pass.
313 /// Don't read this flag directly, call `is_tainted_by_errors()`
314 /// and `set_tainted_by_errors()`.
315 tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
317 /// Track how many errors were reported when this infcx is created.
318 /// If the number of errors increases, that's also a sign (line
319 /// `tainted_by_errors`) to avoid reporting certain kinds of errors.
320 // FIXME(matthewjasper) Merge into `tainted_by_errors`
321 err_count_on_creation: usize,
323 /// This flag is true while there is an active snapshot.
324 in_snapshot: Cell<bool>,
326 /// What is the innermost universe we have created? Starts out as
327 /// `UniverseIndex::root()` but grows from there as we enter
328 /// universal quantifiers.
330 /// N.B., at present, we exclude the universal quantifiers on the
331 /// item we are type-checking, and just consider those names as
332 /// part of the root universe. So this would only get incremented
333 /// when we enter into a higher-ranked (`for<..>`) type or trait
335 universe: Cell<ty::UniverseIndex>,
337 normalize_fn_sig_for_diagnostic:
338 Option<Lrc<dyn Fn(&InferCtxt<'tcx>, ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx>>>,
340 /// During coherence we have to assume that other crates may add
341 /// additional impls which we currently don't know about.
343 /// To deal with this evaluation should be conservative
344 /// and consider the possibility of impls from outside this crate.
345 /// This comes up primarily when resolving ambiguity. Imagine
346 /// there is some trait reference `$0: Bar` where `$0` is an
347 /// inference variable. If `intercrate` is true, then we can never
348 /// say for sure that this reference is not implemented, even if
349 /// there are *no impls at all for `Bar`*, because `$0` could be
350 /// bound to some type that in a downstream crate that implements
353 /// Outside of coherence we set this to false because we are only
354 /// interested in types that the user could actually have written.
355 /// In other words, we consider `$0: Bar` to be unimplemented if
356 /// there is no type that the user could *actually name* that
357 /// would satisfy it. This avoids crippling inference, basically.
358 pub intercrate: bool,
361 /// See the `error_reporting` module for more details.
362 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
363 pub enum ValuePairs<'tcx> {
364 Regions(ExpectedFound<ty::Region<'tcx>>),
365 Terms(ExpectedFound<ty::Term<'tcx>>),
366 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
367 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
370 impl<'tcx> ValuePairs<'tcx> {
371 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
372 if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
373 && let Some(expected) = expected.ty()
374 && let Some(found) = found.ty()
376 Some((expected, found))
383 /// The trace designates the path through inference that we took to
384 /// encounter an error or subtyping constraint.
386 /// See the `error_reporting` module for more details.
387 #[derive(Clone, Debug)]
388 pub struct TypeTrace<'tcx> {
389 pub cause: ObligationCause<'tcx>,
390 pub values: ValuePairs<'tcx>,
393 /// The origin of a `r1 <= r2` constraint.
395 /// See `error_reporting` module for more details
396 #[derive(Clone, Debug)]
397 pub enum SubregionOrigin<'tcx> {
398 /// Arose from a subtyping relation
399 Subtype(Box<TypeTrace<'tcx>>),
401 /// When casting `&'a T` to an `&'b Trait` object,
402 /// relating `'a` to `'b`
403 RelateObjectBound(Span),
405 /// Some type parameter was instantiated with the given type,
406 /// and that type must outlive some region.
407 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
409 /// The given region parameter was instantiated with a region
410 /// that must outlive some other region.
411 RelateRegionParamBound(Span),
413 /// Creating a pointer `b` to contents of another reference
416 /// Creating a pointer `b` to contents of an upvar
417 ReborrowUpvar(Span, ty::UpvarId),
419 /// Data with type `Ty<'tcx>` was borrowed
420 DataBorrowed(Ty<'tcx>, Span),
422 /// (&'a &'b T) where a >= b
423 ReferenceOutlivesReferent(Ty<'tcx>, Span),
425 /// Comparing the signature and requirements of an impl method against
426 /// the containing trait.
427 CompareImplItemObligation {
429 impl_item_def_id: LocalDefId,
430 trait_item_def_id: DefId,
433 /// Checking that the bounds of a trait's associated type hold for a given impl
434 CheckAssociatedTypeBounds {
435 parent: Box<SubregionOrigin<'tcx>>,
436 impl_item_def_id: LocalDefId,
437 trait_item_def_id: DefId,
440 AscribeUserTypeProvePredicate(Span),
443 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
444 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
445 static_assert_size!(SubregionOrigin<'_>, 32);
447 impl<'tcx> SubregionOrigin<'tcx> {
448 pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
450 Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
451 Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
452 _ => ConstraintCategory::BoringNoLocation,
457 /// Times when we replace late-bound regions with variables:
458 #[derive(Clone, Copy, Debug)]
459 pub enum LateBoundRegionConversionTime {
460 /// when a fn is called
463 /// when two higher-ranked types are compared
466 /// when projecting an associated type
467 AssocTypeProjection(DefId),
470 /// Reasons to create a region inference variable
472 /// See `error_reporting` module for more details
473 #[derive(Copy, Clone, Debug)]
474 pub enum RegionVariableOrigin {
475 /// Region variables created for ill-categorized reasons,
476 /// mostly indicates places in need of refactoring
479 /// Regions created by a `&P` or `[...]` pattern
482 /// Regions created by `&` operator
485 /// Regions created as part of an autoref of a method receiver
488 /// Regions created as part of an automatic coercion
491 /// Region variables created as the values for early-bound regions
492 EarlyBoundRegion(Span, Symbol),
494 /// Region variables created for bound regions
495 /// in a function or method that is called
496 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
498 UpvarRegion(ty::UpvarId, Span),
500 /// This origin is used for the inference variables that we create
501 /// during NLL region processing.
502 Nll(NllRegionVariableOrigin),
505 #[derive(Copy, Clone, Debug)]
506 pub enum NllRegionVariableOrigin {
507 /// During NLL region processing, we create variables for free
508 /// regions that we encounter in the function signature and
509 /// elsewhere. This origin indices we've got one of those.
512 /// "Universal" instantiation of a higher-ranked region (e.g.,
513 /// from a `for<'a> T` binder). Meant to represent "any region".
514 Placeholder(ty::PlaceholderRegion),
517 /// If this is true, then this variable was created to represent a lifetime
518 /// bound in a `for` binder. For example, it might have been created to
519 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
520 /// Such variables are created when we are trying to figure out if there
521 /// is any valid instantiation of `'a` that could fit into some scenario.
523 /// This is used to inform error reporting: in the case that we are trying to
524 /// determine whether there is any valid instantiation of a `'a` variable that meets
525 /// some constraint C, we want to blame the "source" of that `for` type,
526 /// rather than blaming the source of the constraint C.
531 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
532 #[derive(Copy, Clone, Debug)]
533 pub enum FixupError<'tcx> {
534 UnresolvedIntTy(IntVid),
535 UnresolvedFloatTy(FloatVid),
537 UnresolvedConst(ConstVid<'tcx>),
540 /// See the `region_obligations` field for more information.
541 #[derive(Clone, Debug)]
542 pub struct RegionObligation<'tcx> {
543 pub sub_region: ty::Region<'tcx>,
544 pub sup_type: Ty<'tcx>,
545 pub origin: SubregionOrigin<'tcx>,
548 impl<'tcx> fmt::Display for FixupError<'tcx> {
549 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550 use self::FixupError::*;
553 UnresolvedIntTy(_) => write!(
555 "cannot determine the type of this integer; \
556 add a suffix to specify the type explicitly"
558 UnresolvedFloatTy(_) => write!(
560 "cannot determine the type of this number; \
561 add a suffix to specify the type explicitly"
563 UnresolvedTy(_) => write!(f, "unconstrained type"),
564 UnresolvedConst(_) => write!(f, "unconstrained const value"),
569 /// Used to configure inference contexts before their creation
570 pub struct InferCtxtBuilder<'tcx> {
572 defining_use_anchor: DefiningAnchor,
573 considering_regions: bool,
574 /// Whether we are in coherence mode.
576 normalize_fn_sig_for_diagnostic:
577 Option<Lrc<dyn Fn(&InferCtxt<'tcx>, ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx>>>,
580 pub trait TyCtxtInferExt<'tcx> {
581 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
584 impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
585 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
588 defining_use_anchor: DefiningAnchor::Error,
589 considering_regions: true,
590 normalize_fn_sig_for_diagnostic: None,
596 impl<'tcx> InferCtxtBuilder<'tcx> {
597 /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
598 /// you need to call this function. Otherwise the opaque type will be treated opaquely.
600 /// It is only meant to be called in two places, for typeck
601 /// (via `Inherited::build`) and for the inference context used
603 pub fn with_opaque_type_inference(mut self, defining_use_anchor: DefiningAnchor) -> Self {
604 self.defining_use_anchor = defining_use_anchor;
608 pub fn intercrate(mut self) -> Self {
609 self.intercrate = true;
613 pub fn ignoring_regions(mut self) -> Self {
614 self.considering_regions = false;
618 pub fn with_normalize_fn_sig_for_diagnostic(
620 fun: Lrc<dyn Fn(&InferCtxt<'tcx>, ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx>>,
622 self.normalize_fn_sig_for_diagnostic = Some(fun);
626 /// Given a canonical value `C` as a starting point, create an
627 /// inference context that contains each of the bound values
628 /// within instantiated as a fresh variable. The `f` closure is
629 /// invoked with the new infcx, along with the instantiated value
630 /// `V` and a substitution `S`. This substitution `S` maps from
631 /// the bound values in `C` to their instantiated values in `V`
632 /// (in other words, `S(C) = V`).
633 pub fn build_with_canonical<T>(
636 canonical: &Canonical<'tcx, T>,
637 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
639 T: TypeFoldable<'tcx>,
641 let infcx = self.build();
642 let (value, subst) = infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
643 (infcx, value, subst)
646 pub fn build(&mut self) -> InferCtxt<'tcx> {
647 let InferCtxtBuilder {
651 ref normalize_fn_sig_for_diagnostic,
658 inner: RefCell::new(InferCtxtInner::new()),
659 lexical_region_resolutions: RefCell::new(None),
660 selection_cache: Default::default(),
661 evaluation_cache: Default::default(),
662 reported_trait_errors: Default::default(),
663 reported_closure_mismatch: Default::default(),
664 tainted_by_errors: Cell::new(None),
665 err_count_on_creation: tcx.sess.err_count(),
666 in_snapshot: Cell::new(false),
667 skip_leak_check: Cell::new(false),
668 universe: Cell::new(ty::UniverseIndex::ROOT),
669 normalize_fn_sig_for_diagnostic: normalize_fn_sig_for_diagnostic
677 impl<'tcx, T> InferOk<'tcx, T> {
678 pub fn unit(self) -> InferOk<'tcx, ()> {
679 InferOk { value: (), obligations: self.obligations }
682 /// Extracts `value`, registering any obligations into `fulfill_cx`.
683 pub fn into_value_registering_obligations(
685 infcx: &InferCtxt<'tcx>,
686 fulfill_cx: &mut dyn TraitEngine<'tcx>,
688 let InferOk { value, obligations } = self;
689 fulfill_cx.register_predicate_obligations(infcx, obligations);
694 impl<'tcx> InferOk<'tcx, ()> {
695 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
700 #[must_use = "once you start a snapshot, you should always consume it"]
701 pub struct CombinedSnapshot<'tcx> {
702 undo_snapshot: Snapshot<'tcx>,
703 region_constraints_snapshot: RegionSnapshot,
704 universe: ty::UniverseIndex,
705 was_in_snapshot: bool,
708 impl<'tcx> InferCtxt<'tcx> {
709 /// Creates a `TypeErrCtxt` for emitting various inference errors.
710 /// During typeck, use `FnCtxt::err_ctxt` instead.
711 pub fn err_ctxt(&self) -> TypeErrCtxt<'_, 'tcx> {
712 TypeErrCtxt { infcx: self, typeck_results: None, fallback_has_occurred: false }
715 pub fn is_in_snapshot(&self) -> bool {
716 self.in_snapshot.get()
719 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
720 t.fold_with(&mut self.freshener())
723 /// Returns the origin of the type variable identified by `vid`, or `None`
724 /// if this is not a type variable.
726 /// No attempt is made to resolve `ty`.
727 pub fn type_var_origin(&self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
729 ty::Infer(ty::TyVar(vid)) => {
730 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
736 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
737 freshen::TypeFreshener::new(self, false)
740 /// Like `freshener`, but does not replace `'static` regions.
741 pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
742 freshen::TypeFreshener::new(self, true)
745 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
746 let mut inner = self.inner.borrow_mut();
747 let mut vars: Vec<Ty<'_>> = inner
749 .unsolved_variables()
751 .map(|t| self.tcx.mk_ty_var(t))
754 (0..inner.int_unification_table().len())
755 .map(|i| ty::IntVid { index: i as u32 })
756 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
757 .map(|v| self.tcx.mk_int_var(v)),
760 (0..inner.float_unification_table().len())
761 .map(|i| ty::FloatVid { index: i as u32 })
762 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
763 .map(|v| self.tcx.mk_float_var(v)),
768 fn combine_fields<'a>(
770 trace: TypeTrace<'tcx>,
771 param_env: ty::ParamEnv<'tcx>,
772 define_opaque_types: bool,
773 ) -> CombineFields<'a, 'tcx> {
779 obligations: PredicateObligations::new(),
784 fn start_snapshot(&self) -> CombinedSnapshot<'tcx> {
785 debug!("start_snapshot()");
787 let in_snapshot = self.in_snapshot.replace(true);
789 let mut inner = self.inner.borrow_mut();
792 undo_snapshot: inner.undo_log.start_snapshot(),
793 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
794 universe: self.universe(),
795 was_in_snapshot: in_snapshot,
799 #[instrument(skip(self, snapshot), level = "debug")]
800 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'tcx>) {
801 let CombinedSnapshot {
803 region_constraints_snapshot,
808 self.in_snapshot.set(was_in_snapshot);
809 self.universe.set(universe);
811 let mut inner = self.inner.borrow_mut();
812 inner.rollback_to(undo_snapshot);
813 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
816 #[instrument(skip(self, snapshot), level = "debug")]
817 fn commit_from(&self, snapshot: CombinedSnapshot<'tcx>) {
818 let CombinedSnapshot {
820 region_constraints_snapshot: _,
825 self.in_snapshot.set(was_in_snapshot);
827 self.inner.borrow_mut().commit(undo_snapshot);
830 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
831 #[instrument(skip(self, f), level = "debug")]
832 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
834 F: FnOnce(&CombinedSnapshot<'tcx>) -> Result<T, E>,
836 let snapshot = self.start_snapshot();
837 let r = f(&snapshot);
838 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
841 self.commit_from(snapshot);
844 self.rollback_to("commit_if_ok -- error", snapshot);
850 /// Execute `f` then unroll any bindings it creates.
851 #[instrument(skip(self, f), level = "debug")]
852 pub fn probe<R, F>(&self, f: F) -> R
854 F: FnOnce(&CombinedSnapshot<'tcx>) -> R,
856 let snapshot = self.start_snapshot();
857 let r = f(&snapshot);
858 self.rollback_to("probe", snapshot);
862 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
863 #[instrument(skip(self, f), level = "debug")]
864 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
866 F: FnOnce(&CombinedSnapshot<'tcx>) -> R,
868 let snapshot = self.start_snapshot();
869 let was_skip_leak_check = self.skip_leak_check.get();
871 self.skip_leak_check.set(true);
873 let r = f(&snapshot);
874 self.rollback_to("probe", snapshot);
875 self.skip_leak_check.set(was_skip_leak_check);
879 /// Scan the constraints produced since `snapshot` began and returns:
881 /// - `None` -- if none of them involve "region outlives" constraints
882 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
883 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
884 pub fn region_constraints_added_in_snapshot(
886 snapshot: &CombinedSnapshot<'tcx>,
890 .unwrap_region_constraints()
891 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
894 pub fn opaque_types_added_in_snapshot(&self, snapshot: &CombinedSnapshot<'tcx>) -> bool {
895 self.inner.borrow().undo_log.opaque_types_in_snapshot(&snapshot.undo_snapshot)
898 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
899 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
902 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
904 T: at::ToTrace<'tcx>,
906 let origin = &ObligationCause::dummy();
908 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
909 // Ignore obligations, since we are unrolling
910 // everything anyway.
915 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
917 T: at::ToTrace<'tcx>,
919 let origin = &ObligationCause::dummy();
921 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
922 // Ignore obligations, since we are unrolling
923 // everything anyway.
928 #[instrument(skip(self), level = "debug")]
931 origin: SubregionOrigin<'tcx>,
935 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
938 /// Require that the region `r` be equal to one of the regions in
939 /// the set `regions`.
940 #[instrument(skip(self), level = "debug")]
941 pub fn member_constraint(
943 key: ty::OpaqueTypeKey<'tcx>,
944 definition_span: Span,
946 region: ty::Region<'tcx>,
947 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
949 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
958 /// Processes a `Coerce` predicate from the fulfillment context.
959 /// This is NOT the preferred way to handle coercion, which is to
960 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
962 /// This method here is actually a fallback that winds up being
963 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
964 /// and records a coercion predicate. Presently, this method is equivalent
965 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
966 /// actually requiring `a <: b`. This is of course a valid coercion,
967 /// but it's not as flexible as `FnCtxt::coerce` would be.
969 /// (We may refactor this in the future, but there are a number of
970 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
971 /// records adjustments that are required on the HIR in order to perform
972 /// the coercion, and we don't currently have a way to manage that.)
973 pub fn coerce_predicate(
975 cause: &ObligationCause<'tcx>,
976 param_env: ty::ParamEnv<'tcx>,
977 predicate: ty::PolyCoercePredicate<'tcx>,
978 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
979 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
980 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
984 self.subtype_predicate(cause, param_env, subtype_predicate)
987 pub fn subtype_predicate(
989 cause: &ObligationCause<'tcx>,
990 param_env: ty::ParamEnv<'tcx>,
991 predicate: ty::PolySubtypePredicate<'tcx>,
992 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
993 // Check for two unresolved inference variables, in which case we can
994 // make no progress. This is partly a micro-optimization, but it's
995 // also an opportunity to "sub-unify" the variables. This isn't
996 // *necessary* to prevent cycles, because they would eventually be sub-unified
997 // anyhow during generalization, but it helps with diagnostics (we can detect
998 // earlier that they are sub-unified).
1000 // Note that we can just skip the binders here because
1001 // type variables can't (at present, at
1002 // least) capture any of the things bound by this binder.
1004 // Note that this sub here is not just for diagnostics - it has semantic
1006 let r_a = self.shallow_resolve(predicate.skip_binder().a);
1007 let r_b = self.shallow_resolve(predicate.skip_binder().b);
1008 match (r_a.kind(), r_b.kind()) {
1009 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
1010 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
1011 return Err((a_vid, b_vid));
1016 Ok(self.commit_if_ok(|_snapshot| {
1017 let ty::SubtypePredicate { a_is_expected, a, b } =
1018 self.replace_bound_vars_with_placeholders(predicate);
1020 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1026 pub fn region_outlives_predicate(
1028 cause: &traits::ObligationCause<'tcx>,
1029 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1031 let ty::OutlivesPredicate(r_a, r_b) = self.replace_bound_vars_with_placeholders(predicate);
1033 SubregionOrigin::from_obligation_cause(cause, || RelateRegionParamBound(cause.span));
1034 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1037 /// Number of type variables created so far.
1038 pub fn num_ty_vars(&self) -> usize {
1039 self.inner.borrow_mut().type_variables().num_vars()
1042 pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1043 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1046 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1047 self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1050 pub fn next_ty_var_id_in_universe(
1052 origin: TypeVariableOrigin,
1053 universe: ty::UniverseIndex,
1055 self.inner.borrow_mut().type_variables().new_var(universe, origin)
1058 pub fn next_ty_var_in_universe(
1060 origin: TypeVariableOrigin,
1061 universe: ty::UniverseIndex,
1063 let vid = self.next_ty_var_id_in_universe(origin, universe);
1064 self.tcx.mk_ty_var(vid)
1067 pub fn next_const_var(&self, ty: Ty<'tcx>, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
1068 self.tcx.mk_const(self.next_const_var_id(origin), ty)
1071 pub fn next_const_var_in_universe(
1074 origin: ConstVariableOrigin,
1075 universe: ty::UniverseIndex,
1076 ) -> ty::Const<'tcx> {
1080 .const_unification_table()
1081 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1082 self.tcx.mk_const(vid, ty)
1085 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1086 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1088 val: ConstVariableValue::Unknown { universe: self.universe() },
1092 fn next_int_var_id(&self) -> IntVid {
1093 self.inner.borrow_mut().int_unification_table().new_key(None)
1096 pub fn next_int_var(&self) -> Ty<'tcx> {
1097 self.tcx.mk_int_var(self.next_int_var_id())
1100 fn next_float_var_id(&self) -> FloatVid {
1101 self.inner.borrow_mut().float_unification_table().new_key(None)
1104 pub fn next_float_var(&self) -> Ty<'tcx> {
1105 self.tcx.mk_float_var(self.next_float_var_id())
1108 /// Creates a fresh region variable with the next available index.
1109 /// The variable will be created in the maximum universe created
1110 /// thus far, allowing it to name any region created thus far.
1111 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1112 self.next_region_var_in_universe(origin, self.universe())
1115 /// Creates a fresh region variable with the next available index
1116 /// in the given universe; typically, you can use
1117 /// `next_region_var` and just use the maximal universe.
1118 pub fn next_region_var_in_universe(
1120 origin: RegionVariableOrigin,
1121 universe: ty::UniverseIndex,
1122 ) -> ty::Region<'tcx> {
1124 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1125 self.tcx.mk_region(ty::ReVar(region_var))
1128 /// Return the universe that the region `r` was created in. For
1129 /// most regions (e.g., `'static`, named regions from the user,
1130 /// etc) this is the root universe U0. For inference variables or
1131 /// placeholders, however, it will return the universe which they
1133 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1134 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1137 /// Number of region variables created so far.
1138 pub fn num_region_vars(&self) -> usize {
1139 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1142 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1143 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1144 self.next_region_var(RegionVariableOrigin::Nll(origin))
1147 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1148 pub fn next_nll_region_var_in_universe(
1150 origin: NllRegionVariableOrigin,
1151 universe: ty::UniverseIndex,
1152 ) -> ty::Region<'tcx> {
1153 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1156 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1158 GenericParamDefKind::Lifetime => {
1159 // Create a region inference variable for the given
1160 // region parameter definition.
1161 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1163 GenericParamDefKind::Type { .. } => {
1164 // Create a type inference variable for the given
1165 // type parameter definition. The substitutions are
1166 // for actual parameters that may be referred to by
1167 // the default of this type parameter, if it exists.
1168 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1169 // used in a path such as `Foo::<T, U>::new()` will
1170 // use an inference variable for `C` with `[T, U]`
1171 // as the substitutions for the default, `(T, U)`.
1172 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1174 TypeVariableOrigin {
1175 kind: TypeVariableOriginKind::TypeParameterDefinition(
1183 self.tcx.mk_ty_var(ty_var_id).into()
1185 GenericParamDefKind::Const { .. } => {
1186 let origin = ConstVariableOrigin {
1187 kind: ConstVariableOriginKind::ConstParameterDefinition(
1194 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1196 val: ConstVariableValue::Unknown { universe: self.universe() },
1198 self.tcx.mk_const(const_var_id, self.tcx.type_of(param.def_id)).into()
1203 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1204 /// type/region parameter to a fresh inference variable.
1205 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1206 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1209 /// Returns `true` if errors have been reported since this infcx was
1210 /// created. This is sometimes used as a heuristic to skip
1211 /// reporting errors that often occur as a result of earlier
1212 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1213 /// inference variables, regionck errors).
1214 #[must_use = "this method does not have any side effects"]
1215 pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1217 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1218 tainted_by_errors={})",
1219 self.tcx.sess.err_count(),
1220 self.err_count_on_creation,
1221 self.tainted_by_errors.get().is_some()
1224 if let Some(e) = self.tainted_by_errors.get() {
1228 if self.tcx.sess.err_count() > self.err_count_on_creation {
1229 // errors reported since this infcx was made
1230 let e = self.tcx.sess.has_errors().unwrap();
1231 self.set_tainted_by_errors(e);
1238 /// Set the "tainted by errors" flag to true. We call this when we
1239 /// observe an error from a prior pass.
1240 pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1241 debug!("set_tainted_by_errors(ErrorGuaranteed)");
1242 self.tainted_by_errors.set(Some(e));
1245 pub fn skip_region_resolution(&self) {
1246 let (var_infos, _) = {
1247 let mut inner = self.inner.borrow_mut();
1248 let inner = &mut *inner;
1249 // Note: `inner.region_obligations` may not be empty, because we
1250 // didn't necessarily call `process_registered_region_obligations`.
1251 // This is okay, because that doesn't introduce new vars.
1253 .region_constraint_storage
1255 .expect("regions already resolved")
1256 .with_log(&mut inner.undo_log)
1257 .into_infos_and_data()
1260 let lexical_region_resolutions = LexicalRegionResolutions {
1261 values: rustc_index::vec::IndexVec::from_elem_n(
1262 crate::infer::lexical_region_resolve::VarValue::Value(self.tcx.lifetimes.re_erased),
1267 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1268 assert!(old_value.is_none());
1271 /// Process the region constraints and return any errors that
1272 /// result. After this, no more unification operations should be
1273 /// done -- or the compiler will panic -- but it is legal to use
1274 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1275 pub fn resolve_regions(
1277 outlives_env: &OutlivesEnvironment<'tcx>,
1278 ) -> Vec<RegionResolutionError<'tcx>> {
1279 let (var_infos, data) = {
1280 let mut inner = self.inner.borrow_mut();
1281 let inner = &mut *inner;
1283 self.tainted_by_errors().is_some() || inner.region_obligations.is_empty(),
1284 "region_obligations not empty: {:#?}",
1285 inner.region_obligations
1288 .region_constraint_storage
1290 .expect("regions already resolved")
1291 .with_log(&mut inner.undo_log)
1292 .into_infos_and_data()
1295 let region_rels = &RegionRelations::new(self.tcx, outlives_env.free_region_map());
1297 let (lexical_region_resolutions, errors) =
1298 lexical_region_resolve::resolve(outlives_env.param_env, region_rels, var_infos, data);
1300 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1301 assert!(old_value.is_none());
1305 /// Obtains (and clears) the current set of region
1306 /// constraints. The inference context is still usable: further
1307 /// unifications will simply add new constraints.
1309 /// This method is not meant to be used with normal lexical region
1310 /// resolution. Rather, it is used in the NLL mode as a kind of
1311 /// interim hack: basically we run normal type-check and generate
1312 /// region constraints as normal, but then we take them and
1313 /// translate them into the form that the NLL solver
1314 /// understands. See the NLL module for mode details.
1315 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1317 self.inner.borrow().region_obligations.is_empty(),
1318 "region_obligations not empty: {:#?}",
1319 self.inner.borrow().region_obligations
1322 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1325 /// Gives temporary access to the region constraint data.
1326 pub fn with_region_constraints<R>(
1328 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1330 let mut inner = self.inner.borrow_mut();
1331 op(inner.unwrap_region_constraints().data())
1334 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1335 let mut inner = self.inner.borrow_mut();
1336 let inner = &mut *inner;
1338 .region_constraint_storage
1340 .expect("regions already resolved")
1341 .with_log(&mut inner.undo_log)
1345 /// Takes ownership of the list of variable regions. This implies
1346 /// that all the region constraints have already been taken, and
1347 /// hence that `resolve_regions_and_report_errors` can never be
1348 /// called. This is used only during NLL processing to "hand off" ownership
1349 /// of the set of region variables into the NLL region context.
1350 pub fn take_region_var_origins(&self) -> VarInfos {
1351 let mut inner = self.inner.borrow_mut();
1352 let (var_infos, data) = inner
1353 .region_constraint_storage
1355 .expect("regions already resolved")
1356 .with_log(&mut inner.undo_log)
1357 .into_infos_and_data();
1358 assert!(data.is_empty());
1362 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1363 self.resolve_vars_if_possible(t).to_string()
1366 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1367 /// universe index of `TyVar(vid)`.
1368 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1369 use self::type_variable::TypeVariableValue;
1371 match self.inner.borrow_mut().type_variables().probe(vid) {
1372 TypeVariableValue::Known { value } => Ok(value),
1373 TypeVariableValue::Unknown { universe } => Err(universe),
1377 /// Resolve any type variables found in `value` -- but only one
1378 /// level. So, if the variable `?X` is bound to some type
1379 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1380 /// itself be bound to a type).
1382 /// Useful when you only need to inspect the outermost level of
1383 /// the type and don't care about nested types (or perhaps you
1384 /// will be resolving them as well, e.g. in a loop).
1385 pub fn shallow_resolve<T>(&self, value: T) -> T
1387 T: TypeFoldable<'tcx>,
1389 value.fold_with(&mut ShallowResolver { infcx: self })
1392 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1393 self.inner.borrow_mut().type_variables().root_var(var)
1396 /// Where possible, replaces type/const variables in
1397 /// `value` with their final value. Note that region variables
1398 /// are unaffected. If a type/const variable has not been unified, it
1399 /// is left as is. This is an idempotent operation that does
1400 /// not affect inference state in any way and so you can do it
1402 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1404 T: TypeFoldable<'tcx>,
1406 if !value.needs_infer() {
1407 return value; // Avoid duplicated subst-folding.
1409 let mut r = resolve::OpportunisticVarResolver::new(self);
1410 value.fold_with(&mut r)
1413 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1415 T: TypeFoldable<'tcx>,
1417 if !value.needs_infer() {
1418 return value; // Avoid duplicated subst-folding.
1420 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1421 value.fold_with(&mut r)
1424 /// Returns the first unresolved type or const variable contained in `T`.
1425 pub fn first_unresolved_const_or_ty_var<T>(
1428 ) -> Option<(ty::Term<'tcx>, Option<Span>)>
1430 T: TypeVisitable<'tcx>,
1432 value.visit_with(&mut resolve::UnresolvedTypeOrConstFinder::new(self)).break_value()
1435 pub fn probe_const_var(
1437 vid: ty::ConstVid<'tcx>,
1438 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1439 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1440 ConstVariableValue::Known { value } => Ok(value),
1441 ConstVariableValue::Unknown { universe } => Err(universe),
1445 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1447 * Attempts to resolve all type/region/const variables in
1448 * `value`. Region inference must have been run already (e.g.,
1449 * by calling `resolve_regions_and_report_errors`). If some
1450 * variable was never unified, an `Err` results.
1452 * This method is idempotent, but it not typically not invoked
1453 * except during the writeback phase.
1456 let value = resolve::fully_resolve(self, value);
1458 value.as_ref().map_or(true, |value| !value.needs_infer()),
1459 "`{value:?}` is not fully resolved"
1464 pub fn replace_bound_vars_with_fresh_vars<T>(
1467 lbrct: LateBoundRegionConversionTime,
1468 value: ty::Binder<'tcx, T>,
1471 T: TypeFoldable<'tcx> + Copy,
1473 if let Some(inner) = value.no_bound_vars() {
1477 struct ToFreshVars<'a, 'tcx> {
1478 infcx: &'a InferCtxt<'tcx>,
1480 lbrct: LateBoundRegionConversionTime,
1481 map: FxHashMap<ty::BoundVar, ty::GenericArg<'tcx>>,
1484 impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'_, 'tcx> {
1485 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1488 .or_insert_with(|| {
1490 .next_region_var(LateBoundRegion(self.span, br.kind, self.lbrct))
1495 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1498 .or_insert_with(|| {
1500 .next_ty_var(TypeVariableOrigin {
1501 kind: TypeVariableOriginKind::MiscVariable,
1508 fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> {
1511 .or_insert_with(|| {
1515 ConstVariableOrigin {
1516 kind: ConstVariableOriginKind::MiscVariable,
1525 let delegate = ToFreshVars { infcx: self, span, lbrct, map: Default::default() };
1526 self.tcx.replace_bound_vars_uncached(value, delegate)
1529 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1530 pub fn verify_generic_bound(
1532 origin: SubregionOrigin<'tcx>,
1533 kind: GenericKind<'tcx>,
1534 a: ty::Region<'tcx>,
1535 bound: VerifyBound<'tcx>,
1537 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1541 .unwrap_region_constraints()
1542 .verify_generic_bound(origin, kind, a, bound);
1545 /// Obtains the latest type of the given closure; this may be a
1546 /// closure in the current function, in which case its
1547 /// `ClosureKind` may not yet be known.
1548 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1549 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1550 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1551 closure_kind_ty.to_opt_closure_kind()
1554 /// Clears the selection, evaluation, and projection caches. This is useful when
1555 /// repeatedly attempting to select an `Obligation` while changing only
1556 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1557 pub fn clear_caches(&self) {
1558 self.selection_cache.clear();
1559 self.evaluation_cache.clear();
1560 self.inner.borrow_mut().projection_cache().clear();
1563 pub fn universe(&self) -> ty::UniverseIndex {
1567 /// Creates and return a fresh universe that extends all previous
1568 /// universes. Updates `self.universe` to that new universe.
1569 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1570 let u = self.universe.get().next_universe();
1571 self.universe.set(u);
1575 pub fn try_const_eval_resolve(
1577 param_env: ty::ParamEnv<'tcx>,
1578 unevaluated: ty::UnevaluatedConst<'tcx>,
1581 ) -> Result<ty::Const<'tcx>, ErrorHandled> {
1582 match self.const_eval_resolve(param_env, unevaluated, span) {
1583 Ok(Some(val)) => Ok(self.tcx.mk_const(val, ty)),
1586 let def_id = unevaluated.def.did;
1588 tcx.def_span(def_id),
1589 "unable to construct a constant value for the unevaluated constant {:?}",
1593 Err(err) => Err(err),
1597 /// Resolves and evaluates a constant.
1599 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1600 /// substitutions and environment are used to resolve the constant. Alternatively if the
1601 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1602 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1603 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1604 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1607 /// This handles inferences variables within both `param_env` and `substs` by
1608 /// performing the operation on their respective canonical forms.
1609 #[instrument(skip(self), level = "debug")]
1610 pub fn const_eval_resolve(
1612 mut param_env: ty::ParamEnv<'tcx>,
1613 unevaluated: ty::UnevaluatedConst<'tcx>,
1615 ) -> EvalToValTreeResult<'tcx> {
1616 let mut substs = self.resolve_vars_if_possible(unevaluated.substs);
1619 // Postpone the evaluation of constants whose substs depend on inference
1622 if substs.has_non_region_infer() {
1623 if let Some(ct) = tcx.bound_abstract_const(unevaluated.def)? {
1624 let ct = tcx.expand_abstract_consts(ct.subst(tcx, substs));
1625 if let Err(e) = ct.error_reported() {
1626 return Err(ErrorHandled::Reported(e));
1627 } else if ct.has_non_region_infer() || ct.has_non_region_param() {
1628 return Err(ErrorHandled::TooGeneric);
1630 substs = replace_param_and_infer_substs_with_placeholder(tcx, substs);
1633 substs = InternalSubsts::identity_for_item(tcx, unevaluated.def.did);
1634 param_env = tcx.param_env(unevaluated.def.did);
1638 let param_env_erased = tcx.erase_regions(param_env);
1639 let substs_erased = tcx.erase_regions(substs);
1640 debug!(?param_env_erased);
1641 debug!(?substs_erased);
1643 let unevaluated = ty::UnevaluatedConst { def: unevaluated.def, substs: substs_erased };
1645 // The return value is the evaluated value which doesn't contain any reference to inference
1646 // variables, thus we don't need to substitute back the original values.
1647 tcx.const_eval_resolve_for_typeck(param_env_erased, unevaluated, span)
1650 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1651 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1652 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1654 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1655 /// inlined, despite being large, because it has only two call sites that
1656 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1657 /// inference variables), and it handles both `Ty` and `ty::Const` without
1658 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1660 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1662 TyOrConstInferVar::Ty(v) => {
1663 use self::type_variable::TypeVariableValue;
1665 // If `inlined_probe` returns a `Known` value, it never equals
1666 // `ty::Infer(ty::TyVar(v))`.
1667 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1668 TypeVariableValue::Unknown { .. } => false,
1669 TypeVariableValue::Known { .. } => true,
1673 TyOrConstInferVar::TyInt(v) => {
1674 // If `inlined_probe_value` returns a value it's always a
1675 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1677 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1680 TyOrConstInferVar::TyFloat(v) => {
1681 // If `probe_value` returns a value it's always a
1682 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1684 // Not `inlined_probe_value(v)` because this call site is colder.
1685 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1688 TyOrConstInferVar::Const(v) => {
1689 // If `probe_value` returns a `Known` value, it never equals
1690 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1692 // Not `inlined_probe_value(v)` because this call site is colder.
1693 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1694 ConstVariableValue::Unknown { .. } => false,
1695 ConstVariableValue::Known { .. } => true,
1702 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
1703 /// Process the region constraints and report any errors that
1704 /// result. After this, no more unification operations should be
1705 /// done -- or the compiler will panic -- but it is legal to use
1706 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1708 /// Make sure to call [`InferCtxt::process_registered_region_obligations`]
1709 /// first, or preferably use [`InferCtxt::check_region_obligations_and_report_errors`]
1710 /// to do both of these operations together.
1711 pub fn resolve_regions_and_report_errors(
1713 generic_param_scope: LocalDefId,
1714 outlives_env: &OutlivesEnvironment<'tcx>,
1716 let errors = self.resolve_regions(outlives_env);
1718 if let None = self.tainted_by_errors() {
1719 // As a heuristic, just skip reporting region errors
1720 // altogether if other errors have been reported while
1721 // this infcx was in use. This is totally hokey but
1722 // otherwise we have a hard time separating legit region
1723 // errors from silly ones.
1724 self.report_region_errors(generic_param_scope, &errors);
1728 // [Note-Type-error-reporting]
1729 // An invariant is that anytime the expected or actual type is Error (the special
1730 // error type, meaning that an error occurred when typechecking this expression),
1731 // this is a derived error. The error cascaded from another error (that was already
1732 // reported), so it's not useful to display it to the user.
1733 // The following methods implement this logic.
1734 // They check if either the actual or expected type is Error, and don't print the error
1735 // in this case. The typechecker should only ever report type errors involving mismatched
1736 // types using one of these methods, and should not call span_err directly for such
1739 pub fn type_error_struct_with_diag<M>(
1743 actual_ty: Ty<'tcx>,
1744 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>
1746 M: FnOnce(String) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1748 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1749 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1751 let mut err = mk_diag(self.ty_to_string(actual_ty));
1753 // Don't report an error if actual type is `Error`.
1754 if actual_ty.references_error() {
1755 err.downgrade_to_delayed_bug();
1761 pub fn report_mismatched_types(
1763 cause: &ObligationCause<'tcx>,
1766 err: TypeError<'tcx>,
1767 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1768 self.report_and_explain_type_error(TypeTrace::types(cause, true, expected, actual), err)
1771 pub fn report_mismatched_consts(
1773 cause: &ObligationCause<'tcx>,
1774 expected: ty::Const<'tcx>,
1775 actual: ty::Const<'tcx>,
1776 err: TypeError<'tcx>,
1777 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1778 self.report_and_explain_type_error(TypeTrace::consts(cause, true, expected, actual), err)
1782 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1783 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1784 #[derive(Copy, Clone, Debug)]
1785 pub enum TyOrConstInferVar<'tcx> {
1786 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1788 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1790 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1793 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1794 Const(ConstVid<'tcx>),
1797 impl<'tcx> TyOrConstInferVar<'tcx> {
1798 /// Tries to extract an inference variable from a type or a constant, returns `None`
1799 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1800 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1801 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1802 match arg.unpack() {
1803 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1804 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1805 GenericArgKind::Lifetime(_) => None,
1809 /// Tries to extract an inference variable from a type, returns `None`
1810 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1811 fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1813 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1814 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1815 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1820 /// Tries to extract an inference variable from a constant, returns `None`
1821 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1822 fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1824 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1830 /// Replace `{integer}` with `i32` and `{float}` with `f64`.
1831 /// Used only for diagnostics.
1832 struct InferenceLiteralEraser<'tcx> {
1836 impl<'tcx> TypeFolder<'tcx> for InferenceLiteralEraser<'tcx> {
1837 fn tcx(&self) -> TyCtxt<'tcx> {
1841 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1843 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1844 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1845 _ => ty.super_fold_with(self),
1850 struct ShallowResolver<'a, 'tcx> {
1851 infcx: &'a InferCtxt<'tcx>,
1854 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1855 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1859 /// If `ty` is a type variable of some kind, resolve it one level
1860 /// (but do not resolve types found in the result). If `typ` is
1861 /// not a type variable, just return it unmodified.
1862 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1864 ty::Infer(ty::TyVar(v)) => {
1865 // Not entirely obvious: if `typ` is a type variable,
1866 // it can be resolved to an int/float variable, which
1867 // can then be recursively resolved, hence the
1868 // recursion. Note though that we prevent type
1869 // variables from unifying to other type variables
1870 // directly (though they may be embedded
1871 // structurally), and we prevent cycles in any case,
1872 // so this recursion should always be of very limited
1875 // Note: if these two lines are combined into one we get
1876 // dynamic borrow errors on `self.inner`.
1877 let known = self.infcx.inner.borrow_mut().type_variables().probe(v).known();
1878 known.map_or(ty, |t| self.fold_ty(t))
1881 ty::Infer(ty::IntVar(v)) => self
1885 .int_unification_table()
1887 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1889 ty::Infer(ty::FloatVar(v)) => self
1893 .float_unification_table()
1895 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1901 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1902 if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
1906 .const_unification_table()
1917 impl<'tcx> TypeTrace<'tcx> {
1918 pub fn span(&self) -> Span {
1923 cause: &ObligationCause<'tcx>,
1924 a_is_expected: bool,
1927 ) -> TypeTrace<'tcx> {
1929 cause: cause.clone(),
1930 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1934 pub fn poly_trait_refs(
1935 cause: &ObligationCause<'tcx>,
1936 a_is_expected: bool,
1937 a: ty::PolyTraitRef<'tcx>,
1938 b: ty::PolyTraitRef<'tcx>,
1939 ) -> TypeTrace<'tcx> {
1941 cause: cause.clone(),
1942 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1947 cause: &ObligationCause<'tcx>,
1948 a_is_expected: bool,
1951 ) -> TypeTrace<'tcx> {
1953 cause: cause.clone(),
1954 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1959 impl<'tcx> SubregionOrigin<'tcx> {
1960 pub fn span(&self) -> Span {
1962 Subtype(ref a) => a.span(),
1963 RelateObjectBound(a) => a,
1964 RelateParamBound(a, ..) => a,
1965 RelateRegionParamBound(a) => a,
1967 ReborrowUpvar(a, _) => a,
1968 DataBorrowed(_, a) => a,
1969 ReferenceOutlivesReferent(_, a) => a,
1970 CompareImplItemObligation { span, .. } => span,
1971 AscribeUserTypeProvePredicate(span) => span,
1972 CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1976 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1978 F: FnOnce() -> Self,
1980 match *cause.code() {
1981 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1982 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1985 traits::ObligationCauseCode::CompareImplItemObligation {
1989 } => SubregionOrigin::CompareImplItemObligation {
1995 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1998 } => SubregionOrigin::CheckAssociatedTypeBounds {
2001 parent: Box::new(default()),
2004 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
2005 SubregionOrigin::AscribeUserTypeProvePredicate(span)
2013 impl RegionVariableOrigin {
2014 pub fn span(&self) -> Span {
2021 | EarlyBoundRegion(a, ..)
2022 | LateBoundRegion(a, ..)
2023 | UpvarRegion(_, a) => a,
2024 Nll(..) => bug!("NLL variable used with `span`"),
2029 /// Replaces substs that reference param or infer variables with suitable
2030 /// placeholders. This function is meant to remove these param and infer
2031 /// substs when they're not actually needed to evaluate a constant.
2032 fn replace_param_and_infer_substs_with_placeholder<'tcx>(
2034 substs: SubstsRef<'tcx>,
2035 ) -> SubstsRef<'tcx> {
2036 tcx.mk_substs(substs.iter().enumerate().map(|(idx, arg)| {
2037 match arg.unpack() {
2038 GenericArgKind::Type(_) if arg.has_non_region_param() || arg.has_non_region_infer() => {
2039 tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
2040 universe: ty::UniverseIndex::ROOT,
2041 name: ty::BoundVar::from_usize(idx),
2045 GenericArgKind::Const(ct) if ct.has_non_region_infer() || ct.has_non_region_param() => {
2047 // If the type references param or infer, replace that too...
2048 if ty.has_non_region_param() || ty.has_non_region_infer() {
2049 bug!("const `{ct}`'s type should not reference params or types");
2052 ty::PlaceholderConst {
2053 universe: ty::UniverseIndex::ROOT,
2054 name: ty::BoundVar::from_usize(idx),