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 { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId },
424 /// Comparing the signature and requirements of an impl associated type
425 /// against the containing trait
426 CompareImplTypeObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId },
429 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
430 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
431 static_assert_size!(SubregionOrigin<'_>, 32);
433 /// Times when we replace late-bound regions with variables:
434 #[derive(Clone, Copy, Debug)]
435 pub enum LateBoundRegionConversionTime {
436 /// when a fn is called
439 /// when two higher-ranked types are compared
442 /// when projecting an associated type
443 AssocTypeProjection(DefId),
446 /// Reasons to create a region inference variable
448 /// See `error_reporting` module for more details
449 #[derive(Copy, Clone, Debug)]
450 pub enum RegionVariableOrigin {
451 /// Region variables created for ill-categorized reasons,
452 /// mostly indicates places in need of refactoring
455 /// Regions created by a `&P` or `[...]` pattern
458 /// Regions created by `&` operator
461 /// Regions created as part of an autoref of a method receiver
462 Autoref(Span, ty::AssocItem),
464 /// Regions created as part of an automatic coercion
467 /// Region variables created as the values for early-bound regions
468 EarlyBoundRegion(Span, Symbol),
470 /// Region variables created for bound regions
471 /// in a function or method that is called
472 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
474 UpvarRegion(ty::UpvarId, Span),
476 /// This origin is used for the inference variables that we create
477 /// during NLL region processing.
478 Nll(NllRegionVariableOrigin),
481 #[derive(Copy, Clone, Debug)]
482 pub enum NllRegionVariableOrigin {
483 /// During NLL region processing, we create variables for free
484 /// regions that we encounter in the function signature and
485 /// elsewhere. This origin indices we've got one of those.
488 /// "Universal" instantiation of a higher-ranked region (e.g.,
489 /// from a `for<'a> T` binder). Meant to represent "any region".
490 Placeholder(ty::PlaceholderRegion),
492 /// The variable we create to represent `'empty(U0)`.
496 /// If this is true, then this variable was created to represent a lifetime
497 /// bound in a `for` binder. For example, it might have been created to
498 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
499 /// Such variables are created when we are trying to figure out if there
500 /// is any valid instantiation of `'a` that could fit into some scenario.
502 /// This is used to inform error reporting: in the case that we are trying to
503 /// determine whether there is any valid instantiation of a `'a` variable that meets
504 /// some constraint C, we want to blame the "source" of that `for` type,
505 /// rather than blaming the source of the constraint C.
510 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
511 #[derive(Copy, Clone, Debug)]
512 pub enum FixupError<'tcx> {
513 UnresolvedIntTy(IntVid),
514 UnresolvedFloatTy(FloatVid),
516 UnresolvedConst(ConstVid<'tcx>),
519 /// See the `region_obligations` field for more information.
521 pub struct RegionObligation<'tcx> {
522 pub sub_region: ty::Region<'tcx>,
523 pub sup_type: Ty<'tcx>,
524 pub origin: SubregionOrigin<'tcx>,
527 impl<'tcx> fmt::Display for FixupError<'tcx> {
528 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529 use self::FixupError::*;
532 UnresolvedIntTy(_) => write!(
534 "cannot determine the type of this integer; \
535 add a suffix to specify the type explicitly"
537 UnresolvedFloatTy(_) => write!(
539 "cannot determine the type of this number; \
540 add a suffix to specify the type explicitly"
542 UnresolvedTy(_) => write!(f, "unconstrained type"),
543 UnresolvedConst(_) => write!(f, "unconstrained const value"),
548 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
549 /// Necessary because we can't write the following bound:
550 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
551 pub struct InferCtxtBuilder<'tcx> {
553 fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
554 defining_use_anchor: LocalDefId,
557 pub trait TyCtxtInferExt<'tcx> {
558 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
561 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
562 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
565 defining_use_anchor: CRATE_DEF_ID,
566 fresh_typeck_results: None,
571 impl<'tcx> InferCtxtBuilder<'tcx> {
572 /// Used only by `rustc_typeck` during body type-checking/inference,
573 /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
574 /// Will also change the scope for opaque type defining use checks to the given owner.
575 pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
576 self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
577 self.with_opaque_type_inference(table_owner)
580 /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
581 /// you need to call this function. Otherwise the opaque type will be treated opaquely.
583 /// It is only meant to be called in two places, for typeck
584 /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used
586 pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self {
587 self.defining_use_anchor = defining_use_anchor;
591 /// Given a canonical value `C` as a starting point, create an
592 /// inference context that contains each of the bound values
593 /// within instantiated as a fresh variable. The `f` closure is
594 /// invoked with the new infcx, along with the instantiated value
595 /// `V` and a substitution `S`. This substitution `S` maps from
596 /// the bound values in `C` to their instantiated values in `V`
597 /// (in other words, `S(C) = V`).
598 pub fn enter_with_canonical<T, R>(
601 canonical: &Canonical<'tcx, T>,
602 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
605 T: TypeFoldable<'tcx>,
609 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
610 f(infcx, value, subst)
614 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
615 let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self;
616 let in_progress_typeck_results = fresh_typeck_results.as_ref();
620 in_progress_typeck_results,
621 inner: RefCell::new(InferCtxtInner::new()),
622 lexical_region_resolutions: RefCell::new(None),
623 selection_cache: Default::default(),
624 evaluation_cache: Default::default(),
625 reported_trait_errors: Default::default(),
626 reported_closure_mismatch: Default::default(),
627 tainted_by_errors_flag: Cell::new(false),
628 err_count_on_creation: tcx.sess.err_count(),
629 in_snapshot: Cell::new(false),
630 skip_leak_check: Cell::new(false),
631 universe: Cell::new(ty::UniverseIndex::ROOT),
636 impl<'tcx, T> InferOk<'tcx, T> {
637 pub fn unit(self) -> InferOk<'tcx, ()> {
638 InferOk { value: (), obligations: self.obligations }
641 /// Extracts `value`, registering any obligations into `fulfill_cx`.
642 pub fn into_value_registering_obligations(
644 infcx: &InferCtxt<'_, 'tcx>,
645 fulfill_cx: &mut dyn TraitEngine<'tcx>,
647 let InferOk { value, obligations } = self;
648 for obligation in obligations {
649 fulfill_cx.register_predicate_obligation(infcx, obligation);
655 impl<'tcx> InferOk<'tcx, ()> {
656 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
661 #[must_use = "once you start a snapshot, you should always consume it"]
662 pub struct CombinedSnapshot<'a, 'tcx> {
663 undo_snapshot: Snapshot<'tcx>,
664 region_constraints_snapshot: RegionSnapshot,
665 universe: ty::UniverseIndex,
666 was_in_snapshot: bool,
667 _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
670 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
671 /// calls `tcx.try_unify_abstract_consts` after
672 /// canonicalizing the consts.
673 pub fn try_unify_abstract_consts(
675 a: ty::Unevaluated<'tcx, ()>,
676 b: ty::Unevaluated<'tcx, ()>,
678 let canonical = self.canonicalize_query((a, b), &mut OriginalQueryValues::default());
679 debug!("canonical consts: {:?}", &canonical.value);
681 self.tcx.try_unify_abstract_consts(canonical.value)
684 pub fn is_in_snapshot(&self) -> bool {
685 self.in_snapshot.get()
688 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
689 t.fold_with(&mut self.freshener())
692 /// Returns the origin of the type variable identified by `vid`, or `None`
693 /// if this is not a type variable.
695 /// No attempt is made to resolve `ty`.
696 pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
698 ty::Infer(ty::TyVar(vid)) => {
699 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
705 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
706 freshen::TypeFreshener::new(self, false)
709 /// Like `freshener`, but does not replace `'static` regions.
710 pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
711 freshen::TypeFreshener::new(self, true)
714 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
715 let mut inner = self.inner.borrow_mut();
716 let mut vars: Vec<Ty<'_>> = inner
718 .unsolved_variables()
720 .map(|t| self.tcx.mk_ty_var(t))
723 (0..inner.int_unification_table().len())
724 .map(|i| ty::IntVid { index: i as u32 })
725 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
726 .map(|v| self.tcx.mk_int_var(v)),
729 (0..inner.float_unification_table().len())
730 .map(|i| ty::FloatVid { index: i as u32 })
731 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
732 .map(|v| self.tcx.mk_float_var(v)),
739 trace: TypeTrace<'tcx>,
740 param_env: ty::ParamEnv<'tcx>,
741 ) -> CombineFields<'a, 'tcx> {
747 obligations: PredicateObligations::new(),
751 /// Clear the "currently in a snapshot" flag, invoke the closure,
752 /// then restore the flag to its original value. This flag is a
753 /// debugging measure designed to detect cases where we start a
754 /// snapshot, create type variables, and register obligations
755 /// which may involve those type variables in the fulfillment cx,
756 /// potentially leaving "dangling type variables" behind.
757 /// In such cases, an assertion will fail when attempting to
758 /// register obligations, within a snapshot. Very useful, much
759 /// better than grovelling through megabytes of `RUSTC_LOG` output.
761 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
762 /// sometimes create a "mini-fulfilment-cx" in which we enroll
763 /// obligations. As long as this fulfillment cx is fully drained
764 /// before we return, this is not a problem, as there won't be any
765 /// escaping obligations in the main cx. In those cases, you can
766 /// use this function.
767 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
769 F: FnOnce(&Self) -> R,
771 let flag = self.in_snapshot.replace(false);
772 let result = func(self);
773 self.in_snapshot.set(flag);
777 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
778 debug!("start_snapshot()");
780 let in_snapshot = self.in_snapshot.replace(true);
782 let mut inner = self.inner.borrow_mut();
785 undo_snapshot: inner.undo_log.start_snapshot(),
786 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
787 universe: self.universe(),
788 was_in_snapshot: in_snapshot,
789 // Borrow typeck results "in progress" (i.e., during typeck)
790 // to ban writes from within a snapshot to them.
791 _in_progress_typeck_results: self
792 .in_progress_typeck_results
793 .map(|typeck_results| typeck_results.borrow()),
797 #[instrument(skip(self, snapshot), level = "debug")]
798 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
799 let CombinedSnapshot {
801 region_constraints_snapshot,
804 _in_progress_typeck_results,
807 self.in_snapshot.set(was_in_snapshot);
808 self.universe.set(universe);
810 let mut inner = self.inner.borrow_mut();
811 inner.rollback_to(undo_snapshot);
812 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
815 #[instrument(skip(self, snapshot), level = "debug")]
816 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
817 let CombinedSnapshot {
819 region_constraints_snapshot: _,
822 _in_progress_typeck_results,
825 self.in_snapshot.set(was_in_snapshot);
827 self.inner.borrow_mut().commit(undo_snapshot);
830 /// Executes `f` and commit the bindings.
831 #[instrument(skip(self, f), level = "debug")]
832 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
834 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
836 let snapshot = self.start_snapshot();
837 let r = f(&snapshot);
838 self.commit_from(snapshot);
842 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
843 #[instrument(skip(self, f), level = "debug")]
844 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
846 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
848 let snapshot = self.start_snapshot();
849 let r = f(&snapshot);
850 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
853 self.commit_from(snapshot);
856 self.rollback_to("commit_if_ok -- error", snapshot);
862 /// Execute `f` then unroll any bindings it creates.
863 #[instrument(skip(self, f), level = "debug")]
864 pub fn probe<R, F>(&self, f: F) -> R
866 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
868 let snapshot = self.start_snapshot();
869 let r = f(&snapshot);
870 self.rollback_to("probe", snapshot);
874 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
875 #[instrument(skip(self, f), level = "debug")]
876 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
878 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
880 let snapshot = self.start_snapshot();
881 let was_skip_leak_check = self.skip_leak_check.get();
883 self.skip_leak_check.set(true);
885 let r = f(&snapshot);
886 self.rollback_to("probe", snapshot);
887 self.skip_leak_check.set(was_skip_leak_check);
891 /// Scan the constraints produced since `snapshot` began and returns:
893 /// - `None` -- if none of them involve "region outlives" constraints
894 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
895 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
896 pub fn region_constraints_added_in_snapshot(
898 snapshot: &CombinedSnapshot<'a, 'tcx>,
902 .unwrap_region_constraints()
903 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
906 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
907 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
910 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
912 T: at::ToTrace<'tcx>,
914 let origin = &ObligationCause::dummy();
916 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
917 // Ignore obligations, since we are unrolling
918 // everything anyway.
923 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
925 T: at::ToTrace<'tcx>,
927 let origin = &ObligationCause::dummy();
929 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
930 // Ignore obligations, since we are unrolling
931 // everything anyway.
936 #[instrument(skip(self), level = "debug")]
939 origin: SubregionOrigin<'tcx>,
943 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
946 /// Require that the region `r` be equal to one of the regions in
947 /// the set `regions`.
948 #[instrument(skip(self), level = "debug")]
949 pub fn member_constraint(
951 opaque_type_def_id: DefId,
952 definition_span: Span,
954 region: ty::Region<'tcx>,
955 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
957 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
966 /// Processes a `Coerce` predicate from the fulfillment context.
967 /// This is NOT the preferred way to handle coercion, which is to
968 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
970 /// This method here is actually a fallback that winds up being
971 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
972 /// and records a coercion predicate. Presently, this method is equivalent
973 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
974 /// actually requiring `a <: b`. This is of course a valid coercion,
975 /// but it's not as flexible as `FnCtxt::coerce` would be.
977 /// (We may refactor this in the future, but there are a number of
978 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
979 /// records adjustments that are required on the HIR in order to perform
980 /// the coercion, and we don't currently have a way to manage that.)
981 pub fn coerce_predicate(
983 cause: &ObligationCause<'tcx>,
984 param_env: ty::ParamEnv<'tcx>,
985 predicate: ty::PolyCoercePredicate<'tcx>,
986 ) -> Option<InferResult<'tcx, ()>> {
987 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
988 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
992 self.subtype_predicate(cause, param_env, subtype_predicate)
995 pub fn subtype_predicate(
997 cause: &ObligationCause<'tcx>,
998 param_env: ty::ParamEnv<'tcx>,
999 predicate: ty::PolySubtypePredicate<'tcx>,
1000 ) -> Option<InferResult<'tcx, ()>> {
1001 // Check for two unresolved inference variables, in which case we can
1002 // make no progress. This is partly a micro-optimization, but it's
1003 // also an opportunity to "sub-unify" the variables. This isn't
1004 // *necessary* to prevent cycles, because they would eventually be sub-unified
1005 // anyhow during generalization, but it helps with diagnostics (we can detect
1006 // earlier that they are sub-unified).
1008 // Note that we can just skip the binders here because
1009 // type variables can't (at present, at
1010 // least) capture any of the things bound by this binder.
1012 // Note that this sub here is not just for diagnostics - it has semantic
1014 let r_a = self.shallow_resolve(predicate.skip_binder().a);
1015 let r_b = self.shallow_resolve(predicate.skip_binder().b);
1016 match (r_a.kind(), r_b.kind()) {
1017 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
1018 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
1024 Some(self.commit_if_ok(|_snapshot| {
1025 let ty::SubtypePredicate { a_is_expected, a, b } =
1026 self.replace_bound_vars_with_placeholders(predicate);
1028 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1034 pub fn region_outlives_predicate(
1036 cause: &traits::ObligationCause<'tcx>,
1037 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1038 ) -> UnitResult<'tcx> {
1039 self.commit_if_ok(|_snapshot| {
1040 let ty::OutlivesPredicate(r_a, r_b) =
1041 self.replace_bound_vars_with_placeholders(predicate);
1042 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1043 RelateRegionParamBound(cause.span)
1045 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1050 /// Number of type variables created so far.
1051 pub fn num_ty_vars(&self) -> usize {
1052 self.inner.borrow_mut().type_variables().num_vars()
1055 pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1056 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1059 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1060 self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1063 pub fn next_ty_var_in_universe(
1065 origin: TypeVariableOrigin,
1066 universe: ty::UniverseIndex,
1068 let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin);
1069 self.tcx.mk_ty_var(vid)
1072 pub fn next_const_var(
1075 origin: ConstVariableOrigin,
1076 ) -> &'tcx ty::Const<'tcx> {
1077 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1080 pub fn next_const_var_in_universe(
1083 origin: ConstVariableOrigin,
1084 universe: ty::UniverseIndex,
1085 ) -> &'tcx ty::Const<'tcx> {
1089 .const_unification_table()
1090 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1091 self.tcx.mk_const_var(vid, ty)
1094 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1095 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1097 val: ConstVariableValue::Unknown { universe: self.universe() },
1101 fn next_int_var_id(&self) -> IntVid {
1102 self.inner.borrow_mut().int_unification_table().new_key(None)
1105 pub fn next_int_var(&self) -> Ty<'tcx> {
1106 self.tcx.mk_int_var(self.next_int_var_id())
1109 fn next_float_var_id(&self) -> FloatVid {
1110 self.inner.borrow_mut().float_unification_table().new_key(None)
1113 pub fn next_float_var(&self) -> Ty<'tcx> {
1114 self.tcx.mk_float_var(self.next_float_var_id())
1117 /// Creates a fresh region variable with the next available index.
1118 /// The variable will be created in the maximum universe created
1119 /// thus far, allowing it to name any region created thus far.
1120 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1121 self.next_region_var_in_universe(origin, self.universe())
1124 /// Creates a fresh region variable with the next available index
1125 /// in the given universe; typically, you can use
1126 /// `next_region_var` and just use the maximal universe.
1127 pub fn next_region_var_in_universe(
1129 origin: RegionVariableOrigin,
1130 universe: ty::UniverseIndex,
1131 ) -> ty::Region<'tcx> {
1133 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1134 self.tcx.mk_region(ty::ReVar(region_var))
1137 /// Return the universe that the region `r` was created in. For
1138 /// most regions (e.g., `'static`, named regions from the user,
1139 /// etc) this is the root universe U0. For inference variables or
1140 /// placeholders, however, it will return the universe which which
1141 /// they are associated.
1142 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1143 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1146 /// Number of region variables created so far.
1147 pub fn num_region_vars(&self) -> usize {
1148 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1151 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1152 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1153 self.next_region_var(RegionVariableOrigin::Nll(origin))
1156 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1157 pub fn next_nll_region_var_in_universe(
1159 origin: NllRegionVariableOrigin,
1160 universe: ty::UniverseIndex,
1161 ) -> ty::Region<'tcx> {
1162 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1165 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1167 GenericParamDefKind::Lifetime => {
1168 // Create a region inference variable for the given
1169 // region parameter definition.
1170 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1172 GenericParamDefKind::Type { .. } => {
1173 // Create a type inference variable for the given
1174 // type parameter definition. The substitutions are
1175 // for actual parameters that may be referred to by
1176 // the default of this type parameter, if it exists.
1177 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1178 // used in a path such as `Foo::<T, U>::new()` will
1179 // use an inference variable for `C` with `[T, U]`
1180 // as the substitutions for the default, `(T, U)`.
1181 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1183 TypeVariableOrigin {
1184 kind: TypeVariableOriginKind::TypeParameterDefinition(
1192 self.tcx.mk_ty_var(ty_var_id).into()
1194 GenericParamDefKind::Const { .. } => {
1195 let origin = ConstVariableOrigin {
1196 kind: ConstVariableOriginKind::ConstParameterDefinition(
1203 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1205 val: ConstVariableValue::Unknown { universe: self.universe() },
1207 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1212 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1213 /// type/region parameter to a fresh inference variable.
1214 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1215 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1218 /// Returns `true` if errors have been reported since this infcx was
1219 /// created. This is sometimes used as a heuristic to skip
1220 /// reporting errors that often occur as a result of earlier
1221 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1222 /// inference variables, regionck errors).
1223 pub fn is_tainted_by_errors(&self) -> bool {
1225 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1226 tainted_by_errors_flag={})",
1227 self.tcx.sess.err_count(),
1228 self.err_count_on_creation,
1229 self.tainted_by_errors_flag.get()
1232 if self.tcx.sess.err_count() > self.err_count_on_creation {
1233 return true; // errors reported since this infcx was made
1235 self.tainted_by_errors_flag.get()
1238 /// Set the "tainted by errors" flag to true. We call this when we
1239 /// observe an error from a prior pass.
1240 pub fn set_tainted_by_errors(&self) {
1241 debug!("set_tainted_by_errors()");
1242 self.tainted_by_errors_flag.set(true)
1245 /// Process the region constraints and return any any errors that
1246 /// result. After this, no more unification operations should be
1247 /// done -- or the compiler will panic -- but it is legal to use
1248 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1249 pub fn resolve_regions(
1251 region_context: DefId,
1252 outlives_env: &OutlivesEnvironment<'tcx>,
1254 ) -> Vec<RegionResolutionError<'tcx>> {
1255 let (var_infos, data) = {
1256 let mut inner = self.inner.borrow_mut();
1257 let inner = &mut *inner;
1259 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1260 "region_obligations not empty: {:#?}",
1261 inner.region_obligations
1264 .region_constraint_storage
1266 .expect("regions already resolved")
1267 .with_log(&mut inner.undo_log)
1268 .into_infos_and_data()
1272 &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1274 let (lexical_region_resolutions, errors) =
1275 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1277 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1278 assert!(old_value.is_none());
1283 /// Process the region constraints and report any errors that
1284 /// result. After this, no more unification operations should be
1285 /// done -- or the compiler will panic -- but it is legal to use
1286 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1287 pub fn resolve_regions_and_report_errors(
1289 region_context: DefId,
1290 outlives_env: &OutlivesEnvironment<'tcx>,
1293 let errors = self.resolve_regions(region_context, outlives_env, mode);
1295 if !self.is_tainted_by_errors() {
1296 // As a heuristic, just skip reporting region errors
1297 // altogether if other errors have been reported while
1298 // this infcx was in use. This is totally hokey but
1299 // otherwise we have a hard time separating legit region
1300 // errors from silly ones.
1301 self.report_region_errors(&errors);
1305 /// Obtains (and clears) the current set of region
1306 /// constraints. The inference context is still usable: further
1307 /// unifications will simply add new constraints.
1309 /// This method is not meant to be used with normal lexical region
1310 /// resolution. Rather, it is used in the NLL mode as a kind of
1311 /// interim hack: basically we run normal type-check and generate
1312 /// region constraints as normal, but then we take them and
1313 /// translate them into the form that the NLL solver
1314 /// understands. See the NLL module for mode details.
1315 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1317 self.inner.borrow().region_obligations.is_empty(),
1318 "region_obligations not empty: {:#?}",
1319 self.inner.borrow().region_obligations
1322 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1325 /// Gives temporary access to the region constraint data.
1326 pub fn with_region_constraints<R>(
1328 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1330 let mut inner = self.inner.borrow_mut();
1331 op(inner.unwrap_region_constraints().data())
1334 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1335 let mut inner = self.inner.borrow_mut();
1336 let inner = &mut *inner;
1338 .region_constraint_storage
1340 .expect("regions already resolved")
1341 .with_log(&mut inner.undo_log)
1345 /// Takes ownership of the list of variable regions. This implies
1346 /// that all the region constraints have already been taken, and
1347 /// hence that `resolve_regions_and_report_errors` can never be
1348 /// called. This is used only during NLL processing to "hand off" ownership
1349 /// of the set of region variables into the NLL region context.
1350 pub fn take_region_var_origins(&self) -> VarInfos {
1351 let mut inner = self.inner.borrow_mut();
1352 let (var_infos, data) = inner
1353 .region_constraint_storage
1355 .expect("regions already resolved")
1356 .with_log(&mut inner.undo_log)
1357 .into_infos_and_data();
1358 assert!(data.is_empty());
1362 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1363 self.resolve_vars_if_possible(t).to_string()
1366 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1367 /// universe index of `TyVar(vid)`.
1368 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1369 use self::type_variable::TypeVariableValue;
1371 match self.inner.borrow_mut().type_variables().probe(vid) {
1372 TypeVariableValue::Known { value } => Ok(value),
1373 TypeVariableValue::Unknown { universe } => Err(universe),
1377 /// Resolve any type variables found in `value` -- but only one
1378 /// level. So, if the variable `?X` is bound to some type
1379 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1380 /// itself be bound to a type).
1382 /// Useful when you only need to inspect the outermost level of
1383 /// the type and don't care about nested types (or perhaps you
1384 /// will be resolving them as well, e.g. in a loop).
1385 pub fn shallow_resolve<T>(&self, value: T) -> T
1387 T: TypeFoldable<'tcx>,
1389 value.fold_with(&mut ShallowResolver { infcx: self })
1392 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1393 self.inner.borrow_mut().type_variables().root_var(var)
1396 /// Where possible, replaces type/const variables in
1397 /// `value` with their final value. Note that region variables
1398 /// are unaffected. If a type/const variable has not been unified, it
1399 /// is left as is. This is an idempotent operation that does
1400 /// not affect inference state in any way and so you can do it
1402 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1404 T: TypeFoldable<'tcx>,
1406 if !value.needs_infer() {
1407 return value; // Avoid duplicated subst-folding.
1409 let mut r = resolve::OpportunisticVarResolver::new(self);
1410 value.fold_with(&mut r)
1413 /// Returns the first unresolved variable contained in `T`. In the
1414 /// process of visiting `T`, this will resolve (where possible)
1415 /// type variables in `T`, but it never constructs the final,
1416 /// resolved type, so it's more efficient than
1417 /// `resolve_vars_if_possible()`.
1418 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1420 T: TypeFoldable<'tcx>,
1422 value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1425 pub fn probe_const_var(
1427 vid: ty::ConstVid<'tcx>,
1428 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1429 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1430 ConstVariableValue::Known { value } => Ok(value),
1431 ConstVariableValue::Unknown { universe } => Err(universe),
1435 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1437 * Attempts to resolve all type/region/const variables in
1438 * `value`. Region inference must have been run already (e.g.,
1439 * by calling `resolve_regions_and_report_errors`). If some
1440 * variable was never unified, an `Err` results.
1442 * This method is idempotent, but it not typically not invoked
1443 * except during the writeback phase.
1446 resolve::fully_resolve(self, value)
1449 // [Note-Type-error-reporting]
1450 // An invariant is that anytime the expected or actual type is Error (the special
1451 // error type, meaning that an error occurred when typechecking this expression),
1452 // this is a derived error. The error cascaded from another error (that was already
1453 // reported), so it's not useful to display it to the user.
1454 // The following methods implement this logic.
1455 // They check if either the actual or expected type is Error, and don't print the error
1456 // in this case. The typechecker should only ever report type errors involving mismatched
1457 // types using one of these methods, and should not call span_err directly for such
1460 pub fn type_error_struct_with_diag<M>(
1464 actual_ty: Ty<'tcx>,
1465 ) -> DiagnosticBuilder<'tcx>
1467 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1469 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1470 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1472 // Don't report an error if actual type is `Error`.
1473 if actual_ty.references_error() {
1474 return self.tcx.sess.diagnostic().struct_dummy();
1477 mk_diag(self.ty_to_string(actual_ty))
1480 pub fn report_mismatched_types(
1482 cause: &ObligationCause<'tcx>,
1485 err: TypeError<'tcx>,
1486 ) -> DiagnosticBuilder<'tcx> {
1487 let trace = TypeTrace::types(cause, true, expected, actual);
1488 self.report_and_explain_type_error(trace, &err)
1491 pub fn report_mismatched_consts(
1493 cause: &ObligationCause<'tcx>,
1494 expected: &'tcx ty::Const<'tcx>,
1495 actual: &'tcx ty::Const<'tcx>,
1496 err: TypeError<'tcx>,
1497 ) -> DiagnosticBuilder<'tcx> {
1498 let trace = TypeTrace::consts(cause, true, expected, actual);
1499 self.report_and_explain_type_error(trace, &err)
1502 pub fn replace_bound_vars_with_fresh_vars<T>(
1505 lbrct: LateBoundRegionConversionTime,
1506 value: ty::Binder<'tcx, T>,
1507 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1509 T: TypeFoldable<'tcx>,
1512 |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct));
1514 self.next_ty_var(TypeVariableOrigin {
1515 kind: TypeVariableOriginKind::MiscVariable,
1519 let fld_c = |_, ty| {
1520 self.next_const_var(
1522 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1525 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1528 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1529 pub fn verify_generic_bound(
1531 origin: SubregionOrigin<'tcx>,
1532 kind: GenericKind<'tcx>,
1533 a: ty::Region<'tcx>,
1534 bound: VerifyBound<'tcx>,
1536 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1540 .unwrap_region_constraints()
1541 .verify_generic_bound(origin, kind, a, bound);
1544 /// Obtains the latest type of the given closure; this may be a
1545 /// closure in the current function, in which case its
1546 /// `ClosureKind` may not yet be known.
1547 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1548 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1549 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1550 closure_kind_ty.to_opt_closure_kind()
1553 /// Clears the selection, evaluation, and projection caches. This is useful when
1554 /// repeatedly attempting to select an `Obligation` while changing only
1555 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1556 pub fn clear_caches(&self) {
1557 self.selection_cache.clear();
1558 self.evaluation_cache.clear();
1559 self.inner.borrow_mut().projection_cache().clear();
1562 pub fn universe(&self) -> ty::UniverseIndex {
1566 /// Creates and return a fresh universe that extends all previous
1567 /// universes. Updates `self.universe` to that new universe.
1568 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1569 let u = self.universe.get().next_universe();
1570 self.universe.set(u);
1574 /// Resolves and evaluates a constant.
1576 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1577 /// substitutions and environment are used to resolve the constant. Alternatively if the
1578 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1579 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1580 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1581 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1584 /// This handles inferences variables within both `param_env` and `substs` by
1585 /// performing the operation on their respective canonical forms.
1586 pub fn const_eval_resolve(
1588 param_env: ty::ParamEnv<'tcx>,
1589 unevaluated: ty::Unevaluated<'tcx>,
1591 ) -> EvalToConstValueResult<'tcx> {
1592 let mut original_values = OriginalQueryValues::default();
1593 let canonical = self.canonicalize_query((param_env, unevaluated), &mut original_values);
1595 let (param_env, unevaluated) = canonical.value;
1596 // The return value is the evaluated value which doesn't contain any reference to inference
1597 // variables, thus we don't need to substitute back the original values.
1598 self.tcx.const_eval_resolve(param_env, unevaluated, span)
1601 /// If `typ` is a type variable of some kind, resolve it one level
1602 /// (but do not resolve types found in the result). If `typ` is
1603 /// not a type variable, just return it unmodified.
1604 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1605 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1607 ty::Infer(ty::TyVar(v)) => {
1608 // Not entirely obvious: if `typ` is a type variable,
1609 // it can be resolved to an int/float variable, which
1610 // can then be recursively resolved, hence the
1611 // recursion. Note though that we prevent type
1612 // variables from unifying to other type variables
1613 // directly (though they may be embedded
1614 // structurally), and we prevent cycles in any case,
1615 // so this recursion should always be of very limited
1618 // Note: if these two lines are combined into one we get
1619 // dynamic borrow errors on `self.inner`.
1620 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1621 known.map_or(typ, |t| self.shallow_resolve_ty(t))
1624 ty::Infer(ty::IntVar(v)) => self
1627 .int_unification_table()
1629 .map(|v| v.to_type(self.tcx))
1632 ty::Infer(ty::FloatVar(v)) => self
1635 .float_unification_table()
1637 .map(|v| v.to_type(self.tcx))
1644 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1645 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1646 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1648 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1649 /// inlined, despite being large, because it has only two call sites that
1650 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1651 /// inference variables), and it handles both `Ty` and `ty::Const` without
1652 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1654 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1656 TyOrConstInferVar::Ty(v) => {
1657 use self::type_variable::TypeVariableValue;
1659 // If `inlined_probe` returns a `Known` value, it never equals
1660 // `ty::Infer(ty::TyVar(v))`.
1661 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1662 TypeVariableValue::Unknown { .. } => false,
1663 TypeVariableValue::Known { .. } => true,
1667 TyOrConstInferVar::TyInt(v) => {
1668 // If `inlined_probe_value` returns a value it's always a
1669 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1671 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1674 TyOrConstInferVar::TyFloat(v) => {
1675 // If `probe_value` returns a value it's always a
1676 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1678 // Not `inlined_probe_value(v)` because this call site is colder.
1679 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1682 TyOrConstInferVar::Const(v) => {
1683 // If `probe_value` returns a `Known` value, it never equals
1684 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1686 // Not `inlined_probe_value(v)` because this call site is colder.
1687 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1688 ConstVariableValue::Unknown { .. } => false,
1689 ConstVariableValue::Known { .. } => true,
1696 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1697 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1698 #[derive(Copy, Clone, Debug)]
1699 pub enum TyOrConstInferVar<'tcx> {
1700 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1702 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1704 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1707 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1708 Const(ConstVid<'tcx>),
1711 impl TyOrConstInferVar<'tcx> {
1712 /// Tries to extract an inference variable from a type or a constant, returns `None`
1713 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1714 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1715 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1716 match arg.unpack() {
1717 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1718 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1719 GenericArgKind::Lifetime(_) => None,
1723 /// Tries to extract an inference variable from a type, returns `None`
1724 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1725 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1727 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1728 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1729 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1734 /// Tries to extract an inference variable from a constant, returns `None`
1735 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1736 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1738 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1744 struct ShallowResolver<'a, 'tcx> {
1745 infcx: &'a InferCtxt<'a, 'tcx>,
1748 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1749 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1753 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1754 self.infcx.shallow_resolve_ty(ty)
1757 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1758 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1762 .const_unification_table()
1773 impl<'tcx> TypeTrace<'tcx> {
1774 pub fn span(&self) -> Span {
1779 cause: &ObligationCause<'tcx>,
1780 a_is_expected: bool,
1783 ) -> TypeTrace<'tcx> {
1784 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1788 cause: &ObligationCause<'tcx>,
1789 a_is_expected: bool,
1790 a: &'tcx ty::Const<'tcx>,
1791 b: &'tcx ty::Const<'tcx>,
1792 ) -> TypeTrace<'tcx> {
1793 TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
1797 impl<'tcx> SubregionOrigin<'tcx> {
1798 pub fn span(&self) -> Span {
1800 Subtype(ref a) => a.span(),
1801 RelateObjectBound(a) => a,
1802 RelateParamBound(a, ..) => a,
1803 RelateRegionParamBound(a) => a,
1805 ReborrowUpvar(a, _) => a,
1806 DataBorrowed(_, a) => a,
1807 ReferenceOutlivesReferent(_, a) => a,
1808 CompareImplMethodObligation { span, .. } => span,
1809 CompareImplTypeObligation { span, .. } => span,
1813 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1815 F: FnOnce() -> Self,
1818 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1819 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1822 traits::ObligationCauseCode::CompareImplMethodObligation {
1825 } => SubregionOrigin::CompareImplMethodObligation {
1831 traits::ObligationCauseCode::CompareImplTypeObligation {
1834 } => SubregionOrigin::CompareImplTypeObligation {
1845 impl RegionVariableOrigin {
1846 pub fn span(&self) -> Span {
1853 | EarlyBoundRegion(a, ..)
1854 | LateBoundRegion(a, ..)
1855 | UpvarRegion(_, a) => a,
1856 Nll(..) => bug!("NLL variable used with `span`"),
1861 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1862 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1865 "RegionObligation(sub_region={:?}, sup_type={:?})",
1866 self.sub_region, self.sup_type