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};
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_data_structures::sync::Lrc;
15 use rustc_data_structures::undo_log::Rollback;
16 use rustc_data_structures::unify as ut;
17 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, EvalToConstValueResult};
24 use rustc_middle::traits::select;
25 use rustc_middle::ty::error::{ExpectedFound, TypeError};
26 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
27 use rustc_middle::ty::relate::RelateResult;
28 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
29 pub use rustc_middle::ty::IntVarValue;
30 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
31 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
32 use rustc_span::symbol::Symbol;
35 use std::cell::{Cell, Ref, RefCell};
38 use self::combine::CombineFields;
39 use self::free_regions::RegionRelations;
40 use self::lexical_region_resolve::LexicalRegionResolutions;
41 use self::outlives::env::OutlivesEnvironment;
42 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
43 use self::region_constraints::{
44 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
46 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
52 pub mod error_reporting;
59 mod lexical_region_resolve;
65 pub mod region_constraints;
68 pub mod type_variable;
73 pub struct InferOk<'tcx, T> {
75 pub obligations: PredicateObligations<'tcx>,
77 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
79 pub type Bound<T> = Option<T>;
80 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
81 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
83 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
84 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
87 /// This type contains all the things within `InferCtxt` that sit within a
88 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
89 /// operations are hot enough that we want only one call to `borrow_mut` per
90 /// call to `start_snapshot` and `rollback_to`.
92 pub struct InferCtxtInner<'tcx> {
93 /// Cache for projections. This cache is snapshotted along with the infcx.
95 /// Public so that `traits::project` can use it.
96 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
98 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
99 /// that might instantiate a general type variable have an order,
100 /// represented by its upper and lower bounds.
101 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
103 /// Map from const parameter variable to the kind of const it represents.
104 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
106 /// Map from integral variable to the kind of integer it represents.
107 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
109 /// Map from floating variable to the kind of float it represents.
110 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
112 /// Tracks the set of region variables and the constraints between them.
113 /// This is initially `Some(_)` but when
114 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
115 /// -- further attempts to perform unification, etc., may fail if new
116 /// region constraints would've been added.
117 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
119 /// A set of constraints that regionck must validate. Each
120 /// constraint has the form `T:'a`, meaning "some type `T` must
121 /// outlive the lifetime 'a". These constraints derive from
122 /// instantiated type parameters. So if you had a struct defined
124 /// ```ignore (illustrative)
125 /// struct Foo<T:'static> { ... }
127 /// then in some expression `let x = Foo { ... }` it will
128 /// instantiate the type parameter `T` with a fresh type `$0`. At
129 /// the same time, it will record a region obligation of
130 /// `$0:'static`. This will get checked later by regionck. (We
131 /// can't generally check these things right away because we have
132 /// to wait until types are resolved.)
134 /// These are stored in a map keyed to the id of the innermost
135 /// enclosing fn body / static initializer expression. This is
136 /// because the location where the obligation was incurred can be
137 /// relevant with respect to which sublifetime assumptions are in
138 /// place. The reason that we store under the fn-id, and not
139 /// something more fine-grained, is so that it is easier for
140 /// regionck to be sure that it has found *all* the region
141 /// obligations (otherwise, it's easy to fail to walk to a
142 /// particular node-id).
144 /// Before running `resolve_regions_and_report_errors`, the creator
145 /// of the inference context is expected to invoke
146 /// [`InferCtxt::process_registered_region_obligations`]
147 /// for each body-id in this map, which will process the
148 /// obligations within. This is expected to be done 'late enough'
149 /// that all type inference variables have been bound and so forth.
150 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
152 undo_log: InferCtxtUndoLogs<'tcx>,
154 /// Caches for opaque type inference.
155 pub opaque_type_storage: OpaqueTypeStorage<'tcx>,
158 impl<'tcx> InferCtxtInner<'tcx> {
159 fn new() -> InferCtxtInner<'tcx> {
161 projection_cache: Default::default(),
162 type_variable_storage: type_variable::TypeVariableStorage::new(),
163 undo_log: InferCtxtUndoLogs::default(),
164 const_unification_storage: ut::UnificationTableStorage::new(),
165 int_unification_storage: ut::UnificationTableStorage::new(),
166 float_unification_storage: ut::UnificationTableStorage::new(),
167 region_constraint_storage: Some(RegionConstraintStorage::new()),
168 region_obligations: vec![],
169 opaque_type_storage: Default::default(),
174 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
175 &self.region_obligations
179 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
180 self.projection_cache.with_log(&mut self.undo_log)
184 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
185 self.type_variable_storage.with_log(&mut self.undo_log)
189 pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
190 self.opaque_type_storage.with_log(&mut self.undo_log)
194 fn int_unification_table(
196 ) -> ut::UnificationTable<
199 &mut ut::UnificationStorage<ty::IntVid>,
200 &mut InferCtxtUndoLogs<'tcx>,
203 self.int_unification_storage.with_log(&mut self.undo_log)
207 fn float_unification_table(
209 ) -> ut::UnificationTable<
212 &mut ut::UnificationStorage<ty::FloatVid>,
213 &mut InferCtxtUndoLogs<'tcx>,
216 self.float_unification_storage.with_log(&mut self.undo_log)
220 fn const_unification_table(
222 ) -> ut::UnificationTable<
225 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
226 &mut InferCtxtUndoLogs<'tcx>,
229 self.const_unification_storage.with_log(&mut self.undo_log)
233 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
234 self.region_constraint_storage
236 .expect("region constraints already solved")
237 .with_log(&mut self.undo_log)
241 pub struct InferCtxt<'a, 'tcx> {
242 pub tcx: TyCtxt<'tcx>,
244 /// The `DefId` of the item in whose context we are performing inference or typeck.
245 /// It is used to check whether an opaque type use is a defining use.
247 /// If it is `None`, we can't resolve opaque types here and need to bubble up
248 /// the obligation. This frequently happens for
249 /// short lived InferCtxt within queries. The opaque type obligations are forwarded
250 /// to the outside until the end up in an `InferCtxt` for typeck or borrowck.
251 pub defining_use_anchor: Option<LocalDefId>,
253 /// During type-checking/inference of a body, `in_progress_typeck_results`
254 /// contains a reference to the typeck results being built up, which are
255 /// used for reading closure kinds/signatures as they are inferred,
256 /// and for error reporting logic to read arbitrary node types.
257 pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
259 pub inner: RefCell<InferCtxtInner<'tcx>>,
261 /// If set, this flag causes us to skip the 'leak check' during
262 /// higher-ranked subtyping operations. This flag is a temporary one used
263 /// to manage the removal of the leak-check: for the time being, we still run the
264 /// leak-check, but we issue warnings. This flag can only be set to true
265 /// when entering a snapshot.
266 skip_leak_check: Cell<bool>,
268 /// Once region inference is done, the values for each variable.
269 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
271 /// Caches the results of trait selection. This cache is used
272 /// for things that have to do with the parameters in scope.
273 pub selection_cache: select::SelectionCache<'tcx>,
275 /// Caches the results of trait evaluation.
276 pub evaluation_cache: select::EvaluationCache<'tcx>,
278 /// the set of predicates on which errors have been reported, to
279 /// avoid reporting the same error twice.
280 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
282 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
284 /// When an error occurs, we want to avoid reporting "derived"
285 /// errors that are due to this original failure. Normally, we
286 /// handle this with the `err_count_on_creation` count, which
287 /// basically just tracks how many errors were reported when we
288 /// started type-checking a fn and checks to see if any new errors
289 /// have been reported since then. Not great, but it works.
291 /// However, when errors originated in other passes -- notably
292 /// resolve -- this heuristic breaks down. Therefore, we have this
293 /// auxiliary flag that one can set whenever one creates a
294 /// type-error that is due to an error in a prior pass.
296 /// Don't read this flag directly, call `is_tainted_by_errors()`
297 /// and `set_tainted_by_errors()`.
298 tainted_by_errors_flag: Cell<bool>,
300 /// Track how many errors were reported when this infcx is created.
301 /// If the number of errors increases, that's also a sign (line
302 /// `tainted_by_errors`) to avoid reporting certain kinds of errors.
303 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
304 err_count_on_creation: usize,
306 /// This flag is true while there is an active snapshot.
307 in_snapshot: Cell<bool>,
309 /// What is the innermost universe we have created? Starts out as
310 /// `UniverseIndex::root()` but grows from there as we enter
311 /// universal quantifiers.
313 /// N.B., at present, we exclude the universal quantifiers on the
314 /// item we are type-checking, and just consider those names as
315 /// part of the root universe. So this would only get incremented
316 /// when we enter into a higher-ranked (`for<..>`) type or trait
318 universe: Cell<ty::UniverseIndex>,
321 /// See the `error_reporting` module for more details.
322 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
323 pub enum ValuePairs<'tcx> {
324 Regions(ExpectedFound<ty::Region<'tcx>>),
325 Terms(ExpectedFound<ty::Term<'tcx>>),
326 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
327 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
330 impl<'tcx> ValuePairs<'tcx> {
331 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
332 if let ValuePairs::Terms(ExpectedFound {
333 expected: ty::Term::Ty(expected),
334 found: ty::Term::Ty(found),
337 Some((*expected, *found))
344 /// The trace designates the path through inference that we took to
345 /// encounter an error or subtyping constraint.
347 /// See the `error_reporting` module for more details.
348 #[derive(Clone, Debug)]
349 pub struct TypeTrace<'tcx> {
350 pub cause: ObligationCause<'tcx>,
351 pub values: ValuePairs<'tcx>,
354 /// The origin of a `r1 <= r2` constraint.
356 /// See `error_reporting` module for more details
357 #[derive(Clone, Debug)]
358 pub enum SubregionOrigin<'tcx> {
359 /// Arose from a subtyping relation
360 Subtype(Box<TypeTrace<'tcx>>),
362 /// When casting `&'a T` to an `&'b Trait` object,
363 /// relating `'a` to `'b`
364 RelateObjectBound(Span),
366 /// Some type parameter was instantiated with the given type,
367 /// and that type must outlive some region.
368 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
370 /// The given region parameter was instantiated with a region
371 /// that must outlive some other region.
372 RelateRegionParamBound(Span),
374 /// Creating a pointer `b` to contents of another reference
377 /// Creating a pointer `b` to contents of an upvar
378 ReborrowUpvar(Span, ty::UpvarId),
380 /// Data with type `Ty<'tcx>` was borrowed
381 DataBorrowed(Ty<'tcx>, Span),
383 /// (&'a &'b T) where a >= b
384 ReferenceOutlivesReferent(Ty<'tcx>, Span),
386 /// Comparing the signature and requirements of an impl method against
387 /// the containing trait.
388 CompareImplMethodObligation {
390 impl_item_def_id: LocalDefId,
391 trait_item_def_id: DefId,
394 /// Comparing the signature and requirements of an impl associated type
395 /// against the containing trait
396 CompareImplTypeObligation { span: Span, impl_item_def_id: LocalDefId, trait_item_def_id: DefId },
398 /// Checking that the bounds of a trait's associated type hold for a given impl
399 CheckAssociatedTypeBounds {
400 parent: Box<SubregionOrigin<'tcx>>,
401 impl_item_def_id: LocalDefId,
402 trait_item_def_id: DefId,
406 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
407 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
408 static_assert_size!(SubregionOrigin<'_>, 32);
410 /// Times when we replace late-bound regions with variables:
411 #[derive(Clone, Copy, Debug)]
412 pub enum LateBoundRegionConversionTime {
413 /// when a fn is called
416 /// when two higher-ranked types are compared
419 /// when projecting an associated type
420 AssocTypeProjection(DefId),
423 /// Reasons to create a region inference variable
425 /// See `error_reporting` module for more details
426 #[derive(Copy, Clone, Debug)]
427 pub enum RegionVariableOrigin {
428 /// Region variables created for ill-categorized reasons,
429 /// mostly indicates places in need of refactoring
432 /// Regions created by a `&P` or `[...]` pattern
435 /// Regions created by `&` operator
438 /// Regions created as part of an autoref of a method receiver
441 /// Regions created as part of an automatic coercion
444 /// Region variables created as the values for early-bound regions
445 EarlyBoundRegion(Span, Symbol),
447 /// Region variables created for bound regions
448 /// in a function or method that is called
449 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
451 UpvarRegion(ty::UpvarId, Span),
453 /// This origin is used for the inference variables that we create
454 /// during NLL region processing.
455 Nll(NllRegionVariableOrigin),
458 #[derive(Copy, Clone, Debug)]
459 pub enum NllRegionVariableOrigin {
460 /// During NLL region processing, we create variables for free
461 /// regions that we encounter in the function signature and
462 /// elsewhere. This origin indices we've got one of those.
465 /// "Universal" instantiation of a higher-ranked region (e.g.,
466 /// from a `for<'a> T` binder). Meant to represent "any region".
467 Placeholder(ty::PlaceholderRegion),
469 /// The variable we create to represent `'empty(U0)`.
473 /// If this is true, then this variable was created to represent a lifetime
474 /// bound in a `for` binder. For example, it might have been created to
475 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
476 /// Such variables are created when we are trying to figure out if there
477 /// is any valid instantiation of `'a` that could fit into some scenario.
479 /// This is used to inform error reporting: in the case that we are trying to
480 /// determine whether there is any valid instantiation of a `'a` variable that meets
481 /// some constraint C, we want to blame the "source" of that `for` type,
482 /// rather than blaming the source of the constraint C.
487 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
488 #[derive(Copy, Clone, Debug)]
489 pub enum FixupError<'tcx> {
490 UnresolvedIntTy(IntVid),
491 UnresolvedFloatTy(FloatVid),
493 UnresolvedConst(ConstVid<'tcx>),
496 /// See the `region_obligations` field for more information.
498 pub struct RegionObligation<'tcx> {
499 pub sub_region: ty::Region<'tcx>,
500 pub sup_type: Ty<'tcx>,
501 pub origin: SubregionOrigin<'tcx>,
504 impl<'tcx> fmt::Display for FixupError<'tcx> {
505 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506 use self::FixupError::*;
509 UnresolvedIntTy(_) => write!(
511 "cannot determine the type of this integer; \
512 add a suffix to specify the type explicitly"
514 UnresolvedFloatTy(_) => write!(
516 "cannot determine the type of this number; \
517 add a suffix to specify the type explicitly"
519 UnresolvedTy(_) => write!(f, "unconstrained type"),
520 UnresolvedConst(_) => write!(f, "unconstrained const value"),
525 /// A temporary returned by `tcx.infer_ctxt()`. This is necessary
526 /// for multiple `InferCtxt` to share the same `in_progress_typeck_results`
527 /// without using `Rc` or something similar.
528 pub struct InferCtxtBuilder<'tcx> {
530 fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
531 defining_use_anchor: Option<LocalDefId>,
534 pub trait TyCtxtInferExt<'tcx> {
535 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
538 impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
539 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
540 InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None }
544 impl<'tcx> InferCtxtBuilder<'tcx> {
545 /// Used only by `rustc_typeck` during body type-checking/inference,
546 /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
547 /// Will also change the scope for opaque type defining use checks to the given owner.
548 pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
549 self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
550 self.with_opaque_type_inference(table_owner)
553 /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
554 /// you need to call this function. Otherwise the opaque type will be treated opaquely.
556 /// It is only meant to be called in two places, for typeck
557 /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used
559 pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self {
560 self.defining_use_anchor = Some(defining_use_anchor);
564 /// Given a canonical value `C` as a starting point, create an
565 /// inference context that contains each of the bound values
566 /// within instantiated as a fresh variable. The `f` closure is
567 /// invoked with the new infcx, along with the instantiated value
568 /// `V` and a substitution `S`. This substitution `S` maps from
569 /// the bound values in `C` to their instantiated values in `V`
570 /// (in other words, `S(C) = V`).
571 pub fn enter_with_canonical<T, R>(
574 canonical: &Canonical<'tcx, T>,
575 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
578 T: TypeFoldable<'tcx>,
582 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
583 f(infcx, value, subst)
587 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
588 let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self;
589 let in_progress_typeck_results = fresh_typeck_results.as_ref();
593 in_progress_typeck_results,
594 inner: RefCell::new(InferCtxtInner::new()),
595 lexical_region_resolutions: RefCell::new(None),
596 selection_cache: Default::default(),
597 evaluation_cache: Default::default(),
598 reported_trait_errors: Default::default(),
599 reported_closure_mismatch: Default::default(),
600 tainted_by_errors_flag: Cell::new(false),
601 err_count_on_creation: tcx.sess.err_count(),
602 in_snapshot: Cell::new(false),
603 skip_leak_check: Cell::new(false),
604 universe: Cell::new(ty::UniverseIndex::ROOT),
609 impl<'tcx, T> InferOk<'tcx, T> {
610 pub fn unit(self) -> InferOk<'tcx, ()> {
611 InferOk { value: (), obligations: self.obligations }
614 /// Extracts `value`, registering any obligations into `fulfill_cx`.
615 pub fn into_value_registering_obligations(
617 infcx: &InferCtxt<'_, 'tcx>,
618 fulfill_cx: &mut dyn TraitEngine<'tcx>,
620 let InferOk { value, obligations } = self;
621 for obligation in obligations {
622 fulfill_cx.register_predicate_obligation(infcx, obligation);
628 impl<'tcx> InferOk<'tcx, ()> {
629 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
634 #[must_use = "once you start a snapshot, you should always consume it"]
635 pub struct CombinedSnapshot<'a, 'tcx> {
636 undo_snapshot: Snapshot<'tcx>,
637 region_constraints_snapshot: RegionSnapshot,
638 universe: ty::UniverseIndex,
639 was_in_snapshot: bool,
640 _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
643 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
644 /// calls `tcx.try_unify_abstract_consts` after
645 /// canonicalizing the consts.
646 #[instrument(skip(self), level = "debug")]
647 pub fn try_unify_abstract_consts(
649 a: ty::Unevaluated<'tcx, ()>,
650 b: ty::Unevaluated<'tcx, ()>,
651 param_env: ty::ParamEnv<'tcx>,
653 // Reject any attempt to unify two unevaluated constants that contain inference
654 // variables, since inference variables in queries lead to ICEs.
655 if a.substs.has_infer_types_or_consts()
656 || b.substs.has_infer_types_or_consts()
657 || param_env.has_infer_types_or_consts()
659 debug!("a or b or param_env contain infer vars in its substs -> cannot unify");
663 let param_env_and = param_env.and((a, b));
664 let erased = self.tcx.erase_regions(param_env_and);
665 debug!("after erase_regions: {:?}", erased);
667 self.tcx.try_unify_abstract_consts(erased)
670 pub fn is_in_snapshot(&self) -> bool {
671 self.in_snapshot.get()
674 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
675 t.fold_with(&mut self.freshener())
678 /// Returns the origin of the type variable identified by `vid`, or `None`
679 /// if this is not a type variable.
681 /// No attempt is made to resolve `ty`.
682 pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
684 ty::Infer(ty::TyVar(vid)) => {
685 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
691 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
692 freshen::TypeFreshener::new(self, false)
695 /// Like `freshener`, but does not replace `'static` regions.
696 pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
697 freshen::TypeFreshener::new(self, true)
700 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
701 let mut inner = self.inner.borrow_mut();
702 let mut vars: Vec<Ty<'_>> = inner
704 .unsolved_variables()
706 .map(|t| self.tcx.mk_ty_var(t))
709 (0..inner.int_unification_table().len())
710 .map(|i| ty::IntVid { index: i as u32 })
711 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
712 .map(|v| self.tcx.mk_int_var(v)),
715 (0..inner.float_unification_table().len())
716 .map(|i| ty::FloatVid { index: i as u32 })
717 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
718 .map(|v| self.tcx.mk_float_var(v)),
725 trace: TypeTrace<'tcx>,
726 param_env: ty::ParamEnv<'tcx>,
727 define_opaque_types: bool,
728 ) -> CombineFields<'a, 'tcx> {
734 obligations: PredicateObligations::new(),
739 /// Clear the "currently in a snapshot" flag, invoke the closure,
740 /// then restore the flag to its original value. This flag is a
741 /// debugging measure designed to detect cases where we start a
742 /// snapshot, create type variables, and register obligations
743 /// which may involve those type variables in the fulfillment cx,
744 /// potentially leaving "dangling type variables" behind.
745 /// In such cases, an assertion will fail when attempting to
746 /// register obligations, within a snapshot. Very useful, much
747 /// better than grovelling through megabytes of `RUSTC_LOG` output.
749 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
750 /// sometimes create a "mini-fulfilment-cx" in which we enroll
751 /// obligations. As long as this fulfillment cx is fully drained
752 /// before we return, this is not a problem, as there won't be any
753 /// escaping obligations in the main cx. In those cases, you can
754 /// use this function.
755 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
757 F: FnOnce(&Self) -> R,
759 let flag = self.in_snapshot.replace(false);
760 let result = func(self);
761 self.in_snapshot.set(flag);
765 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
766 debug!("start_snapshot()");
768 let in_snapshot = self.in_snapshot.replace(true);
770 let mut inner = self.inner.borrow_mut();
773 undo_snapshot: inner.undo_log.start_snapshot(),
774 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
775 universe: self.universe(),
776 was_in_snapshot: in_snapshot,
777 // Borrow typeck results "in progress" (i.e., during typeck)
778 // to ban writes from within a snapshot to them.
779 _in_progress_typeck_results: self
780 .in_progress_typeck_results
781 .map(|typeck_results| typeck_results.borrow()),
785 #[instrument(skip(self, snapshot), level = "debug")]
786 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
787 let CombinedSnapshot {
789 region_constraints_snapshot,
792 _in_progress_typeck_results,
795 self.in_snapshot.set(was_in_snapshot);
796 self.universe.set(universe);
798 let mut inner = self.inner.borrow_mut();
799 inner.rollback_to(undo_snapshot);
800 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
803 #[instrument(skip(self, snapshot), level = "debug")]
804 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
805 let CombinedSnapshot {
807 region_constraints_snapshot: _,
810 _in_progress_typeck_results,
813 self.in_snapshot.set(was_in_snapshot);
815 self.inner.borrow_mut().commit(undo_snapshot);
818 /// Executes `f` and commit the bindings.
819 #[instrument(skip(self, f), level = "debug")]
820 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
822 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
824 let snapshot = self.start_snapshot();
825 let r = f(&snapshot);
826 self.commit_from(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<'a, '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<'a, '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<'a, '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<'a, 'tcx>,
890 .unwrap_region_constraints()
891 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
894 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
895 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
898 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
900 T: at::ToTrace<'tcx>,
902 let origin = &ObligationCause::dummy();
904 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
905 // Ignore obligations, since we are unrolling
906 // everything anyway.
911 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
913 T: at::ToTrace<'tcx>,
915 let origin = &ObligationCause::dummy();
917 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
918 // Ignore obligations, since we are unrolling
919 // everything anyway.
924 #[instrument(skip(self), level = "debug")]
927 origin: SubregionOrigin<'tcx>,
931 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
934 /// Require that the region `r` be equal to one of the regions in
935 /// the set `regions`.
936 #[instrument(skip(self), level = "debug")]
937 pub fn member_constraint(
939 opaque_type_def_id: DefId,
940 definition_span: Span,
942 region: ty::Region<'tcx>,
943 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
945 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
954 /// Processes a `Coerce` predicate from the fulfillment context.
955 /// This is NOT the preferred way to handle coercion, which is to
956 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
958 /// This method here is actually a fallback that winds up being
959 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
960 /// and records a coercion predicate. Presently, this method is equivalent
961 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
962 /// actually requiring `a <: b`. This is of course a valid coercion,
963 /// but it's not as flexible as `FnCtxt::coerce` would be.
965 /// (We may refactor this in the future, but there are a number of
966 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
967 /// records adjustments that are required on the HIR in order to perform
968 /// the coercion, and we don't currently have a way to manage that.)
969 pub fn coerce_predicate(
971 cause: &ObligationCause<'tcx>,
972 param_env: ty::ParamEnv<'tcx>,
973 predicate: ty::PolyCoercePredicate<'tcx>,
974 ) -> Option<InferResult<'tcx, ()>> {
975 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
976 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
980 self.subtype_predicate(cause, param_env, subtype_predicate)
983 pub fn subtype_predicate(
985 cause: &ObligationCause<'tcx>,
986 param_env: ty::ParamEnv<'tcx>,
987 predicate: ty::PolySubtypePredicate<'tcx>,
988 ) -> Option<InferResult<'tcx, ()>> {
989 // Check for two unresolved inference variables, in which case we can
990 // make no progress. This is partly a micro-optimization, but it's
991 // also an opportunity to "sub-unify" the variables. This isn't
992 // *necessary* to prevent cycles, because they would eventually be sub-unified
993 // anyhow during generalization, but it helps with diagnostics (we can detect
994 // earlier that they are sub-unified).
996 // Note that we can just skip the binders here because
997 // type variables can't (at present, at
998 // least) capture any of the things bound by this binder.
1000 // Note that this sub here is not just for diagnostics - it has semantic
1002 let r_a = self.shallow_resolve(predicate.skip_binder().a);
1003 let r_b = self.shallow_resolve(predicate.skip_binder().b);
1004 match (r_a.kind(), r_b.kind()) {
1005 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
1006 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
1012 Some(self.commit_if_ok(|_snapshot| {
1013 let ty::SubtypePredicate { a_is_expected, a, b } =
1014 self.replace_bound_vars_with_placeholders(predicate);
1016 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1022 pub fn region_outlives_predicate(
1024 cause: &traits::ObligationCause<'tcx>,
1025 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1026 ) -> UnitResult<'tcx> {
1027 self.commit_if_ok(|_snapshot| {
1028 let ty::OutlivesPredicate(r_a, r_b) =
1029 self.replace_bound_vars_with_placeholders(predicate);
1030 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1031 RelateRegionParamBound(cause.span)
1033 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1038 /// Number of type variables created so far.
1039 pub fn num_ty_vars(&self) -> usize {
1040 self.inner.borrow_mut().type_variables().num_vars()
1043 pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1044 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1047 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1048 self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1051 pub fn next_ty_var_id_in_universe(
1053 origin: TypeVariableOrigin,
1054 universe: ty::UniverseIndex,
1056 self.inner.borrow_mut().type_variables().new_var(universe, origin)
1059 pub fn next_ty_var_in_universe(
1061 origin: TypeVariableOrigin,
1062 universe: ty::UniverseIndex,
1064 let vid = self.next_ty_var_id_in_universe(origin, universe);
1065 self.tcx.mk_ty_var(vid)
1068 pub fn next_const_var(&self, ty: Ty<'tcx>, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
1069 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1072 pub fn next_const_var_in_universe(
1075 origin: ConstVariableOrigin,
1076 universe: ty::UniverseIndex,
1077 ) -> ty::Const<'tcx> {
1081 .const_unification_table()
1082 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1083 self.tcx.mk_const_var(vid, ty)
1086 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1087 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1089 val: ConstVariableValue::Unknown { universe: self.universe() },
1093 fn next_int_var_id(&self) -> IntVid {
1094 self.inner.borrow_mut().int_unification_table().new_key(None)
1097 pub fn next_int_var(&self) -> Ty<'tcx> {
1098 self.tcx.mk_int_var(self.next_int_var_id())
1101 fn next_float_var_id(&self) -> FloatVid {
1102 self.inner.borrow_mut().float_unification_table().new_key(None)
1105 pub fn next_float_var(&self) -> Ty<'tcx> {
1106 self.tcx.mk_float_var(self.next_float_var_id())
1109 /// Creates a fresh region variable with the next available index.
1110 /// The variable will be created in the maximum universe created
1111 /// thus far, allowing it to name any region created thus far.
1112 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1113 self.next_region_var_in_universe(origin, self.universe())
1116 /// Creates a fresh region variable with the next available index
1117 /// in the given universe; typically, you can use
1118 /// `next_region_var` and just use the maximal universe.
1119 pub fn next_region_var_in_universe(
1121 origin: RegionVariableOrigin,
1122 universe: ty::UniverseIndex,
1123 ) -> ty::Region<'tcx> {
1125 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1126 self.tcx.mk_region(ty::ReVar(region_var))
1129 /// Return the universe that the region `r` was created in. For
1130 /// most regions (e.g., `'static`, named regions from the user,
1131 /// etc) this is the root universe U0. For inference variables or
1132 /// placeholders, however, it will return the universe which which
1133 /// they are associated.
1134 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1135 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1138 /// Number of region variables created so far.
1139 pub fn num_region_vars(&self) -> usize {
1140 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1143 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1144 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1145 self.next_region_var(RegionVariableOrigin::Nll(origin))
1148 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1149 pub fn next_nll_region_var_in_universe(
1151 origin: NllRegionVariableOrigin,
1152 universe: ty::UniverseIndex,
1153 ) -> ty::Region<'tcx> {
1154 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1157 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1159 GenericParamDefKind::Lifetime => {
1160 // Create a region inference variable for the given
1161 // region parameter definition.
1162 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1164 GenericParamDefKind::Type { .. } => {
1165 // Create a type inference variable for the given
1166 // type parameter definition. The substitutions are
1167 // for actual parameters that may be referred to by
1168 // the default of this type parameter, if it exists.
1169 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1170 // used in a path such as `Foo::<T, U>::new()` will
1171 // use an inference variable for `C` with `[T, U]`
1172 // as the substitutions for the default, `(T, U)`.
1173 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1175 TypeVariableOrigin {
1176 kind: TypeVariableOriginKind::TypeParameterDefinition(
1184 self.tcx.mk_ty_var(ty_var_id).into()
1186 GenericParamDefKind::Const { .. } => {
1187 let origin = ConstVariableOrigin {
1188 kind: ConstVariableOriginKind::ConstParameterDefinition(
1195 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1197 val: ConstVariableValue::Unknown { universe: self.universe() },
1199 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1204 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1205 /// type/region parameter to a fresh inference variable.
1206 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1207 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1210 /// Returns `true` if errors have been reported since this infcx was
1211 /// created. This is sometimes used as a heuristic to skip
1212 /// reporting errors that often occur as a result of earlier
1213 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1214 /// inference variables, regionck errors).
1215 pub fn is_tainted_by_errors(&self) -> bool {
1217 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1218 tainted_by_errors_flag={})",
1219 self.tcx.sess.err_count(),
1220 self.err_count_on_creation,
1221 self.tainted_by_errors_flag.get()
1224 if self.tcx.sess.err_count() > self.err_count_on_creation {
1225 return true; // errors reported since this infcx was made
1227 self.tainted_by_errors_flag.get()
1230 /// Set the "tainted by errors" flag to true. We call this when we
1231 /// observe an error from a prior pass.
1232 pub fn set_tainted_by_errors(&self) {
1233 debug!("set_tainted_by_errors()");
1234 self.tainted_by_errors_flag.set(true)
1237 pub fn skip_region_resolution(&self) {
1238 let (var_infos, _) = {
1239 let mut inner = self.inner.borrow_mut();
1240 let inner = &mut *inner;
1241 // Note: `inner.region_obligations` may not be empty, because we
1242 // didn't necessarily call `process_registered_region_obligations`.
1243 // This is okay, because that doesn't introduce new vars.
1245 .region_constraint_storage
1247 .expect("regions already resolved")
1248 .with_log(&mut inner.undo_log)
1249 .into_infos_and_data()
1252 let lexical_region_resolutions = LexicalRegionResolutions {
1253 error_region: self.tcx.lifetimes.re_static,
1254 values: rustc_index::vec::IndexVec::from_elem_n(
1255 crate::infer::lexical_region_resolve::VarValue::Value(self.tcx.lifetimes.re_erased),
1260 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1261 assert!(old_value.is_none());
1264 /// Process the region constraints and return any any errors that
1265 /// result. After this, no more unification operations should be
1266 /// done -- or the compiler will panic -- but it is legal to use
1267 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1268 pub fn resolve_regions(
1270 region_context: DefId,
1271 outlives_env: &OutlivesEnvironment<'tcx>,
1272 ) -> Vec<RegionResolutionError<'tcx>> {
1273 let (var_infos, data) = {
1274 let mut inner = self.inner.borrow_mut();
1275 let inner = &mut *inner;
1277 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1278 "region_obligations not empty: {:#?}",
1279 inner.region_obligations
1282 .region_constraint_storage
1284 .expect("regions already resolved")
1285 .with_log(&mut inner.undo_log)
1286 .into_infos_and_data()
1290 &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1292 let (lexical_region_resolutions, errors) =
1293 lexical_region_resolve::resolve(region_rels, var_infos, data);
1295 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1296 assert!(old_value.is_none());
1301 /// Process the region constraints and report any errors that
1302 /// result. After this, no more unification operations should be
1303 /// done -- or the compiler will panic -- but it is legal to use
1304 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1305 pub fn resolve_regions_and_report_errors(
1307 region_context: DefId,
1308 outlives_env: &OutlivesEnvironment<'tcx>,
1310 let errors = self.resolve_regions(region_context, outlives_env);
1312 if !self.is_tainted_by_errors() {
1313 // As a heuristic, just skip reporting region errors
1314 // altogether if other errors have been reported while
1315 // this infcx was in use. This is totally hokey but
1316 // otherwise we have a hard time separating legit region
1317 // errors from silly ones.
1318 self.report_region_errors(&errors);
1322 /// Obtains (and clears) the current set of region
1323 /// constraints. The inference context is still usable: further
1324 /// unifications will simply add new constraints.
1326 /// This method is not meant to be used with normal lexical region
1327 /// resolution. Rather, it is used in the NLL mode as a kind of
1328 /// interim hack: basically we run normal type-check and generate
1329 /// region constraints as normal, but then we take them and
1330 /// translate them into the form that the NLL solver
1331 /// understands. See the NLL module for mode details.
1332 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1334 self.inner.borrow().region_obligations.is_empty(),
1335 "region_obligations not empty: {:#?}",
1336 self.inner.borrow().region_obligations
1339 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1342 /// Gives temporary access to the region constraint data.
1343 pub fn with_region_constraints<R>(
1345 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1347 let mut inner = self.inner.borrow_mut();
1348 op(inner.unwrap_region_constraints().data())
1351 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1352 let mut inner = self.inner.borrow_mut();
1353 let inner = &mut *inner;
1355 .region_constraint_storage
1357 .expect("regions already resolved")
1358 .with_log(&mut inner.undo_log)
1362 /// Takes ownership of the list of variable regions. This implies
1363 /// that all the region constraints have already been taken, and
1364 /// hence that `resolve_regions_and_report_errors` can never be
1365 /// called. This is used only during NLL processing to "hand off" ownership
1366 /// of the set of region variables into the NLL region context.
1367 pub fn take_region_var_origins(&self) -> VarInfos {
1368 let mut inner = self.inner.borrow_mut();
1369 let (var_infos, data) = inner
1370 .region_constraint_storage
1372 .expect("regions already resolved")
1373 .with_log(&mut inner.undo_log)
1374 .into_infos_and_data();
1375 assert!(data.is_empty());
1379 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1380 self.resolve_vars_if_possible(t).to_string()
1383 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1384 /// universe index of `TyVar(vid)`.
1385 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1386 use self::type_variable::TypeVariableValue;
1388 match self.inner.borrow_mut().type_variables().probe(vid) {
1389 TypeVariableValue::Known { value } => Ok(value),
1390 TypeVariableValue::Unknown { universe } => Err(universe),
1394 /// Resolve any type variables found in `value` -- but only one
1395 /// level. So, if the variable `?X` is bound to some type
1396 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1397 /// itself be bound to a type).
1399 /// Useful when you only need to inspect the outermost level of
1400 /// the type and don't care about nested types (or perhaps you
1401 /// will be resolving them as well, e.g. in a loop).
1402 pub fn shallow_resolve<T>(&self, value: T) -> T
1404 T: TypeFoldable<'tcx>,
1406 value.fold_with(&mut ShallowResolver { infcx: self })
1409 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1410 self.inner.borrow_mut().type_variables().root_var(var)
1413 /// Where possible, replaces type/const variables in
1414 /// `value` with their final value. Note that region variables
1415 /// are unaffected. If a type/const variable has not been unified, it
1416 /// is left as is. This is an idempotent operation that does
1417 /// not affect inference state in any way and so you can do it
1419 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1421 T: TypeFoldable<'tcx>,
1423 if !value.needs_infer() {
1424 return value; // Avoid duplicated subst-folding.
1426 let mut r = resolve::OpportunisticVarResolver::new(self);
1427 value.fold_with(&mut r)
1430 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1432 T: TypeFoldable<'tcx>,
1434 if !value.needs_infer() {
1435 return value; // Avoid duplicated subst-folding.
1437 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1438 value.fold_with(&mut r)
1441 /// Returns the first unresolved variable contained in `T`. In the
1442 /// process of visiting `T`, this will resolve (where possible)
1443 /// type variables in `T`, but it never constructs the final,
1444 /// resolved type, so it's more efficient than
1445 /// `resolve_vars_if_possible()`.
1446 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1448 T: TypeFoldable<'tcx>,
1450 value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1453 pub fn probe_const_var(
1455 vid: ty::ConstVid<'tcx>,
1456 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1457 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1458 ConstVariableValue::Known { value } => Ok(value),
1459 ConstVariableValue::Unknown { universe } => Err(universe),
1463 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1465 * Attempts to resolve all type/region/const variables in
1466 * `value`. Region inference must have been run already (e.g.,
1467 * by calling `resolve_regions_and_report_errors`). If some
1468 * variable was never unified, an `Err` results.
1470 * This method is idempotent, but it not typically not invoked
1471 * except during the writeback phase.
1474 resolve::fully_resolve(self, value)
1477 // [Note-Type-error-reporting]
1478 // An invariant is that anytime the expected or actual type is Error (the special
1479 // error type, meaning that an error occurred when typechecking this expression),
1480 // this is a derived error. The error cascaded from another error (that was already
1481 // reported), so it's not useful to display it to the user.
1482 // The following methods implement this logic.
1483 // They check if either the actual or expected type is Error, and don't print the error
1484 // in this case. The typechecker should only ever report type errors involving mismatched
1485 // types using one of these methods, and should not call span_err directly for such
1488 pub fn type_error_struct_with_diag<M>(
1492 actual_ty: Ty<'tcx>,
1493 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>
1495 M: FnOnce(String) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1497 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1498 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1500 let mut err = mk_diag(self.ty_to_string(actual_ty));
1502 // Don't report an error if actual type is `Error`.
1503 if actual_ty.references_error() {
1504 err.downgrade_to_delayed_bug();
1510 pub fn report_mismatched_types(
1512 cause: &ObligationCause<'tcx>,
1515 err: TypeError<'tcx>,
1516 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1517 let trace = TypeTrace::types(cause, true, expected, actual);
1518 self.report_and_explain_type_error(trace, &err)
1521 pub fn report_mismatched_consts(
1523 cause: &ObligationCause<'tcx>,
1524 expected: ty::Const<'tcx>,
1525 actual: ty::Const<'tcx>,
1526 err: TypeError<'tcx>,
1527 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1528 let trace = TypeTrace::consts(cause, true, expected, actual);
1529 self.report_and_explain_type_error(trace, &err)
1532 pub fn replace_bound_vars_with_fresh_vars<T>(
1535 lbrct: LateBoundRegionConversionTime,
1536 value: ty::Binder<'tcx, T>,
1539 T: TypeFoldable<'tcx> + Copy,
1541 if let Some(inner) = value.no_bound_vars() {
1545 let mut region_map = FxHashMap::default();
1546 let fld_r = |br: ty::BoundRegion| {
1549 .or_insert_with(|| self.next_region_var(LateBoundRegion(span, br.kind, lbrct)))
1552 let mut ty_map = FxHashMap::default();
1553 let fld_t = |bt: ty::BoundTy| {
1554 *ty_map.entry(bt).or_insert_with(|| {
1555 self.next_ty_var(TypeVariableOrigin {
1556 kind: TypeVariableOriginKind::MiscVariable,
1561 let mut ct_map = FxHashMap::default();
1562 let fld_c = |bc: ty::BoundVar, ty| {
1563 *ct_map.entry(bc).or_insert_with(|| {
1564 self.next_const_var(
1566 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1570 self.tcx.replace_bound_vars_uncached(value, fld_r, fld_t, fld_c)
1573 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1574 pub fn verify_generic_bound(
1576 origin: SubregionOrigin<'tcx>,
1577 kind: GenericKind<'tcx>,
1578 a: ty::Region<'tcx>,
1579 bound: VerifyBound<'tcx>,
1581 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1585 .unwrap_region_constraints()
1586 .verify_generic_bound(origin, kind, a, bound);
1589 /// Obtains the latest type of the given closure; this may be a
1590 /// closure in the current function, in which case its
1591 /// `ClosureKind` may not yet be known.
1592 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1593 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1594 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1595 closure_kind_ty.to_opt_closure_kind()
1598 /// Clears the selection, evaluation, and projection caches. This is useful when
1599 /// repeatedly attempting to select an `Obligation` while changing only
1600 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1601 pub fn clear_caches(&self) {
1602 self.selection_cache.clear();
1603 self.evaluation_cache.clear();
1604 self.inner.borrow_mut().projection_cache().clear();
1607 pub fn universe(&self) -> ty::UniverseIndex {
1611 /// Creates and return a fresh universe that extends all previous
1612 /// universes. Updates `self.universe` to that new universe.
1613 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1614 let u = self.universe.get().next_universe();
1615 self.universe.set(u);
1619 /// Resolves and evaluates a constant.
1621 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1622 /// substitutions and environment are used to resolve the constant. Alternatively if the
1623 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1624 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1625 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1626 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1629 /// This handles inferences variables within both `param_env` and `substs` by
1630 /// performing the operation on their respective canonical forms.
1631 #[instrument(skip(self), level = "debug")]
1632 pub fn const_eval_resolve(
1634 param_env: ty::ParamEnv<'tcx>,
1635 unevaluated: ty::Unevaluated<'tcx>,
1637 ) -> EvalToConstValueResult<'tcx> {
1638 let substs = self.resolve_vars_if_possible(unevaluated.substs);
1641 // Postpone the evaluation of constants whose substs depend on inference
1643 if substs.has_infer_types_or_consts() {
1644 debug!("substs have infer types or consts: {:?}", substs);
1645 return Err(ErrorHandled::TooGeneric);
1648 let param_env_erased = self.tcx.erase_regions(param_env);
1649 let substs_erased = self.tcx.erase_regions(substs);
1650 debug!(?param_env_erased);
1651 debug!(?substs_erased);
1653 let unevaluated = ty::Unevaluated {
1654 def: unevaluated.def,
1655 substs: substs_erased,
1656 promoted: unevaluated.promoted,
1659 // The return value is the evaluated value which doesn't contain any reference to inference
1660 // variables, thus we don't need to substitute back the original values.
1661 self.tcx.const_eval_resolve(param_env_erased, unevaluated, span)
1664 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1665 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1666 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1668 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1669 /// inlined, despite being large, because it has only two call sites that
1670 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1671 /// inference variables), and it handles both `Ty` and `ty::Const` without
1672 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1674 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1676 TyOrConstInferVar::Ty(v) => {
1677 use self::type_variable::TypeVariableValue;
1679 // If `inlined_probe` returns a `Known` value, it never equals
1680 // `ty::Infer(ty::TyVar(v))`.
1681 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1682 TypeVariableValue::Unknown { .. } => false,
1683 TypeVariableValue::Known { .. } => true,
1687 TyOrConstInferVar::TyInt(v) => {
1688 // If `inlined_probe_value` returns a value it's always a
1689 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1691 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1694 TyOrConstInferVar::TyFloat(v) => {
1695 // If `probe_value` returns a value it's always a
1696 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1698 // Not `inlined_probe_value(v)` because this call site is colder.
1699 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1702 TyOrConstInferVar::Const(v) => {
1703 // If `probe_value` returns a `Known` value, it never equals
1704 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1706 // Not `inlined_probe_value(v)` because this call site is colder.
1707 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1708 ConstVariableValue::Unknown { .. } => false,
1709 ConstVariableValue::Known { .. } => true,
1716 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1717 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1718 #[derive(Copy, Clone, Debug)]
1719 pub enum TyOrConstInferVar<'tcx> {
1720 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1722 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1724 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1727 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1728 Const(ConstVid<'tcx>),
1731 impl<'tcx> TyOrConstInferVar<'tcx> {
1732 /// Tries to extract an inference variable from a type or a constant, returns `None`
1733 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1734 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1735 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1736 match arg.unpack() {
1737 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1738 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1739 GenericArgKind::Lifetime(_) => None,
1743 /// Tries to extract an inference variable from a type, returns `None`
1744 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1745 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1747 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1748 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1749 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1754 /// Tries to extract an inference variable from a constant, returns `None`
1755 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1756 pub fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1758 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1764 /// Replace `{integer}` with `i32` and `{float}` with `f64`.
1765 /// Used only for diagnostics.
1766 struct InferenceLiteralEraser<'tcx> {
1770 impl<'tcx> TypeFolder<'tcx> for InferenceLiteralEraser<'tcx> {
1771 fn tcx(&self) -> TyCtxt<'tcx> {
1775 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1777 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1778 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1779 _ => ty.super_fold_with(self),
1784 struct ShallowResolver<'a, 'tcx> {
1785 infcx: &'a InferCtxt<'a, 'tcx>,
1788 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1789 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1793 /// If `ty` is a type variable of some kind, resolve it one level
1794 /// (but do not resolve types found in the result). If `typ` is
1795 /// not a type variable, just return it unmodified.
1796 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1798 ty::Infer(ty::TyVar(v)) => {
1799 // Not entirely obvious: if `typ` is a type variable,
1800 // it can be resolved to an int/float variable, which
1801 // can then be recursively resolved, hence the
1802 // recursion. Note though that we prevent type
1803 // variables from unifying to other type variables
1804 // directly (though they may be embedded
1805 // structurally), and we prevent cycles in any case,
1806 // so this recursion should always be of very limited
1809 // Note: if these two lines are combined into one we get
1810 // dynamic borrow errors on `self.inner`.
1811 let known = self.infcx.inner.borrow_mut().type_variables().probe(v).known();
1812 known.map_or(ty, |t| self.fold_ty(t))
1815 ty::Infer(ty::IntVar(v)) => self
1819 .int_unification_table()
1821 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1823 ty::Infer(ty::FloatVar(v)) => self
1827 .float_unification_table()
1829 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1835 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1836 if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
1840 .const_unification_table()
1851 impl<'tcx> TypeTrace<'tcx> {
1852 pub fn span(&self) -> Span {
1857 cause: &ObligationCause<'tcx>,
1858 a_is_expected: bool,
1861 ) -> TypeTrace<'tcx> {
1863 cause: cause.clone(),
1864 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1869 cause: &ObligationCause<'tcx>,
1870 a_is_expected: bool,
1873 ) -> TypeTrace<'tcx> {
1875 cause: cause.clone(),
1876 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1881 impl<'tcx> SubregionOrigin<'tcx> {
1882 pub fn span(&self) -> Span {
1884 Subtype(ref a) => a.span(),
1885 RelateObjectBound(a) => a,
1886 RelateParamBound(a, ..) => a,
1887 RelateRegionParamBound(a) => a,
1889 ReborrowUpvar(a, _) => a,
1890 DataBorrowed(_, a) => a,
1891 ReferenceOutlivesReferent(_, a) => a,
1892 CompareImplMethodObligation { span, .. } => span,
1893 CompareImplTypeObligation { span, .. } => span,
1894 CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1898 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1900 F: FnOnce() -> Self,
1902 match *cause.code() {
1903 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1904 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1907 traits::ObligationCauseCode::CompareImplMethodObligation {
1910 } => SubregionOrigin::CompareImplMethodObligation {
1916 traits::ObligationCauseCode::CompareImplTypeObligation {
1919 } => SubregionOrigin::CompareImplTypeObligation {
1925 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1928 } => SubregionOrigin::CheckAssociatedTypeBounds {
1931 parent: Box::new(default()),
1939 impl RegionVariableOrigin {
1940 pub fn span(&self) -> Span {
1947 | EarlyBoundRegion(a, ..)
1948 | LateBoundRegion(a, ..)
1949 | UpvarRegion(_, a) => a,
1950 Nll(..) => bug!("NLL variable used with `span`"),
1955 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1956 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1959 "RegionObligation(sub_region={:?}, sup_type={:?})",
1960 self.sub_region, self.sup_type