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::{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};
18 use rustc_hir::def_id::{DefId, LocalDefId};
19 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
20 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
21 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
22 use rustc_middle::mir::interpret::{ErrorHandled, EvalToValTreeResult};
23 use rustc_middle::mir::ConstraintCategory;
24 use rustc_middle::traits::select;
25 use rustc_middle::ty::abstract_const::{AbstractConst, FailureKind};
26 use rustc_middle::ty::error::{ExpectedFound, TypeError};
27 use rustc_middle::ty::fold::BoundVarReplacerDelegate;
28 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
29 use rustc_middle::ty::relate::RelateResult;
30 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
31 use rustc_middle::ty::visit::TypeVisitable;
32 pub use rustc_middle::ty::IntVarValue;
33 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
34 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
35 use rustc_span::symbol::Symbol;
36 use rustc_span::{Span, DUMMY_SP};
38 use std::cell::{Cell, RefCell};
41 use self::combine::CombineFields;
42 use self::error_reporting::TypeErrCtxt;
43 use self::free_regions::RegionRelations;
44 use self::lexical_region_resolve::LexicalRegionResolutions;
45 use self::outlives::env::OutlivesEnvironment;
46 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
47 use self::region_constraints::{
48 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
50 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
56 pub mod error_reporting;
63 mod lexical_region_resolve;
69 pub mod region_constraints;
72 pub mod type_variable;
77 pub struct InferOk<'tcx, T> {
79 pub obligations: PredicateObligations<'tcx>,
81 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
83 pub type Bound<T> = Option<T>;
84 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
85 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
87 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
88 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
91 /// This type contains all the things within `InferCtxt` that sit within a
92 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
93 /// operations are hot enough that we want only one call to `borrow_mut` per
94 /// call to `start_snapshot` and `rollback_to`.
96 pub struct InferCtxtInner<'tcx> {
97 /// Cache for projections. This cache is snapshotted along with the infcx.
99 /// Public so that `traits::project` can use it.
100 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
102 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
103 /// that might instantiate a general type variable have an order,
104 /// represented by its upper and lower bounds.
105 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
107 /// Map from const parameter variable to the kind of const it represents.
108 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
110 /// Map from integral variable to the kind of integer it represents.
111 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
113 /// Map from floating variable to the kind of float it represents.
114 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
116 /// Tracks the set of region variables and the constraints between them.
117 /// This is initially `Some(_)` but when
118 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
119 /// -- further attempts to perform unification, etc., may fail if new
120 /// region constraints would've been added.
121 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
123 /// A set of constraints that regionck must validate. Each
124 /// constraint has the form `T:'a`, meaning "some type `T` must
125 /// outlive the lifetime 'a". These constraints derive from
126 /// instantiated type parameters. So if you had a struct defined
128 /// ```ignore (illustrative)
129 /// struct Foo<T:'static> { ... }
131 /// then in some expression `let x = Foo { ... }` it will
132 /// instantiate the type parameter `T` with a fresh type `$0`. At
133 /// the same time, it will record a region obligation of
134 /// `$0:'static`. This will get checked later by regionck. (We
135 /// can't generally check these things right away because we have
136 /// to wait until types are resolved.)
138 /// These are stored in a map keyed to the id of the innermost
139 /// enclosing fn body / static initializer expression. This is
140 /// because the location where the obligation was incurred can be
141 /// relevant with respect to which sublifetime assumptions are in
142 /// place. The reason that we store under the fn-id, and not
143 /// something more fine-grained, is so that it is easier for
144 /// regionck to be sure that it has found *all* the region
145 /// obligations (otherwise, it's easy to fail to walk to a
146 /// particular node-id).
148 /// Before running `resolve_regions_and_report_errors`, the creator
149 /// of the inference context is expected to invoke
150 /// [`InferCtxt::process_registered_region_obligations`]
151 /// for each body-id in this map, which will process the
152 /// obligations within. This is expected to be done 'late enough'
153 /// that all type inference variables have been bound and so forth.
154 region_obligations: Vec<RegionObligation<'tcx>>,
156 undo_log: InferCtxtUndoLogs<'tcx>,
158 /// Caches for opaque type inference.
159 pub opaque_type_storage: OpaqueTypeStorage<'tcx>,
162 impl<'tcx> InferCtxtInner<'tcx> {
163 fn new() -> InferCtxtInner<'tcx> {
165 projection_cache: Default::default(),
166 type_variable_storage: type_variable::TypeVariableStorage::new(),
167 undo_log: InferCtxtUndoLogs::default(),
168 const_unification_storage: ut::UnificationTableStorage::new(),
169 int_unification_storage: ut::UnificationTableStorage::new(),
170 float_unification_storage: ut::UnificationTableStorage::new(),
171 region_constraint_storage: Some(RegionConstraintStorage::new()),
172 region_obligations: vec![],
173 opaque_type_storage: Default::default(),
178 pub fn region_obligations(&self) -> &[RegionObligation<'tcx>] {
179 &self.region_obligations
183 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
184 self.projection_cache.with_log(&mut self.undo_log)
188 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
189 self.type_variable_storage.with_log(&mut self.undo_log)
193 pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
194 self.opaque_type_storage.with_log(&mut self.undo_log)
198 fn int_unification_table(
200 ) -> ut::UnificationTable<
203 &mut ut::UnificationStorage<ty::IntVid>,
204 &mut InferCtxtUndoLogs<'tcx>,
207 self.int_unification_storage.with_log(&mut self.undo_log)
211 fn float_unification_table(
213 ) -> ut::UnificationTable<
216 &mut ut::UnificationStorage<ty::FloatVid>,
217 &mut InferCtxtUndoLogs<'tcx>,
220 self.float_unification_storage.with_log(&mut self.undo_log)
224 fn const_unification_table(
226 ) -> ut::UnificationTable<
229 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
230 &mut InferCtxtUndoLogs<'tcx>,
233 self.const_unification_storage.with_log(&mut self.undo_log)
237 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
238 self.region_constraint_storage
240 .expect("region constraints already solved")
241 .with_log(&mut self.undo_log)
245 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
246 pub enum DefiningAnchor {
247 /// `DefId` of the item.
249 /// When opaque types are not resolved, we `Bubble` up, meaning
250 /// return the opaque/hidden type pair from query, for caller of query to handle it.
252 /// Used to catch type mismatch errors when handling opaque types.
256 pub struct InferCtxt<'tcx> {
257 pub tcx: TyCtxt<'tcx>,
259 /// The `DefId` of the item in whose context we are performing inference or typeck.
260 /// It is used to check whether an opaque type use is a defining use.
262 /// If it is `DefiningAnchor::Bubble`, we can't resolve opaque types here and need to bubble up
263 /// the obligation. This frequently happens for
264 /// short lived InferCtxt within queries. The opaque type obligations are forwarded
265 /// to the outside until the end up in an `InferCtxt` for typeck or borrowck.
267 /// It is default value is `DefiningAnchor::Error`, this way it is easier to catch errors that
268 /// might come up during inference or typeck.
269 pub defining_use_anchor: DefiningAnchor,
271 /// Whether this inference context should care about region obligations in
272 /// the root universe. Most notably, this is used during hir typeck as region
273 /// solving is left to borrowck instead.
274 pub considering_regions: bool,
276 pub inner: RefCell<InferCtxtInner<'tcx>>,
278 /// If set, this flag causes us to skip the 'leak check' during
279 /// higher-ranked subtyping operations. This flag is a temporary one used
280 /// to manage the removal of the leak-check: for the time being, we still run the
281 /// leak-check, but we issue warnings. This flag can only be set to true
282 /// when entering a snapshot.
283 skip_leak_check: Cell<bool>,
285 /// Once region inference is done, the values for each variable.
286 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
288 /// Caches the results of trait selection. This cache is used
289 /// for things that have to do with the parameters in scope.
290 pub selection_cache: select::SelectionCache<'tcx>,
292 /// Caches the results of trait evaluation.
293 pub evaluation_cache: select::EvaluationCache<'tcx>,
295 /// the set of predicates on which errors have been reported, to
296 /// avoid reporting the same error twice.
297 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
299 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
301 /// When an error occurs, we want to avoid reporting "derived"
302 /// errors that are due to this original failure. Normally, we
303 /// handle this with the `err_count_on_creation` count, which
304 /// basically just tracks how many errors were reported when we
305 /// started type-checking a fn and checks to see if any new errors
306 /// have been reported since then. Not great, but it works.
308 /// However, when errors originated in other passes -- notably
309 /// resolve -- this heuristic breaks down. Therefore, we have this
310 /// auxiliary flag that one can set whenever one creates a
311 /// type-error that is due to an error in a prior pass.
313 /// Don't read this flag directly, call `is_tainted_by_errors()`
314 /// and `set_tainted_by_errors()`.
315 tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
317 /// Track how many errors were reported when this infcx is created.
318 /// If the number of errors increases, that's also a sign (line
319 /// `tainted_by_errors`) to avoid reporting certain kinds of errors.
320 // FIXME(matthewjasper) Merge into `tainted_by_errors`
321 err_count_on_creation: usize,
323 /// This flag is true while there is an active snapshot.
324 in_snapshot: Cell<bool>,
326 /// What is the innermost universe we have created? Starts out as
327 /// `UniverseIndex::root()` but grows from there as we enter
328 /// universal quantifiers.
330 /// N.B., at present, we exclude the universal quantifiers on the
331 /// item we are type-checking, and just consider those names as
332 /// part of the root universe. So this would only get incremented
333 /// when we enter into a higher-ranked (`for<..>`) type or trait
335 universe: Cell<ty::UniverseIndex>,
337 normalize_fn_sig_for_diagnostic:
338 Option<Lrc<dyn Fn(&InferCtxt<'tcx>, ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx>>>,
341 /// See the `error_reporting` module for more details.
342 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
343 pub enum ValuePairs<'tcx> {
344 Regions(ExpectedFound<ty::Region<'tcx>>),
345 Terms(ExpectedFound<ty::Term<'tcx>>),
346 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
347 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
350 impl<'tcx> ValuePairs<'tcx> {
351 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
352 if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
353 && let Some(expected) = expected.ty()
354 && let Some(found) = found.ty()
356 Some((expected, found))
363 /// The trace designates the path through inference that we took to
364 /// encounter an error or subtyping constraint.
366 /// See the `error_reporting` module for more details.
367 #[derive(Clone, Debug)]
368 pub struct TypeTrace<'tcx> {
369 pub cause: ObligationCause<'tcx>,
370 pub values: ValuePairs<'tcx>,
373 /// The origin of a `r1 <= r2` constraint.
375 /// See `error_reporting` module for more details
376 #[derive(Clone, Debug)]
377 pub enum SubregionOrigin<'tcx> {
378 /// Arose from a subtyping relation
379 Subtype(Box<TypeTrace<'tcx>>),
381 /// When casting `&'a T` to an `&'b Trait` object,
382 /// relating `'a` to `'b`
383 RelateObjectBound(Span),
385 /// Some type parameter was instantiated with the given type,
386 /// and that type must outlive some region.
387 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
389 /// The given region parameter was instantiated with a region
390 /// that must outlive some other region.
391 RelateRegionParamBound(Span),
393 /// Creating a pointer `b` to contents of another reference
396 /// Creating a pointer `b` to contents of an upvar
397 ReborrowUpvar(Span, ty::UpvarId),
399 /// Data with type `Ty<'tcx>` was borrowed
400 DataBorrowed(Ty<'tcx>, Span),
402 /// (&'a &'b T) where a >= b
403 ReferenceOutlivesReferent(Ty<'tcx>, Span),
405 /// Comparing the signature and requirements of an impl method against
406 /// the containing trait.
407 CompareImplItemObligation {
409 impl_item_def_id: LocalDefId,
410 trait_item_def_id: DefId,
413 /// Checking that the bounds of a trait's associated type hold for a given impl
414 CheckAssociatedTypeBounds {
415 parent: Box<SubregionOrigin<'tcx>>,
416 impl_item_def_id: LocalDefId,
417 trait_item_def_id: DefId,
420 AscribeUserTypeProvePredicate(Span),
423 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
424 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
425 static_assert_size!(SubregionOrigin<'_>, 32);
427 impl<'tcx> SubregionOrigin<'tcx> {
428 pub fn to_constraint_category(&self) -> ConstraintCategory {
430 Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
431 Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
432 _ => ConstraintCategory::BoringNoLocation,
437 /// Times when we replace late-bound regions with variables:
438 #[derive(Clone, Copy, Debug)]
439 pub enum LateBoundRegionConversionTime {
440 /// when a fn is called
443 /// when two higher-ranked types are compared
446 /// when projecting an associated type
447 AssocTypeProjection(DefId),
450 /// Reasons to create a region inference variable
452 /// See `error_reporting` module for more details
453 #[derive(Copy, Clone, Debug)]
454 pub enum RegionVariableOrigin {
455 /// Region variables created for ill-categorized reasons,
456 /// mostly indicates places in need of refactoring
459 /// Regions created by a `&P` or `[...]` pattern
462 /// Regions created by `&` operator
465 /// Regions created as part of an autoref of a method receiver
468 /// Regions created as part of an automatic coercion
471 /// Region variables created as the values for early-bound regions
472 EarlyBoundRegion(Span, Symbol),
474 /// Region variables created for bound regions
475 /// in a function or method that is called
476 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
478 UpvarRegion(ty::UpvarId, Span),
480 /// This origin is used for the inference variables that we create
481 /// during NLL region processing.
482 Nll(NllRegionVariableOrigin),
485 #[derive(Copy, Clone, Debug)]
486 pub enum NllRegionVariableOrigin {
487 /// During NLL region processing, we create variables for free
488 /// regions that we encounter in the function signature and
489 /// elsewhere. This origin indices we've got one of those.
492 /// "Universal" instantiation of a higher-ranked region (e.g.,
493 /// from a `for<'a> T` binder). Meant to represent "any region".
494 Placeholder(ty::PlaceholderRegion),
497 /// If this is true, then this variable was created to represent a lifetime
498 /// bound in a `for` binder. For example, it might have been created to
499 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
500 /// Such variables are created when we are trying to figure out if there
501 /// is any valid instantiation of `'a` that could fit into some scenario.
503 /// This is used to inform error reporting: in the case that we are trying to
504 /// determine whether there is any valid instantiation of a `'a` variable that meets
505 /// some constraint C, we want to blame the "source" of that `for` type,
506 /// rather than blaming the source of the constraint C.
511 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
512 #[derive(Copy, Clone, Debug)]
513 pub enum FixupError<'tcx> {
514 UnresolvedIntTy(IntVid),
515 UnresolvedFloatTy(FloatVid),
517 UnresolvedConst(ConstVid<'tcx>),
520 /// See the `region_obligations` field for more information.
521 #[derive(Clone, Debug)]
522 pub struct RegionObligation<'tcx> {
523 pub sub_region: ty::Region<'tcx>,
524 pub sup_type: Ty<'tcx>,
525 pub origin: SubregionOrigin<'tcx>,
528 impl<'tcx> fmt::Display for FixupError<'tcx> {
529 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530 use self::FixupError::*;
533 UnresolvedIntTy(_) => write!(
535 "cannot determine the type of this integer; \
536 add a suffix to specify the type explicitly"
538 UnresolvedFloatTy(_) => write!(
540 "cannot determine the type of this number; \
541 add a suffix to specify the type explicitly"
543 UnresolvedTy(_) => write!(f, "unconstrained type"),
544 UnresolvedConst(_) => write!(f, "unconstrained const value"),
549 /// Used to configure inference contexts before their creation
550 pub struct InferCtxtBuilder<'tcx> {
552 defining_use_anchor: DefiningAnchor,
553 considering_regions: bool,
554 normalize_fn_sig_for_diagnostic:
555 Option<Lrc<dyn Fn(&InferCtxt<'tcx>, ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx>>>,
558 pub trait TyCtxtInferExt<'tcx> {
559 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
562 impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
563 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
566 defining_use_anchor: DefiningAnchor::Error,
567 considering_regions: true,
568 normalize_fn_sig_for_diagnostic: None,
573 impl<'tcx> InferCtxtBuilder<'tcx> {
574 /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
575 /// you need to call this function. Otherwise the opaque type will be treated opaquely.
577 /// It is only meant to be called in two places, for typeck
578 /// (via `Inherited::build`) and for the inference context used
580 pub fn with_opaque_type_inference(mut self, defining_use_anchor: DefiningAnchor) -> Self {
581 self.defining_use_anchor = defining_use_anchor;
585 pub fn ignoring_regions(mut self) -> Self {
586 self.considering_regions = false;
590 pub fn with_normalize_fn_sig_for_diagnostic(
592 fun: Lrc<dyn Fn(&InferCtxt<'tcx>, ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx>>,
594 self.normalize_fn_sig_for_diagnostic = Some(fun);
598 /// Given a canonical value `C` as a starting point, create an
599 /// inference context that contains each of the bound values
600 /// within instantiated as a fresh variable. The `f` closure is
601 /// invoked with the new infcx, along with the instantiated value
602 /// `V` and a substitution `S`. This substitution `S` maps from
603 /// the bound values in `C` to their instantiated values in `V`
604 /// (in other words, `S(C) = V`).
605 pub fn build_with_canonical<T>(
608 canonical: &Canonical<'tcx, T>,
609 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
611 T: TypeFoldable<'tcx>,
613 let infcx = self.build();
614 let (value, subst) = infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
615 (infcx, value, subst)
618 pub fn build(&mut self) -> InferCtxt<'tcx> {
619 let InferCtxtBuilder {
623 ref normalize_fn_sig_for_diagnostic,
629 inner: RefCell::new(InferCtxtInner::new()),
630 lexical_region_resolutions: RefCell::new(None),
631 selection_cache: Default::default(),
632 evaluation_cache: Default::default(),
633 reported_trait_errors: Default::default(),
634 reported_closure_mismatch: Default::default(),
635 tainted_by_errors: Cell::new(None),
636 err_count_on_creation: tcx.sess.err_count(),
637 in_snapshot: Cell::new(false),
638 skip_leak_check: Cell::new(false),
639 universe: Cell::new(ty::UniverseIndex::ROOT),
640 normalize_fn_sig_for_diagnostic: normalize_fn_sig_for_diagnostic
647 impl<'tcx, T> InferOk<'tcx, T> {
648 pub fn unit(self) -> InferOk<'tcx, ()> {
649 InferOk { value: (), obligations: self.obligations }
652 /// Extracts `value`, registering any obligations into `fulfill_cx`.
653 pub fn into_value_registering_obligations(
655 infcx: &InferCtxt<'tcx>,
656 fulfill_cx: &mut dyn TraitEngine<'tcx>,
658 let InferOk { value, obligations } = self;
659 fulfill_cx.register_predicate_obligations(infcx, obligations);
664 impl<'tcx> InferOk<'tcx, ()> {
665 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
670 #[must_use = "once you start a snapshot, you should always consume it"]
671 pub struct CombinedSnapshot<'tcx> {
672 undo_snapshot: Snapshot<'tcx>,
673 region_constraints_snapshot: RegionSnapshot,
674 universe: ty::UniverseIndex,
675 was_in_snapshot: bool,
678 impl<'tcx> InferCtxt<'tcx> {
679 /// Creates a `TypeErrCtxt` for emitting various inference errors.
680 /// During typeck, use `FnCtxt::infer_err` instead.
681 pub fn err_ctxt(&self) -> TypeErrCtxt<'_, 'tcx> {
682 TypeErrCtxt { infcx: self, typeck_results: None }
685 /// calls `tcx.try_unify_abstract_consts` after
686 /// canonicalizing the consts.
687 #[instrument(skip(self), level = "debug")]
688 pub fn try_unify_abstract_consts(
690 a: ty::UnevaluatedConst<'tcx>,
691 b: ty::UnevaluatedConst<'tcx>,
692 param_env: ty::ParamEnv<'tcx>,
694 // Reject any attempt to unify two unevaluated constants that contain inference
695 // variables, since inference variables in queries lead to ICEs.
696 if a.substs.has_non_region_infer()
697 || b.substs.has_non_region_infer()
698 || param_env.has_non_region_infer()
700 debug!("a or b or param_env contain infer vars in its substs -> cannot unify");
704 let param_env_and = param_env.and((a, b));
705 let erased = self.tcx.erase_regions(param_env_and);
706 debug!("after erase_regions: {:?}", erased);
708 self.tcx.try_unify_abstract_consts(erased)
711 pub fn is_in_snapshot(&self) -> bool {
712 self.in_snapshot.get()
715 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
716 t.fold_with(&mut self.freshener())
719 /// Returns the origin of the type variable identified by `vid`, or `None`
720 /// if this is not a type variable.
722 /// No attempt is made to resolve `ty`.
723 pub fn type_var_origin(&self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
725 ty::Infer(ty::TyVar(vid)) => {
726 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
732 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
733 freshen::TypeFreshener::new(self, false)
736 /// Like `freshener`, but does not replace `'static` regions.
737 pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
738 freshen::TypeFreshener::new(self, true)
741 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
742 let mut inner = self.inner.borrow_mut();
743 let mut vars: Vec<Ty<'_>> = inner
745 .unsolved_variables()
747 .map(|t| self.tcx.mk_ty_var(t))
750 (0..inner.int_unification_table().len())
751 .map(|i| ty::IntVid { index: i as u32 })
752 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
753 .map(|v| self.tcx.mk_int_var(v)),
756 (0..inner.float_unification_table().len())
757 .map(|i| ty::FloatVid { index: i as u32 })
758 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
759 .map(|v| self.tcx.mk_float_var(v)),
764 fn combine_fields<'a>(
766 trace: TypeTrace<'tcx>,
767 param_env: ty::ParamEnv<'tcx>,
768 define_opaque_types: bool,
769 ) -> CombineFields<'a, 'tcx> {
775 obligations: PredicateObligations::new(),
780 /// Clear the "currently in a snapshot" flag, invoke the closure,
781 /// then restore the flag to its original value. This flag is a
782 /// debugging measure designed to detect cases where we start a
783 /// snapshot, create type variables, and register obligations
784 /// which may involve those type variables in the fulfillment cx,
785 /// potentially leaving "dangling type variables" behind.
786 /// In such cases, an assertion will fail when attempting to
787 /// register obligations, within a snapshot. Very useful, much
788 /// better than grovelling through megabytes of `RUSTC_LOG` output.
790 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
791 /// sometimes create a "mini-fulfilment-cx" in which we enroll
792 /// obligations. As long as this fulfillment cx is fully drained
793 /// before we return, this is not a problem, as there won't be any
794 /// escaping obligations in the main cx. In those cases, you can
795 /// use this function.
796 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
798 F: FnOnce(&Self) -> R,
800 let flag = self.in_snapshot.replace(false);
801 let result = func(self);
802 self.in_snapshot.set(flag);
806 fn start_snapshot(&self) -> CombinedSnapshot<'tcx> {
807 debug!("start_snapshot()");
809 let in_snapshot = self.in_snapshot.replace(true);
811 let mut inner = self.inner.borrow_mut();
814 undo_snapshot: inner.undo_log.start_snapshot(),
815 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
816 universe: self.universe(),
817 was_in_snapshot: in_snapshot,
821 #[instrument(skip(self, snapshot), level = "debug")]
822 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'tcx>) {
823 let CombinedSnapshot {
825 region_constraints_snapshot,
830 self.in_snapshot.set(was_in_snapshot);
831 self.universe.set(universe);
833 let mut inner = self.inner.borrow_mut();
834 inner.rollback_to(undo_snapshot);
835 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
838 #[instrument(skip(self, snapshot), level = "debug")]
839 fn commit_from(&self, snapshot: CombinedSnapshot<'tcx>) {
840 let CombinedSnapshot {
842 region_constraints_snapshot: _,
847 self.in_snapshot.set(was_in_snapshot);
849 self.inner.borrow_mut().commit(undo_snapshot);
852 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
853 #[instrument(skip(self, f), level = "debug")]
854 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
856 F: FnOnce(&CombinedSnapshot<'tcx>) -> Result<T, E>,
858 let snapshot = self.start_snapshot();
859 let r = f(&snapshot);
860 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
863 self.commit_from(snapshot);
866 self.rollback_to("commit_if_ok -- error", snapshot);
872 /// Execute `f` then unroll any bindings it creates.
873 #[instrument(skip(self, f), level = "debug")]
874 pub fn probe<R, F>(&self, f: F) -> R
876 F: FnOnce(&CombinedSnapshot<'tcx>) -> R,
878 let snapshot = self.start_snapshot();
879 let r = f(&snapshot);
880 self.rollback_to("probe", snapshot);
884 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
885 #[instrument(skip(self, f), level = "debug")]
886 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
888 F: FnOnce(&CombinedSnapshot<'tcx>) -> R,
890 let snapshot = self.start_snapshot();
891 let was_skip_leak_check = self.skip_leak_check.get();
893 self.skip_leak_check.set(true);
895 let r = f(&snapshot);
896 self.rollback_to("probe", snapshot);
897 self.skip_leak_check.set(was_skip_leak_check);
901 /// Scan the constraints produced since `snapshot` began and returns:
903 /// - `None` -- if none of them involve "region outlives" constraints
904 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
905 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
906 pub fn region_constraints_added_in_snapshot(
908 snapshot: &CombinedSnapshot<'tcx>,
912 .unwrap_region_constraints()
913 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
916 pub fn opaque_types_added_in_snapshot(&self, snapshot: &CombinedSnapshot<'tcx>) -> bool {
917 self.inner.borrow().undo_log.opaque_types_in_snapshot(&snapshot.undo_snapshot)
920 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
921 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
924 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
926 T: at::ToTrace<'tcx>,
928 let origin = &ObligationCause::dummy();
930 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
931 // Ignore obligations, since we are unrolling
932 // everything anyway.
937 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
939 T: at::ToTrace<'tcx>,
941 let origin = &ObligationCause::dummy();
943 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
944 // Ignore obligations, since we are unrolling
945 // everything anyway.
950 #[instrument(skip(self), level = "debug")]
953 origin: SubregionOrigin<'tcx>,
957 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
960 /// Require that the region `r` be equal to one of the regions in
961 /// the set `regions`.
962 #[instrument(skip(self), level = "debug")]
963 pub fn member_constraint(
965 key: ty::OpaqueTypeKey<'tcx>,
966 definition_span: Span,
968 region: ty::Region<'tcx>,
969 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
971 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
980 /// Processes a `Coerce` predicate from the fulfillment context.
981 /// This is NOT the preferred way to handle coercion, which is to
982 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
984 /// This method here is actually a fallback that winds up being
985 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
986 /// and records a coercion predicate. Presently, this method is equivalent
987 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
988 /// actually requiring `a <: b`. This is of course a valid coercion,
989 /// but it's not as flexible as `FnCtxt::coerce` would be.
991 /// (We may refactor this in the future, but there are a number of
992 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
993 /// records adjustments that are required on the HIR in order to perform
994 /// the coercion, and we don't currently have a way to manage that.)
995 pub fn coerce_predicate(
997 cause: &ObligationCause<'tcx>,
998 param_env: ty::ParamEnv<'tcx>,
999 predicate: ty::PolyCoercePredicate<'tcx>,
1000 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
1001 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
1002 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
1006 self.subtype_predicate(cause, param_env, subtype_predicate)
1009 pub fn subtype_predicate(
1011 cause: &ObligationCause<'tcx>,
1012 param_env: ty::ParamEnv<'tcx>,
1013 predicate: ty::PolySubtypePredicate<'tcx>,
1014 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
1015 // Check for two unresolved inference variables, in which case we can
1016 // make no progress. This is partly a micro-optimization, but it's
1017 // also an opportunity to "sub-unify" the variables. This isn't
1018 // *necessary* to prevent cycles, because they would eventually be sub-unified
1019 // anyhow during generalization, but it helps with diagnostics (we can detect
1020 // earlier that they are sub-unified).
1022 // Note that we can just skip the binders here because
1023 // type variables can't (at present, at
1024 // least) capture any of the things bound by this binder.
1026 // Note that this sub here is not just for diagnostics - it has semantic
1028 let r_a = self.shallow_resolve(predicate.skip_binder().a);
1029 let r_b = self.shallow_resolve(predicate.skip_binder().b);
1030 match (r_a.kind(), r_b.kind()) {
1031 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
1032 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
1033 return Err((a_vid, b_vid));
1038 Ok(self.commit_if_ok(|_snapshot| {
1039 let ty::SubtypePredicate { a_is_expected, a, b } =
1040 self.replace_bound_vars_with_placeholders(predicate);
1042 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1048 pub fn region_outlives_predicate(
1050 cause: &traits::ObligationCause<'tcx>,
1051 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1053 let ty::OutlivesPredicate(r_a, r_b) = self.replace_bound_vars_with_placeholders(predicate);
1055 SubregionOrigin::from_obligation_cause(cause, || RelateRegionParamBound(cause.span));
1056 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1059 /// Number of type variables created so far.
1060 pub fn num_ty_vars(&self) -> usize {
1061 self.inner.borrow_mut().type_variables().num_vars()
1064 pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1065 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1068 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1069 self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1072 pub fn next_ty_var_id_in_universe(
1074 origin: TypeVariableOrigin,
1075 universe: ty::UniverseIndex,
1077 self.inner.borrow_mut().type_variables().new_var(universe, origin)
1080 pub fn next_ty_var_in_universe(
1082 origin: TypeVariableOrigin,
1083 universe: ty::UniverseIndex,
1085 let vid = self.next_ty_var_id_in_universe(origin, universe);
1086 self.tcx.mk_ty_var(vid)
1089 pub fn next_const_var(&self, ty: Ty<'tcx>, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
1090 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1093 pub fn next_const_var_in_universe(
1096 origin: ConstVariableOrigin,
1097 universe: ty::UniverseIndex,
1098 ) -> ty::Const<'tcx> {
1102 .const_unification_table()
1103 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1104 self.tcx.mk_const_var(vid, ty)
1107 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1108 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1110 val: ConstVariableValue::Unknown { universe: self.universe() },
1114 fn next_int_var_id(&self) -> IntVid {
1115 self.inner.borrow_mut().int_unification_table().new_key(None)
1118 pub fn next_int_var(&self) -> Ty<'tcx> {
1119 self.tcx.mk_int_var(self.next_int_var_id())
1122 fn next_float_var_id(&self) -> FloatVid {
1123 self.inner.borrow_mut().float_unification_table().new_key(None)
1126 pub fn next_float_var(&self) -> Ty<'tcx> {
1127 self.tcx.mk_float_var(self.next_float_var_id())
1130 /// Creates a fresh region variable with the next available index.
1131 /// The variable will be created in the maximum universe created
1132 /// thus far, allowing it to name any region created thus far.
1133 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1134 self.next_region_var_in_universe(origin, self.universe())
1137 /// Creates a fresh region variable with the next available index
1138 /// in the given universe; typically, you can use
1139 /// `next_region_var` and just use the maximal universe.
1140 pub fn next_region_var_in_universe(
1142 origin: RegionVariableOrigin,
1143 universe: ty::UniverseIndex,
1144 ) -> ty::Region<'tcx> {
1146 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1147 self.tcx.mk_region(ty::ReVar(region_var))
1150 /// Return the universe that the region `r` was created in. For
1151 /// most regions (e.g., `'static`, named regions from the user,
1152 /// etc) this is the root universe U0. For inference variables or
1153 /// placeholders, however, it will return the universe which they
1155 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1156 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1159 /// Number of region variables created so far.
1160 pub fn num_region_vars(&self) -> usize {
1161 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1164 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1165 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1166 self.next_region_var(RegionVariableOrigin::Nll(origin))
1169 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1170 pub fn next_nll_region_var_in_universe(
1172 origin: NllRegionVariableOrigin,
1173 universe: ty::UniverseIndex,
1174 ) -> ty::Region<'tcx> {
1175 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1178 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1180 GenericParamDefKind::Lifetime => {
1181 // Create a region inference variable for the given
1182 // region parameter definition.
1183 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1185 GenericParamDefKind::Type { .. } => {
1186 // Create a type inference variable for the given
1187 // type parameter definition. The substitutions are
1188 // for actual parameters that may be referred to by
1189 // the default of this type parameter, if it exists.
1190 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1191 // used in a path such as `Foo::<T, U>::new()` will
1192 // use an inference variable for `C` with `[T, U]`
1193 // as the substitutions for the default, `(T, U)`.
1194 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1196 TypeVariableOrigin {
1197 kind: TypeVariableOriginKind::TypeParameterDefinition(
1205 self.tcx.mk_ty_var(ty_var_id).into()
1207 GenericParamDefKind::Const { .. } => {
1208 let origin = ConstVariableOrigin {
1209 kind: ConstVariableOriginKind::ConstParameterDefinition(
1216 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1218 val: ConstVariableValue::Unknown { universe: self.universe() },
1220 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1225 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1226 /// type/region parameter to a fresh inference variable.
1227 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1228 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1231 /// Returns `true` if errors have been reported since this infcx was
1232 /// created. This is sometimes used as a heuristic to skip
1233 /// reporting errors that often occur as a result of earlier
1234 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1235 /// inference variables, regionck errors).
1236 pub fn is_tainted_by_errors(&self) -> bool {
1238 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1239 tainted_by_errors={})",
1240 self.tcx.sess.err_count(),
1241 self.err_count_on_creation,
1242 self.tainted_by_errors.get().is_some()
1245 if self.tcx.sess.err_count() > self.err_count_on_creation {
1246 return true; // errors reported since this infcx was made
1248 self.tainted_by_errors.get().is_some()
1251 /// Set the "tainted by errors" flag to true. We call this when we
1252 /// observe an error from a prior pass.
1253 pub fn set_tainted_by_errors(&self) {
1254 debug!("set_tainted_by_errors()");
1255 self.tainted_by_errors.set(Some(
1256 self.tcx.sess.delay_span_bug(DUMMY_SP, "`InferCtxt` incorrectly tainted by errors"),
1260 pub fn skip_region_resolution(&self) {
1261 let (var_infos, _) = {
1262 let mut inner = self.inner.borrow_mut();
1263 let inner = &mut *inner;
1264 // Note: `inner.region_obligations` may not be empty, because we
1265 // didn't necessarily call `process_registered_region_obligations`.
1266 // This is okay, because that doesn't introduce new vars.
1268 .region_constraint_storage
1270 .expect("regions already resolved")
1271 .with_log(&mut inner.undo_log)
1272 .into_infos_and_data()
1275 let lexical_region_resolutions = LexicalRegionResolutions {
1276 values: rustc_index::vec::IndexVec::from_elem_n(
1277 crate::infer::lexical_region_resolve::VarValue::Value(self.tcx.lifetimes.re_erased),
1282 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1283 assert!(old_value.is_none());
1286 /// Process the region constraints and return any errors that
1287 /// result. After this, no more unification operations should be
1288 /// done -- or the compiler will panic -- but it is legal to use
1289 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1290 pub fn resolve_regions(
1292 outlives_env: &OutlivesEnvironment<'tcx>,
1293 ) -> Vec<RegionResolutionError<'tcx>> {
1294 let (var_infos, data) = {
1295 let mut inner = self.inner.borrow_mut();
1296 let inner = &mut *inner;
1298 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1299 "region_obligations not empty: {:#?}",
1300 inner.region_obligations
1303 .region_constraint_storage
1305 .expect("regions already resolved")
1306 .with_log(&mut inner.undo_log)
1307 .into_infos_and_data()
1310 let region_rels = &RegionRelations::new(self.tcx, outlives_env.free_region_map());
1312 let (lexical_region_resolutions, errors) =
1313 lexical_region_resolve::resolve(outlives_env.param_env, region_rels, var_infos, data);
1315 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1316 assert!(old_value.is_none());
1320 /// Obtains (and clears) the current set of region
1321 /// constraints. The inference context is still usable: further
1322 /// unifications will simply add new constraints.
1324 /// This method is not meant to be used with normal lexical region
1325 /// resolution. Rather, it is used in the NLL mode as a kind of
1326 /// interim hack: basically we run normal type-check and generate
1327 /// region constraints as normal, but then we take them and
1328 /// translate them into the form that the NLL solver
1329 /// understands. See the NLL module for mode details.
1330 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1332 self.inner.borrow().region_obligations.is_empty(),
1333 "region_obligations not empty: {:#?}",
1334 self.inner.borrow().region_obligations
1337 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1340 /// Gives temporary access to the region constraint data.
1341 pub fn with_region_constraints<R>(
1343 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1345 let mut inner = self.inner.borrow_mut();
1346 op(inner.unwrap_region_constraints().data())
1349 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1350 let mut inner = self.inner.borrow_mut();
1351 let inner = &mut *inner;
1353 .region_constraint_storage
1355 .expect("regions already resolved")
1356 .with_log(&mut inner.undo_log)
1360 /// Takes ownership of the list of variable regions. This implies
1361 /// that all the region constraints have already been taken, and
1362 /// hence that `resolve_regions_and_report_errors` can never be
1363 /// called. This is used only during NLL processing to "hand off" ownership
1364 /// of the set of region variables into the NLL region context.
1365 pub fn take_region_var_origins(&self) -> VarInfos {
1366 let mut inner = self.inner.borrow_mut();
1367 let (var_infos, data) = inner
1368 .region_constraint_storage
1370 .expect("regions already resolved")
1371 .with_log(&mut inner.undo_log)
1372 .into_infos_and_data();
1373 assert!(data.is_empty());
1377 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1378 self.resolve_vars_if_possible(t).to_string()
1381 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1382 /// universe index of `TyVar(vid)`.
1383 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1384 use self::type_variable::TypeVariableValue;
1386 match self.inner.borrow_mut().type_variables().probe(vid) {
1387 TypeVariableValue::Known { value } => Ok(value),
1388 TypeVariableValue::Unknown { universe } => Err(universe),
1392 /// Resolve any type variables found in `value` -- but only one
1393 /// level. So, if the variable `?X` is bound to some type
1394 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1395 /// itself be bound to a type).
1397 /// Useful when you only need to inspect the outermost level of
1398 /// the type and don't care about nested types (or perhaps you
1399 /// will be resolving them as well, e.g. in a loop).
1400 pub fn shallow_resolve<T>(&self, value: T) -> T
1402 T: TypeFoldable<'tcx>,
1404 value.fold_with(&mut ShallowResolver { infcx: self })
1407 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1408 self.inner.borrow_mut().type_variables().root_var(var)
1411 /// Where possible, replaces type/const variables in
1412 /// `value` with their final value. Note that region variables
1413 /// are unaffected. If a type/const variable has not been unified, it
1414 /// is left as is. This is an idempotent operation that does
1415 /// not affect inference state in any way and so you can do it
1417 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1419 T: TypeFoldable<'tcx>,
1421 if !value.needs_infer() {
1422 return value; // Avoid duplicated subst-folding.
1424 let mut r = resolve::OpportunisticVarResolver::new(self);
1425 value.fold_with(&mut r)
1428 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1430 T: TypeFoldable<'tcx>,
1432 if !value.needs_infer() {
1433 return value; // Avoid duplicated subst-folding.
1435 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1436 value.fold_with(&mut r)
1439 /// Returns the first unresolved variable contained in `T`. In the
1440 /// process of visiting `T`, this will resolve (where possible)
1441 /// type variables in `T`, but it never constructs the final,
1442 /// resolved type, so it's more efficient than
1443 /// `resolve_vars_if_possible()`.
1444 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1446 T: TypeVisitable<'tcx>,
1448 value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1451 pub fn probe_const_var(
1453 vid: ty::ConstVid<'tcx>,
1454 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1455 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1456 ConstVariableValue::Known { value } => Ok(value),
1457 ConstVariableValue::Unknown { universe } => Err(universe),
1461 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1463 * Attempts to resolve all type/region/const variables in
1464 * `value`. Region inference must have been run already (e.g.,
1465 * by calling `resolve_regions_and_report_errors`). If some
1466 * variable was never unified, an `Err` results.
1468 * This method is idempotent, but it not typically not invoked
1469 * except during the writeback phase.
1472 resolve::fully_resolve(self, value)
1475 pub fn replace_bound_vars_with_fresh_vars<T>(
1478 lbrct: LateBoundRegionConversionTime,
1479 value: ty::Binder<'tcx, T>,
1482 T: TypeFoldable<'tcx> + Copy,
1484 if let Some(inner) = value.no_bound_vars() {
1488 struct ToFreshVars<'a, 'tcx> {
1489 infcx: &'a InferCtxt<'tcx>,
1491 lbrct: LateBoundRegionConversionTime,
1492 map: FxHashMap<ty::BoundVar, ty::GenericArg<'tcx>>,
1495 impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'_, 'tcx> {
1496 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1499 .or_insert_with(|| {
1501 .next_region_var(LateBoundRegion(self.span, br.kind, self.lbrct))
1506 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1509 .or_insert_with(|| {
1511 .next_ty_var(TypeVariableOrigin {
1512 kind: TypeVariableOriginKind::MiscVariable,
1519 fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> {
1522 .or_insert_with(|| {
1526 ConstVariableOrigin {
1527 kind: ConstVariableOriginKind::MiscVariable,
1536 let delegate = ToFreshVars { infcx: self, span, lbrct, map: Default::default() };
1537 self.tcx.replace_bound_vars_uncached(value, delegate)
1540 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1541 pub fn verify_generic_bound(
1543 origin: SubregionOrigin<'tcx>,
1544 kind: GenericKind<'tcx>,
1545 a: ty::Region<'tcx>,
1546 bound: VerifyBound<'tcx>,
1548 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1552 .unwrap_region_constraints()
1553 .verify_generic_bound(origin, kind, a, bound);
1556 /// Obtains the latest type of the given closure; this may be a
1557 /// closure in the current function, in which case its
1558 /// `ClosureKind` may not yet be known.
1559 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1560 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1561 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1562 closure_kind_ty.to_opt_closure_kind()
1565 /// Clears the selection, evaluation, and projection caches. This is useful when
1566 /// repeatedly attempting to select an `Obligation` while changing only
1567 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1568 pub fn clear_caches(&self) {
1569 self.selection_cache.clear();
1570 self.evaluation_cache.clear();
1571 self.inner.borrow_mut().projection_cache().clear();
1574 pub fn universe(&self) -> ty::UniverseIndex {
1578 /// Creates and return a fresh universe that extends all previous
1579 /// universes. Updates `self.universe` to that new universe.
1580 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1581 let u = self.universe.get().next_universe();
1582 self.universe.set(u);
1586 pub fn try_const_eval_resolve(
1588 param_env: ty::ParamEnv<'tcx>,
1589 unevaluated: ty::UnevaluatedConst<'tcx>,
1592 ) -> Result<ty::Const<'tcx>, ErrorHandled> {
1593 match self.const_eval_resolve(param_env, unevaluated, span) {
1594 Ok(Some(val)) => Ok(ty::Const::from_value(self.tcx, val, ty)),
1597 let def_id = unevaluated.def.did;
1599 tcx.def_span(def_id),
1600 "unable to construct a constant value for the unevaluated constant {:?}",
1604 Err(err) => Err(err),
1608 /// Resolves and evaluates a constant.
1610 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1611 /// substitutions and environment are used to resolve the constant. Alternatively if the
1612 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1613 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1614 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1615 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1618 /// This handles inferences variables within both `param_env` and `substs` by
1619 /// performing the operation on their respective canonical forms.
1620 #[instrument(skip(self), level = "debug")]
1621 pub fn const_eval_resolve(
1623 mut param_env: ty::ParamEnv<'tcx>,
1624 unevaluated: ty::UnevaluatedConst<'tcx>,
1626 ) -> EvalToValTreeResult<'tcx> {
1627 let mut substs = self.resolve_vars_if_possible(unevaluated.substs);
1630 // Postpone the evaluation of constants whose substs depend on inference
1632 if substs.has_non_region_infer() {
1633 let ac = AbstractConst::new(self.tcx, unevaluated);
1636 substs = InternalSubsts::identity_for_item(self.tcx, unevaluated.def.did);
1637 param_env = self.tcx.param_env(unevaluated.def.did);
1640 if ct.unify_failure_kind(self.tcx) == FailureKind::Concrete {
1641 substs = replace_param_and_infer_substs_with_placeholder(self.tcx, substs);
1643 return Err(ErrorHandled::TooGeneric);
1646 Err(guar) => return Err(ErrorHandled::Reported(guar)),
1650 let param_env_erased = self.tcx.erase_regions(param_env);
1651 let substs_erased = self.tcx.erase_regions(substs);
1652 debug!(?param_env_erased);
1653 debug!(?substs_erased);
1655 let unevaluated = ty::UnevaluatedConst { def: unevaluated.def, substs: substs_erased };
1657 // The return value is the evaluated value which doesn't contain any reference to inference
1658 // variables, thus we don't need to substitute back the original values.
1659 self.tcx.const_eval_resolve_for_typeck(param_env_erased, unevaluated, span)
1662 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1663 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1664 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1666 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1667 /// inlined, despite being large, because it has only two call sites that
1668 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1669 /// inference variables), and it handles both `Ty` and `ty::Const` without
1670 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1672 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1674 TyOrConstInferVar::Ty(v) => {
1675 use self::type_variable::TypeVariableValue;
1677 // If `inlined_probe` returns a `Known` value, it never equals
1678 // `ty::Infer(ty::TyVar(v))`.
1679 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1680 TypeVariableValue::Unknown { .. } => false,
1681 TypeVariableValue::Known { .. } => true,
1685 TyOrConstInferVar::TyInt(v) => {
1686 // If `inlined_probe_value` returns a value it's always a
1687 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1689 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1692 TyOrConstInferVar::TyFloat(v) => {
1693 // If `probe_value` returns a value it's always a
1694 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1696 // Not `inlined_probe_value(v)` because this call site is colder.
1697 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1700 TyOrConstInferVar::Const(v) => {
1701 // If `probe_value` returns a `Known` value, it never equals
1702 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1704 // Not `inlined_probe_value(v)` because this call site is colder.
1705 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1706 ConstVariableValue::Unknown { .. } => false,
1707 ConstVariableValue::Known { .. } => true,
1714 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
1715 /// Process the region constraints and report any errors that
1716 /// result. After this, no more unification operations should be
1717 /// done -- or the compiler will panic -- but it is legal to use
1718 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1720 /// Make sure to call [`InferCtxt::process_registered_region_obligations`]
1721 /// first, or preferably use [`InferCtxt::check_region_obligations_and_report_errors`]
1722 /// to do both of these operations together.
1723 pub fn resolve_regions_and_report_errors(
1725 generic_param_scope: LocalDefId,
1726 outlives_env: &OutlivesEnvironment<'tcx>,
1728 let errors = self.resolve_regions(outlives_env);
1730 if !self.is_tainted_by_errors() {
1731 // As a heuristic, just skip reporting region errors
1732 // altogether if other errors have been reported while
1733 // this infcx was in use. This is totally hokey but
1734 // otherwise we have a hard time separating legit region
1735 // errors from silly ones.
1736 self.report_region_errors(generic_param_scope, &errors);
1740 // [Note-Type-error-reporting]
1741 // An invariant is that anytime the expected or actual type is Error (the special
1742 // error type, meaning that an error occurred when typechecking this expression),
1743 // this is a derived error. The error cascaded from another error (that was already
1744 // reported), so it's not useful to display it to the user.
1745 // The following methods implement this logic.
1746 // They check if either the actual or expected type is Error, and don't print the error
1747 // in this case. The typechecker should only ever report type errors involving mismatched
1748 // types using one of these methods, and should not call span_err directly for such
1751 pub fn type_error_struct_with_diag<M>(
1755 actual_ty: Ty<'tcx>,
1756 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>
1758 M: FnOnce(String) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1760 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1761 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1763 let mut err = mk_diag(self.ty_to_string(actual_ty));
1765 // Don't report an error if actual type is `Error`.
1766 if actual_ty.references_error() {
1767 err.downgrade_to_delayed_bug();
1773 pub fn report_mismatched_types(
1775 cause: &ObligationCause<'tcx>,
1778 err: TypeError<'tcx>,
1779 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1780 self.report_and_explain_type_error(TypeTrace::types(cause, true, expected, actual), err)
1783 pub fn report_mismatched_consts(
1785 cause: &ObligationCause<'tcx>,
1786 expected: ty::Const<'tcx>,
1787 actual: ty::Const<'tcx>,
1788 err: TypeError<'tcx>,
1789 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1790 self.report_and_explain_type_error(TypeTrace::consts(cause, true, expected, actual), err)
1794 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1795 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1796 #[derive(Copy, Clone, Debug)]
1797 pub enum TyOrConstInferVar<'tcx> {
1798 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1800 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1802 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1805 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1806 Const(ConstVid<'tcx>),
1809 impl<'tcx> TyOrConstInferVar<'tcx> {
1810 /// Tries to extract an inference variable from a type or a constant, returns `None`
1811 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1812 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1813 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1814 match arg.unpack() {
1815 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1816 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1817 GenericArgKind::Lifetime(_) => None,
1821 /// Tries to extract an inference variable from a type, returns `None`
1822 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1823 fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1825 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1826 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1827 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1832 /// Tries to extract an inference variable from a constant, returns `None`
1833 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1834 fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1836 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1842 /// Replace `{integer}` with `i32` and `{float}` with `f64`.
1843 /// Used only for diagnostics.
1844 struct InferenceLiteralEraser<'tcx> {
1848 impl<'tcx> TypeFolder<'tcx> for InferenceLiteralEraser<'tcx> {
1849 fn tcx(&self) -> TyCtxt<'tcx> {
1853 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1855 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1856 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1857 _ => ty.super_fold_with(self),
1862 struct ShallowResolver<'a, 'tcx> {
1863 infcx: &'a InferCtxt<'tcx>,
1866 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1867 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1871 /// If `ty` is a type variable of some kind, resolve it one level
1872 /// (but do not resolve types found in the result). If `typ` is
1873 /// not a type variable, just return it unmodified.
1874 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1876 ty::Infer(ty::TyVar(v)) => {
1877 // Not entirely obvious: if `typ` is a type variable,
1878 // it can be resolved to an int/float variable, which
1879 // can then be recursively resolved, hence the
1880 // recursion. Note though that we prevent type
1881 // variables from unifying to other type variables
1882 // directly (though they may be embedded
1883 // structurally), and we prevent cycles in any case,
1884 // so this recursion should always be of very limited
1887 // Note: if these two lines are combined into one we get
1888 // dynamic borrow errors on `self.inner`.
1889 let known = self.infcx.inner.borrow_mut().type_variables().probe(v).known();
1890 known.map_or(ty, |t| self.fold_ty(t))
1893 ty::Infer(ty::IntVar(v)) => self
1897 .int_unification_table()
1899 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1901 ty::Infer(ty::FloatVar(v)) => self
1905 .float_unification_table()
1907 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1913 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1914 if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
1918 .const_unification_table()
1929 impl<'tcx> TypeTrace<'tcx> {
1930 pub fn span(&self) -> Span {
1935 cause: &ObligationCause<'tcx>,
1936 a_is_expected: bool,
1939 ) -> TypeTrace<'tcx> {
1941 cause: cause.clone(),
1942 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1946 pub fn poly_trait_refs(
1947 cause: &ObligationCause<'tcx>,
1948 a_is_expected: bool,
1949 a: ty::PolyTraitRef<'tcx>,
1950 b: ty::PolyTraitRef<'tcx>,
1951 ) -> TypeTrace<'tcx> {
1953 cause: cause.clone(),
1954 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1959 cause: &ObligationCause<'tcx>,
1960 a_is_expected: bool,
1963 ) -> TypeTrace<'tcx> {
1965 cause: cause.clone(),
1966 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1971 impl<'tcx> SubregionOrigin<'tcx> {
1972 pub fn span(&self) -> Span {
1974 Subtype(ref a) => a.span(),
1975 RelateObjectBound(a) => a,
1976 RelateParamBound(a, ..) => a,
1977 RelateRegionParamBound(a) => a,
1979 ReborrowUpvar(a, _) => a,
1980 DataBorrowed(_, a) => a,
1981 ReferenceOutlivesReferent(_, a) => a,
1982 CompareImplItemObligation { span, .. } => span,
1983 AscribeUserTypeProvePredicate(span) => span,
1984 CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1988 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1990 F: FnOnce() -> Self,
1992 match *cause.code() {
1993 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1994 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1997 traits::ObligationCauseCode::CompareImplItemObligation {
2001 } => SubregionOrigin::CompareImplItemObligation {
2007 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
2010 } => SubregionOrigin::CheckAssociatedTypeBounds {
2013 parent: Box::new(default()),
2016 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
2017 SubregionOrigin::AscribeUserTypeProvePredicate(span)
2025 impl RegionVariableOrigin {
2026 pub fn span(&self) -> Span {
2033 | EarlyBoundRegion(a, ..)
2034 | LateBoundRegion(a, ..)
2035 | UpvarRegion(_, a) => a,
2036 Nll(..) => bug!("NLL variable used with `span`"),
2041 /// Replaces substs that reference param or infer variables with suitable
2042 /// placeholders. This function is meant to remove these param and infer
2043 /// substs when they're not actually needed to evaluate a constant.
2044 fn replace_param_and_infer_substs_with_placeholder<'tcx>(
2046 substs: SubstsRef<'tcx>,
2047 ) -> SubstsRef<'tcx> {
2048 tcx.mk_substs(substs.iter().enumerate().map(|(idx, arg)| {
2049 match arg.unpack() {
2050 GenericArgKind::Type(_) if arg.has_non_region_param() || arg.has_non_region_infer() => {
2051 tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
2052 universe: ty::UniverseIndex::ROOT,
2053 name: ty::BoundVar::from_usize(idx),
2057 GenericArgKind::Const(ct) if ct.has_non_region_infer() || ct.has_non_region_param() => {
2059 // If the type references param or infer, replace that too...
2060 if ty.has_non_region_param() || ty.has_non_region_infer() {
2061 bug!("const `{ct}`'s type should not reference params or types");
2063 tcx.mk_const(ty::ConstS {
2065 kind: ty::ConstKind::Placeholder(ty::PlaceholderConst {
2066 universe: ty::UniverseIndex::ROOT,
2067 name: ty::BoundVar::from_usize(idx),