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 hir::def_id::CRATE_DEF_ID;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_data_structures::sync::Lrc;
16 use rustc_data_structures::undo_log::Rollback;
17 use rustc_data_structures::unify as ut;
18 use rustc_errors::DiagnosticBuilder;
20 use rustc_hir::def_id::{DefId, LocalDefId};
21 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
22 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
23 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
24 use rustc_middle::mir::interpret::EvalToConstValueResult;
25 use rustc_middle::traits::select;
26 use rustc_middle::ty::error::{ExpectedFound, TypeError};
27 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
28 use rustc_middle::ty::relate::RelateResult;
29 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
30 pub use rustc_middle::ty::IntVarValue;
31 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
32 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
33 use rustc_session::config::BorrowckMode;
34 use rustc_span::symbol::Symbol;
37 use std::cell::{Cell, Ref, RefCell};
38 use std::collections::BTreeMap;
41 use self::combine::CombineFields;
42 use self::free_regions::RegionRelations;
43 use self::lexical_region_resolve::LexicalRegionResolutions;
44 use self::outlives::env::OutlivesEnvironment;
45 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
46 use self::region_constraints::{
47 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
49 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
55 pub mod error_reporting;
62 mod lexical_region_resolve;
68 pub mod region_constraints;
71 pub mod type_variable;
74 use crate::infer::canonical::OriginalQueryValues;
75 pub use rustc_middle::infer::unify_key;
79 pub struct InferOk<'tcx, T> {
81 pub obligations: PredicateObligations<'tcx>,
83 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
85 pub type Bound<T> = Option<T>;
86 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
87 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
89 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
90 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
93 /// How we should handle region solving.
95 /// This is used so that the region values inferred by HIR region solving are
96 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
97 /// typeck will also do.
98 #[derive(Copy, Clone, Debug)]
99 pub enum RegionckMode {
100 /// The default mode: report region errors, don't erase regions.
102 /// Erase the results of region after solving.
104 /// A flag that is used to suppress region errors, when we are doing
105 /// region checks that the NLL borrow checker will also do -- it might
107 suppress_errors: bool,
111 impl Default for RegionckMode {
112 fn default() -> Self {
118 /// Indicates that the MIR borrowck will repeat these region
119 /// checks, so we should ignore errors if NLL is (unconditionally)
121 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
122 // FIXME(Centril): Once we actually remove `::Migrate` also make
123 // this always `true` and then proceed to eliminate the dead code.
124 match tcx.borrowck_mode() {
125 // If we're on Migrate mode, report AST region errors
126 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
128 // If we're on MIR, don't report AST region errors as they should be reported by NLL
129 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
134 /// This type contains all the things within `InferCtxt` that sit within a
135 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
136 /// operations are hot enough that we want only one call to `borrow_mut` per
137 /// call to `start_snapshot` and `rollback_to`.
138 pub struct InferCtxtInner<'tcx> {
139 /// Cache for projections. This cache is snapshotted along with the infcx.
141 /// Public so that `traits::project` can use it.
142 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
144 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
145 /// that might instantiate a general type variable have an order,
146 /// represented by its upper and lower bounds.
147 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
149 /// Map from const parameter variable to the kind of const it represents.
150 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
152 /// Map from integral variable to the kind of integer it represents.
153 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
155 /// Map from floating variable to the kind of float it represents.
156 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
158 /// Tracks the set of region variables and the constraints between them.
159 /// This is initially `Some(_)` but when
160 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
161 /// -- further attempts to perform unification, etc., may fail if new
162 /// region constraints would've been added.
163 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
165 /// A set of constraints that regionck must validate. Each
166 /// constraint has the form `T:'a`, meaning "some type `T` must
167 /// outlive the lifetime 'a". These constraints derive from
168 /// instantiated type parameters. So if you had a struct defined
171 /// struct Foo<T:'static> { ... }
173 /// then in some expression `let x = Foo { ... }` it will
174 /// instantiate the type parameter `T` with a fresh type `$0`. At
175 /// the same time, it will record a region obligation of
176 /// `$0:'static`. This will get checked later by regionck. (We
177 /// can't generally check these things right away because we have
178 /// to wait until types are resolved.)
180 /// These are stored in a map keyed to the id of the innermost
181 /// enclosing fn body / static initializer expression. This is
182 /// because the location where the obligation was incurred can be
183 /// relevant with respect to which sublifetime assumptions are in
184 /// place. The reason that we store under the fn-id, and not
185 /// something more fine-grained, is so that it is easier for
186 /// regionck to be sure that it has found *all* the region
187 /// obligations (otherwise, it's easy to fail to walk to a
188 /// particular node-id).
190 /// Before running `resolve_regions_and_report_errors`, the creator
191 /// of the inference context is expected to invoke
192 /// `process_region_obligations` (defined in `self::region_obligations`)
193 /// for each body-id in this map, which will process the
194 /// obligations within. This is expected to be done 'late enough'
195 /// that all type inference variables have been bound and so forth.
196 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
198 undo_log: InferCtxtUndoLogs<'tcx>,
200 // Opaque types found in explicit return types and their
201 // associated fresh inference variable. Writeback resolves these
202 // variables to get the concrete type, which can be used to
203 // 'de-opaque' OpaqueTypeDecl, after typeck is done with all functions.
204 pub opaque_types: OpaqueTypeMap<'tcx>,
206 /// A map from inference variables created from opaque
207 /// type instantiations (`ty::Infer`) to the actual opaque
208 /// type (`ty::Opaque`). Used during fallback to map unconstrained
209 /// opaque type inference variables to their corresponding
211 pub opaque_types_vars: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
214 impl<'tcx> InferCtxtInner<'tcx> {
215 fn new() -> InferCtxtInner<'tcx> {
217 projection_cache: Default::default(),
218 type_variable_storage: type_variable::TypeVariableStorage::new(),
219 undo_log: InferCtxtUndoLogs::default(),
220 const_unification_storage: ut::UnificationTableStorage::new(),
221 int_unification_storage: ut::UnificationTableStorage::new(),
222 float_unification_storage: ut::UnificationTableStorage::new(),
223 region_constraint_storage: Some(RegionConstraintStorage::new()),
224 region_obligations: vec![],
225 opaque_types: Default::default(),
226 opaque_types_vars: Default::default(),
231 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
232 &self.region_obligations
236 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
237 self.projection_cache.with_log(&mut self.undo_log)
241 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
242 self.type_variable_storage.with_log(&mut self.undo_log)
246 fn int_unification_table(
248 ) -> ut::UnificationTable<
251 &mut ut::UnificationStorage<ty::IntVid>,
252 &mut InferCtxtUndoLogs<'tcx>,
255 self.int_unification_storage.with_log(&mut self.undo_log)
259 fn float_unification_table(
261 ) -> ut::UnificationTable<
264 &mut ut::UnificationStorage<ty::FloatVid>,
265 &mut InferCtxtUndoLogs<'tcx>,
268 self.float_unification_storage.with_log(&mut self.undo_log)
272 fn const_unification_table(
274 ) -> ut::UnificationTable<
277 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
278 &mut InferCtxtUndoLogs<'tcx>,
281 self.const_unification_storage.with_log(&mut self.undo_log)
285 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
286 self.region_constraint_storage
288 .expect("region constraints already solved")
289 .with_log(&mut self.undo_log)
293 pub struct InferCtxt<'a, 'tcx> {
294 pub tcx: TyCtxt<'tcx>,
296 /// The `DefId` of the item in whose context we are performing inference or typeck.
297 /// It is used to check whether an opaque type use is a defining use.
298 pub defining_use_anchor: LocalDefId,
300 /// During type-checking/inference of a body, `in_progress_typeck_results`
301 /// contains a reference to the typeck results being built up, which are
302 /// used for reading closure kinds/signatures as they are inferred,
303 /// and for error reporting logic to read arbitrary node types.
304 pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
306 pub inner: RefCell<InferCtxtInner<'tcx>>,
308 /// If set, this flag causes us to skip the 'leak check' during
309 /// higher-ranked subtyping operations. This flag is a temporary one used
310 /// to manage the removal of the leak-check: for the time being, we still run the
311 /// leak-check, but we issue warnings. This flag can only be set to true
312 /// when entering a snapshot.
313 skip_leak_check: Cell<bool>,
315 /// Once region inference is done, the values for each variable.
316 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
318 /// Caches the results of trait selection. This cache is used
319 /// for things that have to do with the parameters in scope.
320 pub selection_cache: select::SelectionCache<'tcx>,
322 /// Caches the results of trait evaluation.
323 pub evaluation_cache: select::EvaluationCache<'tcx>,
325 /// the set of predicates on which errors have been reported, to
326 /// avoid reporting the same error twice.
327 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
329 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
331 /// When an error occurs, we want to avoid reporting "derived"
332 /// errors that are due to this original failure. Normally, we
333 /// handle this with the `err_count_on_creation` count, which
334 /// basically just tracks how many errors were reported when we
335 /// started type-checking a fn and checks to see if any new errors
336 /// have been reported since then. Not great, but it works.
338 /// However, when errors originated in other passes -- notably
339 /// resolve -- this heuristic breaks down. Therefore, we have this
340 /// auxiliary flag that one can set whenever one creates a
341 /// type-error that is due to an error in a prior pass.
343 /// Don't read this flag directly, call `is_tainted_by_errors()`
344 /// and `set_tainted_by_errors()`.
345 tainted_by_errors_flag: Cell<bool>,
347 /// Track how many errors were reported when this infcx is created.
348 /// If the number of errors increases, that's also a sign (line
349 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
350 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
351 err_count_on_creation: usize,
353 /// This flag is true while there is an active snapshot.
354 in_snapshot: Cell<bool>,
356 /// What is the innermost universe we have created? Starts out as
357 /// `UniverseIndex::root()` but grows from there as we enter
358 /// universal quantifiers.
360 /// N.B., at present, we exclude the universal quantifiers on the
361 /// item we are type-checking, and just consider those names as
362 /// part of the root universe. So this would only get incremented
363 /// when we enter into a higher-ranked (`for<..>`) type or trait
365 universe: Cell<ty::UniverseIndex>,
368 /// See the `error_reporting` module for more details.
369 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
370 pub enum ValuePairs<'tcx> {
371 Types(ExpectedFound<Ty<'tcx>>),
372 Regions(ExpectedFound<ty::Region<'tcx>>),
373 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
374 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
375 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
378 /// The trace designates the path through inference that we took to
379 /// encounter an error or subtyping constraint.
381 /// See the `error_reporting` module for more details.
382 #[derive(Clone, Debug)]
383 pub struct TypeTrace<'tcx> {
384 cause: ObligationCause<'tcx>,
385 values: ValuePairs<'tcx>,
388 /// The origin of a `r1 <= r2` constraint.
390 /// See `error_reporting` module for more details
391 #[derive(Clone, Debug)]
392 pub enum SubregionOrigin<'tcx> {
393 /// Arose from a subtyping relation
394 Subtype(Box<TypeTrace<'tcx>>),
396 /// When casting `&'a T` to an `&'b Trait` object,
397 /// relating `'a` to `'b`
398 RelateObjectBound(Span),
400 /// Some type parameter was instantiated with the given type,
401 /// and that type must outlive some region.
402 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
404 /// The given region parameter was instantiated with a region
405 /// that must outlive some other region.
406 RelateRegionParamBound(Span),
408 /// Creating a pointer `b` to contents of another reference
411 /// Creating a pointer `b` to contents of an upvar
412 ReborrowUpvar(Span, ty::UpvarId),
414 /// Data with type `Ty<'tcx>` was borrowed
415 DataBorrowed(Ty<'tcx>, Span),
417 /// (&'a &'b T) where a >= b
418 ReferenceOutlivesReferent(Ty<'tcx>, Span),
420 /// Comparing the signature and requirements of an impl method against
421 /// the containing trait.
422 CompareImplMethodObligation {
425 impl_item_def_id: DefId,
426 trait_item_def_id: DefId,
429 /// Comparing the signature and requirements of an impl associated type
430 /// against the containing trait
431 CompareImplTypeObligation {
434 impl_item_def_id: DefId,
435 trait_item_def_id: DefId,
439 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
440 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
441 static_assert_size!(SubregionOrigin<'_>, 32);
443 /// Times when we replace late-bound regions with variables:
444 #[derive(Clone, Copy, Debug)]
445 pub enum LateBoundRegionConversionTime {
446 /// when a fn is called
449 /// when two higher-ranked types are compared
452 /// when projecting an associated type
453 AssocTypeProjection(DefId),
456 /// Reasons to create a region inference variable
458 /// See `error_reporting` module for more details
459 #[derive(Copy, Clone, Debug)]
460 pub enum RegionVariableOrigin {
461 /// Region variables created for ill-categorized reasons,
462 /// mostly indicates places in need of refactoring
465 /// Regions created by a `&P` or `[...]` pattern
468 /// Regions created by `&` operator
471 /// Regions created as part of an autoref of a method receiver
472 Autoref(Span, ty::AssocItem),
474 /// Regions created as part of an automatic coercion
477 /// Region variables created as the values for early-bound regions
478 EarlyBoundRegion(Span, Symbol),
480 /// Region variables created for bound regions
481 /// in a function or method that is called
482 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
484 UpvarRegion(ty::UpvarId, Span),
486 /// This origin is used for the inference variables that we create
487 /// during NLL region processing.
488 Nll(NllRegionVariableOrigin),
491 #[derive(Copy, Clone, Debug)]
492 pub enum NllRegionVariableOrigin {
493 /// During NLL region processing, we create variables for free
494 /// regions that we encounter in the function signature and
495 /// elsewhere. This origin indices we've got one of those.
498 /// "Universal" instantiation of a higher-ranked region (e.g.,
499 /// from a `for<'a> T` binder). Meant to represent "any region".
500 Placeholder(ty::PlaceholderRegion),
502 /// The variable we create to represent `'empty(U0)`.
506 /// If this is true, then this variable was created to represent a lifetime
507 /// bound in a `for` binder. For example, it might have been created to
508 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
509 /// Such variables are created when we are trying to figure out if there
510 /// is any valid instantiation of `'a` that could fit into some scenario.
512 /// This is used to inform error reporting: in the case that we are trying to
513 /// determine whether there is any valid instantiation of a `'a` variable that meets
514 /// some constraint C, we want to blame the "source" of that `for` type,
515 /// rather than blaming the source of the constraint C.
520 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
521 #[derive(Copy, Clone, Debug)]
522 pub enum FixupError<'tcx> {
523 UnresolvedIntTy(IntVid),
524 UnresolvedFloatTy(FloatVid),
526 UnresolvedConst(ConstVid<'tcx>),
529 /// See the `region_obligations` field for more information.
531 pub struct RegionObligation<'tcx> {
532 pub sub_region: ty::Region<'tcx>,
533 pub sup_type: Ty<'tcx>,
534 pub origin: SubregionOrigin<'tcx>,
537 impl<'tcx> fmt::Display for FixupError<'tcx> {
538 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539 use self::FixupError::*;
542 UnresolvedIntTy(_) => write!(
544 "cannot determine the type of this integer; \
545 add a suffix to specify the type explicitly"
547 UnresolvedFloatTy(_) => write!(
549 "cannot determine the type of this number; \
550 add a suffix to specify the type explicitly"
552 UnresolvedTy(_) => write!(f, "unconstrained type"),
553 UnresolvedConst(_) => write!(f, "unconstrained const value"),
558 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
559 /// Necessary because we can't write the following bound:
560 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
561 pub struct InferCtxtBuilder<'tcx> {
563 fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
564 defining_use_anchor: LocalDefId,
567 pub trait TyCtxtInferExt<'tcx> {
568 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
571 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
572 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
575 defining_use_anchor: CRATE_DEF_ID,
576 fresh_typeck_results: None,
581 impl<'tcx> InferCtxtBuilder<'tcx> {
582 /// Used only by `rustc_typeck` during body type-checking/inference,
583 /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
584 /// Will also change the scope for opaque type defining use checks to the given owner.
585 pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
586 self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
587 self.with_opaque_type_inference(table_owner)
590 /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
591 /// you need to call this function. Otherwise the opaque type will be treated opaquely.
593 /// It is only meant to be called in two places, for typeck
594 /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used
596 pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self {
597 self.defining_use_anchor = defining_use_anchor;
601 /// Given a canonical value `C` as a starting point, create an
602 /// inference context that contains each of the bound values
603 /// within instantiated as a fresh variable. The `f` closure is
604 /// invoked with the new infcx, along with the instantiated value
605 /// `V` and a substitution `S`. This substitution `S` maps from
606 /// the bound values in `C` to their instantiated values in `V`
607 /// (in other words, `S(C) = V`).
608 pub fn enter_with_canonical<T, R>(
611 canonical: &Canonical<'tcx, T>,
612 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
615 T: TypeFoldable<'tcx>,
619 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
620 f(infcx, value, subst)
624 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
625 let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self;
626 let in_progress_typeck_results = fresh_typeck_results.as_ref();
630 in_progress_typeck_results,
631 inner: RefCell::new(InferCtxtInner::new()),
632 lexical_region_resolutions: RefCell::new(None),
633 selection_cache: Default::default(),
634 evaluation_cache: Default::default(),
635 reported_trait_errors: Default::default(),
636 reported_closure_mismatch: Default::default(),
637 tainted_by_errors_flag: Cell::new(false),
638 err_count_on_creation: tcx.sess.err_count(),
639 in_snapshot: Cell::new(false),
640 skip_leak_check: Cell::new(false),
641 universe: Cell::new(ty::UniverseIndex::ROOT),
646 impl<'tcx, T> InferOk<'tcx, T> {
647 pub fn unit(self) -> InferOk<'tcx, ()> {
648 InferOk { value: (), obligations: self.obligations }
651 /// Extracts `value`, registering any obligations into `fulfill_cx`.
652 pub fn into_value_registering_obligations(
654 infcx: &InferCtxt<'_, 'tcx>,
655 fulfill_cx: &mut dyn TraitEngine<'tcx>,
657 let InferOk { value, obligations } = self;
658 for obligation in obligations {
659 fulfill_cx.register_predicate_obligation(infcx, obligation);
665 impl<'tcx> InferOk<'tcx, ()> {
666 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
671 #[must_use = "once you start a snapshot, you should always consume it"]
672 pub struct CombinedSnapshot<'a, 'tcx> {
673 undo_snapshot: Snapshot<'tcx>,
674 region_constraints_snapshot: RegionSnapshot,
675 universe: ty::UniverseIndex,
676 was_in_snapshot: bool,
677 _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
680 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
681 /// calls `tcx.try_unify_abstract_consts` after
682 /// canonicalizing the consts.
683 pub fn try_unify_abstract_consts(
685 a: ty::Unevaluated<'tcx, ()>,
686 b: ty::Unevaluated<'tcx, ()>,
688 let canonical = self.canonicalize_query((a, b), &mut OriginalQueryValues::default());
689 debug!("canonical consts: {:?}", &canonical.value);
691 self.tcx.try_unify_abstract_consts(canonical.value)
694 pub fn is_in_snapshot(&self) -> bool {
695 self.in_snapshot.get()
698 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
699 t.fold_with(&mut self.freshener())
702 /// Returns the origin of the type variable identified by `vid`, or `None`
703 /// if this is not a type variable.
705 /// No attempt is made to resolve `ty`.
706 pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
708 ty::Infer(ty::TyVar(vid)) => {
709 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
715 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
716 freshen::TypeFreshener::new(self, false)
719 /// Like `freshener`, but does not replace `'static` regions.
720 pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
721 freshen::TypeFreshener::new(self, true)
724 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
725 let mut inner = self.inner.borrow_mut();
726 let mut vars: Vec<Ty<'_>> = inner
728 .unsolved_variables()
730 .map(|t| self.tcx.mk_ty_var(t))
733 (0..inner.int_unification_table().len())
734 .map(|i| ty::IntVid { index: i as u32 })
735 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
736 .map(|v| self.tcx.mk_int_var(v)),
739 (0..inner.float_unification_table().len())
740 .map(|i| ty::FloatVid { index: i as u32 })
741 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
742 .map(|v| self.tcx.mk_float_var(v)),
749 trace: TypeTrace<'tcx>,
750 param_env: ty::ParamEnv<'tcx>,
751 ) -> CombineFields<'a, 'tcx> {
757 obligations: PredicateObligations::new(),
761 /// Clear the "currently in a snapshot" flag, invoke the closure,
762 /// then restore the flag to its original value. This flag is a
763 /// debugging measure designed to detect cases where we start a
764 /// snapshot, create type variables, and register obligations
765 /// which may involve those type variables in the fulfillment cx,
766 /// potentially leaving "dangling type variables" behind.
767 /// In such cases, an assertion will fail when attempting to
768 /// register obligations, within a snapshot. Very useful, much
769 /// better than grovelling through megabytes of `RUSTC_LOG` output.
771 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
772 /// sometimes create a "mini-fulfilment-cx" in which we enroll
773 /// obligations. As long as this fulfillment cx is fully drained
774 /// before we return, this is not a problem, as there won't be any
775 /// escaping obligations in the main cx. In those cases, you can
776 /// use this function.
777 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
779 F: FnOnce(&Self) -> R,
781 let flag = self.in_snapshot.replace(false);
782 let result = func(self);
783 self.in_snapshot.set(flag);
787 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
788 debug!("start_snapshot()");
790 let in_snapshot = self.in_snapshot.replace(true);
792 let mut inner = self.inner.borrow_mut();
795 undo_snapshot: inner.undo_log.start_snapshot(),
796 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
797 universe: self.universe(),
798 was_in_snapshot: in_snapshot,
799 // Borrow typeck results "in progress" (i.e., during typeck)
800 // to ban writes from within a snapshot to them.
801 _in_progress_typeck_results: self
802 .in_progress_typeck_results
803 .map(|typeck_results| typeck_results.borrow()),
807 #[instrument(skip(self, snapshot), level = "debug")]
808 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
809 let CombinedSnapshot {
811 region_constraints_snapshot,
814 _in_progress_typeck_results,
817 self.in_snapshot.set(was_in_snapshot);
818 self.universe.set(universe);
820 let mut inner = self.inner.borrow_mut();
821 inner.rollback_to(undo_snapshot);
822 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
825 #[instrument(skip(self, snapshot), level = "debug")]
826 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
827 let CombinedSnapshot {
829 region_constraints_snapshot: _,
832 _in_progress_typeck_results,
835 self.in_snapshot.set(was_in_snapshot);
837 self.inner.borrow_mut().commit(undo_snapshot);
840 /// Executes `f` and commit the bindings.
841 #[instrument(skip(self, f), level = "debug")]
842 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
844 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
846 let snapshot = self.start_snapshot();
847 let r = f(&snapshot);
848 self.commit_from(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<'a, '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<'a, '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<'a, '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<'a, 'tcx>,
912 .unwrap_region_constraints()
913 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
916 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
917 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
920 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
922 T: at::ToTrace<'tcx>,
924 let origin = &ObligationCause::dummy();
926 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
927 // Ignore obligations, since we are unrolling
928 // everything anyway.
933 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
935 T: at::ToTrace<'tcx>,
937 let origin = &ObligationCause::dummy();
939 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
940 // Ignore obligations, since we are unrolling
941 // everything anyway.
946 #[instrument(skip(self), level = "debug")]
949 origin: SubregionOrigin<'tcx>,
953 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
956 /// Require that the region `r` be equal to one of the regions in
957 /// the set `regions`.
958 #[instrument(skip(self), level = "debug")]
959 pub fn member_constraint(
961 opaque_type_def_id: DefId,
962 definition_span: Span,
964 region: ty::Region<'tcx>,
965 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
967 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
976 /// Processes a `Coerce` predicate from the fulfillment context.
977 /// This is NOT the preferred way to handle coercion, which is to
978 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
980 /// This method here is actually a fallback that winds up being
981 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
982 /// and records a coercion predicate. Presently, this method is equivalent
983 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
984 /// actually requiring `a <: b`. This is of course a valid coercion,
985 /// but it's not as flexible as `FnCtxt::coerce` would be.
987 /// (We may refactor this in the future, but there are a number of
988 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
989 /// records adjustments that are required on the HIR in order to perform
990 /// the coercion, and we don't currently have a way to manage that.)
991 pub fn coerce_predicate(
993 cause: &ObligationCause<'tcx>,
994 param_env: ty::ParamEnv<'tcx>,
995 predicate: ty::PolyCoercePredicate<'tcx>,
996 ) -> Option<InferResult<'tcx, ()>> {
997 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
998 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
1002 self.subtype_predicate(cause, param_env, subtype_predicate)
1005 pub fn subtype_predicate(
1007 cause: &ObligationCause<'tcx>,
1008 param_env: ty::ParamEnv<'tcx>,
1009 predicate: ty::PolySubtypePredicate<'tcx>,
1010 ) -> Option<InferResult<'tcx, ()>> {
1011 // Check for two unresolved inference variables, in which case we can
1012 // make no progress. This is partly a micro-optimization, but it's
1013 // also an opportunity to "sub-unify" the variables. This isn't
1014 // *necessary* to prevent cycles, because they would eventually be sub-unified
1015 // anyhow during generalization, but it helps with diagnostics (we can detect
1016 // earlier that they are sub-unified).
1018 // Note that we can just skip the binders here because
1019 // type variables can't (at present, at
1020 // least) capture any of the things bound by this binder.
1022 // Note that this sub here is not just for diagnostics - it has semantic
1024 let r_a = self.shallow_resolve(predicate.skip_binder().a);
1025 let r_b = self.shallow_resolve(predicate.skip_binder().b);
1026 match (r_a.kind(), r_b.kind()) {
1027 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
1028 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
1034 Some(self.commit_if_ok(|_snapshot| {
1035 let ty::SubtypePredicate { a_is_expected, a, b } =
1036 self.replace_bound_vars_with_placeholders(predicate);
1038 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1044 pub fn region_outlives_predicate(
1046 cause: &traits::ObligationCause<'tcx>,
1047 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1048 ) -> UnitResult<'tcx> {
1049 self.commit_if_ok(|_snapshot| {
1050 let ty::OutlivesPredicate(r_a, r_b) =
1051 self.replace_bound_vars_with_placeholders(predicate);
1052 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1053 RelateRegionParamBound(cause.span)
1055 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1060 /// Number of type variables created so far.
1061 pub fn num_ty_vars(&self) -> usize {
1062 self.inner.borrow_mut().type_variables().num_vars()
1065 pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1066 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1069 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1070 self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1073 pub fn next_ty_var_in_universe(
1075 origin: TypeVariableOrigin,
1076 universe: ty::UniverseIndex,
1078 let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin);
1079 self.tcx.mk_ty_var(vid)
1082 pub fn next_const_var(
1085 origin: ConstVariableOrigin,
1086 ) -> &'tcx ty::Const<'tcx> {
1087 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1090 pub fn next_const_var_in_universe(
1093 origin: ConstVariableOrigin,
1094 universe: ty::UniverseIndex,
1095 ) -> &'tcx ty::Const<'tcx> {
1099 .const_unification_table()
1100 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1101 self.tcx.mk_const_var(vid, ty)
1104 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1105 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1107 val: ConstVariableValue::Unknown { universe: self.universe() },
1111 fn next_int_var_id(&self) -> IntVid {
1112 self.inner.borrow_mut().int_unification_table().new_key(None)
1115 pub fn next_int_var(&self) -> Ty<'tcx> {
1116 self.tcx.mk_int_var(self.next_int_var_id())
1119 fn next_float_var_id(&self) -> FloatVid {
1120 self.inner.borrow_mut().float_unification_table().new_key(None)
1123 pub fn next_float_var(&self) -> Ty<'tcx> {
1124 self.tcx.mk_float_var(self.next_float_var_id())
1127 /// Creates a fresh region variable with the next available index.
1128 /// The variable will be created in the maximum universe created
1129 /// thus far, allowing it to name any region created thus far.
1130 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1131 self.next_region_var_in_universe(origin, self.universe())
1134 /// Creates a fresh region variable with the next available index
1135 /// in the given universe; typically, you can use
1136 /// `next_region_var` and just use the maximal universe.
1137 pub fn next_region_var_in_universe(
1139 origin: RegionVariableOrigin,
1140 universe: ty::UniverseIndex,
1141 ) -> ty::Region<'tcx> {
1143 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1144 self.tcx.mk_region(ty::ReVar(region_var))
1147 /// Return the universe that the region `r` was created in. For
1148 /// most regions (e.g., `'static`, named regions from the user,
1149 /// etc) this is the root universe U0. For inference variables or
1150 /// placeholders, however, it will return the universe which which
1151 /// they are associated.
1152 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1153 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1156 /// Number of region variables created so far.
1157 pub fn num_region_vars(&self) -> usize {
1158 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1161 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1162 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1163 self.next_region_var(RegionVariableOrigin::Nll(origin))
1166 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1167 pub fn next_nll_region_var_in_universe(
1169 origin: NllRegionVariableOrigin,
1170 universe: ty::UniverseIndex,
1171 ) -> ty::Region<'tcx> {
1172 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1175 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1177 GenericParamDefKind::Lifetime => {
1178 // Create a region inference variable for the given
1179 // region parameter definition.
1180 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1182 GenericParamDefKind::Type { .. } => {
1183 // Create a type inference variable for the given
1184 // type parameter definition. The substitutions are
1185 // for actual parameters that may be referred to by
1186 // the default of this type parameter, if it exists.
1187 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1188 // used in a path such as `Foo::<T, U>::new()` will
1189 // use an inference variable for `C` with `[T, U]`
1190 // as the substitutions for the default, `(T, U)`.
1191 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1193 TypeVariableOrigin {
1194 kind: TypeVariableOriginKind::TypeParameterDefinition(
1202 self.tcx.mk_ty_var(ty_var_id).into()
1204 GenericParamDefKind::Const { .. } => {
1205 let origin = ConstVariableOrigin {
1206 kind: ConstVariableOriginKind::ConstParameterDefinition(
1213 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1215 val: ConstVariableValue::Unknown { universe: self.universe() },
1217 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1222 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1223 /// type/region parameter to a fresh inference variable.
1224 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1225 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1228 /// Returns `true` if errors have been reported since this infcx was
1229 /// created. This is sometimes used as a heuristic to skip
1230 /// reporting errors that often occur as a result of earlier
1231 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1232 /// inference variables, regionck errors).
1233 pub fn is_tainted_by_errors(&self) -> bool {
1235 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1236 tainted_by_errors_flag={})",
1237 self.tcx.sess.err_count(),
1238 self.err_count_on_creation,
1239 self.tainted_by_errors_flag.get()
1242 if self.tcx.sess.err_count() > self.err_count_on_creation {
1243 return true; // errors reported since this infcx was made
1245 self.tainted_by_errors_flag.get()
1248 /// Set the "tainted by errors" flag to true. We call this when we
1249 /// observe an error from a prior pass.
1250 pub fn set_tainted_by_errors(&self) {
1251 debug!("set_tainted_by_errors()");
1252 self.tainted_by_errors_flag.set(true)
1255 /// Process the region constraints and return any any errors that
1256 /// result. After this, no more unification operations should be
1257 /// done -- or the compiler will panic -- but it is legal to use
1258 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1259 pub fn resolve_regions(
1261 region_context: DefId,
1262 outlives_env: &OutlivesEnvironment<'tcx>,
1264 ) -> Vec<RegionResolutionError<'tcx>> {
1265 let (var_infos, data) = {
1266 let mut inner = self.inner.borrow_mut();
1267 let inner = &mut *inner;
1269 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1270 "region_obligations not empty: {:#?}",
1271 inner.region_obligations
1274 .region_constraint_storage
1276 .expect("regions already resolved")
1277 .with_log(&mut inner.undo_log)
1278 .into_infos_and_data()
1282 &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1284 let (lexical_region_resolutions, errors) =
1285 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1287 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1288 assert!(old_value.is_none());
1293 /// Process the region constraints and report any errors that
1294 /// result. After this, no more unification operations should be
1295 /// done -- or the compiler will panic -- but it is legal to use
1296 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1297 pub fn resolve_regions_and_report_errors(
1299 region_context: DefId,
1300 outlives_env: &OutlivesEnvironment<'tcx>,
1303 let errors = self.resolve_regions(region_context, outlives_env, mode);
1305 if !self.is_tainted_by_errors() {
1306 // As a heuristic, just skip reporting region errors
1307 // altogether if other errors have been reported while
1308 // this infcx was in use. This is totally hokey but
1309 // otherwise we have a hard time separating legit region
1310 // errors from silly ones.
1311 self.report_region_errors(&errors);
1315 /// Obtains (and clears) the current set of region
1316 /// constraints. The inference context is still usable: further
1317 /// unifications will simply add new constraints.
1319 /// This method is not meant to be used with normal lexical region
1320 /// resolution. Rather, it is used in the NLL mode as a kind of
1321 /// interim hack: basically we run normal type-check and generate
1322 /// region constraints as normal, but then we take them and
1323 /// translate them into the form that the NLL solver
1324 /// understands. See the NLL module for mode details.
1325 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1327 self.inner.borrow().region_obligations.is_empty(),
1328 "region_obligations not empty: {:#?}",
1329 self.inner.borrow().region_obligations
1332 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1335 /// Gives temporary access to the region constraint data.
1336 pub fn with_region_constraints<R>(
1338 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1340 let mut inner = self.inner.borrow_mut();
1341 op(inner.unwrap_region_constraints().data())
1344 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1345 let mut inner = self.inner.borrow_mut();
1346 let inner = &mut *inner;
1348 .region_constraint_storage
1350 .expect("regions already resolved")
1351 .with_log(&mut inner.undo_log)
1355 /// Takes ownership of the list of variable regions. This implies
1356 /// that all the region constraints have already been taken, and
1357 /// hence that `resolve_regions_and_report_errors` can never be
1358 /// called. This is used only during NLL processing to "hand off" ownership
1359 /// of the set of region variables into the NLL region context.
1360 pub fn take_region_var_origins(&self) -> VarInfos {
1361 let mut inner = self.inner.borrow_mut();
1362 let (var_infos, data) = inner
1363 .region_constraint_storage
1365 .expect("regions already resolved")
1366 .with_log(&mut inner.undo_log)
1367 .into_infos_and_data();
1368 assert!(data.is_empty());
1372 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1373 self.resolve_vars_if_possible(t).to_string()
1376 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1377 /// universe index of `TyVar(vid)`.
1378 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1379 use self::type_variable::TypeVariableValue;
1381 match self.inner.borrow_mut().type_variables().probe(vid) {
1382 TypeVariableValue::Known { value } => Ok(value),
1383 TypeVariableValue::Unknown { universe } => Err(universe),
1387 /// Resolve any type variables found in `value` -- but only one
1388 /// level. So, if the variable `?X` is bound to some type
1389 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1390 /// itself be bound to a type).
1392 /// Useful when you only need to inspect the outermost level of
1393 /// the type and don't care about nested types (or perhaps you
1394 /// will be resolving them as well, e.g. in a loop).
1395 pub fn shallow_resolve<T>(&self, value: T) -> T
1397 T: TypeFoldable<'tcx>,
1399 value.fold_with(&mut ShallowResolver { infcx: self })
1402 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1403 self.inner.borrow_mut().type_variables().root_var(var)
1406 /// Where possible, replaces type/const variables in
1407 /// `value` with their final value. Note that region variables
1408 /// are unaffected. If a type/const variable has not been unified, it
1409 /// is left as is. This is an idempotent operation that does
1410 /// not affect inference state in any way and so you can do it
1412 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1414 T: TypeFoldable<'tcx>,
1416 if !value.needs_infer() {
1417 return value; // Avoid duplicated subst-folding.
1419 let mut r = resolve::OpportunisticVarResolver::new(self);
1420 value.fold_with(&mut r)
1423 /// Returns the first unresolved variable contained in `T`. In the
1424 /// process of visiting `T`, this will resolve (where possible)
1425 /// type variables in `T`, but it never constructs the final,
1426 /// resolved type, so it's more efficient than
1427 /// `resolve_vars_if_possible()`.
1428 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1430 T: TypeFoldable<'tcx>,
1432 value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1435 pub fn probe_const_var(
1437 vid: ty::ConstVid<'tcx>,
1438 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1439 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1440 ConstVariableValue::Known { value } => Ok(value),
1441 ConstVariableValue::Unknown { universe } => Err(universe),
1445 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1447 * Attempts to resolve all type/region/const variables in
1448 * `value`. Region inference must have been run already (e.g.,
1449 * by calling `resolve_regions_and_report_errors`). If some
1450 * variable was never unified, an `Err` results.
1452 * This method is idempotent, but it not typically not invoked
1453 * except during the writeback phase.
1456 resolve::fully_resolve(self, value)
1459 // [Note-Type-error-reporting]
1460 // An invariant is that anytime the expected or actual type is Error (the special
1461 // error type, meaning that an error occurred when typechecking this expression),
1462 // this is a derived error. The error cascaded from another error (that was already
1463 // reported), so it's not useful to display it to the user.
1464 // The following methods implement this logic.
1465 // They check if either the actual or expected type is Error, and don't print the error
1466 // in this case. The typechecker should only ever report type errors involving mismatched
1467 // types using one of these methods, and should not call span_err directly for such
1470 pub fn type_error_struct_with_diag<M>(
1474 actual_ty: Ty<'tcx>,
1475 ) -> DiagnosticBuilder<'tcx>
1477 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1479 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1480 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1482 // Don't report an error if actual type is `Error`.
1483 if actual_ty.references_error() {
1484 return self.tcx.sess.diagnostic().struct_dummy();
1487 mk_diag(self.ty_to_string(actual_ty))
1490 pub fn report_mismatched_types(
1492 cause: &ObligationCause<'tcx>,
1495 err: TypeError<'tcx>,
1496 ) -> DiagnosticBuilder<'tcx> {
1497 let trace = TypeTrace::types(cause, true, expected, actual);
1498 self.report_and_explain_type_error(trace, &err)
1501 pub fn report_mismatched_consts(
1503 cause: &ObligationCause<'tcx>,
1504 expected: &'tcx ty::Const<'tcx>,
1505 actual: &'tcx ty::Const<'tcx>,
1506 err: TypeError<'tcx>,
1507 ) -> DiagnosticBuilder<'tcx> {
1508 let trace = TypeTrace::consts(cause, true, expected, actual);
1509 self.report_and_explain_type_error(trace, &err)
1512 pub fn replace_bound_vars_with_fresh_vars<T>(
1515 lbrct: LateBoundRegionConversionTime,
1516 value: ty::Binder<'tcx, T>,
1517 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1519 T: TypeFoldable<'tcx>,
1522 |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct));
1524 self.next_ty_var(TypeVariableOrigin {
1525 kind: TypeVariableOriginKind::MiscVariable,
1529 let fld_c = |_, ty| {
1530 self.next_const_var(
1532 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1535 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1538 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1539 pub fn verify_generic_bound(
1541 origin: SubregionOrigin<'tcx>,
1542 kind: GenericKind<'tcx>,
1543 a: ty::Region<'tcx>,
1544 bound: VerifyBound<'tcx>,
1546 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1550 .unwrap_region_constraints()
1551 .verify_generic_bound(origin, kind, a, bound);
1554 /// Obtains the latest type of the given closure; this may be a
1555 /// closure in the current function, in which case its
1556 /// `ClosureKind` may not yet be known.
1557 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1558 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1559 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1560 closure_kind_ty.to_opt_closure_kind()
1563 /// Clears the selection, evaluation, and projection caches. This is useful when
1564 /// repeatedly attempting to select an `Obligation` while changing only
1565 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1566 pub fn clear_caches(&self) {
1567 self.selection_cache.clear();
1568 self.evaluation_cache.clear();
1569 self.inner.borrow_mut().projection_cache().clear();
1572 pub fn universe(&self) -> ty::UniverseIndex {
1576 /// Creates and return a fresh universe that extends all previous
1577 /// universes. Updates `self.universe` to that new universe.
1578 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1579 let u = self.universe.get().next_universe();
1580 self.universe.set(u);
1584 /// Resolves and evaluates a constant.
1586 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1587 /// substitutions and environment are used to resolve the constant. Alternatively if the
1588 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1589 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1590 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1591 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1594 /// This handles inferences variables within both `param_env` and `substs` by
1595 /// performing the operation on their respective canonical forms.
1596 pub fn const_eval_resolve(
1598 param_env: ty::ParamEnv<'tcx>,
1599 unevaluated: ty::Unevaluated<'tcx>,
1601 ) -> EvalToConstValueResult<'tcx> {
1602 let mut original_values = OriginalQueryValues::default();
1603 let canonical = self.canonicalize_query((param_env, unevaluated), &mut original_values);
1605 let (param_env, unevaluated) = canonical.value;
1606 // The return value is the evaluated value which doesn't contain any reference to inference
1607 // variables, thus we don't need to substitute back the original values.
1608 self.tcx.const_eval_resolve(param_env, unevaluated, span)
1611 /// If `typ` is a type variable of some kind, resolve it one level
1612 /// (but do not resolve types found in the result). If `typ` is
1613 /// not a type variable, just return it unmodified.
1614 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1615 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1617 ty::Infer(ty::TyVar(v)) => {
1618 // Not entirely obvious: if `typ` is a type variable,
1619 // it can be resolved to an int/float variable, which
1620 // can then be recursively resolved, hence the
1621 // recursion. Note though that we prevent type
1622 // variables from unifying to other type variables
1623 // directly (though they may be embedded
1624 // structurally), and we prevent cycles in any case,
1625 // so this recursion should always be of very limited
1628 // Note: if these two lines are combined into one we get
1629 // dynamic borrow errors on `self.inner`.
1630 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1631 known.map_or(typ, |t| self.shallow_resolve_ty(t))
1634 ty::Infer(ty::IntVar(v)) => self
1637 .int_unification_table()
1639 .map(|v| v.to_type(self.tcx))
1642 ty::Infer(ty::FloatVar(v)) => self
1645 .float_unification_table()
1647 .map(|v| v.to_type(self.tcx))
1654 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1655 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1656 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1658 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1659 /// inlined, despite being large, because it has only two call sites that
1660 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1661 /// inference variables), and it handles both `Ty` and `ty::Const` without
1662 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1664 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1666 TyOrConstInferVar::Ty(v) => {
1667 use self::type_variable::TypeVariableValue;
1669 // If `inlined_probe` returns a `Known` value, it never equals
1670 // `ty::Infer(ty::TyVar(v))`.
1671 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1672 TypeVariableValue::Unknown { .. } => false,
1673 TypeVariableValue::Known { .. } => true,
1677 TyOrConstInferVar::TyInt(v) => {
1678 // If `inlined_probe_value` returns a value it's always a
1679 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1681 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1684 TyOrConstInferVar::TyFloat(v) => {
1685 // If `probe_value` returns a value it's always a
1686 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1688 // Not `inlined_probe_value(v)` because this call site is colder.
1689 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1692 TyOrConstInferVar::Const(v) => {
1693 // If `probe_value` returns a `Known` value, it never equals
1694 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1696 // Not `inlined_probe_value(v)` because this call site is colder.
1697 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1698 ConstVariableValue::Unknown { .. } => false,
1699 ConstVariableValue::Known { .. } => true,
1706 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1707 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1708 #[derive(Copy, Clone, Debug)]
1709 pub enum TyOrConstInferVar<'tcx> {
1710 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1712 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1714 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1717 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1718 Const(ConstVid<'tcx>),
1721 impl TyOrConstInferVar<'tcx> {
1722 /// Tries to extract an inference variable from a type or a constant, returns `None`
1723 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1724 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1725 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1726 match arg.unpack() {
1727 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1728 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1729 GenericArgKind::Lifetime(_) => None,
1733 /// Tries to extract an inference variable from a type, returns `None`
1734 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1735 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1737 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1738 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1739 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1744 /// Tries to extract an inference variable from a constant, returns `None`
1745 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1746 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1748 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1754 struct ShallowResolver<'a, 'tcx> {
1755 infcx: &'a InferCtxt<'a, 'tcx>,
1758 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1759 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1763 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1764 self.infcx.shallow_resolve_ty(ty)
1767 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1768 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1772 .const_unification_table()
1783 impl<'tcx> TypeTrace<'tcx> {
1784 pub fn span(&self) -> Span {
1789 cause: &ObligationCause<'tcx>,
1790 a_is_expected: bool,
1793 ) -> TypeTrace<'tcx> {
1794 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1798 cause: &ObligationCause<'tcx>,
1799 a_is_expected: bool,
1800 a: &'tcx ty::Const<'tcx>,
1801 b: &'tcx ty::Const<'tcx>,
1802 ) -> TypeTrace<'tcx> {
1803 TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
1807 impl<'tcx> SubregionOrigin<'tcx> {
1808 pub fn span(&self) -> Span {
1810 Subtype(ref a) => a.span(),
1811 RelateObjectBound(a) => a,
1812 RelateParamBound(a, ..) => a,
1813 RelateRegionParamBound(a) => a,
1815 ReborrowUpvar(a, _) => a,
1816 DataBorrowed(_, a) => a,
1817 ReferenceOutlivesReferent(_, a) => a,
1818 CompareImplMethodObligation { span, .. } => span,
1819 CompareImplTypeObligation { span, .. } => span,
1823 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1825 F: FnOnce() -> Self,
1828 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1829 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1832 traits::ObligationCauseCode::CompareImplMethodObligation {
1836 } => SubregionOrigin::CompareImplMethodObligation {
1843 traits::ObligationCauseCode::CompareImplTypeObligation {
1847 } => SubregionOrigin::CompareImplTypeObligation {
1859 impl RegionVariableOrigin {
1860 pub fn span(&self) -> Span {
1867 | EarlyBoundRegion(a, ..)
1868 | LateBoundRegion(a, ..)
1869 | UpvarRegion(_, a) => a,
1870 Nll(..) => bug!("NLL variable used with `span`"),
1875 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1876 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1879 "RegionObligation(sub_region={:?}, sup_type={:?})",
1880 self.sub_region, self.sup_type