1 pub use self::freshen::TypeFreshener;
2 pub use self::LateBoundRegionConversionTime::*;
3 pub use self::RegionVariableOrigin::*;
4 pub use self::SubregionOrigin::*;
5 pub use self::ValuePairs::*;
7 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
9 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_data_structures::sync::Lrc;
13 use rustc_data_structures::undo_log::Rollback;
14 use rustc_data_structures::unify as ut;
15 use rustc_errors::DiagnosticBuilder;
17 use rustc_hir::def_id::{DefId, LocalDefId};
18 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
19 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
20 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
21 use rustc_middle::mir::interpret::EvalToConstValueResult;
22 use rustc_middle::traits::select;
23 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
24 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
25 use rustc_middle::ty::relate::RelateResult;
26 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
27 pub use rustc_middle::ty::IntVarValue;
28 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
29 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
30 use rustc_session::config::BorrowckMode;
31 use rustc_span::symbol::Symbol;
34 use std::cell::{Cell, Ref, RefCell};
35 use std::collections::BTreeMap;
38 use self::combine::CombineFields;
39 use self::free_regions::RegionRelations;
40 use self::lexical_region_resolve::LexicalRegionResolutions;
41 use self::outlives::env::OutlivesEnvironment;
42 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
43 use self::region_constraints::{
44 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
46 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
52 pub mod error_reporting;
59 mod lexical_region_resolve;
63 pub mod region_constraints;
66 pub mod type_variable;
69 use crate::infer::canonical::OriginalQueryValues;
70 pub use rustc_middle::infer::unify_key;
74 pub struct InferOk<'tcx, T> {
76 pub obligations: PredicateObligations<'tcx>,
78 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
80 pub type Bound<T> = Option<T>;
81 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
82 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
84 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
85 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
88 /// How we should handle region solving.
90 /// This is used so that the region values inferred by HIR region solving are
91 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
92 /// typeck will also do.
93 #[derive(Copy, Clone, Debug)]
94 pub enum RegionckMode {
95 /// The default mode: report region errors, don't erase regions.
97 /// Erase the results of region after solving.
99 /// A flag that is used to suppress region errors, when we are doing
100 /// region checks that the NLL borrow checker will also do -- it might
102 suppress_errors: bool,
106 impl Default for RegionckMode {
107 fn default() -> Self {
113 /// Indicates that the MIR borrowck will repeat these region
114 /// checks, so we should ignore errors if NLL is (unconditionally)
116 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
117 // FIXME(Centril): Once we actually remove `::Migrate` also make
118 // this always `true` and then proceed to eliminate the dead code.
119 match tcx.borrowck_mode() {
120 // If we're on Migrate mode, report AST region errors
121 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
123 // If we're on MIR, don't report AST region errors as they should be reported by NLL
124 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
129 /// This type contains all the things within `InferCtxt` that sit within a
130 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
131 /// operations are hot enough that we want only one call to `borrow_mut` per
132 /// call to `start_snapshot` and `rollback_to`.
133 pub struct InferCtxtInner<'tcx> {
134 /// Cache for projections. This cache is snapshotted along with the infcx.
136 /// Public so that `traits::project` can use it.
137 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
139 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
140 /// that might instantiate a general type variable have an order,
141 /// represented by its upper and lower bounds.
142 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
144 /// Map from const parameter variable to the kind of const it represents.
145 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
147 /// Map from integral variable to the kind of integer it represents.
148 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
150 /// Map from floating variable to the kind of float it represents.
151 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
153 /// Tracks the set of region variables and the constraints between them.
154 /// This is initially `Some(_)` but when
155 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
156 /// -- further attempts to perform unification, etc., may fail if new
157 /// region constraints would've been added.
158 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
160 /// A set of constraints that regionck must validate. Each
161 /// constraint has the form `T:'a`, meaning "some type `T` must
162 /// outlive the lifetime 'a". These constraints derive from
163 /// instantiated type parameters. So if you had a struct defined
166 /// struct Foo<T:'static> { ... }
168 /// then in some expression `let x = Foo { ... }` it will
169 /// instantiate the type parameter `T` with a fresh type `$0`. At
170 /// the same time, it will record a region obligation of
171 /// `$0:'static`. This will get checked later by regionck. (We
172 /// can't generally check these things right away because we have
173 /// to wait until types are resolved.)
175 /// These are stored in a map keyed to the id of the innermost
176 /// enclosing fn body / static initializer expression. This is
177 /// because the location where the obligation was incurred can be
178 /// relevant with respect to which sublifetime assumptions are in
179 /// place. The reason that we store under the fn-id, and not
180 /// something more fine-grained, is so that it is easier for
181 /// regionck to be sure that it has found *all* the region
182 /// obligations (otherwise, it's easy to fail to walk to a
183 /// particular node-id).
185 /// Before running `resolve_regions_and_report_errors`, the creator
186 /// of the inference context is expected to invoke
187 /// `process_region_obligations` (defined in `self::region_obligations`)
188 /// for each body-id in this map, which will process the
189 /// obligations within. This is expected to be done 'late enough'
190 /// that all type inference variables have been bound and so forth.
191 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
193 undo_log: InferCtxtUndoLogs<'tcx>,
196 impl<'tcx> InferCtxtInner<'tcx> {
197 fn new() -> InferCtxtInner<'tcx> {
199 projection_cache: Default::default(),
200 type_variable_storage: type_variable::TypeVariableStorage::new(),
201 undo_log: InferCtxtUndoLogs::default(),
202 const_unification_storage: ut::UnificationTableStorage::new(),
203 int_unification_storage: ut::UnificationTableStorage::new(),
204 float_unification_storage: ut::UnificationTableStorage::new(),
205 region_constraint_storage: Some(RegionConstraintStorage::new()),
206 region_obligations: vec![],
211 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
212 &self.region_obligations
216 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
217 self.projection_cache.with_log(&mut self.undo_log)
221 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
222 self.type_variable_storage.with_log(&mut self.undo_log)
226 fn int_unification_table(
228 ) -> ut::UnificationTable<
231 &mut ut::UnificationStorage<ty::IntVid>,
232 &mut InferCtxtUndoLogs<'tcx>,
235 self.int_unification_storage.with_log(&mut self.undo_log)
239 fn float_unification_table(
241 ) -> ut::UnificationTable<
244 &mut ut::UnificationStorage<ty::FloatVid>,
245 &mut InferCtxtUndoLogs<'tcx>,
248 self.float_unification_storage.with_log(&mut self.undo_log)
252 fn const_unification_table(
254 ) -> ut::UnificationTable<
257 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
258 &mut InferCtxtUndoLogs<'tcx>,
261 self.const_unification_storage.with_log(&mut self.undo_log)
265 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
266 self.region_constraint_storage
268 .expect("region constraints already solved")
269 .with_log(&mut self.undo_log)
273 pub struct InferCtxt<'a, 'tcx> {
274 pub tcx: TyCtxt<'tcx>,
276 /// During type-checking/inference of a body, `in_progress_typeck_results`
277 /// contains a reference to the typeck results being built up, which are
278 /// used for reading closure kinds/signatures as they are inferred,
279 /// and for error reporting logic to read arbitrary node types.
280 pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
282 pub inner: RefCell<InferCtxtInner<'tcx>>,
284 /// If set, this flag causes us to skip the 'leak check' during
285 /// higher-ranked subtyping operations. This flag is a temporary one used
286 /// to manage the removal of the leak-check: for the time being, we still run the
287 /// leak-check, but we issue warnings. This flag can only be set to true
288 /// when entering a snapshot.
289 skip_leak_check: Cell<bool>,
291 /// Once region inference is done, the values for each variable.
292 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
294 /// Caches the results of trait selection. This cache is used
295 /// for things that have to do with the parameters in scope.
296 pub selection_cache: select::SelectionCache<'tcx>,
298 /// Caches the results of trait evaluation.
299 pub evaluation_cache: select::EvaluationCache<'tcx>,
301 /// the set of predicates on which errors have been reported, to
302 /// avoid reporting the same error twice.
303 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
305 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
307 /// When an error occurs, we want to avoid reporting "derived"
308 /// errors that are due to this original failure. Normally, we
309 /// handle this with the `err_count_on_creation` count, which
310 /// basically just tracks how many errors were reported when we
311 /// started type-checking a fn and checks to see if any new errors
312 /// have been reported since then. Not great, but it works.
314 /// However, when errors originated in other passes -- notably
315 /// resolve -- this heuristic breaks down. Therefore, we have this
316 /// auxiliary flag that one can set whenever one creates a
317 /// type-error that is due to an error in a prior pass.
319 /// Don't read this flag directly, call `is_tainted_by_errors()`
320 /// and `set_tainted_by_errors()`.
321 tainted_by_errors_flag: Cell<bool>,
323 /// Track how many errors were reported when this infcx is created.
324 /// If the number of errors increases, that's also a sign (line
325 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
326 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
327 err_count_on_creation: usize,
329 /// This flag is true while there is an active snapshot.
330 in_snapshot: Cell<bool>,
332 /// What is the innermost universe we have created? Starts out as
333 /// `UniverseIndex::root()` but grows from there as we enter
334 /// universal quantifiers.
336 /// N.B., at present, we exclude the universal quantifiers on the
337 /// item we are type-checking, and just consider those names as
338 /// part of the root universe. So this would only get incremented
339 /// when we enter into a higher-ranked (`for<..>`) type or trait
341 universe: Cell<ty::UniverseIndex>,
344 /// See the `error_reporting` module for more details.
345 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
346 pub enum ValuePairs<'tcx> {
347 Types(ExpectedFound<Ty<'tcx>>),
348 Regions(ExpectedFound<ty::Region<'tcx>>),
349 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
350 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
351 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
354 /// The trace designates the path through inference that we took to
355 /// encounter an error or subtyping constraint.
357 /// See the `error_reporting` module for more details.
358 #[derive(Clone, Debug)]
359 pub struct TypeTrace<'tcx> {
360 cause: ObligationCause<'tcx>,
361 values: ValuePairs<'tcx>,
364 /// The origin of a `r1 <= r2` constraint.
366 /// See `error_reporting` module for more details
367 #[derive(Clone, Debug)]
368 pub enum SubregionOrigin<'tcx> {
369 /// Arose from a subtyping relation
370 Subtype(Box<TypeTrace<'tcx>>),
372 /// When casting `&'a T` to an `&'b Trait` object,
373 /// relating `'a` to `'b`
374 RelateObjectBound(Span),
376 /// Some type parameter was instantiated with the given type,
377 /// and that type must outlive some region.
378 RelateParamBound(Span, Ty<'tcx>),
380 /// The given region parameter was instantiated with a region
381 /// that must outlive some other region.
382 RelateRegionParamBound(Span),
384 /// Creating a pointer `b` to contents of another reference
387 /// Creating a pointer `b` to contents of an upvar
388 ReborrowUpvar(Span, ty::UpvarId),
390 /// Data with type `Ty<'tcx>` was borrowed
391 DataBorrowed(Ty<'tcx>, Span),
393 /// (&'a &'b T) where a >= b
394 ReferenceOutlivesReferent(Ty<'tcx>, Span),
396 /// Region in return type of invoked fn must enclose call
399 /// Comparing the signature and requirements of an impl method against
400 /// the containing trait.
401 CompareImplMethodObligation {
404 impl_item_def_id: DefId,
405 trait_item_def_id: DefId,
409 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
410 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
411 static_assert_size!(SubregionOrigin<'_>, 32);
413 /// Times when we replace late-bound regions with variables:
414 #[derive(Clone, Copy, Debug)]
415 pub enum LateBoundRegionConversionTime {
416 /// when a fn is called
419 /// when two higher-ranked types are compared
422 /// when projecting an associated type
423 AssocTypeProjection(DefId),
426 /// Reasons to create a region inference variable
428 /// See `error_reporting` module for more details
429 #[derive(Copy, Clone, Debug)]
430 pub enum RegionVariableOrigin {
431 /// Region variables created for ill-categorized reasons,
432 /// mostly indicates places in need of refactoring
435 /// Regions created by a `&P` or `[...]` pattern
438 /// Regions created by `&` operator
441 /// Regions created as part of an autoref of a method receiver
442 Autoref(Span, ty::AssocItem),
444 /// Regions created as part of an automatic coercion
447 /// Region variables created as the values for early-bound regions
448 EarlyBoundRegion(Span, Symbol),
450 /// Region variables created for bound regions
451 /// in a function or method that is called
452 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
454 UpvarRegion(ty::UpvarId, Span),
456 /// This origin is used for the inference variables that we create
457 /// during NLL region processing.
458 Nll(NllRegionVariableOrigin),
461 #[derive(Copy, Clone, Debug)]
462 pub enum NllRegionVariableOrigin {
463 /// During NLL region processing, we create variables for free
464 /// regions that we encounter in the function signature and
465 /// elsewhere. This origin indices we've got one of those.
468 /// "Universal" instantiation of a higher-ranked region (e.g.,
469 /// from a `for<'a> T` binder). Meant to represent "any region".
470 Placeholder(ty::PlaceholderRegion),
472 /// The variable we create to represent `'empty(U0)`.
476 /// If this is true, then this variable was created to represent a lifetime
477 /// bound in a `for` binder. For example, it might have been created to
478 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
479 /// Such variables are created when we are trying to figure out if there
480 /// is any valid instantiation of `'a` that could fit into some scenario.
482 /// This is used to inform error reporting: in the case that we are trying to
483 /// determine whether there is any valid instantiation of a `'a` variable that meets
484 /// some constraint C, we want to blame the "source" of that `for` type,
485 /// rather than blaming the source of the constraint C.
490 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
491 #[derive(Copy, Clone, Debug)]
492 pub enum FixupError<'tcx> {
493 UnresolvedIntTy(IntVid),
494 UnresolvedFloatTy(FloatVid),
496 UnresolvedConst(ConstVid<'tcx>),
499 /// See the `region_obligations` field for more information.
501 pub struct RegionObligation<'tcx> {
502 pub sub_region: ty::Region<'tcx>,
503 pub sup_type: Ty<'tcx>,
504 pub origin: SubregionOrigin<'tcx>,
507 impl<'tcx> fmt::Display for FixupError<'tcx> {
508 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509 use self::FixupError::*;
512 UnresolvedIntTy(_) => write!(
514 "cannot determine the type of this integer; \
515 add a suffix to specify the type explicitly"
517 UnresolvedFloatTy(_) => write!(
519 "cannot determine the type of this number; \
520 add a suffix to specify the type explicitly"
522 UnresolvedTy(_) => write!(f, "unconstrained type"),
523 UnresolvedConst(_) => write!(f, "unconstrained const value"),
528 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
529 /// Necessary because we can't write the following bound:
530 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
531 pub struct InferCtxtBuilder<'tcx> {
533 fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
536 pub trait TyCtxtInferExt<'tcx> {
537 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
540 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
541 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
542 InferCtxtBuilder { tcx: self, fresh_typeck_results: None }
546 impl<'tcx> InferCtxtBuilder<'tcx> {
547 /// Used only by `rustc_typeck` during body type-checking/inference,
548 /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
549 pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
550 self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
554 /// Given a canonical value `C` as a starting point, create an
555 /// inference context that contains each of the bound values
556 /// within instantiated as a fresh variable. The `f` closure is
557 /// invoked with the new infcx, along with the instantiated value
558 /// `V` and a substitution `S`. This substitution `S` maps from
559 /// the bound values in `C` to their instantiated values in `V`
560 /// (in other words, `S(C) = V`).
561 pub fn enter_with_canonical<T, R>(
564 canonical: &Canonical<'tcx, T>,
565 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
568 T: TypeFoldable<'tcx>,
572 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
573 f(infcx, value, subst)
577 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
578 let InferCtxtBuilder { tcx, ref fresh_typeck_results } = *self;
579 let in_progress_typeck_results = fresh_typeck_results.as_ref();
582 in_progress_typeck_results,
583 inner: RefCell::new(InferCtxtInner::new()),
584 lexical_region_resolutions: RefCell::new(None),
585 selection_cache: Default::default(),
586 evaluation_cache: Default::default(),
587 reported_trait_errors: Default::default(),
588 reported_closure_mismatch: Default::default(),
589 tainted_by_errors_flag: Cell::new(false),
590 err_count_on_creation: tcx.sess.err_count(),
591 in_snapshot: Cell::new(false),
592 skip_leak_check: Cell::new(false),
593 universe: Cell::new(ty::UniverseIndex::ROOT),
598 impl<'tcx, T> InferOk<'tcx, T> {
599 pub fn unit(self) -> InferOk<'tcx, ()> {
600 InferOk { value: (), obligations: self.obligations }
603 /// Extracts `value`, registering any obligations into `fulfill_cx`.
604 pub fn into_value_registering_obligations(
606 infcx: &InferCtxt<'_, 'tcx>,
607 fulfill_cx: &mut dyn TraitEngine<'tcx>,
609 let InferOk { value, obligations } = self;
610 for obligation in obligations {
611 fulfill_cx.register_predicate_obligation(infcx, obligation);
617 impl<'tcx> InferOk<'tcx, ()> {
618 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
623 #[must_use = "once you start a snapshot, you should always consume it"]
624 pub struct CombinedSnapshot<'a, 'tcx> {
625 undo_snapshot: Snapshot<'tcx>,
626 region_constraints_snapshot: RegionSnapshot,
627 universe: ty::UniverseIndex,
628 was_in_snapshot: bool,
629 _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
632 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
633 pub fn is_in_snapshot(&self) -> bool {
634 self.in_snapshot.get()
637 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
638 t.fold_with(&mut self.freshener())
641 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
643 ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
648 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
649 freshen::TypeFreshener::new(self)
652 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
653 use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
654 use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
656 ty::Infer(ty::IntVar(vid)) => {
657 if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
663 ty::Infer(ty::FloatVar(vid)) => {
664 if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
674 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
675 let mut inner = self.inner.borrow_mut();
676 let mut vars: Vec<Ty<'_>> = inner
678 .unsolved_variables()
680 .map(|t| self.tcx.mk_ty_var(t))
683 (0..inner.int_unification_table().len())
684 .map(|i| ty::IntVid { index: i as u32 })
685 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
686 .map(|v| self.tcx.mk_int_var(v)),
689 (0..inner.float_unification_table().len())
690 .map(|i| ty::FloatVid { index: i as u32 })
691 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
692 .map(|v| self.tcx.mk_float_var(v)),
699 trace: TypeTrace<'tcx>,
700 param_env: ty::ParamEnv<'tcx>,
701 ) -> CombineFields<'a, 'tcx> {
707 obligations: PredicateObligations::new(),
711 /// Clear the "currently in a snapshot" flag, invoke the closure,
712 /// then restore the flag to its original value. This flag is a
713 /// debugging measure designed to detect cases where we start a
714 /// snapshot, create type variables, and register obligations
715 /// which may involve those type variables in the fulfillment cx,
716 /// potentially leaving "dangling type variables" behind.
717 /// In such cases, an assertion will fail when attempting to
718 /// register obligations, within a snapshot. Very useful, much
719 /// better than grovelling through megabytes of `RUSTC_LOG` output.
721 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
722 /// sometimes create a "mini-fulfilment-cx" in which we enroll
723 /// obligations. As long as this fulfillment cx is fully drained
724 /// before we return, this is not a problem, as there won't be any
725 /// escaping obligations in the main cx. In those cases, you can
726 /// use this function.
727 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
729 F: FnOnce(&Self) -> R,
731 let flag = self.in_snapshot.replace(false);
732 let result = func(self);
733 self.in_snapshot.set(flag);
737 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
738 debug!("start_snapshot()");
740 let in_snapshot = self.in_snapshot.replace(true);
742 let mut inner = self.inner.borrow_mut();
745 undo_snapshot: inner.undo_log.start_snapshot(),
746 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
747 universe: self.universe(),
748 was_in_snapshot: in_snapshot,
749 // Borrow typeck results "in progress" (i.e., during typeck)
750 // to ban writes from within a snapshot to them.
751 _in_progress_typeck_results: self
752 .in_progress_typeck_results
753 .map(|typeck_results| typeck_results.borrow()),
757 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
758 debug!("rollback_to(cause={})", cause);
759 let CombinedSnapshot {
761 region_constraints_snapshot,
764 _in_progress_typeck_results,
767 self.in_snapshot.set(was_in_snapshot);
768 self.universe.set(universe);
770 let mut inner = self.inner.borrow_mut();
771 inner.rollback_to(undo_snapshot);
772 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
775 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
776 debug!("commit_from()");
777 let CombinedSnapshot {
779 region_constraints_snapshot: _,
782 _in_progress_typeck_results,
785 self.in_snapshot.set(was_in_snapshot);
787 self.inner.borrow_mut().commit(undo_snapshot);
790 /// Executes `f` and commit the bindings.
791 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
793 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
795 debug!("commit_unconditionally()");
796 let snapshot = self.start_snapshot();
797 let r = f(&snapshot);
798 self.commit_from(snapshot);
802 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
803 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
805 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
807 debug!("commit_if_ok()");
808 let snapshot = self.start_snapshot();
809 let r = f(&snapshot);
810 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
813 self.commit_from(snapshot);
816 self.rollback_to("commit_if_ok -- error", snapshot);
822 /// Execute `f` then unroll any bindings it creates.
823 pub fn probe<R, F>(&self, f: F) -> R
825 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
828 let snapshot = self.start_snapshot();
829 let r = f(&snapshot);
830 self.rollback_to("probe", snapshot);
834 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
835 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
837 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
840 let snapshot = self.start_snapshot();
841 let was_skip_leak_check = self.skip_leak_check.get();
843 self.skip_leak_check.set(true);
845 let r = f(&snapshot);
846 self.rollback_to("probe", snapshot);
847 self.skip_leak_check.set(was_skip_leak_check);
851 /// Scan the constraints produced since `snapshot` began and returns:
853 /// - `None` -- if none of them involve "region outlives" constraints
854 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
855 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
856 pub fn region_constraints_added_in_snapshot(
858 snapshot: &CombinedSnapshot<'a, 'tcx>,
862 .unwrap_region_constraints()
863 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
866 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
867 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
870 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
872 T: at::ToTrace<'tcx>,
874 let origin = &ObligationCause::dummy();
876 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
877 // Ignore obligations, since we are unrolling
878 // everything anyway.
883 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
885 T: at::ToTrace<'tcx>,
887 let origin = &ObligationCause::dummy();
889 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
890 // Ignore obligations, since we are unrolling
891 // everything anyway.
898 origin: SubregionOrigin<'tcx>,
902 debug!("sub_regions({:?} <: {:?})", a, b);
903 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
906 /// Require that the region `r` be equal to one of the regions in
907 /// the set `regions`.
908 pub fn member_constraint(
910 opaque_type_def_id: DefId,
911 definition_span: Span,
913 region: ty::Region<'tcx>,
914 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
916 debug!("member_constraint({:?} <: {:?})", region, in_regions);
917 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
926 pub fn subtype_predicate(
928 cause: &ObligationCause<'tcx>,
929 param_env: ty::ParamEnv<'tcx>,
930 predicate: ty::PolySubtypePredicate<'tcx>,
931 ) -> Option<InferResult<'tcx, ()>> {
932 // Subtle: it's ok to skip the binder here and resolve because
933 // `shallow_resolve` just ignores anything that is not a type
934 // variable, and because type variable's can't (at present, at
935 // least) capture any of the things bound by this binder.
937 // NOTE(nmatsakis): really, there is no *particular* reason to do this
938 // `shallow_resolve` here except as a micro-optimization.
939 // Naturally I could not resist.
940 let two_unbound_type_vars = {
941 let a = self.shallow_resolve(predicate.skip_binder().a);
942 let b = self.shallow_resolve(predicate.skip_binder().b);
943 a.is_ty_var() && b.is_ty_var()
946 if two_unbound_type_vars {
947 // Two unbound type variables? Can't make progress.
951 Some(self.commit_if_ok(|_snapshot| {
952 let ty::SubtypePredicate { a_is_expected, a, b } =
953 self.replace_bound_vars_with_placeholders(predicate);
955 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
961 pub fn region_outlives_predicate(
963 cause: &traits::ObligationCause<'tcx>,
964 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
965 ) -> UnitResult<'tcx> {
966 self.commit_if_ok(|_snapshot| {
967 let ty::OutlivesPredicate(r_a, r_b) =
968 self.replace_bound_vars_with_placeholders(predicate);
969 let origin = SubregionOrigin::from_obligation_cause(cause, || {
970 RelateRegionParamBound(cause.span)
972 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
977 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
978 self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
981 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
982 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
985 pub fn next_ty_var_in_universe(
987 origin: TypeVariableOrigin,
988 universe: ty::UniverseIndex,
990 let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
991 self.tcx.mk_ty_var(vid)
994 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
995 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
998 pub fn next_const_var(
1001 origin: ConstVariableOrigin,
1002 ) -> &'tcx ty::Const<'tcx> {
1003 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1006 pub fn next_const_var_in_universe(
1009 origin: ConstVariableOrigin,
1010 universe: ty::UniverseIndex,
1011 ) -> &'tcx ty::Const<'tcx> {
1015 .const_unification_table()
1016 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1017 self.tcx.mk_const_var(vid, ty)
1020 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1021 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1023 val: ConstVariableValue::Unknown { universe: self.universe() },
1027 fn next_int_var_id(&self) -> IntVid {
1028 self.inner.borrow_mut().int_unification_table().new_key(None)
1031 pub fn next_int_var(&self) -> Ty<'tcx> {
1032 self.tcx.mk_int_var(self.next_int_var_id())
1035 fn next_float_var_id(&self) -> FloatVid {
1036 self.inner.borrow_mut().float_unification_table().new_key(None)
1039 pub fn next_float_var(&self) -> Ty<'tcx> {
1040 self.tcx.mk_float_var(self.next_float_var_id())
1043 /// Creates a fresh region variable with the next available index.
1044 /// The variable will be created in the maximum universe created
1045 /// thus far, allowing it to name any region created thus far.
1046 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1047 self.next_region_var_in_universe(origin, self.universe())
1050 /// Creates a fresh region variable with the next available index
1051 /// in the given universe; typically, you can use
1052 /// `next_region_var` and just use the maximal universe.
1053 pub fn next_region_var_in_universe(
1055 origin: RegionVariableOrigin,
1056 universe: ty::UniverseIndex,
1057 ) -> ty::Region<'tcx> {
1059 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1060 self.tcx.mk_region(ty::ReVar(region_var))
1063 /// Return the universe that the region `r` was created in. For
1064 /// most regions (e.g., `'static`, named regions from the user,
1065 /// etc) this is the root universe U0. For inference variables or
1066 /// placeholders, however, it will return the universe which which
1067 /// they are associated.
1068 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1069 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1072 /// Number of region variables created so far.
1073 pub fn num_region_vars(&self) -> usize {
1074 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1077 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1078 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1079 self.next_region_var(RegionVariableOrigin::Nll(origin))
1082 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1083 pub fn next_nll_region_var_in_universe(
1085 origin: NllRegionVariableOrigin,
1086 universe: ty::UniverseIndex,
1087 ) -> ty::Region<'tcx> {
1088 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1091 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1093 GenericParamDefKind::Lifetime => {
1094 // Create a region inference variable for the given
1095 // region parameter definition.
1096 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1098 GenericParamDefKind::Type { .. } => {
1099 // Create a type inference variable for the given
1100 // type parameter definition. The substitutions are
1101 // for actual parameters that may be referred to by
1102 // the default of this type parameter, if it exists.
1103 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1104 // used in a path such as `Foo::<T, U>::new()` will
1105 // use an inference variable for `C` with `[T, U]`
1106 // as the substitutions for the default, `(T, U)`.
1107 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1110 TypeVariableOrigin {
1111 kind: TypeVariableOriginKind::TypeParameterDefinition(
1119 self.tcx.mk_ty_var(ty_var_id).into()
1121 GenericParamDefKind::Const { .. } => {
1122 let origin = ConstVariableOrigin {
1123 kind: ConstVariableOriginKind::ConstParameterDefinition(
1130 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1132 val: ConstVariableValue::Unknown { universe: self.universe() },
1134 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1139 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1140 /// type/region parameter to a fresh inference variable.
1141 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1142 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1145 /// Returns `true` if errors have been reported since this infcx was
1146 /// created. This is sometimes used as a heuristic to skip
1147 /// reporting errors that often occur as a result of earlier
1148 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1149 /// inference variables, regionck errors).
1150 pub fn is_tainted_by_errors(&self) -> bool {
1152 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1153 tainted_by_errors_flag={})",
1154 self.tcx.sess.err_count(),
1155 self.err_count_on_creation,
1156 self.tainted_by_errors_flag.get()
1159 if self.tcx.sess.err_count() > self.err_count_on_creation {
1160 return true; // errors reported since this infcx was made
1162 self.tainted_by_errors_flag.get()
1165 /// Set the "tainted by errors" flag to true. We call this when we
1166 /// observe an error from a prior pass.
1167 pub fn set_tainted_by_errors(&self) {
1168 debug!("set_tainted_by_errors()");
1169 self.tainted_by_errors_flag.set(true)
1172 /// Process the region constraints and report any errors that
1173 /// result. After this, no more unification operations should be
1174 /// done -- or the compiler will panic -- but it is legal to use
1175 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1176 pub fn resolve_regions_and_report_errors(
1178 region_context: DefId,
1179 outlives_env: &OutlivesEnvironment<'tcx>,
1182 let (var_infos, data) = {
1183 let mut inner = self.inner.borrow_mut();
1184 let inner = &mut *inner;
1186 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1187 "region_obligations not empty: {:#?}",
1188 inner.region_obligations
1191 .region_constraint_storage
1193 .expect("regions already resolved")
1194 .with_log(&mut inner.undo_log)
1195 .into_infos_and_data()
1199 &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1201 let (lexical_region_resolutions, errors) =
1202 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1204 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1205 assert!(old_value.is_none());
1207 if !self.is_tainted_by_errors() {
1208 // As a heuristic, just skip reporting region errors
1209 // altogether if other errors have been reported while
1210 // this infcx was in use. This is totally hokey but
1211 // otherwise we have a hard time separating legit region
1212 // errors from silly ones.
1213 self.report_region_errors(&errors);
1217 /// Obtains (and clears) the current set of region
1218 /// constraints. The inference context is still usable: further
1219 /// unifications will simply add new constraints.
1221 /// This method is not meant to be used with normal lexical region
1222 /// resolution. Rather, it is used in the NLL mode as a kind of
1223 /// interim hack: basically we run normal type-check and generate
1224 /// region constraints as normal, but then we take them and
1225 /// translate them into the form that the NLL solver
1226 /// understands. See the NLL module for mode details.
1227 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1229 self.inner.borrow().region_obligations.is_empty(),
1230 "region_obligations not empty: {:#?}",
1231 self.inner.borrow().region_obligations
1234 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1237 /// Gives temporary access to the region constraint data.
1238 pub fn with_region_constraints<R>(
1240 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1242 let mut inner = self.inner.borrow_mut();
1243 op(inner.unwrap_region_constraints().data())
1246 /// Takes ownership of the list of variable regions. This implies
1247 /// that all the region constraints have already been taken, and
1248 /// hence that `resolve_regions_and_report_errors` can never be
1249 /// called. This is used only during NLL processing to "hand off" ownership
1250 /// of the set of region variables into the NLL region context.
1251 pub fn take_region_var_origins(&self) -> VarInfos {
1252 let mut inner = self.inner.borrow_mut();
1253 let (var_infos, data) = inner
1254 .region_constraint_storage
1256 .expect("regions already resolved")
1257 .with_log(&mut inner.undo_log)
1258 .into_infos_and_data();
1259 assert!(data.is_empty());
1263 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1264 self.resolve_vars_if_possible(t).to_string()
1267 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1268 /// universe index of `TyVar(vid)`.
1269 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1270 use self::type_variable::TypeVariableValue;
1272 match self.inner.borrow_mut().type_variables().probe(vid) {
1273 TypeVariableValue::Known { value } => Ok(value),
1274 TypeVariableValue::Unknown { universe } => Err(universe),
1278 /// Resolve any type variables found in `value` -- but only one
1279 /// level. So, if the variable `?X` is bound to some type
1280 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1281 /// itself be bound to a type).
1283 /// Useful when you only need to inspect the outermost level of
1284 /// the type and don't care about nested types (or perhaps you
1285 /// will be resolving them as well, e.g. in a loop).
1286 pub fn shallow_resolve<T>(&self, value: T) -> T
1288 T: TypeFoldable<'tcx>,
1290 value.fold_with(&mut ShallowResolver { infcx: self })
1293 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1294 self.inner.borrow_mut().type_variables().root_var(var)
1297 /// Where possible, replaces type/const variables in
1298 /// `value` with their final value. Note that region variables
1299 /// are unaffected. If a type/const variable has not been unified, it
1300 /// is left as is. This is an idempotent operation that does
1301 /// not affect inference state in any way and so you can do it
1303 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1305 T: TypeFoldable<'tcx>,
1307 if !value.needs_infer() {
1308 return value; // Avoid duplicated subst-folding.
1310 let mut r = resolve::OpportunisticVarResolver::new(self);
1311 value.fold_with(&mut r)
1314 /// Returns the first unresolved variable contained in `T`. In the
1315 /// process of visiting `T`, this will resolve (where possible)
1316 /// type variables in `T`, but it never constructs the final,
1317 /// resolved type, so it's more efficient than
1318 /// `resolve_vars_if_possible()`.
1319 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1321 T: TypeFoldable<'tcx>,
1323 value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1326 pub fn probe_const_var(
1328 vid: ty::ConstVid<'tcx>,
1329 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1330 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1331 ConstVariableValue::Known { value } => Ok(value),
1332 ConstVariableValue::Unknown { universe } => Err(universe),
1336 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1338 * Attempts to resolve all type/region/const variables in
1339 * `value`. Region inference must have been run already (e.g.,
1340 * by calling `resolve_regions_and_report_errors`). If some
1341 * variable was never unified, an `Err` results.
1343 * This method is idempotent, but it not typically not invoked
1344 * except during the writeback phase.
1347 resolve::fully_resolve(self, value)
1350 // [Note-Type-error-reporting]
1351 // An invariant is that anytime the expected or actual type is Error (the special
1352 // error type, meaning that an error occurred when typechecking this expression),
1353 // this is a derived error. The error cascaded from another error (that was already
1354 // reported), so it's not useful to display it to the user.
1355 // The following methods implement this logic.
1356 // They check if either the actual or expected type is Error, and don't print the error
1357 // in this case. The typechecker should only ever report type errors involving mismatched
1358 // types using one of these methods, and should not call span_err directly for such
1361 pub fn type_error_struct_with_diag<M>(
1365 actual_ty: Ty<'tcx>,
1366 ) -> DiagnosticBuilder<'tcx>
1368 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1370 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1371 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1373 // Don't report an error if actual type is `Error`.
1374 if actual_ty.references_error() {
1375 return self.tcx.sess.diagnostic().struct_dummy();
1378 mk_diag(self.ty_to_string(actual_ty))
1381 pub fn report_mismatched_types(
1383 cause: &ObligationCause<'tcx>,
1386 err: TypeError<'tcx>,
1387 ) -> DiagnosticBuilder<'tcx> {
1388 let trace = TypeTrace::types(cause, true, expected, actual);
1389 self.report_and_explain_type_error(trace, &err)
1392 pub fn report_mismatched_consts(
1394 cause: &ObligationCause<'tcx>,
1395 expected: &'tcx ty::Const<'tcx>,
1396 actual: &'tcx ty::Const<'tcx>,
1397 err: TypeError<'tcx>,
1398 ) -> DiagnosticBuilder<'tcx> {
1399 let trace = TypeTrace::consts(cause, true, expected, actual);
1400 self.report_and_explain_type_error(trace, &err)
1403 pub fn replace_bound_vars_with_fresh_vars<T>(
1406 lbrct: LateBoundRegionConversionTime,
1407 value: ty::Binder<'tcx, T>,
1408 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1410 T: TypeFoldable<'tcx>,
1413 |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct));
1415 self.next_ty_var(TypeVariableOrigin {
1416 kind: TypeVariableOriginKind::MiscVariable,
1420 let fld_c = |_, ty| {
1421 self.next_const_var(
1423 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1426 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1429 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1430 pub fn verify_generic_bound(
1432 origin: SubregionOrigin<'tcx>,
1433 kind: GenericKind<'tcx>,
1434 a: ty::Region<'tcx>,
1435 bound: VerifyBound<'tcx>,
1437 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1441 .unwrap_region_constraints()
1442 .verify_generic_bound(origin, kind, a, bound);
1445 /// Obtains the latest type of the given closure; this may be a
1446 /// closure in the current function, in which case its
1447 /// `ClosureKind` may not yet be known.
1448 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1449 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1450 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1451 closure_kind_ty.to_opt_closure_kind()
1454 /// Clears the selection, evaluation, and projection caches. This is useful when
1455 /// repeatedly attempting to select an `Obligation` while changing only
1456 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1457 pub fn clear_caches(&self) {
1458 self.selection_cache.clear();
1459 self.evaluation_cache.clear();
1460 self.inner.borrow_mut().projection_cache().clear();
1463 fn universe(&self) -> ty::UniverseIndex {
1467 /// Creates and return a fresh universe that extends all previous
1468 /// universes. Updates `self.universe` to that new universe.
1469 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1470 let u = self.universe.get().next_universe();
1471 self.universe.set(u);
1475 /// Resolves and evaluates a constant.
1477 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1478 /// substitutions and environment are used to resolve the constant. Alternatively if the
1479 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1480 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1481 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1482 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1485 /// This handles inferences variables within both `param_env` and `substs` by
1486 /// performing the operation on their respective canonical forms.
1487 pub fn const_eval_resolve(
1489 param_env: ty::ParamEnv<'tcx>,
1490 ty::Unevaluated { def, substs, promoted }: ty::Unevaluated<'tcx>,
1492 ) -> EvalToConstValueResult<'tcx> {
1493 let mut original_values = OriginalQueryValues::default();
1494 let canonical = self.canonicalize_query((param_env, substs), &mut original_values);
1496 let (param_env, substs) = canonical.value;
1497 // The return value is the evaluated value which doesn't contain any reference to inference
1498 // variables, thus we don't need to substitute back the original values.
1499 self.tcx.const_eval_resolve(param_env, ty::Unevaluated { def, substs, promoted }, span)
1502 /// If `typ` is a type variable of some kind, resolve it one level
1503 /// (but do not resolve types found in the result). If `typ` is
1504 /// not a type variable, just return it unmodified.
1505 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1506 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1508 ty::Infer(ty::TyVar(v)) => {
1509 // Not entirely obvious: if `typ` is a type variable,
1510 // it can be resolved to an int/float variable, which
1511 // can then be recursively resolved, hence the
1512 // recursion. Note though that we prevent type
1513 // variables from unifying to other type variables
1514 // directly (though they may be embedded
1515 // structurally), and we prevent cycles in any case,
1516 // so this recursion should always be of very limited
1519 // Note: if these two lines are combined into one we get
1520 // dynamic borrow errors on `self.inner`.
1521 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1522 known.map_or(typ, |t| self.shallow_resolve_ty(t))
1525 ty::Infer(ty::IntVar(v)) => self
1528 .int_unification_table()
1530 .map(|v| v.to_type(self.tcx))
1533 ty::Infer(ty::FloatVar(v)) => self
1536 .float_unification_table()
1538 .map(|v| v.to_type(self.tcx))
1545 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1546 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1547 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1549 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1550 /// inlined, despite being large, because it has only two call sites that
1551 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1552 /// inference variables), and it handles both `Ty` and `ty::Const` without
1553 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1555 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1557 TyOrConstInferVar::Ty(v) => {
1558 use self::type_variable::TypeVariableValue;
1560 // If `inlined_probe` returns a `Known` value, it never equals
1561 // `ty::Infer(ty::TyVar(v))`.
1562 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1563 TypeVariableValue::Unknown { .. } => false,
1564 TypeVariableValue::Known { .. } => true,
1568 TyOrConstInferVar::TyInt(v) => {
1569 // If `inlined_probe_value` returns a value it's always a
1570 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1572 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1575 TyOrConstInferVar::TyFloat(v) => {
1576 // If `probe_value` returns a value it's always a
1577 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1579 // Not `inlined_probe_value(v)` because this call site is colder.
1580 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1583 TyOrConstInferVar::Const(v) => {
1584 // If `probe_value` returns a `Known` value, it never equals
1585 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1587 // Not `inlined_probe_value(v)` because this call site is colder.
1588 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1589 ConstVariableValue::Unknown { .. } => false,
1590 ConstVariableValue::Known { .. } => true,
1597 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1598 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1599 #[derive(Copy, Clone, Debug)]
1600 pub enum TyOrConstInferVar<'tcx> {
1601 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1603 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1605 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1608 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1609 Const(ConstVid<'tcx>),
1612 impl TyOrConstInferVar<'tcx> {
1613 /// Tries to extract an inference variable from a type or a constant, returns `None`
1614 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1615 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1616 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1617 match arg.unpack() {
1618 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1619 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1620 GenericArgKind::Lifetime(_) => None,
1624 /// Tries to extract an inference variable from a type, returns `None`
1625 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1626 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1628 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1629 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1630 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1635 /// Tries to extract an inference variable from a constant, returns `None`
1636 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1637 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1639 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1645 struct ShallowResolver<'a, 'tcx> {
1646 infcx: &'a InferCtxt<'a, 'tcx>,
1649 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1650 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1654 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1655 self.infcx.shallow_resolve_ty(ty)
1658 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1659 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1663 .const_unification_table()
1674 impl<'tcx> TypeTrace<'tcx> {
1675 pub fn span(&self) -> Span {
1680 cause: &ObligationCause<'tcx>,
1681 a_is_expected: bool,
1684 ) -> TypeTrace<'tcx> {
1685 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1689 cause: &ObligationCause<'tcx>,
1690 a_is_expected: bool,
1691 a: &'tcx ty::Const<'tcx>,
1692 b: &'tcx ty::Const<'tcx>,
1693 ) -> TypeTrace<'tcx> {
1694 TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
1698 impl<'tcx> SubregionOrigin<'tcx> {
1699 pub fn span(&self) -> Span {
1701 Subtype(ref a) => a.span(),
1702 RelateObjectBound(a) => a,
1703 RelateParamBound(a, _) => a,
1704 RelateRegionParamBound(a) => a,
1706 ReborrowUpvar(a, _) => a,
1707 DataBorrowed(_, a) => a,
1708 ReferenceOutlivesReferent(_, a) => a,
1710 CompareImplMethodObligation { span, .. } => span,
1714 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1716 F: FnOnce() -> Self,
1719 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1720 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1723 traits::ObligationCauseCode::CompareImplMethodObligation {
1727 } => SubregionOrigin::CompareImplMethodObligation {
1739 impl RegionVariableOrigin {
1740 pub fn span(&self) -> Span {
1747 | EarlyBoundRegion(a, ..)
1748 | LateBoundRegion(a, ..)
1749 | UpvarRegion(_, a) => a,
1750 Nll(..) => bug!("NLL variable used with `span`"),
1755 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1756 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1759 "RegionObligation(sub_region={:?}, sup_type={:?})",
1760 self.sub_region, self.sup_type