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::OpaqueTypeMap;
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};
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_session::config::BorrowckMode;
33 use rustc_span::symbol::Symbol;
36 use std::cell::{Cell, Ref, RefCell};
37 use std::collections::BTreeMap;
40 use self::combine::CombineFields;
41 use self::free_regions::RegionRelations;
42 use self::lexical_region_resolve::LexicalRegionResolutions;
43 use self::outlives::env::OutlivesEnvironment;
44 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
45 use self::region_constraints::{
46 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
48 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
54 pub mod error_reporting;
61 mod lexical_region_resolve;
67 pub mod region_constraints;
70 pub mod type_variable;
73 pub use rustc_middle::infer::unify_key;
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 /// How we should handle region solving.
93 /// This is used so that the region values inferred by HIR region solving are
94 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
95 /// typeck will also do.
96 #[derive(Copy, Clone, Debug, Default)]
97 pub enum RegionckMode {
98 /// The default mode: report region errors, don't erase regions.
101 /// Erase the results of region after solving.
103 /// A flag that is used to suppress region errors, when we are doing
104 /// region checks that the NLL borrow checker will also do -- it might
106 suppress_errors: bool,
111 /// Indicates that the MIR borrowck will repeat these region
112 /// checks, so we should ignore errors if NLL is (unconditionally)
114 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
115 // FIXME(Centril): Once we actually remove `::Migrate` also make
116 // this always `true` and then proceed to eliminate the dead code.
117 match tcx.borrowck_mode() {
118 // If we're on Migrate mode, report AST region errors
119 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
121 // If we're on MIR, don't report AST region errors as they should be reported by NLL
122 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
127 /// This type contains all the things within `InferCtxt` that sit within a
128 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
129 /// operations are hot enough that we want only one call to `borrow_mut` per
130 /// call to `start_snapshot` and `rollback_to`.
132 pub struct InferCtxtInner<'tcx> {
133 /// Cache for projections. This cache is snapshotted along with the infcx.
135 /// Public so that `traits::project` can use it.
136 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
138 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
139 /// that might instantiate a general type variable have an order,
140 /// represented by its upper and lower bounds.
141 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
143 /// Map from const parameter variable to the kind of const it represents.
144 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
146 /// Map from integral variable to the kind of integer it represents.
147 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
149 /// Map from floating variable to the kind of float it represents.
150 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
152 /// Tracks the set of region variables and the constraints between them.
153 /// This is initially `Some(_)` but when
154 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
155 /// -- further attempts to perform unification, etc., may fail if new
156 /// region constraints would've been added.
157 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
159 /// A set of constraints that regionck must validate. Each
160 /// constraint has the form `T:'a`, meaning "some type `T` must
161 /// outlive the lifetime 'a". These constraints derive from
162 /// instantiated type parameters. So if you had a struct defined
165 /// struct Foo<T:'static> { ... }
167 /// then in some expression `let x = Foo { ... }` it will
168 /// instantiate the type parameter `T` with a fresh type `$0`. At
169 /// the same time, it will record a region obligation of
170 /// `$0:'static`. This will get checked later by regionck. (We
171 /// can't generally check these things right away because we have
172 /// to wait until types are resolved.)
174 /// These are stored in a map keyed to the id of the innermost
175 /// enclosing fn body / static initializer expression. This is
176 /// because the location where the obligation was incurred can be
177 /// relevant with respect to which sublifetime assumptions are in
178 /// place. The reason that we store under the fn-id, and not
179 /// something more fine-grained, is so that it is easier for
180 /// regionck to be sure that it has found *all* the region
181 /// obligations (otherwise, it's easy to fail to walk to a
182 /// particular node-id).
184 /// Before running `resolve_regions_and_report_errors`, the creator
185 /// of the inference context is expected to invoke
186 /// `process_region_obligations` (defined in `self::region_obligations`)
187 /// for each body-id in this map, which will process the
188 /// obligations within. This is expected to be done 'late enough'
189 /// that all type inference variables have been bound and so forth.
190 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
192 undo_log: InferCtxtUndoLogs<'tcx>,
194 // Opaque types found in explicit return types and their
195 // associated fresh inference variable. Writeback resolves these
196 // variables to get the concrete type, which can be used to
197 // 'de-opaque' OpaqueTypeDecl outside of type inference.
198 pub opaque_types: OpaqueTypeMap<'tcx>,
200 /// A map from inference variables created from opaque
201 /// type instantiations (`ty::Infer`) to the actual opaque
202 /// type (`ty::Opaque`). Used during fallback to map unconstrained
203 /// opaque type inference variables to their corresponding
205 pub opaque_types_vars: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
208 impl<'tcx> InferCtxtInner<'tcx> {
209 fn new() -> InferCtxtInner<'tcx> {
211 projection_cache: Default::default(),
212 type_variable_storage: type_variable::TypeVariableStorage::new(),
213 undo_log: InferCtxtUndoLogs::default(),
214 const_unification_storage: ut::UnificationTableStorage::new(),
215 int_unification_storage: ut::UnificationTableStorage::new(),
216 float_unification_storage: ut::UnificationTableStorage::new(),
217 region_constraint_storage: Some(RegionConstraintStorage::new()),
218 region_obligations: vec![],
219 opaque_types: Default::default(),
220 opaque_types_vars: Default::default(),
225 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
226 &self.region_obligations
230 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
231 self.projection_cache.with_log(&mut self.undo_log)
235 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
236 self.type_variable_storage.with_log(&mut self.undo_log)
240 fn int_unification_table(
242 ) -> ut::UnificationTable<
245 &mut ut::UnificationStorage<ty::IntVid>,
246 &mut InferCtxtUndoLogs<'tcx>,
249 self.int_unification_storage.with_log(&mut self.undo_log)
253 fn float_unification_table(
255 ) -> ut::UnificationTable<
258 &mut ut::UnificationStorage<ty::FloatVid>,
259 &mut InferCtxtUndoLogs<'tcx>,
262 self.float_unification_storage.with_log(&mut self.undo_log)
266 fn const_unification_table(
268 ) -> ut::UnificationTable<
271 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
272 &mut InferCtxtUndoLogs<'tcx>,
275 self.const_unification_storage.with_log(&mut self.undo_log)
279 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
280 self.region_constraint_storage
282 .expect("region constraints already solved")
283 .with_log(&mut self.undo_log)
287 pub struct InferCtxt<'a, 'tcx> {
288 pub tcx: TyCtxt<'tcx>,
290 /// The `DefId` of the item in whose context we are performing inference or typeck.
291 /// It is used to check whether an opaque type use is a defining use.
293 /// If it is `None`, we can't resolve opaque types here and need to bubble up
294 /// the obligation. This frequently happens for
295 /// short lived InferCtxt within queries. The opaque type obligations are forwarded
296 /// to the outside until the end up in an `InferCtxt` for typeck or borrowck.
297 pub defining_use_anchor: Option<LocalDefId>,
299 /// During type-checking/inference of a body, `in_progress_typeck_results`
300 /// contains a reference to the typeck results being built up, which are
301 /// used for reading closure kinds/signatures as they are inferred,
302 /// and for error reporting logic to read arbitrary node types.
303 pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
305 pub inner: RefCell<InferCtxtInner<'tcx>>,
307 /// If set, this flag causes us to skip the 'leak check' during
308 /// higher-ranked subtyping operations. This flag is a temporary one used
309 /// to manage the removal of the leak-check: for the time being, we still run the
310 /// leak-check, but we issue warnings. This flag can only be set to true
311 /// when entering a snapshot.
312 skip_leak_check: Cell<bool>,
314 /// Once region inference is done, the values for each variable.
315 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
317 /// Caches the results of trait selection. This cache is used
318 /// for things that have to do with the parameters in scope.
319 pub selection_cache: select::SelectionCache<'tcx>,
321 /// Caches the results of trait evaluation.
322 pub evaluation_cache: select::EvaluationCache<'tcx>,
324 /// the set of predicates on which errors have been reported, to
325 /// avoid reporting the same error twice.
326 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
328 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
330 /// When an error occurs, we want to avoid reporting "derived"
331 /// errors that are due to this original failure. Normally, we
332 /// handle this with the `err_count_on_creation` count, which
333 /// basically just tracks how many errors were reported when we
334 /// started type-checking a fn and checks to see if any new errors
335 /// have been reported since then. Not great, but it works.
337 /// However, when errors originated in other passes -- notably
338 /// resolve -- this heuristic breaks down. Therefore, we have this
339 /// auxiliary flag that one can set whenever one creates a
340 /// type-error that is due to an error in a prior pass.
342 /// Don't read this flag directly, call `is_tainted_by_errors()`
343 /// and `set_tainted_by_errors()`.
344 tainted_by_errors_flag: Cell<bool>,
346 /// Track how many errors were reported when this infcx is created.
347 /// If the number of errors increases, that's also a sign (line
348 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
349 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
350 err_count_on_creation: usize,
352 /// This flag is true while there is an active snapshot.
353 in_snapshot: Cell<bool>,
355 /// What is the innermost universe we have created? Starts out as
356 /// `UniverseIndex::root()` but grows from there as we enter
357 /// universal quantifiers.
359 /// N.B., at present, we exclude the universal quantifiers on the
360 /// item we are type-checking, and just consider those names as
361 /// part of the root universe. So this would only get incremented
362 /// when we enter into a higher-ranked (`for<..>`) type or trait
364 universe: Cell<ty::UniverseIndex>,
367 /// See the `error_reporting` module for more details.
368 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
369 pub enum ValuePairs<'tcx> {
370 Regions(ExpectedFound<ty::Region<'tcx>>),
371 Terms(ExpectedFound<ty::Term<'tcx>>),
372 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
373 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
376 impl<'tcx> ValuePairs<'tcx> {
377 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
378 if let ValuePairs::Terms(ExpectedFound {
379 expected: ty::Term::Ty(expected),
380 found: ty::Term::Ty(found),
383 Some((*expected, *found))
390 /// The trace designates the path through inference that we took to
391 /// encounter an error or subtyping constraint.
393 /// See the `error_reporting` module for more details.
394 #[derive(Clone, Debug)]
395 pub struct TypeTrace<'tcx> {
396 cause: ObligationCause<'tcx>,
397 values: ValuePairs<'tcx>,
400 /// The origin of a `r1 <= r2` constraint.
402 /// See `error_reporting` module for more details
403 #[derive(Clone, Debug)]
404 pub enum SubregionOrigin<'tcx> {
405 /// Arose from a subtyping relation
406 Subtype(Box<TypeTrace<'tcx>>),
408 /// When casting `&'a T` to an `&'b Trait` object,
409 /// relating `'a` to `'b`
410 RelateObjectBound(Span),
412 /// Some type parameter was instantiated with the given type,
413 /// and that type must outlive some region.
414 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
416 /// The given region parameter was instantiated with a region
417 /// that must outlive some other region.
418 RelateRegionParamBound(Span),
420 /// Creating a pointer `b` to contents of another reference
423 /// Creating a pointer `b` to contents of an upvar
424 ReborrowUpvar(Span, ty::UpvarId),
426 /// Data with type `Ty<'tcx>` was borrowed
427 DataBorrowed(Ty<'tcx>, Span),
429 /// (&'a &'b T) where a >= b
430 ReferenceOutlivesReferent(Ty<'tcx>, Span),
432 /// Comparing the signature and requirements of an impl method against
433 /// the containing trait.
434 CompareImplMethodObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId },
436 /// Comparing the signature and requirements of an impl associated type
437 /// against the containing trait
438 CompareImplTypeObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId },
440 /// Checking that the bounds of a trait's associated type hold for a given impl
441 CheckAssociatedTypeBounds {
442 parent: Box<SubregionOrigin<'tcx>>,
443 impl_item_def_id: DefId,
444 trait_item_def_id: DefId,
448 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
449 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
450 static_assert_size!(SubregionOrigin<'_>, 32);
452 /// Times when we replace late-bound regions with variables:
453 #[derive(Clone, Copy, Debug)]
454 pub enum LateBoundRegionConversionTime {
455 /// when a fn is called
458 /// when two higher-ranked types are compared
461 /// when projecting an associated type
462 AssocTypeProjection(DefId),
465 /// Reasons to create a region inference variable
467 /// See `error_reporting` module for more details
468 #[derive(Copy, Clone, Debug)]
469 pub enum RegionVariableOrigin {
470 /// Region variables created for ill-categorized reasons,
471 /// mostly indicates places in need of refactoring
474 /// Regions created by a `&P` or `[...]` pattern
477 /// Regions created by `&` operator
480 /// Regions created as part of an autoref of a method receiver
483 /// Regions created as part of an automatic coercion
486 /// Region variables created as the values for early-bound regions
487 EarlyBoundRegion(Span, Symbol),
489 /// Region variables created for bound regions
490 /// in a function or method that is called
491 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
493 UpvarRegion(ty::UpvarId, Span),
495 /// This origin is used for the inference variables that we create
496 /// during NLL region processing.
497 Nll(NllRegionVariableOrigin),
500 #[derive(Copy, Clone, Debug)]
501 pub enum NllRegionVariableOrigin {
502 /// During NLL region processing, we create variables for free
503 /// regions that we encounter in the function signature and
504 /// elsewhere. This origin indices we've got one of those.
507 /// "Universal" instantiation of a higher-ranked region (e.g.,
508 /// from a `for<'a> T` binder). Meant to represent "any region".
509 Placeholder(ty::PlaceholderRegion),
511 /// The variable we create to represent `'empty(U0)`.
515 /// If this is true, then this variable was created to represent a lifetime
516 /// bound in a `for` binder. For example, it might have been created to
517 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
518 /// Such variables are created when we are trying to figure out if there
519 /// is any valid instantiation of `'a` that could fit into some scenario.
521 /// This is used to inform error reporting: in the case that we are trying to
522 /// determine whether there is any valid instantiation of a `'a` variable that meets
523 /// some constraint C, we want to blame the "source" of that `for` type,
524 /// rather than blaming the source of the constraint C.
529 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
530 #[derive(Copy, Clone, Debug)]
531 pub enum FixupError<'tcx> {
532 UnresolvedIntTy(IntVid),
533 UnresolvedFloatTy(FloatVid),
535 UnresolvedConst(ConstVid<'tcx>),
538 /// See the `region_obligations` field for more information.
540 pub struct RegionObligation<'tcx> {
541 pub sub_region: ty::Region<'tcx>,
542 pub sup_type: Ty<'tcx>,
543 pub origin: SubregionOrigin<'tcx>,
546 impl<'tcx> fmt::Display for FixupError<'tcx> {
547 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
548 use self::FixupError::*;
551 UnresolvedIntTy(_) => write!(
553 "cannot determine the type of this integer; \
554 add a suffix to specify the type explicitly"
556 UnresolvedFloatTy(_) => write!(
558 "cannot determine the type of this number; \
559 add a suffix to specify the type explicitly"
561 UnresolvedTy(_) => write!(f, "unconstrained type"),
562 UnresolvedConst(_) => write!(f, "unconstrained const value"),
567 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
568 /// Necessary because we can't write the following bound:
569 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
570 pub struct InferCtxtBuilder<'tcx> {
572 fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
573 defining_use_anchor: Option<LocalDefId>,
576 pub trait TyCtxtInferExt<'tcx> {
577 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
580 impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
581 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
582 InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None }
586 impl<'tcx> InferCtxtBuilder<'tcx> {
587 /// Used only by `rustc_typeck` during body type-checking/inference,
588 /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
589 /// Will also change the scope for opaque type defining use checks to the given owner.
590 pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
591 self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
592 self.with_opaque_type_inference(table_owner)
595 /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
596 /// you need to call this function. Otherwise the opaque type will be treated opaquely.
598 /// It is only meant to be called in two places, for typeck
599 /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used
601 pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self {
602 self.defining_use_anchor = Some(defining_use_anchor);
606 /// Given a canonical value `C` as a starting point, create an
607 /// inference context that contains each of the bound values
608 /// within instantiated as a fresh variable. The `f` closure is
609 /// invoked with the new infcx, along with the instantiated value
610 /// `V` and a substitution `S`. This substitution `S` maps from
611 /// the bound values in `C` to their instantiated values in `V`
612 /// (in other words, `S(C) = V`).
613 pub fn enter_with_canonical<T, R>(
616 canonical: &Canonical<'tcx, T>,
617 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
620 T: TypeFoldable<'tcx>,
624 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
625 f(infcx, value, subst)
629 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
630 let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self;
631 let in_progress_typeck_results = fresh_typeck_results.as_ref();
635 in_progress_typeck_results,
636 inner: RefCell::new(InferCtxtInner::new()),
637 lexical_region_resolutions: RefCell::new(None),
638 selection_cache: Default::default(),
639 evaluation_cache: Default::default(),
640 reported_trait_errors: Default::default(),
641 reported_closure_mismatch: Default::default(),
642 tainted_by_errors_flag: Cell::new(false),
643 err_count_on_creation: tcx.sess.err_count(),
644 in_snapshot: Cell::new(false),
645 skip_leak_check: Cell::new(false),
646 universe: Cell::new(ty::UniverseIndex::ROOT),
651 impl<'tcx, T> InferOk<'tcx, T> {
652 pub fn unit(self) -> InferOk<'tcx, ()> {
653 InferOk { value: (), obligations: self.obligations }
656 /// Extracts `value`, registering any obligations into `fulfill_cx`.
657 pub fn into_value_registering_obligations(
659 infcx: &InferCtxt<'_, 'tcx>,
660 fulfill_cx: &mut dyn TraitEngine<'tcx>,
662 let InferOk { value, obligations } = self;
663 for obligation in obligations {
664 fulfill_cx.register_predicate_obligation(infcx, obligation);
670 impl<'tcx> InferOk<'tcx, ()> {
671 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
676 #[must_use = "once you start a snapshot, you should always consume it"]
677 pub struct CombinedSnapshot<'a, 'tcx> {
678 undo_snapshot: Snapshot<'tcx>,
679 region_constraints_snapshot: RegionSnapshot,
680 universe: ty::UniverseIndex,
681 was_in_snapshot: bool,
682 _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
685 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
686 /// calls `tcx.try_unify_abstract_consts` after
687 /// canonicalizing the consts.
688 #[instrument(skip(self), level = "debug")]
689 pub fn try_unify_abstract_consts(
691 a: ty::Unevaluated<'tcx, ()>,
692 b: ty::Unevaluated<'tcx, ()>,
693 param_env: ty::ParamEnv<'tcx>,
695 // Reject any attempt to unify two unevaluated constants that contain inference
696 // variables, since inference variables in queries lead to ICEs.
697 if a.substs.has_infer_types_or_consts()
698 || b.substs.has_infer_types_or_consts()
699 || param_env.has_infer_types_or_consts()
701 debug!("a or b or param_env contain infer vars in its substs -> cannot unify");
705 let param_env_and = param_env.and((a, b));
706 let erased = self.tcx.erase_regions(param_env_and);
707 debug!("after erase_regions: {:?}", erased);
709 self.tcx.try_unify_abstract_consts(erased)
712 pub fn is_in_snapshot(&self) -> bool {
713 self.in_snapshot.get()
716 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
717 t.fold_with(&mut self.freshener())
720 /// Returns the origin of the type variable identified by `vid`, or `None`
721 /// if this is not a type variable.
723 /// No attempt is made to resolve `ty`.
724 pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
726 ty::Infer(ty::TyVar(vid)) => {
727 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
733 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
734 freshen::TypeFreshener::new(self, false)
737 /// Like `freshener`, but does not replace `'static` regions.
738 pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
739 freshen::TypeFreshener::new(self, true)
742 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
743 let mut inner = self.inner.borrow_mut();
744 let mut vars: Vec<Ty<'_>> = inner
746 .unsolved_variables()
748 .map(|t| self.tcx.mk_ty_var(t))
751 (0..inner.int_unification_table().len())
752 .map(|i| ty::IntVid { index: i as u32 })
753 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
754 .map(|v| self.tcx.mk_int_var(v)),
757 (0..inner.float_unification_table().len())
758 .map(|i| ty::FloatVid { index: i as u32 })
759 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
760 .map(|v| self.tcx.mk_float_var(v)),
767 trace: TypeTrace<'tcx>,
768 param_env: ty::ParamEnv<'tcx>,
769 ) -> CombineFields<'a, 'tcx> {
775 obligations: PredicateObligations::new(),
779 /// Clear the "currently in a snapshot" flag, invoke the closure,
780 /// then restore the flag to its original value. This flag is a
781 /// debugging measure designed to detect cases where we start a
782 /// snapshot, create type variables, and register obligations
783 /// which may involve those type variables in the fulfillment cx,
784 /// potentially leaving "dangling type variables" behind.
785 /// In such cases, an assertion will fail when attempting to
786 /// register obligations, within a snapshot. Very useful, much
787 /// better than grovelling through megabytes of `RUSTC_LOG` output.
789 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
790 /// sometimes create a "mini-fulfilment-cx" in which we enroll
791 /// obligations. As long as this fulfillment cx is fully drained
792 /// before we return, this is not a problem, as there won't be any
793 /// escaping obligations in the main cx. In those cases, you can
794 /// use this function.
795 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
797 F: FnOnce(&Self) -> R,
799 let flag = self.in_snapshot.replace(false);
800 let result = func(self);
801 self.in_snapshot.set(flag);
805 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
806 debug!("start_snapshot()");
808 let in_snapshot = self.in_snapshot.replace(true);
810 let mut inner = self.inner.borrow_mut();
813 undo_snapshot: inner.undo_log.start_snapshot(),
814 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
815 universe: self.universe(),
816 was_in_snapshot: in_snapshot,
817 // Borrow typeck results "in progress" (i.e., during typeck)
818 // to ban writes from within a snapshot to them.
819 _in_progress_typeck_results: self
820 .in_progress_typeck_results
821 .map(|typeck_results| typeck_results.borrow()),
825 #[instrument(skip(self, snapshot), level = "debug")]
826 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
827 let CombinedSnapshot {
829 region_constraints_snapshot,
832 _in_progress_typeck_results,
835 self.in_snapshot.set(was_in_snapshot);
836 self.universe.set(universe);
838 let mut inner = self.inner.borrow_mut();
839 inner.rollback_to(undo_snapshot);
840 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
843 #[instrument(skip(self, snapshot), level = "debug")]
844 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
845 let CombinedSnapshot {
847 region_constraints_snapshot: _,
850 _in_progress_typeck_results,
853 self.in_snapshot.set(was_in_snapshot);
855 self.inner.borrow_mut().commit(undo_snapshot);
858 /// Executes `f` and commit the bindings.
859 #[instrument(skip(self, f), level = "debug")]
860 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
862 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
864 let snapshot = self.start_snapshot();
865 let r = f(&snapshot);
866 self.commit_from(snapshot);
870 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
871 #[instrument(skip(self, f), level = "debug")]
872 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
874 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
876 let snapshot = self.start_snapshot();
877 let r = f(&snapshot);
878 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
881 self.commit_from(snapshot);
884 self.rollback_to("commit_if_ok -- error", snapshot);
890 /// Execute `f` then unroll any bindings it creates.
891 #[instrument(skip(self, f), level = "debug")]
892 pub fn probe<R, F>(&self, f: F) -> R
894 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
896 let snapshot = self.start_snapshot();
897 let r = f(&snapshot);
898 self.rollback_to("probe", snapshot);
902 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
903 #[instrument(skip(self, f), level = "debug")]
904 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
906 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
908 let snapshot = self.start_snapshot();
909 let was_skip_leak_check = self.skip_leak_check.get();
911 self.skip_leak_check.set(true);
913 let r = f(&snapshot);
914 self.rollback_to("probe", snapshot);
915 self.skip_leak_check.set(was_skip_leak_check);
919 /// Scan the constraints produced since `snapshot` began and returns:
921 /// - `None` -- if none of them involve "region outlives" constraints
922 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
923 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
924 pub fn region_constraints_added_in_snapshot(
926 snapshot: &CombinedSnapshot<'a, 'tcx>,
930 .unwrap_region_constraints()
931 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
934 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
935 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
938 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
940 T: at::ToTrace<'tcx>,
942 let origin = &ObligationCause::dummy();
944 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
945 // Ignore obligations, since we are unrolling
946 // everything anyway.
951 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
953 T: at::ToTrace<'tcx>,
955 let origin = &ObligationCause::dummy();
957 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
958 // Ignore obligations, since we are unrolling
959 // everything anyway.
964 #[instrument(skip(self), level = "debug")]
967 origin: SubregionOrigin<'tcx>,
971 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
974 /// Require that the region `r` be equal to one of the regions in
975 /// the set `regions`.
976 #[instrument(skip(self), level = "debug")]
977 pub fn member_constraint(
979 opaque_type_def_id: DefId,
980 definition_span: Span,
982 region: ty::Region<'tcx>,
983 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
985 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
994 /// Processes a `Coerce` predicate from the fulfillment context.
995 /// This is NOT the preferred way to handle coercion, which is to
996 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
998 /// This method here is actually a fallback that winds up being
999 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
1000 /// and records a coercion predicate. Presently, this method is equivalent
1001 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
1002 /// actually requiring `a <: b`. This is of course a valid coercion,
1003 /// but it's not as flexible as `FnCtxt::coerce` would be.
1005 /// (We may refactor this in the future, but there are a number of
1006 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
1007 /// records adjustments that are required on the HIR in order to perform
1008 /// the coercion, and we don't currently have a way to manage that.)
1009 pub fn coerce_predicate(
1011 cause: &ObligationCause<'tcx>,
1012 param_env: ty::ParamEnv<'tcx>,
1013 predicate: ty::PolyCoercePredicate<'tcx>,
1014 ) -> Option<InferResult<'tcx, ()>> {
1015 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
1016 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
1020 self.subtype_predicate(cause, param_env, subtype_predicate)
1023 pub fn subtype_predicate(
1025 cause: &ObligationCause<'tcx>,
1026 param_env: ty::ParamEnv<'tcx>,
1027 predicate: ty::PolySubtypePredicate<'tcx>,
1028 ) -> Option<InferResult<'tcx, ()>> {
1029 // Check for two unresolved inference variables, in which case we can
1030 // make no progress. This is partly a micro-optimization, but it's
1031 // also an opportunity to "sub-unify" the variables. This isn't
1032 // *necessary* to prevent cycles, because they would eventually be sub-unified
1033 // anyhow during generalization, but it helps with diagnostics (we can detect
1034 // earlier that they are sub-unified).
1036 // Note that we can just skip the binders here because
1037 // type variables can't (at present, at
1038 // least) capture any of the things bound by this binder.
1040 // Note that this sub here is not just for diagnostics - it has semantic
1042 let r_a = self.shallow_resolve(predicate.skip_binder().a);
1043 let r_b = self.shallow_resolve(predicate.skip_binder().b);
1044 match (r_a.kind(), r_b.kind()) {
1045 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
1046 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
1052 Some(self.commit_if_ok(|_snapshot| {
1053 let ty::SubtypePredicate { a_is_expected, a, b } =
1054 self.replace_bound_vars_with_placeholders(predicate);
1056 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1062 pub fn region_outlives_predicate(
1064 cause: &traits::ObligationCause<'tcx>,
1065 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1066 ) -> UnitResult<'tcx> {
1067 self.commit_if_ok(|_snapshot| {
1068 let ty::OutlivesPredicate(r_a, r_b) =
1069 self.replace_bound_vars_with_placeholders(predicate);
1070 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1071 RelateRegionParamBound(cause.span)
1073 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1078 /// Number of type variables created so far.
1079 pub fn num_ty_vars(&self) -> usize {
1080 self.inner.borrow_mut().type_variables().num_vars()
1083 pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1084 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1087 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1088 self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1091 pub fn next_ty_var_in_universe(
1093 origin: TypeVariableOrigin,
1094 universe: ty::UniverseIndex,
1096 let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin);
1097 self.tcx.mk_ty_var(vid)
1100 pub fn next_const_var(&self, ty: Ty<'tcx>, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
1101 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1104 pub fn next_const_var_in_universe(
1107 origin: ConstVariableOrigin,
1108 universe: ty::UniverseIndex,
1109 ) -> ty::Const<'tcx> {
1113 .const_unification_table()
1114 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1115 self.tcx.mk_const_var(vid, ty)
1118 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1119 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1121 val: ConstVariableValue::Unknown { universe: self.universe() },
1125 fn next_int_var_id(&self) -> IntVid {
1126 self.inner.borrow_mut().int_unification_table().new_key(None)
1129 pub fn next_int_var(&self) -> Ty<'tcx> {
1130 self.tcx.mk_int_var(self.next_int_var_id())
1133 fn next_float_var_id(&self) -> FloatVid {
1134 self.inner.borrow_mut().float_unification_table().new_key(None)
1137 pub fn next_float_var(&self) -> Ty<'tcx> {
1138 self.tcx.mk_float_var(self.next_float_var_id())
1141 /// Creates a fresh region variable with the next available index.
1142 /// The variable will be created in the maximum universe created
1143 /// thus far, allowing it to name any region created thus far.
1144 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1145 self.next_region_var_in_universe(origin, self.universe())
1148 /// Creates a fresh region variable with the next available index
1149 /// in the given universe; typically, you can use
1150 /// `next_region_var` and just use the maximal universe.
1151 pub fn next_region_var_in_universe(
1153 origin: RegionVariableOrigin,
1154 universe: ty::UniverseIndex,
1155 ) -> ty::Region<'tcx> {
1157 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1158 self.tcx.mk_region(ty::ReVar(region_var))
1161 /// Return the universe that the region `r` was created in. For
1162 /// most regions (e.g., `'static`, named regions from the user,
1163 /// etc) this is the root universe U0. For inference variables or
1164 /// placeholders, however, it will return the universe which which
1165 /// they are associated.
1166 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1167 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1170 /// Number of region variables created so far.
1171 pub fn num_region_vars(&self) -> usize {
1172 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1175 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1176 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1177 self.next_region_var(RegionVariableOrigin::Nll(origin))
1180 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1181 pub fn next_nll_region_var_in_universe(
1183 origin: NllRegionVariableOrigin,
1184 universe: ty::UniverseIndex,
1185 ) -> ty::Region<'tcx> {
1186 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1189 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1191 GenericParamDefKind::Lifetime => {
1192 // Create a region inference variable for the given
1193 // region parameter definition.
1194 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1196 GenericParamDefKind::Type { .. } => {
1197 // Create a type inference variable for the given
1198 // type parameter definition. The substitutions are
1199 // for actual parameters that may be referred to by
1200 // the default of this type parameter, if it exists.
1201 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1202 // used in a path such as `Foo::<T, U>::new()` will
1203 // use an inference variable for `C` with `[T, U]`
1204 // as the substitutions for the default, `(T, U)`.
1205 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1207 TypeVariableOrigin {
1208 kind: TypeVariableOriginKind::TypeParameterDefinition(
1216 self.tcx.mk_ty_var(ty_var_id).into()
1218 GenericParamDefKind::Const { .. } => {
1219 let origin = ConstVariableOrigin {
1220 kind: ConstVariableOriginKind::ConstParameterDefinition(
1227 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1229 val: ConstVariableValue::Unknown { universe: self.universe() },
1231 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1236 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1237 /// type/region parameter to a fresh inference variable.
1238 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1239 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1242 /// Returns `true` if errors have been reported since this infcx was
1243 /// created. This is sometimes used as a heuristic to skip
1244 /// reporting errors that often occur as a result of earlier
1245 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1246 /// inference variables, regionck errors).
1247 pub fn is_tainted_by_errors(&self) -> bool {
1249 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1250 tainted_by_errors_flag={})",
1251 self.tcx.sess.err_count(),
1252 self.err_count_on_creation,
1253 self.tainted_by_errors_flag.get()
1256 if self.tcx.sess.err_count() > self.err_count_on_creation {
1257 return true; // errors reported since this infcx was made
1259 self.tainted_by_errors_flag.get()
1262 /// Set the "tainted by errors" flag to true. We call this when we
1263 /// observe an error from a prior pass.
1264 pub fn set_tainted_by_errors(&self) {
1265 debug!("set_tainted_by_errors()");
1266 self.tainted_by_errors_flag.set(true)
1269 /// Process the region constraints and return any any errors that
1270 /// result. After this, no more unification operations should be
1271 /// done -- or the compiler will panic -- but it is legal to use
1272 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1273 pub fn resolve_regions(
1275 region_context: DefId,
1276 outlives_env: &OutlivesEnvironment<'tcx>,
1278 ) -> Vec<RegionResolutionError<'tcx>> {
1279 let (var_infos, data) = {
1280 let mut inner = self.inner.borrow_mut();
1281 let inner = &mut *inner;
1283 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1284 "region_obligations not empty: {:#?}",
1285 inner.region_obligations
1288 .region_constraint_storage
1290 .expect("regions already resolved")
1291 .with_log(&mut inner.undo_log)
1292 .into_infos_and_data()
1296 &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1298 let (lexical_region_resolutions, errors) =
1299 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1301 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1302 assert!(old_value.is_none());
1307 /// Process the region constraints and report any errors that
1308 /// result. After this, no more unification operations should be
1309 /// done -- or the compiler will panic -- but it is legal to use
1310 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1311 pub fn resolve_regions_and_report_errors(
1313 region_context: DefId,
1314 outlives_env: &OutlivesEnvironment<'tcx>,
1317 let errors = self.resolve_regions(region_context, outlives_env, mode);
1319 if !self.is_tainted_by_errors() {
1320 // As a heuristic, just skip reporting region errors
1321 // altogether if other errors have been reported while
1322 // this infcx was in use. This is totally hokey but
1323 // otherwise we have a hard time separating legit region
1324 // errors from silly ones.
1325 self.report_region_errors(&errors);
1329 /// Obtains (and clears) the current set of region
1330 /// constraints. The inference context is still usable: further
1331 /// unifications will simply add new constraints.
1333 /// This method is not meant to be used with normal lexical region
1334 /// resolution. Rather, it is used in the NLL mode as a kind of
1335 /// interim hack: basically we run normal type-check and generate
1336 /// region constraints as normal, but then we take them and
1337 /// translate them into the form that the NLL solver
1338 /// understands. See the NLL module for mode details.
1339 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1341 self.inner.borrow().region_obligations.is_empty(),
1342 "region_obligations not empty: {:#?}",
1343 self.inner.borrow().region_obligations
1346 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1349 /// Gives temporary access to the region constraint data.
1350 pub fn with_region_constraints<R>(
1352 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1354 let mut inner = self.inner.borrow_mut();
1355 op(inner.unwrap_region_constraints().data())
1358 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1359 let mut inner = self.inner.borrow_mut();
1360 let inner = &mut *inner;
1362 .region_constraint_storage
1364 .expect("regions already resolved")
1365 .with_log(&mut inner.undo_log)
1369 /// Takes ownership of the list of variable regions. This implies
1370 /// that all the region constraints have already been taken, and
1371 /// hence that `resolve_regions_and_report_errors` can never be
1372 /// called. This is used only during NLL processing to "hand off" ownership
1373 /// of the set of region variables into the NLL region context.
1374 pub fn take_region_var_origins(&self) -> VarInfos {
1375 let mut inner = self.inner.borrow_mut();
1376 let (var_infos, data) = inner
1377 .region_constraint_storage
1379 .expect("regions already resolved")
1380 .with_log(&mut inner.undo_log)
1381 .into_infos_and_data();
1382 assert!(data.is_empty());
1386 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1387 self.resolve_vars_if_possible(t).to_string()
1390 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1391 /// universe index of `TyVar(vid)`.
1392 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1393 use self::type_variable::TypeVariableValue;
1395 match self.inner.borrow_mut().type_variables().probe(vid) {
1396 TypeVariableValue::Known { value } => Ok(value),
1397 TypeVariableValue::Unknown { universe } => Err(universe),
1401 /// Resolve any type variables found in `value` -- but only one
1402 /// level. So, if the variable `?X` is bound to some type
1403 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1404 /// itself be bound to a type).
1406 /// Useful when you only need to inspect the outermost level of
1407 /// the type and don't care about nested types (or perhaps you
1408 /// will be resolving them as well, e.g. in a loop).
1409 pub fn shallow_resolve<T>(&self, value: T) -> T
1411 T: TypeFoldable<'tcx>,
1413 value.fold_with(&mut ShallowResolver { infcx: self })
1416 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1417 self.inner.borrow_mut().type_variables().root_var(var)
1420 /// Where possible, replaces type/const variables in
1421 /// `value` with their final value. Note that region variables
1422 /// are unaffected. If a type/const variable has not been unified, it
1423 /// is left as is. This is an idempotent operation that does
1424 /// not affect inference state in any way and so you can do it
1426 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1428 T: TypeFoldable<'tcx>,
1430 if !value.needs_infer() {
1431 return value; // Avoid duplicated subst-folding.
1433 let mut r = resolve::OpportunisticVarResolver::new(self);
1434 value.fold_with(&mut r)
1437 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1439 T: TypeFoldable<'tcx>,
1441 if !value.needs_infer() {
1442 return value; // Avoid duplicated subst-folding.
1444 let mut r = InferenceLiteralEraser { infcx: self };
1445 value.fold_with(&mut r)
1448 /// Returns the first unresolved variable contained in `T`. In the
1449 /// process of visiting `T`, this will resolve (where possible)
1450 /// type variables in `T`, but it never constructs the final,
1451 /// resolved type, so it's more efficient than
1452 /// `resolve_vars_if_possible()`.
1453 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1455 T: TypeFoldable<'tcx>,
1457 value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1460 pub fn probe_const_var(
1462 vid: ty::ConstVid<'tcx>,
1463 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1464 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1465 ConstVariableValue::Known { value } => Ok(value),
1466 ConstVariableValue::Unknown { universe } => Err(universe),
1470 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1472 * Attempts to resolve all type/region/const variables in
1473 * `value`. Region inference must have been run already (e.g.,
1474 * by calling `resolve_regions_and_report_errors`). If some
1475 * variable was never unified, an `Err` results.
1477 * This method is idempotent, but it not typically not invoked
1478 * except during the writeback phase.
1481 resolve::fully_resolve(self, value)
1484 // [Note-Type-error-reporting]
1485 // An invariant is that anytime the expected or actual type is Error (the special
1486 // error type, meaning that an error occurred when typechecking this expression),
1487 // this is a derived error. The error cascaded from another error (that was already
1488 // reported), so it's not useful to display it to the user.
1489 // The following methods implement this logic.
1490 // They check if either the actual or expected type is Error, and don't print the error
1491 // in this case. The typechecker should only ever report type errors involving mismatched
1492 // types using one of these methods, and should not call span_err directly for such
1495 pub fn type_error_struct_with_diag<M>(
1499 actual_ty: Ty<'tcx>,
1500 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>
1502 M: FnOnce(String) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1504 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1505 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1507 let mut err = mk_diag(self.ty_to_string(actual_ty));
1509 // Don't report an error if actual type is `Error`.
1510 if actual_ty.references_error() {
1511 err.downgrade_to_delayed_bug();
1517 pub fn report_mismatched_types(
1519 cause: &ObligationCause<'tcx>,
1522 err: TypeError<'tcx>,
1523 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1524 let trace = TypeTrace::types(cause, true, expected, actual);
1525 self.report_and_explain_type_error(trace, &err)
1528 pub fn report_mismatched_consts(
1530 cause: &ObligationCause<'tcx>,
1531 expected: ty::Const<'tcx>,
1532 actual: ty::Const<'tcx>,
1533 err: TypeError<'tcx>,
1534 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1535 let trace = TypeTrace::consts(cause, true, expected, actual);
1536 self.report_and_explain_type_error(trace, &err)
1539 pub fn replace_bound_vars_with_fresh_vars<T>(
1542 lbrct: LateBoundRegionConversionTime,
1543 value: ty::Binder<'tcx, T>,
1544 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1546 T: TypeFoldable<'tcx>,
1549 |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct));
1551 self.next_ty_var(TypeVariableOrigin {
1552 kind: TypeVariableOriginKind::MiscVariable,
1556 let fld_c = |_, ty| {
1557 self.next_const_var(
1559 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1562 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1565 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1566 pub fn verify_generic_bound(
1568 origin: SubregionOrigin<'tcx>,
1569 kind: GenericKind<'tcx>,
1570 a: ty::Region<'tcx>,
1571 bound: VerifyBound<'tcx>,
1573 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1577 .unwrap_region_constraints()
1578 .verify_generic_bound(origin, kind, a, bound);
1581 /// Obtains the latest type of the given closure; this may be a
1582 /// closure in the current function, in which case its
1583 /// `ClosureKind` may not yet be known.
1584 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1585 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1586 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1587 closure_kind_ty.to_opt_closure_kind()
1590 /// Clears the selection, evaluation, and projection caches. This is useful when
1591 /// repeatedly attempting to select an `Obligation` while changing only
1592 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1593 pub fn clear_caches(&self) {
1594 self.selection_cache.clear();
1595 self.evaluation_cache.clear();
1596 self.inner.borrow_mut().projection_cache().clear();
1599 pub fn universe(&self) -> ty::UniverseIndex {
1603 /// Creates and return a fresh universe that extends all previous
1604 /// universes. Updates `self.universe` to that new universe.
1605 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1606 let u = self.universe.get().next_universe();
1607 self.universe.set(u);
1611 /// Resolves and evaluates a constant.
1613 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1614 /// substitutions and environment are used to resolve the constant. Alternatively if the
1615 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1616 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1617 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1618 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1621 /// This handles inferences variables within both `param_env` and `substs` by
1622 /// performing the operation on their respective canonical forms.
1623 #[instrument(skip(self), level = "debug")]
1624 pub fn const_eval_resolve(
1626 param_env: ty::ParamEnv<'tcx>,
1627 unevaluated: ty::Unevaluated<'tcx>,
1629 ) -> EvalToConstValueResult<'tcx> {
1630 let substs = self.resolve_vars_if_possible(unevaluated.substs);
1633 // Postpone the evaluation of constants whose substs depend on inference
1635 if substs.has_infer_types_or_consts() {
1636 debug!("substs have infer types or consts: {:?}", substs);
1637 return Err(ErrorHandled::TooGeneric);
1640 let param_env_erased = self.tcx.erase_regions(param_env);
1641 let substs_erased = self.tcx.erase_regions(substs);
1642 debug!(?param_env_erased);
1643 debug!(?substs_erased);
1645 let unevaluated = ty::Unevaluated {
1646 def: unevaluated.def,
1647 substs: substs_erased,
1648 promoted: unevaluated.promoted,
1651 // The return value is the evaluated value which doesn't contain any reference to inference
1652 // variables, thus we don't need to substitute back the original values.
1653 self.tcx.const_eval_resolve(param_env_erased, unevaluated, span)
1656 /// If `typ` is a type variable of some kind, resolve it one level
1657 /// (but do not resolve types found in the result). If `typ` is
1658 /// not a type variable, just return it unmodified.
1659 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1660 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1662 ty::Infer(ty::TyVar(v)) => {
1663 // Not entirely obvious: if `typ` is a type variable,
1664 // it can be resolved to an int/float variable, which
1665 // can then be recursively resolved, hence the
1666 // recursion. Note though that we prevent type
1667 // variables from unifying to other type variables
1668 // directly (though they may be embedded
1669 // structurally), and we prevent cycles in any case,
1670 // so this recursion should always be of very limited
1673 // Note: if these two lines are combined into one we get
1674 // dynamic borrow errors on `self.inner`.
1675 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1676 known.map_or(typ, |t| self.shallow_resolve_ty(t))
1679 ty::Infer(ty::IntVar(v)) => self
1682 .int_unification_table()
1684 .map(|v| v.to_type(self.tcx))
1687 ty::Infer(ty::FloatVar(v)) => self
1690 .float_unification_table()
1692 .map(|v| v.to_type(self.tcx))
1699 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1700 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1701 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1703 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1704 /// inlined, despite being large, because it has only two call sites that
1705 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1706 /// inference variables), and it handles both `Ty` and `ty::Const` without
1707 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1709 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1711 TyOrConstInferVar::Ty(v) => {
1712 use self::type_variable::TypeVariableValue;
1714 // If `inlined_probe` returns a `Known` value, it never equals
1715 // `ty::Infer(ty::TyVar(v))`.
1716 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1717 TypeVariableValue::Unknown { .. } => false,
1718 TypeVariableValue::Known { .. } => true,
1722 TyOrConstInferVar::TyInt(v) => {
1723 // If `inlined_probe_value` returns a value it's always a
1724 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1726 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1729 TyOrConstInferVar::TyFloat(v) => {
1730 // If `probe_value` returns a value it's always a
1731 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1733 // Not `inlined_probe_value(v)` because this call site is colder.
1734 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1737 TyOrConstInferVar::Const(v) => {
1738 // If `probe_value` returns a `Known` value, it never equals
1739 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1741 // Not `inlined_probe_value(v)` because this call site is colder.
1742 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1743 ConstVariableValue::Unknown { .. } => false,
1744 ConstVariableValue::Known { .. } => true,
1751 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1752 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1753 #[derive(Copy, Clone, Debug)]
1754 pub enum TyOrConstInferVar<'tcx> {
1755 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1757 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1759 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1762 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1763 Const(ConstVid<'tcx>),
1766 impl<'tcx> TyOrConstInferVar<'tcx> {
1767 /// Tries to extract an inference variable from a type or a constant, returns `None`
1768 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1769 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1770 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1771 match arg.unpack() {
1772 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1773 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1774 GenericArgKind::Lifetime(_) => None,
1778 /// Tries to extract an inference variable from a type, returns `None`
1779 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1780 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1782 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1783 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1784 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1789 /// Tries to extract an inference variable from a constant, returns `None`
1790 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1791 pub fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1793 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1799 /// Replace `{integer}` with `i32` and `{float}` with `f64`.
1800 /// Used only for diagnostics.
1801 struct InferenceLiteralEraser<'a, 'tcx> {
1802 infcx: &'a InferCtxt<'a, 'tcx>,
1805 impl<'a, 'tcx> TypeFolder<'tcx> for InferenceLiteralEraser<'a, 'tcx> {
1806 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1810 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1812 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx().types.i32,
1813 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx().types.f64,
1814 _ => ty.super_fold_with(self),
1819 struct ShallowResolver<'a, 'tcx> {
1820 infcx: &'a InferCtxt<'a, 'tcx>,
1823 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1824 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1828 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1829 self.infcx.shallow_resolve_ty(ty)
1832 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1833 if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.val() {
1837 .const_unification_table()
1848 impl<'tcx> TypeTrace<'tcx> {
1849 pub fn span(&self) -> Span {
1854 cause: &ObligationCause<'tcx>,
1855 a_is_expected: bool,
1858 ) -> TypeTrace<'tcx> {
1860 cause: cause.clone(),
1861 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1866 cause: &ObligationCause<'tcx>,
1867 a_is_expected: bool,
1870 ) -> TypeTrace<'tcx> {
1872 cause: cause.clone(),
1873 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1878 impl<'tcx> SubregionOrigin<'tcx> {
1879 pub fn span(&self) -> Span {
1881 Subtype(ref a) => a.span(),
1882 RelateObjectBound(a) => a,
1883 RelateParamBound(a, ..) => a,
1884 RelateRegionParamBound(a) => a,
1886 ReborrowUpvar(a, _) => a,
1887 DataBorrowed(_, a) => a,
1888 ReferenceOutlivesReferent(_, a) => a,
1889 CompareImplMethodObligation { span, .. } => span,
1890 CompareImplTypeObligation { span, .. } => span,
1891 CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1895 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1897 F: FnOnce() -> Self,
1899 match *cause.code() {
1900 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1901 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1904 traits::ObligationCauseCode::CompareImplMethodObligation {
1907 } => SubregionOrigin::CompareImplMethodObligation {
1913 traits::ObligationCauseCode::CompareImplTypeObligation {
1916 } => SubregionOrigin::CompareImplTypeObligation {
1922 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1925 } => SubregionOrigin::CheckAssociatedTypeBounds {
1928 parent: Box::new(default()),
1936 impl RegionVariableOrigin {
1937 pub fn span(&self) -> Span {
1944 | EarlyBoundRegion(a, ..)
1945 | LateBoundRegion(a, ..)
1946 | UpvarRegion(_, a) => a,
1947 Nll(..) => bug!("NLL variable used with `span`"),
1952 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1953 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1956 "RegionObligation(sub_region={:?}, sup_type={:?})",
1957 self.sub_region, self.sup_type