1 //! See the Book for more information.
3 pub use self::freshen::TypeFreshener;
4 pub use self::LateBoundRegionConversionTime::*;
5 pub use self::RegionVariableOrigin::*;
6 pub use self::SubregionOrigin::*;
7 pub use self::ValuePairs::*;
8 pub use crate::ty::IntVarValue;
11 use crate::hir::def_id::DefId;
12 use crate::infer::canonical::{Canonical, CanonicalVarValues};
13 use crate::middle::free_region::RegionRelations;
14 use crate::middle::lang_items;
15 use crate::middle::region;
16 use crate::session::config::BorrowckMode;
17 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
18 use crate::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
19 use crate::ty::fold::TypeFoldable;
20 use crate::ty::relate::RelateResult;
21 use crate::ty::subst::{Kind, InternalSubsts, SubstsRef};
22 use crate::ty::{self, GenericParamDefKind, Ty, TyCtxt, CtxtInterners};
23 use crate::ty::{FloatVid, IntVid, TyVid};
24 use crate::util::nodemap::FxHashMap;
26 use arena::SyncDroplessArena;
27 use errors::DiagnosticBuilder;
28 use rustc_data_structures::unify as ut;
29 use std::cell::{Cell, Ref, RefCell, RefMut};
30 use std::collections::BTreeMap;
33 use syntax_pos::symbol::InternedString;
36 use self::combine::CombineFields;
37 use self::lexical_region_resolve::LexicalRegionResolutions;
38 use self::outlives::env::OutlivesEnvironment;
39 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
40 use self::region_constraints::{RegionConstraintCollector, RegionSnapshot};
41 use self::type_variable::TypeVariableOrigin;
42 use self::unify_key::ToType;
48 pub mod error_reporting;
54 mod lexical_region_resolve;
59 pub mod region_constraints;
62 pub mod type_variable;
67 pub struct InferOk<'tcx, T> {
69 pub obligations: PredicateObligations<'tcx>,
71 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
73 pub type Bound<T> = Option<T>;
74 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
75 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
77 /// A flag that is used to suppress region errors. This is normally
78 /// false, but sometimes -- when we are doing region checks that the
79 /// NLL borrow checker will also do -- it might be set to true.
80 #[derive(Copy, Clone, Default, Debug)]
81 pub struct SuppressRegionErrors {
85 impl SuppressRegionErrors {
86 pub fn suppressed(self) -> bool {
90 /// Indicates that the MIR borrowck will repeat these region
91 /// checks, so we should ignore errors if NLL is (unconditionally)
93 pub fn when_nll_is_enabled(tcx: TyCtxt<'_, '_, '_>) -> Self {
94 match tcx.borrowck_mode() {
95 // If we're on Migrate mode, report AST region errors
96 BorrowckMode::Migrate => SuppressRegionErrors { suppressed: false },
98 // If we're on MIR or Compare mode, don't report AST region errors as they should
100 BorrowckMode::Compare | BorrowckMode::Mir => SuppressRegionErrors { suppressed: true },
105 pub struct InferCtxt<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
106 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
108 /// During type-checking/inference of a body, `in_progress_tables`
109 /// contains a reference to the tables being built up, which are
110 /// used for reading closure kinds/signatures as they are inferred,
111 /// and for error reporting logic to read arbitrary node types.
112 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
114 /// Cache for projections. This cache is snapshotted along with the
117 /// Public so that `traits::project` can use it.
118 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
120 /// We instantiate `UnificationTable` with `bounds<Ty>` because the
121 /// types that might instantiate a general type variable have an
122 /// order, represented by its upper and lower bounds.
123 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
125 /// Map from integral variable to the kind of integer it represents
126 int_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::IntVid>>>,
128 /// Map from floating variable to the kind of float it represents
129 float_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::FloatVid>>>,
131 /// Tracks the set of region variables and the constraints between
132 /// them. This is initially `Some(_)` but when
133 /// `resolve_regions_and_report_errors` is invoked, this gets set
134 /// to `None` -- further attempts to perform unification etc may
135 /// fail if new region constraints would've been added.
136 region_constraints: RefCell<Option<RegionConstraintCollector<'tcx>>>,
138 /// Once region inference is done, the values for each variable.
139 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
141 /// Caches the results of trait selection. This cache is used
142 /// for things that have to do with the parameters in scope.
143 pub selection_cache: traits::SelectionCache<'tcx>,
145 /// Caches the results of trait evaluation.
146 pub evaluation_cache: traits::EvaluationCache<'tcx>,
148 /// the set of predicates on which errors have been reported, to
149 /// avoid reporting the same error twice.
150 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
152 /// When an error occurs, we want to avoid reporting "derived"
153 /// errors that are due to this original failure. Normally, we
154 /// handle this with the `err_count_on_creation` count, which
155 /// basically just tracks how many errors were reported when we
156 /// started type-checking a fn and checks to see if any new errors
157 /// have been reported since then. Not great, but it works.
159 /// However, when errors originated in other passes -- notably
160 /// resolve -- this heuristic breaks down. Therefore, we have this
161 /// auxiliary flag that one can set whenever one creates a
162 /// type-error that is due to an error in a prior pass.
164 /// Don't read this flag directly, call `is_tainted_by_errors()`
165 /// and `set_tainted_by_errors()`.
166 tainted_by_errors_flag: Cell<bool>,
168 /// Track how many errors were reported when this infcx is created.
169 /// If the number of errors increases, that's also a sign (line
170 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
171 err_count_on_creation: usize,
173 /// This flag is true while there is an active snapshot.
174 in_snapshot: Cell<bool>,
176 /// A set of constraints that regionck must validate. Each
177 /// constraint has the form `T:'a`, meaning "some type `T` must
178 /// outlive the lifetime 'a". These constraints derive from
179 /// instantiated type parameters. So if you had a struct defined
182 /// struct Foo<T:'static> { ... }
184 /// then in some expression `let x = Foo { ... }` it will
185 /// instantiate the type parameter `T` with a fresh type `$0`. At
186 /// the same time, it will record a region obligation of
187 /// `$0:'static`. This will get checked later by regionck. (We
188 /// can't generally check these things right away because we have
189 /// to wait until types are resolved.)
191 /// These are stored in a map keyed to the id of the innermost
192 /// enclosing fn body / static initializer expression. This is
193 /// because the location where the obligation was incurred can be
194 /// relevant with respect to which sublifetime assumptions are in
195 /// place. The reason that we store under the fn-id, and not
196 /// something more fine-grained, is so that it is easier for
197 /// regionck to be sure that it has found *all* the region
198 /// obligations (otherwise, it's easy to fail to walk to a
199 /// particular node-id).
201 /// Before running `resolve_regions_and_report_errors`, the creator
202 /// of the inference context is expected to invoke
203 /// `process_region_obligations` (defined in `self::region_obligations`)
204 /// for each body-id in this map, which will process the
205 /// obligations within. This is expected to be done 'late enough'
206 /// that all type inference variables have been bound and so forth.
207 pub region_obligations: RefCell<Vec<(hir::HirId, RegionObligation<'tcx>)>>,
209 /// What is the innermost universe we have created? Starts out as
210 /// `UniverseIndex::root()` but grows from there as we enter
211 /// universal quantifiers.
213 /// N.B., at present, we exclude the universal quantifiers on the
214 /// item we are type-checking, and just consider those names as
215 /// part of the root universe. So this would only get incremented
216 /// when we enter into a higher-ranked (`for<..>`) type or trait
218 universe: Cell<ty::UniverseIndex>,
221 /// A map returned by `replace_bound_vars_with_placeholders()`
222 /// indicating the placeholder region that each late-bound region was
224 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
226 /// See the `error_reporting` module for more details.
227 #[derive(Clone, Debug, PartialEq, Eq)]
228 pub enum ValuePairs<'tcx> {
229 Types(ExpectedFound<Ty<'tcx>>),
230 Regions(ExpectedFound<ty::Region<'tcx>>),
231 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
232 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
235 /// The trace designates the path through inference that we took to
236 /// encounter an error or subtyping constraint.
238 /// See the `error_reporting` module for more details.
240 pub struct TypeTrace<'tcx> {
241 cause: ObligationCause<'tcx>,
242 values: ValuePairs<'tcx>,
245 /// The origin of a `r1 <= r2` constraint.
247 /// See `error_reporting` module for more details
248 #[derive(Clone, Debug)]
249 pub enum SubregionOrigin<'tcx> {
250 /// Arose from a subtyping relation
251 Subtype(TypeTrace<'tcx>),
253 /// Stack-allocated closures cannot outlive innermost loop
254 /// or function so as to ensure we only require finite stack
255 InfStackClosure(Span),
257 /// Invocation of closure must be within its lifetime
260 /// Dereference of reference must be within its lifetime
263 /// Closure bound must not outlive captured free variables
264 FreeVariable(Span, ast::NodeId),
266 /// Index into slice must be within its lifetime
269 /// When casting `&'a T` to an `&'b Trait` object,
270 /// relating `'a` to `'b`
271 RelateObjectBound(Span),
273 /// Some type parameter was instantiated with the given type,
274 /// and that type must outlive some region.
275 RelateParamBound(Span, Ty<'tcx>),
277 /// The given region parameter was instantiated with a region
278 /// that must outlive some other region.
279 RelateRegionParamBound(Span),
281 /// A bound placed on type parameters that states that must outlive
282 /// the moment of their instantiation.
283 RelateDefaultParamBound(Span, Ty<'tcx>),
285 /// Creating a pointer `b` to contents of another reference
288 /// Creating a pointer `b` to contents of an upvar
289 ReborrowUpvar(Span, ty::UpvarId),
291 /// Data with type `Ty<'tcx>` was borrowed
292 DataBorrowed(Ty<'tcx>, Span),
294 /// (&'a &'b T) where a >= b
295 ReferenceOutlivesReferent(Ty<'tcx>, Span),
297 /// Type or region parameters must be in scope.
298 ParameterInScope(ParameterOrigin, Span),
300 /// The type T of an expression E must outlive the lifetime for E.
301 ExprTypeIsNotInScope(Ty<'tcx>, Span),
303 /// A `ref b` whose region does not enclose the decl site
304 BindingTypeIsNotValidAtDecl(Span),
306 /// Regions appearing in a method receiver must outlive method call
309 /// Regions appearing in a function argument must outlive func call
312 /// Region in return type of invoked fn must enclose call
315 /// Operands must be in scope
318 /// Region resulting from a `&` expr must enclose the `&` expr
321 /// An auto-borrow that does not enclose the expr where it occurs
324 /// Region constraint arriving from destructor safety
325 SafeDestructor(Span),
327 /// Comparing the signature and requirements of an impl method against
328 /// the containing trait.
329 CompareImplMethodObligation {
331 item_name: ast::Name,
332 impl_item_def_id: DefId,
333 trait_item_def_id: DefId,
337 /// Places that type/region parameters can appear.
338 #[derive(Clone, Copy, Debug)]
339 pub enum ParameterOrigin {
341 MethodCall, // foo.bar() <-- parameters on impl providing bar()
342 OverloadedOperator, // a + b when overloaded
343 OverloadedDeref, // *a when overloaded
346 /// Times when we replace late-bound regions with variables:
347 #[derive(Clone, Copy, Debug)]
348 pub enum LateBoundRegionConversionTime {
349 /// when a fn is called
352 /// when two higher-ranked types are compared
355 /// when projecting an associated type
356 AssocTypeProjection(DefId),
359 /// Reasons to create a region inference variable
361 /// See `error_reporting` module for more details
362 #[derive(Copy, Clone, Debug)]
363 pub enum RegionVariableOrigin {
364 /// Region variables created for ill-categorized reasons,
365 /// mostly indicates places in need of refactoring
368 /// Regions created by a `&P` or `[...]` pattern
371 /// Regions created by `&` operator
374 /// Regions created as part of an autoref of a method receiver
377 /// Regions created as part of an automatic coercion
380 /// Region variables created as the values for early-bound regions
381 EarlyBoundRegion(Span, InternedString),
383 /// Region variables created for bound regions
384 /// in a function or method that is called
385 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
387 UpvarRegion(ty::UpvarId, Span),
389 BoundRegionInCoherence(ast::Name),
391 /// This origin is used for the inference variables that we create
392 /// during NLL region processing.
393 NLL(NLLRegionVariableOrigin),
396 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
397 pub enum NLLRegionVariableOrigin {
398 /// During NLL region processing, we create variables for free
399 /// regions that we encounter in the function signature and
400 /// elsewhere. This origin indices we've got one of those.
403 /// "Universal" instantiation of a higher-ranked region (e.g.,
404 /// from a `for<'a> T` binder). Meant to represent "any region".
405 Placeholder(ty::PlaceholderRegion),
410 impl NLLRegionVariableOrigin {
411 pub fn is_universal(self) -> bool {
413 NLLRegionVariableOrigin::FreeRegion => true,
414 NLLRegionVariableOrigin::Placeholder(..) => true,
415 NLLRegionVariableOrigin::Existential => false,
419 pub fn is_existential(self) -> bool {
424 #[derive(Copy, Clone, Debug)]
425 pub enum FixupError {
426 UnresolvedIntTy(IntVid),
427 UnresolvedFloatTy(FloatVid),
431 /// See the `region_obligations` field for more information.
433 pub struct RegionObligation<'tcx> {
434 pub sub_region: ty::Region<'tcx>,
435 pub sup_type: Ty<'tcx>,
436 pub origin: SubregionOrigin<'tcx>,
439 impl fmt::Display for FixupError {
440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441 use self::FixupError::*;
444 UnresolvedIntTy(_) => write!(
446 "cannot determine the type of this integer; \
447 add a suffix to specify the type explicitly"
449 UnresolvedFloatTy(_) => write!(
451 "cannot determine the type of this number; \
452 add a suffix to specify the type explicitly"
454 UnresolvedTy(_) => write!(f, "unconstrained type"),
459 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
460 /// Necessary because we can't write the following bound:
461 /// `F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>)`.
462 pub struct InferCtxtBuilder<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
463 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
464 arena: SyncDroplessArena,
465 interners: Option<CtxtInterners<'tcx>>,
466 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
469 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
470 pub fn infer_ctxt(self) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
473 arena: SyncDroplessArena::default(),
480 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
481 /// Used only by `rustc_typeck` during body type-checking/inference,
482 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
483 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
484 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
488 /// Given a canonical value `C` as a starting point, create an
489 /// inference context that contains each of the bound values
490 /// within instantiated as a fresh variable. The `f` closure is
491 /// invoked with the new infcx, along with the instantiated value
492 /// `V` and a substitution `S`. This substitution `S` maps from
493 /// the bound values in `C` to their instantiated values in `V`
494 /// (in other words, `S(C) = V`).
495 pub fn enter_with_canonical<T, R>(
498 canonical: &Canonical<'tcx, T>,
499 f: impl for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
502 T: TypeFoldable<'tcx>,
506 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
507 f(infcx, value, subst)
511 pub fn enter<R>(&'tcx mut self, f: impl for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R) -> R {
512 let InferCtxtBuilder {
518 let in_progress_tables = fresh_tables.as_ref();
519 // Check that we haven't entered before
520 assert!(interners.is_none());
521 global_tcx.enter_local(arena, interners, |tcx| {
525 projection_cache: Default::default(),
526 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
527 int_unification_table: RefCell::new(ut::UnificationTable::new()),
528 float_unification_table: RefCell::new(ut::UnificationTable::new()),
529 region_constraints: RefCell::new(Some(RegionConstraintCollector::new())),
530 lexical_region_resolutions: RefCell::new(None),
531 selection_cache: Default::default(),
532 evaluation_cache: Default::default(),
533 reported_trait_errors: Default::default(),
534 tainted_by_errors_flag: Cell::new(false),
535 err_count_on_creation: tcx.sess.err_count(),
536 in_snapshot: Cell::new(false),
537 region_obligations: RefCell::new(vec![]),
538 universe: Cell::new(ty::UniverseIndex::ROOT),
544 impl<T> ExpectedFound<T> {
545 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
560 impl<'tcx, T> InferOk<'tcx, T> {
561 pub fn unit(self) -> InferOk<'tcx, ()> {
564 obligations: self.obligations,
568 /// Extracts `value`, registering any obligations into `fulfill_cx`.
569 pub fn into_value_registering_obligations(
571 infcx: &InferCtxt<'_, '_, 'tcx>,
572 fulfill_cx: &mut dyn TraitEngine<'tcx>,
574 let InferOk { value, obligations } = self;
575 for obligation in obligations {
576 fulfill_cx.register_predicate_obligation(infcx, obligation);
582 impl<'tcx> InferOk<'tcx, ()> {
583 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
588 #[must_use = "once you start a snapshot, you should always consume it"]
589 pub struct CombinedSnapshot<'a, 'tcx: 'a> {
590 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
591 type_snapshot: type_variable::Snapshot<'tcx>,
592 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
593 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
594 region_constraints_snapshot: RegionSnapshot,
595 region_obligations_snapshot: usize,
596 universe: ty::UniverseIndex,
597 was_in_snapshot: bool,
598 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
601 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
602 pub fn is_in_snapshot(&self) -> bool {
603 self.in_snapshot.get()
606 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
607 t.fold_with(&mut self.freshener())
610 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
612 ty::Infer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
617 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
618 freshen::TypeFreshener::new(self)
621 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
622 use crate::ty::error::UnconstrainedNumeric::Neither;
623 use crate::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
625 ty::Infer(ty::IntVar(vid)) => {
626 if self.int_unification_table
636 ty::Infer(ty::FloatVar(vid)) => {
637 if self.float_unification_table
651 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
652 let mut type_variables = self.type_variables.borrow_mut();
653 let mut int_unification_table = self.int_unification_table.borrow_mut();
654 let mut float_unification_table = self.float_unification_table.borrow_mut();
657 .unsolved_variables()
659 .map(|t| self.tcx.mk_ty_var(t))
661 (0..int_unification_table.len())
662 .map(|i| ty::IntVid { index: i as u32 })
663 .filter(|&vid| int_unification_table.probe_value(vid).is_none())
664 .map(|v| self.tcx.mk_int_var(v)),
667 (0..float_unification_table.len())
668 .map(|i| ty::FloatVid { index: i as u32 })
669 .filter(|&vid| float_unification_table.probe_value(vid).is_none())
670 .map(|v| self.tcx.mk_float_var(v)),
677 trace: TypeTrace<'tcx>,
678 param_env: ty::ParamEnv<'tcx>,
679 ) -> CombineFields<'a, 'gcx, 'tcx> {
685 obligations: PredicateObligations::new(),
689 /// Clear the "currently in a snapshot" flag, invoke the closure,
690 /// then restore the flag to its original value. This flag is a
691 /// debugging measure designed to detect cases where we start a
692 /// snapshot, create type variables, and register obligations
693 /// which may involve those type variables in the fulfillment cx,
694 /// potentially leaving "dangling type variables" behind.
695 /// In such cases, an assertion will fail when attempting to
696 /// register obligations, within a snapshot. Very useful, much
697 /// better than grovelling through megabytes of `RUSTC_LOG` output.
699 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
700 /// sometimes create a "mini-fulfilment-cx" in which we enroll
701 /// obligations. As long as this fulfillment cx is fully drained
702 /// before we return, this is not a problem, as there won't be any
703 /// escaping obligations in the main cx. In those cases, you can
704 /// use this function.
705 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
707 F: FnOnce(&Self) -> R,
709 let flag = self.in_snapshot.get();
710 self.in_snapshot.set(false);
711 let result = func(self);
712 self.in_snapshot.set(flag);
716 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
717 debug!("start_snapshot()");
719 let in_snapshot = self.in_snapshot.get();
720 self.in_snapshot.set(true);
723 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
724 type_snapshot: self.type_variables.borrow_mut().snapshot(),
725 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
726 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
727 region_constraints_snapshot: self.borrow_region_constraints().start_snapshot(),
728 region_obligations_snapshot: self.region_obligations.borrow().len(),
729 universe: self.universe(),
730 was_in_snapshot: in_snapshot,
731 // Borrow tables "in progress" (i.e., during typeck)
732 // to ban writes from within a snapshot to them.
733 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
737 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
738 debug!("rollback_to(cause={})", cause);
739 let CombinedSnapshot {
740 projection_cache_snapshot,
744 region_constraints_snapshot,
745 region_obligations_snapshot,
751 self.in_snapshot.set(was_in_snapshot);
752 self.universe.set(universe);
754 self.projection_cache
756 .rollback_to(projection_cache_snapshot);
757 self.type_variables.borrow_mut().rollback_to(type_snapshot);
758 self.int_unification_table
760 .rollback_to(int_snapshot);
761 self.float_unification_table
763 .rollback_to(float_snapshot);
764 self.region_obligations
766 .truncate(region_obligations_snapshot);
767 self.borrow_region_constraints()
768 .rollback_to(region_constraints_snapshot);
771 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
772 debug!("commit_from()");
773 let CombinedSnapshot {
774 projection_cache_snapshot,
778 region_constraints_snapshot,
779 region_obligations_snapshot: _,
785 self.in_snapshot.set(was_in_snapshot);
787 self.projection_cache
789 .commit(projection_cache_snapshot);
790 self.type_variables.borrow_mut().commit(type_snapshot);
791 self.int_unification_table.borrow_mut().commit(int_snapshot);
792 self.float_unification_table
794 .commit(float_snapshot);
795 self.borrow_region_constraints()
796 .commit(region_constraints_snapshot);
799 /// Executes `f` and commit the bindings.
800 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
805 let snapshot = self.start_snapshot();
807 self.commit_from(snapshot);
811 /// Executes `f` and commit the bindings if closure `f` returns `Ok(_)`.
812 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
814 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
816 debug!("commit_if_ok()");
817 let snapshot = self.start_snapshot();
818 let r = f(&snapshot);
819 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
822 self.commit_from(snapshot);
825 self.rollback_to("commit_if_ok -- error", snapshot);
831 /// Execute `f` in a snapshot, and commit the bindings it creates.
832 pub fn in_snapshot<T, F>(&self, f: F) -> T
834 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> T,
836 debug!("in_snapshot()");
837 let snapshot = self.start_snapshot();
838 let r = f(&snapshot);
839 self.commit_from(snapshot);
843 /// Executes `f` then unroll any bindings it creates.
844 pub fn probe<R, F>(&self, f: F) -> R
846 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
849 let snapshot = self.start_snapshot();
850 let r = f(&snapshot);
851 self.rollback_to("probe", snapshot);
855 /// Scan the constraints produced since `snapshot` began and returns:
857 /// - `None` -- if none of them involve "region outlives" constraints
858 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
859 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
860 pub fn region_constraints_added_in_snapshot(
862 snapshot: &CombinedSnapshot<'a, 'tcx>,
864 self.borrow_region_constraints().region_constraints_added_in_snapshot(
865 &snapshot.region_constraints_snapshot,
869 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
870 self.borrow_region_constraints().add_given(sub, sup);
873 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
875 T: at::ToTrace<'tcx>,
877 let origin = &ObligationCause::dummy();
879 self.at(origin, param_env)
881 .map(|InferOk { obligations: _, .. }| {
882 // Ignore obligations, since we are unrolling
883 // everything anyway.
888 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
890 T: at::ToTrace<'tcx>,
892 let origin = &ObligationCause::dummy();
894 self.at(origin, param_env)
896 .map(|InferOk { obligations: _, .. }| {
897 // Ignore obligations, since we are unrolling
898 // everything anyway.
905 origin: SubregionOrigin<'tcx>,
909 debug!("sub_regions({:?} <: {:?})", a, b);
910 self.borrow_region_constraints()
911 .make_subregion(origin, a, b);
914 pub fn subtype_predicate(
916 cause: &ObligationCause<'tcx>,
917 param_env: ty::ParamEnv<'tcx>,
918 predicate: &ty::PolySubtypePredicate<'tcx>,
919 ) -> Option<InferResult<'tcx, ()>> {
920 // Subtle: it's ok to skip the binder here and resolve because
921 // `shallow_resolve` just ignores anything that is not a type
922 // variable, and because type variable's can't (at present, at
923 // least) capture any of the things bound by this binder.
925 // Really, there is no *particular* reason to do this
926 // `shallow_resolve` here except as a
927 // micro-optimization. Naturally I could not
928 // resist. -nmatsakis
929 let two_unbound_type_vars = {
930 let a = self.shallow_resolve(predicate.skip_binder().a);
931 let b = self.shallow_resolve(predicate.skip_binder().b);
932 a.is_ty_var() && b.is_ty_var()
935 if two_unbound_type_vars {
936 // Two unbound type variables? Can't make progress.
940 Some(self.commit_if_ok(|snapshot| {
942 ty::SubtypePredicate {
948 ) = self.replace_bound_vars_with_placeholders(predicate);
950 let ok = self.at(cause, param_env)
951 .sub_exp(a_is_expected, a, b)?;
953 self.leak_check(false, &placeholder_map, snapshot)?;
959 pub fn region_outlives_predicate(
961 cause: &traits::ObligationCause<'tcx>,
962 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
963 ) -> UnitResult<'tcx> {
964 self.commit_if_ok(|snapshot| {
965 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
966 self.replace_bound_vars_with_placeholders(predicate);
967 let origin = SubregionOrigin::from_obligation_cause(
969 || RelateRegionParamBound(cause.span),
971 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
972 self.leak_check(false, &placeholder_map, snapshot)?;
977 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
980 .new_var(self.universe(), diverging, origin)
983 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
984 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
987 pub fn next_ty_var_in_universe(
989 origin: TypeVariableOrigin,
990 universe: ty::UniverseIndex
992 let vid = self.type_variables
994 .new_var(universe, false, origin);
995 self.tcx.mk_ty_var(vid)
998 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
999 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1002 fn next_int_var_id(&self) -> IntVid {
1003 self.int_unification_table.borrow_mut().new_key(None)
1006 pub fn next_int_var(&self) -> Ty<'tcx> {
1007 self.tcx.mk_int_var(self.next_int_var_id())
1010 fn next_float_var_id(&self) -> FloatVid {
1011 self.float_unification_table.borrow_mut().new_key(None)
1014 pub fn next_float_var(&self) -> Ty<'tcx> {
1015 self.tcx.mk_float_var(self.next_float_var_id())
1018 /// Creates a fresh region variable with the next available index.
1019 /// The variable will be created in the maximum universe created
1020 /// thus far, allowing it to name any region created thus far.
1021 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1022 self.next_region_var_in_universe(origin, self.universe())
1025 /// Creates a fresh region variable with the next available index
1026 /// in the given universe; typically, you can use
1027 /// `next_region_var` and just use the maximal universe.
1028 pub fn next_region_var_in_universe(
1030 origin: RegionVariableOrigin,
1031 universe: ty::UniverseIndex,
1032 ) -> ty::Region<'tcx> {
1033 let region_var = self.borrow_region_constraints()
1034 .new_region_var(universe, origin);
1035 self.tcx.mk_region(ty::ReVar(region_var))
1038 /// Return the universe that the region `r` was created in. For
1039 /// most regions (e.g., `'static`, named regions from the user,
1040 /// etc) this is the root universe U0. For inference variables or
1041 /// placeholders, however, it will return the universe which which
1042 /// they are associated.
1043 fn universe_of_region(
1045 r: ty::Region<'tcx>,
1046 ) -> ty::UniverseIndex {
1047 self.borrow_region_constraints().universe(r)
1050 /// Number of region variables created so far.
1051 pub fn num_region_vars(&self) -> usize {
1052 self.borrow_region_constraints().num_region_vars()
1055 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1056 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1057 self.next_region_var(RegionVariableOrigin::NLL(origin))
1060 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1061 pub fn next_nll_region_var_in_universe(
1063 origin: NLLRegionVariableOrigin,
1064 universe: ty::UniverseIndex,
1065 ) -> ty::Region<'tcx> {
1066 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1069 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> Kind<'tcx> {
1071 GenericParamDefKind::Lifetime => {
1072 // Create a region inference variable for the given
1073 // region parameter definition.
1074 self.next_region_var(EarlyBoundRegion(span, param.name))
1077 GenericParamDefKind::Type { .. } => {
1078 // Create a type inference variable for the given
1079 // type parameter definition. The substitutions are
1080 // for actual parameters that may be referred to by
1081 // the default of this type parameter, if it exists.
1082 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1083 // used in a path such as `Foo::<T, U>::new()` will
1084 // use an inference variable for `C` with `[T, U]`
1085 // as the substitutions for the default, `(T, U)`.
1086 let ty_var_id = self.type_variables.borrow_mut().new_var(
1089 TypeVariableOrigin::TypeParameterDefinition(span, param.name),
1092 self.tcx.mk_ty_var(ty_var_id).into()
1094 GenericParamDefKind::Const { .. } => {
1095 unimplemented!() // FIXME(const_generics)
1100 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1101 /// type/region parameter to a fresh inference variable.
1102 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1103 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1106 /// Returns `true` if errors have been reported since this infcx was
1107 /// created. This is sometimes used as a heuristic to skip
1108 /// reporting errors that often occur as a result of earlier
1109 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1110 /// inference variables, regionck errors).
1111 pub fn is_tainted_by_errors(&self) -> bool {
1113 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1114 tainted_by_errors_flag={})",
1115 self.tcx.sess.err_count(),
1116 self.err_count_on_creation,
1117 self.tainted_by_errors_flag.get()
1120 if self.tcx.sess.err_count() > self.err_count_on_creation {
1121 return true; // errors reported since this infcx was made
1123 self.tainted_by_errors_flag.get()
1126 /// Set the "tainted by errors" flag to true. We call this when we
1127 /// observe an error from a prior pass.
1128 pub fn set_tainted_by_errors(&self) {
1129 debug!("set_tainted_by_errors()");
1130 self.tainted_by_errors_flag.set(true)
1133 /// Process the region constraints and report any errors that
1134 /// result. After this, no more unification operations should be
1135 /// done -- or the compiler will panic -- but it is legal to use
1136 /// `resolve_type_vars_if_possible` as well as `fully_resolve`.
1137 pub fn resolve_regions_and_report_errors(
1139 region_context: DefId,
1140 region_map: ®ion::ScopeTree,
1141 outlives_env: &OutlivesEnvironment<'tcx>,
1142 suppress: SuppressRegionErrors,
1145 self.is_tainted_by_errors() || self.region_obligations.borrow().is_empty(),
1146 "region_obligations not empty: {:#?}",
1147 self.region_obligations.borrow()
1150 let region_rels = &RegionRelations::new(
1154 outlives_env.free_region_map(),
1156 let (var_infos, data) = self.region_constraints
1159 .expect("regions already resolved")
1160 .into_infos_and_data();
1161 let (lexical_region_resolutions, errors) =
1162 lexical_region_resolve::resolve(region_rels, var_infos, data);
1164 let old_value = self.lexical_region_resolutions
1165 .replace(Some(lexical_region_resolutions));
1166 assert!(old_value.is_none());
1168 if !self.is_tainted_by_errors() {
1169 // As a heuristic, just skip reporting region errors
1170 // altogether if other errors have been reported while
1171 // this infcx was in use. This is totally hokey but
1172 // otherwise we have a hard time separating legit region
1173 // errors from silly ones.
1174 self.report_region_errors(region_map, &errors, suppress);
1178 /// Obtains (and clears) the current set of region
1179 /// constraints. The inference context is still usable: further
1180 /// unifications will simply add new constraints.
1182 /// This method is not meant to be used with normal lexical region
1183 /// resolution. Rather, it is used in the NLL mode as a kind of
1184 /// interim hack: basically we run normal type-check and generate
1185 /// region constraints as normal, but then we take them and
1186 /// translate them into the form that the NLL solver
1187 /// understands. See the NLL module for mode details.
1188 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1190 self.region_obligations.borrow().is_empty(),
1191 "region_obligations not empty: {:#?}",
1192 self.region_obligations.borrow()
1195 self.borrow_region_constraints().take_and_reset_data()
1198 /// Gives temporary access to the region constraint data.
1199 #[allow(non_camel_case_types)] // bug with impl trait
1200 pub fn with_region_constraints<R>(
1202 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1204 let region_constraints = self.borrow_region_constraints();
1205 op(region_constraints.data())
1208 /// Takes ownership of the list of variable regions. This implies
1209 /// that all the region constraints have already been taken, and
1210 /// hence that `resolve_regions_and_report_errors` can never be
1211 /// called. This is used only during NLL processing to "hand off" ownership
1212 /// of the set of region variables into the NLL region context.
1213 pub fn take_region_var_origins(&self) -> VarInfos {
1214 let (var_infos, data) = self.region_constraints
1217 .expect("regions already resolved")
1218 .into_infos_and_data();
1219 assert!(data.is_empty());
1223 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1224 self.resolve_type_vars_if_possible(&t).to_string()
1227 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1228 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1229 format!("({})", tstrs.join(", "))
1232 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1233 self.resolve_type_vars_if_possible(t).to_string()
1236 // We have this force-inlined variant of shallow_resolve() for the one
1237 // callsite that is extremely hot. All other callsites use the normal
1240 pub fn inlined_shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1242 ty::Infer(ty::TyVar(v)) => {
1243 // Not entirely obvious: if `typ` is a type variable,
1244 // it can be resolved to an int/float variable, which
1245 // can then be recursively resolved, hence the
1246 // recursion. Note though that we prevent type
1247 // variables from unifyxing to other type variables
1248 // directly (though they may be embedded
1249 // structurally), and we prevent cycles in any case,
1250 // so this recursion should always be of very limited
1256 .map(|t| self.shallow_resolve(t))
1260 ty::Infer(ty::IntVar(v)) => self.int_unification_table
1263 .map(|v| v.to_type(self.tcx))
1266 ty::Infer(ty::FloatVar(v)) => self.float_unification_table
1269 .map(|v| v.to_type(self.tcx))
1276 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1277 /// universe index of `TyVar(vid)`.
1278 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1279 use self::type_variable::TypeVariableValue;
1281 match self.type_variables.borrow_mut().probe(vid) {
1282 TypeVariableValue::Known { value } => Ok(value),
1283 TypeVariableValue::Unknown { universe } => Err(universe),
1287 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1288 self.inlined_shallow_resolve(typ)
1291 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1292 self.type_variables.borrow_mut().root_var(var)
1295 /// Where possible, replaces type/int/float variables in
1296 /// `value` with their final value. Note that region variables
1297 /// are unaffected. If a type variable has not been unified, it
1298 /// is left as is. This is an idempotent operation that does
1299 /// not affect inference state in any way and so you can do it
1301 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1303 T: TypeFoldable<'tcx>,
1305 if !value.needs_infer() {
1306 return value.clone(); // avoid duplicated subst-folding
1308 let mut r = resolve::OpportunisticTypeResolver::new(self);
1309 value.fold_with(&mut r)
1312 /// Returns first unresolved variable contained in `T`. In the
1313 /// process of visiting `T`, this will resolve (where possible)
1314 /// type variables in `T`, but it never constructs the final,
1315 /// resolved type, so it's more efficient than
1316 /// `resolve_type_vars_if_possible()`.
1317 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1319 T: TypeFoldable<'tcx>,
1321 let mut r = resolve::UnresolvedTypeFinder::new(self);
1322 value.visit_with(&mut r);
1326 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1328 * Attempts to resolve all type/region variables in
1329 * `value`. Region inference must have been run already (e.g.,
1330 * by calling `resolve_regions_and_report_errors`). If some
1331 * variable was never unified, an `Err` results.
1333 * This method is idempotent, but it not typically not invoked
1334 * except during the writeback phase.
1337 resolve::fully_resolve(self, value)
1340 // [Note-Type-error-reporting]
1341 // An invariant is that anytime the expected or actual type is Error (the special
1342 // error type, meaning that an error occurred when typechecking this expression),
1343 // this is a derived error. The error cascaded from another error (that was already
1344 // reported), so it's not useful to display it to the user.
1345 // The following methods implement this logic.
1346 // They check if either the actual or expected type is Error, and don't print the error
1347 // in this case. The typechecker should only ever report type errors involving mismatched
1348 // types using one of these methods, and should not call span_err directly for such
1351 pub fn type_error_struct_with_diag<M>(
1355 actual_ty: Ty<'tcx>,
1356 ) -> DiagnosticBuilder<'tcx>
1358 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1360 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1361 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1363 // Don't report an error if actual type is `Error`.
1364 if actual_ty.references_error() {
1365 return self.tcx.sess.diagnostic().struct_dummy();
1368 mk_diag(self.ty_to_string(actual_ty))
1371 pub fn report_mismatched_types(
1373 cause: &ObligationCause<'tcx>,
1376 err: TypeError<'tcx>,
1377 ) -> DiagnosticBuilder<'tcx> {
1378 let trace = TypeTrace::types(cause, true, expected, actual);
1379 self.report_and_explain_type_error(trace, &err)
1382 pub fn replace_bound_vars_with_fresh_vars<T>(
1385 lbrct: LateBoundRegionConversionTime,
1386 value: &ty::Binder<T>
1387 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1389 T: TypeFoldable<'tcx>
1391 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1392 let fld_t = |_| self.next_ty_var(TypeVariableOrigin::MiscVariable(span));
1393 self.tcx.replace_bound_vars(value, fld_r, fld_t)
1396 /// See the [`region_constraints::verify_generic_bound`] method.
1397 pub fn verify_generic_bound(
1399 origin: SubregionOrigin<'tcx>,
1400 kind: GenericKind<'tcx>,
1401 a: ty::Region<'tcx>,
1402 bound: VerifyBound<'tcx>,
1404 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1406 self.borrow_region_constraints()
1407 .verify_generic_bound(origin, kind, a, bound);
1410 pub fn type_is_copy_modulo_regions(
1412 param_env: ty::ParamEnv<'tcx>,
1416 let ty = self.resolve_type_vars_if_possible(&ty);
1418 // Even if the type may have no inference variables, during
1419 // type-checking closure types are in local tables only.
1420 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1421 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1422 return ty.is_copy_modulo_regions(self.tcx.global_tcx(), param_env, span);
1426 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1428 // this can get called from typeck (by euv), and moves_by_default
1429 // rightly refuses to work with inference variables, but
1430 // moves_by_default has a cache, which we want to use in other
1432 traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id, span)
1435 /// Obtains the latest type of the given closure; this may be a
1436 /// closure in the current function, in which case its
1437 /// `ClosureKind` may not yet be known.
1438 pub fn closure_kind(
1440 closure_def_id: DefId,
1441 closure_substs: ty::ClosureSubsts<'tcx>,
1442 ) -> Option<ty::ClosureKind> {
1443 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx);
1444 let closure_kind_ty = self.shallow_resolve(&closure_kind_ty);
1445 closure_kind_ty.to_opt_closure_kind()
1448 /// Obtain the signature of a closure. For closures, unlike
1449 /// `tcx.fn_sig(def_id)`, this method will work during the
1450 /// type-checking of the enclosing function and return the closure
1451 /// signature in its partially inferred state.
1455 substs: ty::ClosureSubsts<'tcx>,
1456 ) -> ty::PolyFnSig<'tcx> {
1457 let closure_sig_ty = substs.closure_sig_ty(def_id, self.tcx);
1458 let closure_sig_ty = self.shallow_resolve(&closure_sig_ty);
1459 closure_sig_ty.fn_sig(self.tcx)
1462 /// Normalizes associated types in `value`, potentially returning
1463 /// new obligations that must further be processed.
1464 pub fn partially_normalize_associated_types_in<T>(
1467 body_id: hir::HirId,
1468 param_env: ty::ParamEnv<'tcx>,
1470 ) -> InferOk<'tcx, T>
1472 T: TypeFoldable<'tcx>,
1474 debug!("partially_normalize_associated_types_in(value={:?})", value);
1475 let mut selcx = traits::SelectionContext::new(self);
1476 let cause = ObligationCause::misc(span, body_id);
1477 let traits::Normalized { value, obligations } =
1478 traits::normalize(&mut selcx, param_env, cause, value);
1480 "partially_normalize_associated_types_in: result={:?} predicates={:?}",
1483 InferOk { value, obligations }
1486 pub fn borrow_region_constraints(&self) -> RefMut<'_, RegionConstraintCollector<'tcx>> {
1487 RefMut::map(self.region_constraints.borrow_mut(), |c| {
1488 c.as_mut().expect("region constraints already solved")
1492 /// Clears the selection, evaluation, and projection caches. This is useful when
1493 /// repeatedly attempting to select an `Obligation` while changing only
1494 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1495 pub fn clear_caches(&self) {
1496 self.selection_cache.clear();
1497 self.evaluation_cache.clear();
1498 self.projection_cache.borrow_mut().clear();
1501 fn universe(&self) -> ty::UniverseIndex {
1505 /// Creates and return a fresh universe that extends all previous
1506 /// universes. Updates `self.universe` to that new universe.
1507 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1508 let u = self.universe.get().next_universe();
1509 self.universe.set(u);
1514 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1515 pub fn span(&self) -> Span {
1520 cause: &ObligationCause<'tcx>,
1521 a_is_expected: bool,
1524 ) -> TypeTrace<'tcx> {
1526 cause: cause.clone(),
1527 values: Types(ExpectedFound::new(a_is_expected, a, b)),
1531 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1533 cause: ObligationCause::dummy(),
1534 values: Types(ExpectedFound {
1535 expected: tcx.types.err,
1536 found: tcx.types.err,
1542 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1543 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1544 write!(f, "TypeTrace({:?})", self.cause)
1548 impl<'tcx> SubregionOrigin<'tcx> {
1549 pub fn span(&self) -> Span {
1551 Subtype(ref a) => a.span(),
1552 InfStackClosure(a) => a,
1553 InvokeClosure(a) => a,
1554 DerefPointer(a) => a,
1555 FreeVariable(a, _) => a,
1557 RelateObjectBound(a) => a,
1558 RelateParamBound(a, _) => a,
1559 RelateRegionParamBound(a) => a,
1560 RelateDefaultParamBound(a, _) => a,
1562 ReborrowUpvar(a, _) => a,
1563 DataBorrowed(_, a) => a,
1564 ReferenceOutlivesReferent(_, a) => a,
1565 ParameterInScope(_, a) => a,
1566 ExprTypeIsNotInScope(_, a) => a,
1567 BindingTypeIsNotValidAtDecl(a) => a,
1574 SafeDestructor(a) => a,
1575 CompareImplMethodObligation { span, .. } => span,
1579 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1581 F: FnOnce() -> Self,
1584 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1585 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1588 traits::ObligationCauseCode::CompareImplMethodObligation {
1592 } => SubregionOrigin::CompareImplMethodObligation {
1604 impl RegionVariableOrigin {
1605 pub fn span(&self) -> Span {
1607 MiscVariable(a) => a,
1608 PatternRegion(a) => a,
1609 AddrOfRegion(a) => a,
1612 EarlyBoundRegion(a, ..) => a,
1613 LateBoundRegion(a, ..) => a,
1614 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1615 UpvarRegion(_, a) => a,
1616 NLL(..) => bug!("NLL variable used with `span`"),
1621 EnumTypeFoldableImpl! {
1622 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1623 (ValuePairs::Types)(a),
1624 (ValuePairs::Regions)(a),
1625 (ValuePairs::TraitRefs)(a),
1626 (ValuePairs::PolyTraitRefs)(a),
1630 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1631 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1634 "RegionObligation(sub_region={:?}, sup_type={:?})",
1635 self.sub_region, self.sup_type