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, InferTy, 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 /// During coherence we have to assume that other crates may add
337 /// additional impls which we currently don't know about.
339 /// To deal with this evaluation should be conservative
340 /// and consider the possibility of impls from outside this crate.
341 /// This comes up primarily when resolving ambiguity. Imagine
342 /// there is some trait reference `$0: Bar` where `$0` is an
343 /// inference variable. If `intercrate` is true, then we can never
344 /// say for sure that this reference is not implemented, even if
345 /// there are *no impls at all for `Bar`*, because `$0` could be
346 /// bound to some type that in a downstream crate that implements
349 /// Outside of coherence we set this to false because we are only
350 /// interested in types that the user could actually have written.
351 /// In other words, we consider `$0: Bar` to be unimplemented if
352 /// there is no type that the user could *actually name* that
353 /// would satisfy it. This avoids crippling inference, basically.
354 pub intercrate: bool,
357 /// See the `error_reporting` module for more details.
358 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
359 pub enum ValuePairs<'tcx> {
360 Regions(ExpectedFound<ty::Region<'tcx>>),
361 Terms(ExpectedFound<ty::Term<'tcx>>),
362 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
363 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
364 Sigs(ExpectedFound<ty::FnSig<'tcx>>),
367 impl<'tcx> ValuePairs<'tcx> {
368 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
369 if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
370 && let Some(expected) = expected.ty()
371 && let Some(found) = found.ty()
373 Some((expected, found))
380 /// The trace designates the path through inference that we took to
381 /// encounter an error or subtyping constraint.
383 /// See the `error_reporting` module for more details.
384 #[derive(Clone, Debug)]
385 pub struct TypeTrace<'tcx> {
386 pub cause: ObligationCause<'tcx>,
387 pub values: ValuePairs<'tcx>,
390 /// The origin of a `r1 <= r2` constraint.
392 /// See `error_reporting` module for more details
393 #[derive(Clone, Debug)]
394 pub enum SubregionOrigin<'tcx> {
395 /// Arose from a subtyping relation
396 Subtype(Box<TypeTrace<'tcx>>),
398 /// When casting `&'a T` to an `&'b Trait` object,
399 /// relating `'a` to `'b`
400 RelateObjectBound(Span),
402 /// Some type parameter was instantiated with the given type,
403 /// and that type must outlive some region.
404 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
406 /// The given region parameter was instantiated with a region
407 /// that must outlive some other region.
408 RelateRegionParamBound(Span),
410 /// Creating a pointer `b` to contents of another reference
413 /// (&'a &'b T) where a >= b
414 ReferenceOutlivesReferent(Ty<'tcx>, Span),
416 /// Comparing the signature and requirements of an impl method against
417 /// the containing trait.
418 CompareImplItemObligation {
420 impl_item_def_id: LocalDefId,
421 trait_item_def_id: DefId,
424 /// Checking that the bounds of a trait's associated type hold for a given impl
425 CheckAssociatedTypeBounds {
426 parent: Box<SubregionOrigin<'tcx>>,
427 impl_item_def_id: LocalDefId,
428 trait_item_def_id: DefId,
431 AscribeUserTypeProvePredicate(Span),
434 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
435 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
436 static_assert_size!(SubregionOrigin<'_>, 32);
438 impl<'tcx> SubregionOrigin<'tcx> {
439 pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
441 Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
442 Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
443 _ => ConstraintCategory::BoringNoLocation,
448 /// Times when we replace late-bound regions with variables:
449 #[derive(Clone, Copy, Debug)]
450 pub enum LateBoundRegionConversionTime {
451 /// when a fn is called
454 /// when two higher-ranked types are compared
457 /// when projecting an associated type
458 AssocTypeProjection(DefId),
461 /// Reasons to create a region inference variable
463 /// See `error_reporting` module for more details
464 #[derive(Copy, Clone, Debug)]
465 pub enum RegionVariableOrigin {
466 /// Region variables created for ill-categorized reasons,
467 /// mostly indicates places in need of refactoring
470 /// Regions created by a `&P` or `[...]` pattern
473 /// Regions created by `&` operator
476 /// Regions created as part of an autoref of a method receiver
479 /// Regions created as part of an automatic coercion
482 /// Region variables created as the values for early-bound regions
483 EarlyBoundRegion(Span, Symbol),
485 /// Region variables created for bound regions
486 /// in a function or method that is called
487 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
489 UpvarRegion(ty::UpvarId, Span),
491 /// This origin is used for the inference variables that we create
492 /// during NLL region processing.
493 Nll(NllRegionVariableOrigin),
496 #[derive(Copy, Clone, Debug)]
497 pub enum NllRegionVariableOrigin {
498 /// During NLL region processing, we create variables for free
499 /// regions that we encounter in the function signature and
500 /// elsewhere. This origin indices we've got one of those.
503 /// "Universal" instantiation of a higher-ranked region (e.g.,
504 /// from a `for<'a> T` binder). Meant to represent "any region".
505 Placeholder(ty::PlaceholderRegion),
508 /// If this is true, then this variable was created to represent a lifetime
509 /// bound in a `for` binder. For example, it might have been created to
510 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
511 /// Such variables are created when we are trying to figure out if there
512 /// is any valid instantiation of `'a` that could fit into some scenario.
514 /// This is used to inform error reporting: in the case that we are trying to
515 /// determine whether there is any valid instantiation of a `'a` variable that meets
516 /// some constraint C, we want to blame the "source" of that `for` type,
517 /// rather than blaming the source of the constraint C.
522 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
523 #[derive(Copy, Clone, Debug)]
524 pub enum FixupError<'tcx> {
525 UnresolvedIntTy(IntVid),
526 UnresolvedFloatTy(FloatVid),
528 UnresolvedConst(ConstVid<'tcx>),
531 /// See the `region_obligations` field for more information.
532 #[derive(Clone, Debug)]
533 pub struct RegionObligation<'tcx> {
534 pub sub_region: ty::Region<'tcx>,
535 pub sup_type: Ty<'tcx>,
536 pub origin: SubregionOrigin<'tcx>,
539 impl<'tcx> fmt::Display for FixupError<'tcx> {
540 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541 use self::FixupError::*;
544 UnresolvedIntTy(_) => write!(
546 "cannot determine the type of this integer; \
547 add a suffix to specify the type explicitly"
549 UnresolvedFloatTy(_) => write!(
551 "cannot determine the type of this number; \
552 add a suffix to specify the type explicitly"
554 UnresolvedTy(_) => write!(f, "unconstrained type"),
555 UnresolvedConst(_) => write!(f, "unconstrained const value"),
560 /// Used to configure inference contexts before their creation
561 pub struct InferCtxtBuilder<'tcx> {
563 defining_use_anchor: DefiningAnchor,
564 considering_regions: bool,
565 /// Whether we are in coherence mode.
569 pub trait TyCtxtInferExt<'tcx> {
570 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
573 impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
574 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
577 defining_use_anchor: DefiningAnchor::Error,
578 considering_regions: true,
584 impl<'tcx> InferCtxtBuilder<'tcx> {
585 /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
586 /// you need to call this function. Otherwise the opaque type will be treated opaquely.
588 /// It is only meant to be called in two places, for typeck
589 /// (via `Inherited::build`) and for the inference context used
591 pub fn with_opaque_type_inference(mut self, defining_use_anchor: DefiningAnchor) -> Self {
592 self.defining_use_anchor = defining_use_anchor;
596 pub fn intercrate(mut self) -> Self {
597 self.intercrate = true;
601 pub fn ignoring_regions(mut self) -> Self {
602 self.considering_regions = false;
606 /// Given a canonical value `C` as a starting point, create an
607 /// inference context that contains each of the bound values
608 /// within instantiated as a fresh variable. The `f` closure is
609 /// invoked with the new infcx, along with the instantiated value
610 /// `V` and a substitution `S`. This substitution `S` maps from
611 /// the bound values in `C` to their instantiated values in `V`
612 /// (in other words, `S(C) = V`).
613 pub fn build_with_canonical<T>(
616 canonical: &Canonical<'tcx, T>,
617 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
619 T: TypeFoldable<'tcx>,
621 let infcx = self.build();
622 let (value, subst) = infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
623 (infcx, value, subst)
626 pub fn build(&mut self) -> InferCtxt<'tcx> {
627 let InferCtxtBuilder { tcx, defining_use_anchor, considering_regions, intercrate } = *self;
632 inner: RefCell::new(InferCtxtInner::new()),
633 lexical_region_resolutions: RefCell::new(None),
634 selection_cache: Default::default(),
635 evaluation_cache: Default::default(),
636 reported_trait_errors: Default::default(),
637 reported_closure_mismatch: Default::default(),
638 tainted_by_errors: Cell::new(None),
639 err_count_on_creation: tcx.sess.err_count(),
640 in_snapshot: Cell::new(false),
641 skip_leak_check: Cell::new(false),
642 universe: Cell::new(ty::UniverseIndex::ROOT),
648 impl<'tcx, T> InferOk<'tcx, T> {
649 pub fn unit(self) -> InferOk<'tcx, ()> {
650 InferOk { value: (), obligations: self.obligations }
653 /// Extracts `value`, registering any obligations into `fulfill_cx`.
654 pub fn into_value_registering_obligations(
656 infcx: &InferCtxt<'tcx>,
657 fulfill_cx: &mut dyn TraitEngine<'tcx>,
659 let InferOk { value, obligations } = self;
660 fulfill_cx.register_predicate_obligations(infcx, obligations);
665 impl<'tcx> InferOk<'tcx, ()> {
666 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
671 #[must_use = "once you start a snapshot, you should always consume it"]
672 pub struct CombinedSnapshot<'tcx> {
673 undo_snapshot: Snapshot<'tcx>,
674 region_constraints_snapshot: RegionSnapshot,
675 universe: ty::UniverseIndex,
676 was_in_snapshot: bool,
679 impl<'tcx> InferCtxt<'tcx> {
680 /// Creates a `TypeErrCtxt` for emitting various inference errors.
681 /// During typeck, use `FnCtxt::err_ctxt` instead.
682 pub fn err_ctxt(&self) -> TypeErrCtxt<'_, 'tcx> {
685 typeck_results: None,
686 fallback_has_occurred: false,
687 normalize_fn_sig: Box::new(|fn_sig| fn_sig),
688 autoderef_steps: Box::new(|ty| {
689 debug_assert!(false, "shouldn't be using autoderef_steps outside of typeck");
695 pub fn is_in_snapshot(&self) -> bool {
696 self.in_snapshot.get()
699 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
700 t.fold_with(&mut self.freshener())
703 /// Returns the origin of the type variable identified by `vid`, or `None`
704 /// if this is not a type variable.
706 /// No attempt is made to resolve `ty`.
707 pub fn type_var_origin(&self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
709 ty::Infer(ty::TyVar(vid)) => {
710 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
716 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
717 freshen::TypeFreshener::new(self, false)
720 /// Like `freshener`, but does not replace `'static` regions.
721 pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
722 freshen::TypeFreshener::new(self, true)
725 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
726 let mut inner = self.inner.borrow_mut();
727 let mut vars: Vec<Ty<'_>> = inner
729 .unsolved_variables()
731 .map(|t| self.tcx.mk_ty_var(t))
734 (0..inner.int_unification_table().len())
735 .map(|i| ty::IntVid { index: i as u32 })
736 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
737 .map(|v| self.tcx.mk_int_var(v)),
740 (0..inner.float_unification_table().len())
741 .map(|i| ty::FloatVid { index: i as u32 })
742 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
743 .map(|v| self.tcx.mk_float_var(v)),
748 fn combine_fields<'a>(
750 trace: TypeTrace<'tcx>,
751 param_env: ty::ParamEnv<'tcx>,
752 define_opaque_types: bool,
753 ) -> CombineFields<'a, 'tcx> {
759 obligations: PredicateObligations::new(),
764 fn start_snapshot(&self) -> CombinedSnapshot<'tcx> {
765 debug!("start_snapshot()");
767 let in_snapshot = self.in_snapshot.replace(true);
769 let mut inner = self.inner.borrow_mut();
772 undo_snapshot: inner.undo_log.start_snapshot(),
773 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
774 universe: self.universe(),
775 was_in_snapshot: in_snapshot,
779 #[instrument(skip(self, snapshot), level = "debug")]
780 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'tcx>) {
781 let CombinedSnapshot {
783 region_constraints_snapshot,
788 self.in_snapshot.set(was_in_snapshot);
789 self.universe.set(universe);
791 let mut inner = self.inner.borrow_mut();
792 inner.rollback_to(undo_snapshot);
793 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
796 #[instrument(skip(self, snapshot), level = "debug")]
797 fn commit_from(&self, snapshot: CombinedSnapshot<'tcx>) {
798 let CombinedSnapshot {
800 region_constraints_snapshot: _,
805 self.in_snapshot.set(was_in_snapshot);
807 self.inner.borrow_mut().commit(undo_snapshot);
810 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
811 #[instrument(skip(self, f), level = "debug")]
812 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
814 F: FnOnce(&CombinedSnapshot<'tcx>) -> Result<T, E>,
816 let snapshot = self.start_snapshot();
817 let r = f(&snapshot);
818 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
821 self.commit_from(snapshot);
824 self.rollback_to("commit_if_ok -- error", snapshot);
830 /// Execute `f` then unroll any bindings it creates.
831 #[instrument(skip(self, f), level = "debug")]
832 pub fn probe<R, F>(&self, f: F) -> R
834 F: FnOnce(&CombinedSnapshot<'tcx>) -> R,
836 let snapshot = self.start_snapshot();
837 let r = f(&snapshot);
838 self.rollback_to("probe", snapshot);
842 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
843 #[instrument(skip(self, f), level = "debug")]
844 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
846 F: FnOnce(&CombinedSnapshot<'tcx>) -> R,
848 let snapshot = self.start_snapshot();
849 let was_skip_leak_check = self.skip_leak_check.get();
851 self.skip_leak_check.set(true);
853 let r = f(&snapshot);
854 self.rollback_to("probe", snapshot);
855 self.skip_leak_check.set(was_skip_leak_check);
859 /// Scan the constraints produced since `snapshot` began and returns:
861 /// - `None` -- if none of them involve "region outlives" constraints
862 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
863 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
864 pub fn region_constraints_added_in_snapshot(
866 snapshot: &CombinedSnapshot<'tcx>,
870 .unwrap_region_constraints()
871 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
874 pub fn opaque_types_added_in_snapshot(&self, snapshot: &CombinedSnapshot<'tcx>) -> bool {
875 self.inner.borrow().undo_log.opaque_types_in_snapshot(&snapshot.undo_snapshot)
878 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
879 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
882 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
884 T: at::ToTrace<'tcx>,
886 let origin = &ObligationCause::dummy();
888 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
889 // Ignore obligations, since we are unrolling
890 // everything anyway.
895 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
897 T: at::ToTrace<'tcx>,
899 let origin = &ObligationCause::dummy();
901 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
902 // Ignore obligations, since we are unrolling
903 // everything anyway.
908 #[instrument(skip(self), level = "debug")]
911 origin: SubregionOrigin<'tcx>,
915 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
918 /// Require that the region `r` be equal to one of the regions in
919 /// the set `regions`.
920 #[instrument(skip(self), level = "debug")]
921 pub fn member_constraint(
923 key: ty::OpaqueTypeKey<'tcx>,
924 definition_span: Span,
926 region: ty::Region<'tcx>,
927 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
929 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
938 /// Processes a `Coerce` predicate from the fulfillment context.
939 /// This is NOT the preferred way to handle coercion, which is to
940 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
942 /// This method here is actually a fallback that winds up being
943 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
944 /// and records a coercion predicate. Presently, this method is equivalent
945 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
946 /// actually requiring `a <: b`. This is of course a valid coercion,
947 /// but it's not as flexible as `FnCtxt::coerce` would be.
949 /// (We may refactor this in the future, but there are a number of
950 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
951 /// records adjustments that are required on the HIR in order to perform
952 /// the coercion, and we don't currently have a way to manage that.)
953 pub fn coerce_predicate(
955 cause: &ObligationCause<'tcx>,
956 param_env: ty::ParamEnv<'tcx>,
957 predicate: ty::PolyCoercePredicate<'tcx>,
958 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
959 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
960 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
964 self.subtype_predicate(cause, param_env, subtype_predicate)
967 pub fn subtype_predicate(
969 cause: &ObligationCause<'tcx>,
970 param_env: ty::ParamEnv<'tcx>,
971 predicate: ty::PolySubtypePredicate<'tcx>,
972 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
973 // Check for two unresolved inference variables, in which case we can
974 // make no progress. This is partly a micro-optimization, but it's
975 // also an opportunity to "sub-unify" the variables. This isn't
976 // *necessary* to prevent cycles, because they would eventually be sub-unified
977 // anyhow during generalization, but it helps with diagnostics (we can detect
978 // earlier that they are sub-unified).
980 // Note that we can just skip the binders here because
981 // type variables can't (at present, at
982 // least) capture any of the things bound by this binder.
984 // Note that this sub here is not just for diagnostics - it has semantic
986 let r_a = self.shallow_resolve(predicate.skip_binder().a);
987 let r_b = self.shallow_resolve(predicate.skip_binder().b);
988 match (r_a.kind(), r_b.kind()) {
989 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
990 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
991 return Err((a_vid, b_vid));
996 Ok(self.commit_if_ok(|_snapshot| {
997 let ty::SubtypePredicate { a_is_expected, a, b } =
998 self.replace_bound_vars_with_placeholders(predicate);
1000 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1006 pub fn region_outlives_predicate(
1008 cause: &traits::ObligationCause<'tcx>,
1009 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1011 let ty::OutlivesPredicate(r_a, r_b) = self.replace_bound_vars_with_placeholders(predicate);
1013 SubregionOrigin::from_obligation_cause(cause, || RelateRegionParamBound(cause.span));
1014 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1017 /// Number of type variables created so far.
1018 pub fn num_ty_vars(&self) -> usize {
1019 self.inner.borrow_mut().type_variables().num_vars()
1022 pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1023 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1026 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1027 self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1030 pub fn next_ty_var_id_in_universe(
1032 origin: TypeVariableOrigin,
1033 universe: ty::UniverseIndex,
1035 self.inner.borrow_mut().type_variables().new_var(universe, origin)
1038 pub fn next_ty_var_in_universe(
1040 origin: TypeVariableOrigin,
1041 universe: ty::UniverseIndex,
1043 let vid = self.next_ty_var_id_in_universe(origin, universe);
1044 self.tcx.mk_ty_var(vid)
1047 pub fn next_const_var(&self, ty: Ty<'tcx>, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
1048 self.tcx.mk_const(self.next_const_var_id(origin), ty)
1051 pub fn next_const_var_in_universe(
1054 origin: ConstVariableOrigin,
1055 universe: ty::UniverseIndex,
1056 ) -> ty::Const<'tcx> {
1060 .const_unification_table()
1061 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1062 self.tcx.mk_const(vid, ty)
1065 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1066 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1068 val: ConstVariableValue::Unknown { universe: self.universe() },
1072 fn next_int_var_id(&self) -> IntVid {
1073 self.inner.borrow_mut().int_unification_table().new_key(None)
1076 pub fn next_int_var(&self) -> Ty<'tcx> {
1077 self.tcx.mk_int_var(self.next_int_var_id())
1080 fn next_float_var_id(&self) -> FloatVid {
1081 self.inner.borrow_mut().float_unification_table().new_key(None)
1084 pub fn next_float_var(&self) -> Ty<'tcx> {
1085 self.tcx.mk_float_var(self.next_float_var_id())
1088 /// Creates a fresh region variable with the next available index.
1089 /// The variable will be created in the maximum universe created
1090 /// thus far, allowing it to name any region created thus far.
1091 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1092 self.next_region_var_in_universe(origin, self.universe())
1095 /// Creates a fresh region variable with the next available index
1096 /// in the given universe; typically, you can use
1097 /// `next_region_var` and just use the maximal universe.
1098 pub fn next_region_var_in_universe(
1100 origin: RegionVariableOrigin,
1101 universe: ty::UniverseIndex,
1102 ) -> ty::Region<'tcx> {
1104 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1105 self.tcx.mk_region(ty::ReVar(region_var))
1108 /// Return the universe that the region `r` was created in. For
1109 /// most regions (e.g., `'static`, named regions from the user,
1110 /// etc) this is the root universe U0. For inference variables or
1111 /// placeholders, however, it will return the universe which they
1113 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1114 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1117 /// Number of region variables created so far.
1118 pub fn num_region_vars(&self) -> usize {
1119 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1122 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1123 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1124 self.next_region_var(RegionVariableOrigin::Nll(origin))
1127 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1128 pub fn next_nll_region_var_in_universe(
1130 origin: NllRegionVariableOrigin,
1131 universe: ty::UniverseIndex,
1132 ) -> ty::Region<'tcx> {
1133 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1136 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1138 GenericParamDefKind::Lifetime => {
1139 // Create a region inference variable for the given
1140 // region parameter definition.
1141 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1143 GenericParamDefKind::Type { .. } => {
1144 // Create a type inference variable for the given
1145 // type parameter definition. The substitutions are
1146 // for actual parameters that may be referred to by
1147 // the default of this type parameter, if it exists.
1148 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1149 // used in a path such as `Foo::<T, U>::new()` will
1150 // use an inference variable for `C` with `[T, U]`
1151 // as the substitutions for the default, `(T, U)`.
1152 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1154 TypeVariableOrigin {
1155 kind: TypeVariableOriginKind::TypeParameterDefinition(
1163 self.tcx.mk_ty_var(ty_var_id).into()
1165 GenericParamDefKind::Const { .. } => {
1166 let origin = ConstVariableOrigin {
1167 kind: ConstVariableOriginKind::ConstParameterDefinition(
1174 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1176 val: ConstVariableValue::Unknown { universe: self.universe() },
1178 self.tcx.mk_const(const_var_id, self.tcx.type_of(param.def_id)).into()
1183 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1184 /// type/region parameter to a fresh inference variable.
1185 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1186 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1189 /// Returns `true` if errors have been reported since this infcx was
1190 /// created. This is sometimes used as a heuristic to skip
1191 /// reporting errors that often occur as a result of earlier
1192 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1193 /// inference variables, regionck errors).
1194 #[must_use = "this method does not have any side effects"]
1195 pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1197 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1198 tainted_by_errors={})",
1199 self.tcx.sess.err_count(),
1200 self.err_count_on_creation,
1201 self.tainted_by_errors.get().is_some()
1204 if let Some(e) = self.tainted_by_errors.get() {
1208 if self.tcx.sess.err_count() > self.err_count_on_creation {
1209 // errors reported since this infcx was made
1210 let e = self.tcx.sess.has_errors().unwrap();
1211 self.set_tainted_by_errors(e);
1218 /// Set the "tainted by errors" flag to true. We call this when we
1219 /// observe an error from a prior pass.
1220 pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1221 debug!("set_tainted_by_errors(ErrorGuaranteed)");
1222 self.tainted_by_errors.set(Some(e));
1225 pub fn skip_region_resolution(&self) {
1226 let (var_infos, _) = {
1227 let mut inner = self.inner.borrow_mut();
1228 let inner = &mut *inner;
1229 // Note: `inner.region_obligations` may not be empty, because we
1230 // didn't necessarily call `process_registered_region_obligations`.
1231 // This is okay, because that doesn't introduce new vars.
1233 .region_constraint_storage
1235 .expect("regions already resolved")
1236 .with_log(&mut inner.undo_log)
1237 .into_infos_and_data()
1240 let lexical_region_resolutions = LexicalRegionResolutions {
1241 values: rustc_index::vec::IndexVec::from_elem_n(
1242 crate::infer::lexical_region_resolve::VarValue::Value(self.tcx.lifetimes.re_erased),
1247 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1248 assert!(old_value.is_none());
1251 /// Process the region constraints and return any errors that
1252 /// result. After this, no more unification operations should be
1253 /// done -- or the compiler will panic -- but it is legal to use
1254 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1255 pub fn resolve_regions(
1257 outlives_env: &OutlivesEnvironment<'tcx>,
1258 ) -> Vec<RegionResolutionError<'tcx>> {
1259 let (var_infos, data) = {
1260 let mut inner = self.inner.borrow_mut();
1261 let inner = &mut *inner;
1263 self.tainted_by_errors().is_some() || inner.region_obligations.is_empty(),
1264 "region_obligations not empty: {:#?}",
1265 inner.region_obligations
1268 .region_constraint_storage
1270 .expect("regions already resolved")
1271 .with_log(&mut inner.undo_log)
1272 .into_infos_and_data()
1275 let region_rels = &RegionRelations::new(self.tcx, outlives_env.free_region_map());
1277 let (lexical_region_resolutions, errors) =
1278 lexical_region_resolve::resolve(outlives_env.param_env, region_rels, var_infos, data);
1280 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1281 assert!(old_value.is_none());
1285 /// Obtains (and clears) the current set of region
1286 /// constraints. The inference context is still usable: further
1287 /// unifications will simply add new constraints.
1289 /// This method is not meant to be used with normal lexical region
1290 /// resolution. Rather, it is used in the NLL mode as a kind of
1291 /// interim hack: basically we run normal type-check and generate
1292 /// region constraints as normal, but then we take them and
1293 /// translate them into the form that the NLL solver
1294 /// understands. See the NLL module for mode details.
1295 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1297 self.inner.borrow().region_obligations.is_empty(),
1298 "region_obligations not empty: {:#?}",
1299 self.inner.borrow().region_obligations
1302 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1305 /// Gives temporary access to the region constraint data.
1306 pub fn with_region_constraints<R>(
1308 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1310 let mut inner = self.inner.borrow_mut();
1311 op(inner.unwrap_region_constraints().data())
1314 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1315 let mut inner = self.inner.borrow_mut();
1316 let inner = &mut *inner;
1318 .region_constraint_storage
1320 .expect("regions already resolved")
1321 .with_log(&mut inner.undo_log)
1325 /// Takes ownership of the list of variable regions. This implies
1326 /// that all the region constraints have already been taken, and
1327 /// hence that `resolve_regions_and_report_errors` can never be
1328 /// called. This is used only during NLL processing to "hand off" ownership
1329 /// of the set of region variables into the NLL region context.
1330 pub fn take_region_var_origins(&self) -> VarInfos {
1331 let mut inner = self.inner.borrow_mut();
1332 let (var_infos, data) = inner
1333 .region_constraint_storage
1335 .expect("regions already resolved")
1336 .with_log(&mut inner.undo_log)
1337 .into_infos_and_data();
1338 assert!(data.is_empty());
1342 #[instrument(level = "debug", skip(self), ret)]
1343 pub fn take_opaque_types(&self) -> opaque_types::OpaqueTypeMap<'tcx> {
1344 debug_assert_ne!(self.defining_use_anchor, DefiningAnchor::Error);
1345 std::mem::take(&mut self.inner.borrow_mut().opaque_type_storage.opaque_types)
1348 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1349 self.resolve_vars_if_possible(t).to_string()
1352 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1353 /// universe index of `TyVar(vid)`.
1354 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1355 use self::type_variable::TypeVariableValue;
1357 match self.inner.borrow_mut().type_variables().probe(vid) {
1358 TypeVariableValue::Known { value } => Ok(value),
1359 TypeVariableValue::Unknown { universe } => Err(universe),
1363 /// Resolve any type variables found in `value` -- but only one
1364 /// level. So, if the variable `?X` is bound to some type
1365 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1366 /// itself be bound to a type).
1368 /// Useful when you only need to inspect the outermost level of
1369 /// the type and don't care about nested types (or perhaps you
1370 /// will be resolving them as well, e.g. in a loop).
1371 pub fn shallow_resolve<T>(&self, value: T) -> T
1373 T: TypeFoldable<'tcx>,
1375 value.fold_with(&mut ShallowResolver { infcx: self })
1378 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1379 self.inner.borrow_mut().type_variables().root_var(var)
1382 /// Where possible, replaces type/const variables in
1383 /// `value` with their final value. Note that region variables
1384 /// are unaffected. If a type/const variable has not been unified, it
1385 /// is left as is. This is an idempotent operation that does
1386 /// not affect inference state in any way and so you can do it
1388 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1390 T: TypeFoldable<'tcx>,
1392 if !value.has_non_region_infer() {
1395 let mut r = resolve::OpportunisticVarResolver::new(self);
1396 value.fold_with(&mut r)
1399 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1401 T: TypeFoldable<'tcx>,
1403 if !value.needs_infer() {
1404 return value; // Avoid duplicated subst-folding.
1406 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1407 value.fold_with(&mut r)
1410 /// Returns the first unresolved type or const variable contained in `T`.
1411 pub fn first_unresolved_const_or_ty_var<T>(
1414 ) -> Option<(ty::Term<'tcx>, Option<Span>)>
1416 T: TypeVisitable<'tcx>,
1418 value.visit_with(&mut resolve::UnresolvedTypeOrConstFinder::new(self)).break_value()
1421 pub fn probe_const_var(
1423 vid: ty::ConstVid<'tcx>,
1424 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1425 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1426 ConstVariableValue::Known { value } => Ok(value),
1427 ConstVariableValue::Unknown { universe } => Err(universe),
1431 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1433 * Attempts to resolve all type/region/const variables in
1434 * `value`. Region inference must have been run already (e.g.,
1435 * by calling `resolve_regions_and_report_errors`). If some
1436 * variable was never unified, an `Err` results.
1438 * This method is idempotent, but it not typically not invoked
1439 * except during the writeback phase.
1442 let value = resolve::fully_resolve(self, value);
1444 value.as_ref().map_or(true, |value| !value.needs_infer()),
1445 "`{value:?}` is not fully resolved"
1450 pub fn replace_bound_vars_with_fresh_vars<T>(
1453 lbrct: LateBoundRegionConversionTime,
1454 value: ty::Binder<'tcx, T>,
1457 T: TypeFoldable<'tcx> + Copy,
1459 if let Some(inner) = value.no_bound_vars() {
1463 struct ToFreshVars<'a, 'tcx> {
1464 infcx: &'a InferCtxt<'tcx>,
1466 lbrct: LateBoundRegionConversionTime,
1467 map: FxHashMap<ty::BoundVar, ty::GenericArg<'tcx>>,
1470 impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'_, 'tcx> {
1471 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1474 .or_insert_with(|| {
1476 .next_region_var(LateBoundRegion(self.span, br.kind, self.lbrct))
1481 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1484 .or_insert_with(|| {
1486 .next_ty_var(TypeVariableOrigin {
1487 kind: TypeVariableOriginKind::MiscVariable,
1494 fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> {
1497 .or_insert_with(|| {
1501 ConstVariableOrigin {
1502 kind: ConstVariableOriginKind::MiscVariable,
1511 let delegate = ToFreshVars { infcx: self, span, lbrct, map: Default::default() };
1512 self.tcx.replace_bound_vars_uncached(value, delegate)
1515 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1516 pub fn verify_generic_bound(
1518 origin: SubregionOrigin<'tcx>,
1519 kind: GenericKind<'tcx>,
1520 a: ty::Region<'tcx>,
1521 bound: VerifyBound<'tcx>,
1523 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1527 .unwrap_region_constraints()
1528 .verify_generic_bound(origin, kind, a, bound);
1531 /// Obtains the latest type of the given closure; this may be a
1532 /// closure in the current function, in which case its
1533 /// `ClosureKind` may not yet be known.
1534 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1535 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1536 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1537 closure_kind_ty.to_opt_closure_kind()
1540 /// Clears the selection, evaluation, and projection caches. This is useful when
1541 /// repeatedly attempting to select an `Obligation` while changing only
1542 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1543 pub fn clear_caches(&self) {
1544 self.selection_cache.clear();
1545 self.evaluation_cache.clear();
1546 self.inner.borrow_mut().projection_cache().clear();
1549 pub fn universe(&self) -> ty::UniverseIndex {
1553 /// Creates and return a fresh universe that extends all previous
1554 /// universes. Updates `self.universe` to that new universe.
1555 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1556 let u = self.universe.get().next_universe();
1557 self.universe.set(u);
1561 pub fn try_const_eval_resolve(
1563 param_env: ty::ParamEnv<'tcx>,
1564 unevaluated: ty::UnevaluatedConst<'tcx>,
1567 ) -> Result<ty::Const<'tcx>, ErrorHandled> {
1568 match self.const_eval_resolve(param_env, unevaluated, span) {
1569 Ok(Some(val)) => Ok(self.tcx.mk_const(val, ty)),
1572 let def_id = unevaluated.def.did;
1574 tcx.def_span(def_id),
1575 "unable to construct a constant value for the unevaluated constant {:?}",
1579 Err(err) => Err(err),
1583 /// Resolves and evaluates a constant.
1585 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1586 /// substitutions and environment are used to resolve the constant. Alternatively if the
1587 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1588 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1589 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1590 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1593 /// This handles inferences variables within both `param_env` and `substs` by
1594 /// performing the operation on their respective canonical forms.
1595 #[instrument(skip(self), level = "debug")]
1596 pub fn const_eval_resolve(
1598 mut param_env: ty::ParamEnv<'tcx>,
1599 unevaluated: ty::UnevaluatedConst<'tcx>,
1601 ) -> EvalToValTreeResult<'tcx> {
1602 let mut substs = self.resolve_vars_if_possible(unevaluated.substs);
1605 // Postpone the evaluation of constants whose substs depend on inference
1608 if substs.has_non_region_infer() {
1609 if let Some(ct) = tcx.bound_abstract_const(unevaluated.def)? {
1610 let ct = tcx.expand_abstract_consts(ct.subst(tcx, substs));
1611 if let Err(e) = ct.error_reported() {
1612 return Err(ErrorHandled::Reported(e));
1613 } else if ct.has_non_region_infer() || ct.has_non_region_param() {
1614 return Err(ErrorHandled::TooGeneric);
1616 substs = replace_param_and_infer_substs_with_placeholder(tcx, substs);
1619 substs = InternalSubsts::identity_for_item(tcx, unevaluated.def.did);
1620 param_env = tcx.param_env(unevaluated.def.did);
1624 let param_env_erased = tcx.erase_regions(param_env);
1625 let substs_erased = tcx.erase_regions(substs);
1626 debug!(?param_env_erased);
1627 debug!(?substs_erased);
1629 let unevaluated = ty::UnevaluatedConst { def: unevaluated.def, substs: substs_erased };
1631 // The return value is the evaluated value which doesn't contain any reference to inference
1632 // variables, thus we don't need to substitute back the original values.
1633 tcx.const_eval_resolve_for_typeck(param_env_erased, unevaluated, span)
1636 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1637 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1638 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1640 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1641 /// inlined, despite being large, because it has only two call sites that
1642 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1643 /// inference variables), and it handles both `Ty` and `ty::Const` without
1644 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1646 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1648 TyOrConstInferVar::Ty(v) => {
1649 use self::type_variable::TypeVariableValue;
1651 // If `inlined_probe` returns a `Known` value, it never equals
1652 // `ty::Infer(ty::TyVar(v))`.
1653 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1654 TypeVariableValue::Unknown { .. } => false,
1655 TypeVariableValue::Known { .. } => true,
1659 TyOrConstInferVar::TyInt(v) => {
1660 // If `inlined_probe_value` returns a value it's always a
1661 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1663 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1666 TyOrConstInferVar::TyFloat(v) => {
1667 // If `probe_value` returns a value it's always a
1668 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1670 // Not `inlined_probe_value(v)` because this call site is colder.
1671 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1674 TyOrConstInferVar::Const(v) => {
1675 // If `probe_value` returns a `Known` value, it never equals
1676 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1678 // Not `inlined_probe_value(v)` because this call site is colder.
1679 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1680 ConstVariableValue::Unknown { .. } => false,
1681 ConstVariableValue::Known { .. } => true,
1688 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
1689 /// Processes registered region obliations and resolves regions, reporting
1690 /// any errors if any were raised. Prefer using this function over manually
1691 /// calling `resolve_regions_and_report_errors`.
1692 pub fn check_region_obligations_and_report_errors(
1694 generic_param_scope: LocalDefId,
1695 outlives_env: &OutlivesEnvironment<'tcx>,
1696 ) -> Result<(), ErrorGuaranteed> {
1697 self.process_registered_region_obligations(
1698 outlives_env.region_bound_pairs(),
1699 outlives_env.param_env,
1702 self.resolve_regions_and_report_errors(generic_param_scope, outlives_env)
1705 /// Process the region constraints and report any errors that
1706 /// result. After this, no more unification operations should be
1707 /// done -- or the compiler will panic -- but it is legal to use
1708 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1710 /// Make sure to call [`InferCtxt::process_registered_region_obligations`]
1711 /// first, or preferably use [`TypeErrCtxt::check_region_obligations_and_report_errors`]
1712 /// to do both of these operations together.
1713 pub fn resolve_regions_and_report_errors(
1715 generic_param_scope: LocalDefId,
1716 outlives_env: &OutlivesEnvironment<'tcx>,
1717 ) -> Result<(), ErrorGuaranteed> {
1718 let errors = self.resolve_regions(outlives_env);
1720 if let None = self.tainted_by_errors() {
1721 // As a heuristic, just skip reporting region errors
1722 // altogether if other errors have been reported while
1723 // this infcx was in use. This is totally hokey but
1724 // otherwise we have a hard time separating legit region
1725 // errors from silly ones.
1726 self.report_region_errors(generic_param_scope, &errors);
1729 if errors.is_empty() {
1735 .delay_span_bug(rustc_span::DUMMY_SP, "error should have been emitted"))
1739 // [Note-Type-error-reporting]
1740 // An invariant is that anytime the expected or actual type is Error (the special
1741 // error type, meaning that an error occurred when typechecking this expression),
1742 // this is a derived error. The error cascaded from another error (that was already
1743 // reported), so it's not useful to display it to the user.
1744 // The following methods implement this logic.
1745 // They check if either the actual or expected type is Error, and don't print the error
1746 // in this case. The typechecker should only ever report type errors involving mismatched
1747 // types using one of these methods, and should not call span_err directly for such
1750 pub fn type_error_struct_with_diag<M>(
1754 actual_ty: Ty<'tcx>,
1755 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>
1757 M: FnOnce(String) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1759 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1760 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1762 let mut err = mk_diag(self.ty_to_string(actual_ty));
1764 // Don't report an error if actual type is `Error`.
1765 if actual_ty.references_error() {
1766 err.downgrade_to_delayed_bug();
1772 pub fn report_mismatched_types(
1774 cause: &ObligationCause<'tcx>,
1777 err: TypeError<'tcx>,
1778 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1779 self.report_and_explain_type_error(TypeTrace::types(cause, true, expected, actual), err)
1782 pub fn report_mismatched_consts(
1784 cause: &ObligationCause<'tcx>,
1785 expected: ty::Const<'tcx>,
1786 actual: ty::Const<'tcx>,
1787 err: TypeError<'tcx>,
1788 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1789 self.report_and_explain_type_error(TypeTrace::consts(cause, true, expected, actual), err)
1793 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1794 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1795 #[derive(Copy, Clone, Debug)]
1796 pub enum TyOrConstInferVar<'tcx> {
1797 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1799 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1801 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1804 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1805 Const(ConstVid<'tcx>),
1808 impl<'tcx> TyOrConstInferVar<'tcx> {
1809 /// Tries to extract an inference variable from a type or a constant, returns `None`
1810 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1811 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1812 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1813 match arg.unpack() {
1814 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1815 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1816 GenericArgKind::Lifetime(_) => None,
1820 /// Tries to extract an inference variable from a type, returns `None`
1821 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1822 fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1824 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1825 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1826 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1831 /// Tries to extract an inference variable from a constant, returns `None`
1832 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1833 fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1835 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1841 /// Replace `{integer}` with `i32` and `{float}` with `f64`.
1842 /// Used only for diagnostics.
1843 struct InferenceLiteralEraser<'tcx> {
1847 impl<'tcx> TypeFolder<'tcx> for InferenceLiteralEraser<'tcx> {
1848 fn tcx(&self) -> TyCtxt<'tcx> {
1852 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1854 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1855 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1856 _ => ty.super_fold_with(self),
1861 struct ShallowResolver<'a, 'tcx> {
1862 infcx: &'a InferCtxt<'tcx>,
1865 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1866 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1870 /// If `ty` is a type variable of some kind, resolve it one level
1871 /// (but do not resolve types found in the result). If `typ` is
1872 /// not a type variable, just return it unmodified.
1874 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1875 if let ty::Infer(v) = ty.kind() { self.fold_infer_ty(*v).unwrap_or(ty) } else { ty }
1878 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1879 if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
1883 .const_unification_table()
1894 impl<'a, 'tcx> ShallowResolver<'a, 'tcx> {
1895 // This is separate from `fold_ty` to keep that method small and inlinable.
1897 fn fold_infer_ty(&mut self, v: InferTy) -> Option<Ty<'tcx>> {
1900 // Not entirely obvious: if `typ` is a type variable,
1901 // it can be resolved to an int/float variable, which
1902 // can then be recursively resolved, hence the
1903 // recursion. Note though that we prevent type
1904 // variables from unifying to other type variables
1905 // directly (though they may be embedded
1906 // structurally), and we prevent cycles in any case,
1907 // so this recursion should always be of very limited
1910 // Note: if these two lines are combined into one we get
1911 // dynamic borrow errors on `self.inner`.
1912 let known = self.infcx.inner.borrow_mut().type_variables().probe(v).known();
1913 known.map(|t| self.fold_ty(t))
1916 ty::IntVar(v) => self
1920 .int_unification_table()
1922 .map(|v| v.to_type(self.infcx.tcx)),
1924 ty::FloatVar(v) => self
1928 .float_unification_table()
1930 .map(|v| v.to_type(self.infcx.tcx)),
1932 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => None,
1937 impl<'tcx> TypeTrace<'tcx> {
1938 pub fn span(&self) -> Span {
1943 cause: &ObligationCause<'tcx>,
1944 a_is_expected: bool,
1947 ) -> TypeTrace<'tcx> {
1949 cause: cause.clone(),
1950 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1954 pub fn poly_trait_refs(
1955 cause: &ObligationCause<'tcx>,
1956 a_is_expected: bool,
1957 a: ty::PolyTraitRef<'tcx>,
1958 b: ty::PolyTraitRef<'tcx>,
1959 ) -> TypeTrace<'tcx> {
1961 cause: cause.clone(),
1962 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b)),
1967 cause: &ObligationCause<'tcx>,
1968 a_is_expected: bool,
1971 ) -> TypeTrace<'tcx> {
1973 cause: cause.clone(),
1974 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1979 impl<'tcx> SubregionOrigin<'tcx> {
1980 pub fn span(&self) -> Span {
1982 Subtype(ref a) => a.span(),
1983 RelateObjectBound(a) => a,
1984 RelateParamBound(a, ..) => a,
1985 RelateRegionParamBound(a) => a,
1987 ReferenceOutlivesReferent(_, a) => a,
1988 CompareImplItemObligation { span, .. } => span,
1989 AscribeUserTypeProvePredicate(span) => span,
1990 CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1994 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1996 F: FnOnce() -> Self,
1998 match *cause.code() {
1999 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
2000 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
2003 traits::ObligationCauseCode::CompareImplItemObligation {
2007 } => SubregionOrigin::CompareImplItemObligation {
2013 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
2016 } => SubregionOrigin::CheckAssociatedTypeBounds {
2019 parent: Box::new(default()),
2022 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
2023 SubregionOrigin::AscribeUserTypeProvePredicate(span)
2031 impl RegionVariableOrigin {
2032 pub fn span(&self) -> Span {
2039 | EarlyBoundRegion(a, ..)
2040 | LateBoundRegion(a, ..)
2041 | UpvarRegion(_, a) => a,
2042 Nll(..) => bug!("NLL variable used with `span`"),
2047 /// Replaces substs that reference param or infer variables with suitable
2048 /// placeholders. This function is meant to remove these param and infer
2049 /// substs when they're not actually needed to evaluate a constant.
2050 fn replace_param_and_infer_substs_with_placeholder<'tcx>(
2052 substs: SubstsRef<'tcx>,
2053 ) -> SubstsRef<'tcx> {
2054 struct ReplaceParamAndInferWithPlaceholder<'tcx> {
2059 impl<'tcx> TypeFolder<'tcx> for ReplaceParamAndInferWithPlaceholder<'tcx> {
2060 fn tcx(&self) -> TyCtxt<'tcx> {
2064 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2065 if let ty::Infer(_) = t.kind() {
2066 self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
2067 universe: ty::UniverseIndex::ROOT,
2068 name: ty::BoundTyKind::Anon({
2075 t.super_fold_with(self)
2079 fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
2080 if let ty::ConstKind::Infer(_) = c.kind() {
2082 // If the type references param or infer then ICE ICE ICE
2083 if ty.has_non_region_param() || ty.has_non_region_infer() {
2084 bug!("const `{c}`'s type should not reference params or types");
2087 ty::PlaceholderConst {
2088 universe: ty::UniverseIndex::ROOT,
2089 name: ty::BoundVar::from_u32({
2098 c.super_fold_with(self)
2103 substs.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: 0 })