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 AST or Migrate mode, report AST region errors
96 BorrowckMode::Ast | 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_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 RUST_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 placehodler
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_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);
998 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
999 self.tcx.mk_var(self.next_ty_var_id(true, origin))
1002 pub fn next_int_var_id(&self) -> IntVid {
1003 self.int_unification_table.borrow_mut().new_key(None)
1006 pub fn next_float_var_id(&self) -> FloatVid {
1007 self.float_unification_table.borrow_mut().new_key(None)
1010 /// Creates a fresh region variable with the next available index.
1011 /// The variable will be created in the maximum universe created
1012 /// thus far, allowing it to name any region created thus far.
1013 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1014 self.next_region_var_in_universe(origin, self.universe())
1017 /// Creates a fresh region variable with the next available index
1018 /// in the given universe; typically, you can use
1019 /// `next_region_var` and just use the maximal universe.
1020 pub fn next_region_var_in_universe(
1022 origin: RegionVariableOrigin,
1023 universe: ty::UniverseIndex,
1024 ) -> ty::Region<'tcx> {
1025 let region_var = self.borrow_region_constraints()
1026 .new_region_var(universe, origin);
1027 self.tcx.mk_region(ty::ReVar(region_var))
1030 /// Return the universe that the region `r` was created in. For
1031 /// most regions (e.g., `'static`, named regions from the user,
1032 /// etc) this is the root universe U0. For inference variables or
1033 /// placeholders, however, it will return the universe which which
1034 /// they are associated.
1035 fn universe_of_region(
1037 r: ty::Region<'tcx>,
1038 ) -> ty::UniverseIndex {
1039 self.borrow_region_constraints().universe(r)
1042 /// Number of region variables created so far.
1043 pub fn num_region_vars(&self) -> usize {
1044 self.borrow_region_constraints().num_region_vars()
1047 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1048 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1049 self.next_region_var(RegionVariableOrigin::NLL(origin))
1052 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1053 pub fn next_nll_region_var_in_universe(
1055 origin: NLLRegionVariableOrigin,
1056 universe: ty::UniverseIndex,
1057 ) -> ty::Region<'tcx> {
1058 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1061 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> Kind<'tcx> {
1063 GenericParamDefKind::Lifetime => {
1064 // Create a region inference variable for the given
1065 // region parameter definition.
1066 self.next_region_var(EarlyBoundRegion(span, param.name))
1069 GenericParamDefKind::Type { .. } => {
1070 // Create a type inference variable for the given
1071 // type parameter definition. The substitutions are
1072 // for actual parameters that may be referred to by
1073 // the default of this type parameter, if it exists.
1074 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1075 // used in a path such as `Foo::<T, U>::new()` will
1076 // use an inference variable for `C` with `[T, U]`
1077 // as the substitutions for the default, `(T, U)`.
1078 let ty_var_id = self.type_variables.borrow_mut().new_var(
1081 TypeVariableOrigin::TypeParameterDefinition(span, param.name),
1084 self.tcx.mk_var(ty_var_id).into()
1089 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1090 /// type/region parameter to a fresh inference variable.
1091 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1092 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1095 /// Returns `true` if errors have been reported since this infcx was
1096 /// created. This is sometimes used as a heuristic to skip
1097 /// reporting errors that often occur as a result of earlier
1098 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1099 /// inference variables, regionck errors).
1100 pub fn is_tainted_by_errors(&self) -> bool {
1102 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1103 tainted_by_errors_flag={})",
1104 self.tcx.sess.err_count(),
1105 self.err_count_on_creation,
1106 self.tainted_by_errors_flag.get()
1109 if self.tcx.sess.err_count() > self.err_count_on_creation {
1110 return true; // errors reported since this infcx was made
1112 self.tainted_by_errors_flag.get()
1115 /// Set the "tainted by errors" flag to true. We call this when we
1116 /// observe an error from a prior pass.
1117 pub fn set_tainted_by_errors(&self) {
1118 debug!("set_tainted_by_errors()");
1119 self.tainted_by_errors_flag.set(true)
1122 /// Process the region constraints and report any errors that
1123 /// result. After this, no more unification operations should be
1124 /// done -- or the compiler will panic -- but it is legal to use
1125 /// `resolve_type_vars_if_possible` as well as `fully_resolve`.
1126 pub fn resolve_regions_and_report_errors(
1128 region_context: DefId,
1129 region_map: ®ion::ScopeTree,
1130 outlives_env: &OutlivesEnvironment<'tcx>,
1131 suppress: SuppressRegionErrors,
1134 self.is_tainted_by_errors() || self.region_obligations.borrow().is_empty(),
1135 "region_obligations not empty: {:#?}",
1136 self.region_obligations.borrow()
1139 let region_rels = &RegionRelations::new(
1143 outlives_env.free_region_map(),
1145 let (var_infos, data) = self.region_constraints
1148 .expect("regions already resolved")
1149 .into_infos_and_data();
1150 let (lexical_region_resolutions, errors) =
1151 lexical_region_resolve::resolve(region_rels, var_infos, data);
1153 let old_value = self.lexical_region_resolutions
1154 .replace(Some(lexical_region_resolutions));
1155 assert!(old_value.is_none());
1157 if !self.is_tainted_by_errors() {
1158 // As a heuristic, just skip reporting region errors
1159 // altogether if other errors have been reported while
1160 // this infcx was in use. This is totally hokey but
1161 // otherwise we have a hard time separating legit region
1162 // errors from silly ones.
1163 self.report_region_errors(region_map, &errors, suppress);
1167 /// Obtains (and clears) the current set of region
1168 /// constraints. The inference context is still usable: further
1169 /// unifications will simply add new constraints.
1171 /// This method is not meant to be used with normal lexical region
1172 /// resolution. Rather, it is used in the NLL mode as a kind of
1173 /// interim hack: basically we run normal type-check and generate
1174 /// region constraints as normal, but then we take them and
1175 /// translate them into the form that the NLL solver
1176 /// understands. See the NLL module for mode details.
1177 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1179 self.region_obligations.borrow().is_empty(),
1180 "region_obligations not empty: {:#?}",
1181 self.region_obligations.borrow()
1184 self.borrow_region_constraints().take_and_reset_data()
1187 /// Gives temporary access to the region constraint data.
1188 #[allow(non_camel_case_types)] // bug with impl trait
1189 pub fn with_region_constraints<R>(
1191 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1193 let region_constraints = self.borrow_region_constraints();
1194 op(region_constraints.data())
1197 /// Takes ownership of the list of variable regions. This implies
1198 /// that all the region constraints have already been taken, and
1199 /// hence that `resolve_regions_and_report_errors` can never be
1200 /// called. This is used only during NLL processing to "hand off" ownership
1201 /// of the set of region variables into the NLL region context.
1202 pub fn take_region_var_origins(&self) -> VarInfos {
1203 let (var_infos, data) = self.region_constraints
1206 .expect("regions already resolved")
1207 .into_infos_and_data();
1208 assert!(data.is_empty());
1212 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1213 self.resolve_type_vars_if_possible(&t).to_string()
1216 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1217 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1218 format!("({})", tstrs.join(", "))
1221 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1222 self.resolve_type_vars_if_possible(t).to_string()
1225 // We have this force-inlined variant of shallow_resolve() for the one
1226 // callsite that is extremely hot. All other callsites use the normal
1229 pub fn inlined_shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1231 ty::Infer(ty::TyVar(v)) => {
1232 // Not entirely obvious: if `typ` is a type variable,
1233 // it can be resolved to an int/float variable, which
1234 // can then be recursively resolved, hence the
1235 // recursion. Note though that we prevent type
1236 // variables from unifyxing to other type variables
1237 // directly (though they may be embedded
1238 // structurally), and we prevent cycles in any case,
1239 // so this recursion should always be of very limited
1245 .map(|t| self.shallow_resolve(t))
1249 ty::Infer(ty::IntVar(v)) => self.int_unification_table
1252 .map(|v| v.to_type(self.tcx))
1255 ty::Infer(ty::FloatVar(v)) => self.float_unification_table
1258 .map(|v| v.to_type(self.tcx))
1265 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1266 /// universe index of `TyVar(vid)`.
1267 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1268 use self::type_variable::TypeVariableValue;
1270 match self.type_variables.borrow_mut().probe(vid) {
1271 TypeVariableValue::Known { value } => Ok(value),
1272 TypeVariableValue::Unknown { universe } => Err(universe),
1276 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1277 self.inlined_shallow_resolve(typ)
1280 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1281 self.type_variables.borrow_mut().root_var(var)
1284 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1286 T: TypeFoldable<'tcx>,
1289 * Where possible, replaces type/int/float variables in
1290 * `value` with their final value. Note that region variables
1291 * are unaffected. If a type variable has not been unified, it
1292 * is left as is. This is an idempotent operation that does
1293 * not affect inference state in any way and so you can do it
1297 if !value.needs_infer() {
1298 return value.clone(); // avoid duplicated subst-folding
1300 let mut r = resolve::OpportunisticTypeResolver::new(self);
1301 value.fold_with(&mut r)
1304 /// Returns `true` if `T` contains unresolved type variables. In the
1305 /// process of visiting `T`, this will resolve (where possible)
1306 /// type variables in `T`, but it never constructs the final,
1307 /// resolved type, so it's more efficient than
1308 /// `resolve_type_vars_if_possible()`.
1309 pub fn any_unresolved_type_vars<T>(&self, value: &T) -> bool
1311 T: TypeFoldable<'tcx>,
1313 let mut r = resolve::UnresolvedTypeFinder::new(self);
1314 value.visit_with(&mut r)
1317 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1319 * Attempts to resolve all type/region variables in
1320 * `value`. Region inference must have been run already (e.g.,
1321 * by calling `resolve_regions_and_report_errors`). If some
1322 * variable was never unified, an `Err` results.
1324 * This method is idempotent, but it not typically not invoked
1325 * except during the writeback phase.
1328 resolve::fully_resolve(self, value)
1331 // [Note-Type-error-reporting]
1332 // An invariant is that anytime the expected or actual type is Error (the special
1333 // error type, meaning that an error occurred when typechecking this expression),
1334 // this is a derived error. The error cascaded from another error (that was already
1335 // reported), so it's not useful to display it to the user.
1336 // The following methods implement this logic.
1337 // They check if either the actual or expected type is Error, and don't print the error
1338 // in this case. The typechecker should only ever report type errors involving mismatched
1339 // types using one of these methods, and should not call span_err directly for such
1342 pub fn type_error_struct_with_diag<M>(
1346 actual_ty: Ty<'tcx>,
1347 ) -> DiagnosticBuilder<'tcx>
1349 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1351 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1352 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1354 // Don't report an error if actual type is `Error`.
1355 if actual_ty.references_error() {
1356 return self.tcx.sess.diagnostic().struct_dummy();
1359 mk_diag(self.ty_to_string(actual_ty))
1362 pub fn report_mismatched_types(
1364 cause: &ObligationCause<'tcx>,
1367 err: TypeError<'tcx>,
1368 ) -> DiagnosticBuilder<'tcx> {
1369 let trace = TypeTrace::types(cause, true, expected, actual);
1370 self.report_and_explain_type_error(trace, &err)
1373 pub fn replace_bound_vars_with_fresh_vars<T>(
1376 lbrct: LateBoundRegionConversionTime,
1377 value: &ty::Binder<T>
1378 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1380 T: TypeFoldable<'tcx>
1382 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1383 let fld_t = |_| self.next_ty_var(TypeVariableOrigin::MiscVariable(span));
1384 self.tcx.replace_bound_vars(value, fld_r, fld_t)
1387 /// See the [`region_constraints::verify_generic_bound`] method.
1388 pub fn verify_generic_bound(
1390 origin: SubregionOrigin<'tcx>,
1391 kind: GenericKind<'tcx>,
1392 a: ty::Region<'tcx>,
1393 bound: VerifyBound<'tcx>,
1395 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1397 self.borrow_region_constraints()
1398 .verify_generic_bound(origin, kind, a, bound);
1401 pub fn type_is_copy_modulo_regions(
1403 param_env: ty::ParamEnv<'tcx>,
1407 let ty = self.resolve_type_vars_if_possible(&ty);
1409 // Even if the type may have no inference variables, during
1410 // type-checking closure types are in local tables only.
1411 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1412 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1413 return ty.is_copy_modulo_regions(self.tcx.global_tcx(), param_env, span);
1417 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1419 // this can get called from typeck (by euv), and moves_by_default
1420 // rightly refuses to work with inference variables, but
1421 // moves_by_default has a cache, which we want to use in other
1423 traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id, span)
1426 /// Obtains the latest type of the given closure; this may be a
1427 /// closure in the current function, in which case its
1428 /// `ClosureKind` may not yet be known.
1429 pub fn closure_kind(
1431 closure_def_id: DefId,
1432 closure_substs: ty::ClosureSubsts<'tcx>,
1433 ) -> Option<ty::ClosureKind> {
1434 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx);
1435 let closure_kind_ty = self.shallow_resolve(&closure_kind_ty);
1436 closure_kind_ty.to_opt_closure_kind()
1439 /// Obtain the signature of a closure. For closures, unlike
1440 /// `tcx.fn_sig(def_id)`, this method will work during the
1441 /// type-checking of the enclosing function and return the closure
1442 /// signature in its partially inferred state.
1446 substs: ty::ClosureSubsts<'tcx>,
1447 ) -> ty::PolyFnSig<'tcx> {
1448 let closure_sig_ty = substs.closure_sig_ty(def_id, self.tcx);
1449 let closure_sig_ty = self.shallow_resolve(&closure_sig_ty);
1450 closure_sig_ty.fn_sig(self.tcx)
1453 /// Normalizes associated types in `value`, potentially returning
1454 /// new obligations that must further be processed.
1455 pub fn partially_normalize_associated_types_in<T>(
1458 body_id: hir::HirId,
1459 param_env: ty::ParamEnv<'tcx>,
1461 ) -> InferOk<'tcx, T>
1463 T: TypeFoldable<'tcx>,
1465 debug!("partially_normalize_associated_types_in(value={:?})", value);
1466 let mut selcx = traits::SelectionContext::new(self);
1467 let cause = ObligationCause::misc(span, body_id);
1468 let traits::Normalized { value, obligations } =
1469 traits::normalize(&mut selcx, param_env, cause, value);
1471 "partially_normalize_associated_types_in: result={:?} predicates={:?}",
1474 InferOk { value, obligations }
1477 pub fn borrow_region_constraints(&self) -> RefMut<'_, RegionConstraintCollector<'tcx>> {
1478 RefMut::map(self.region_constraints.borrow_mut(), |c| {
1479 c.as_mut().expect("region constraints already solved")
1483 /// Clears the selection, evaluation, and projection caches. This is useful when
1484 /// repeatedly attempting to select an `Obligation` while changing only
1485 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1486 pub fn clear_caches(&self) {
1487 self.selection_cache.clear();
1488 self.evaluation_cache.clear();
1489 self.projection_cache.borrow_mut().clear();
1492 fn universe(&self) -> ty::UniverseIndex {
1496 /// Creates and return a fresh universe that extends all previous
1497 /// universes. Updates `self.universe` to that new universe.
1498 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1499 let u = self.universe.get().next_universe();
1500 self.universe.set(u);
1505 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1506 pub fn span(&self) -> Span {
1511 cause: &ObligationCause<'tcx>,
1512 a_is_expected: bool,
1515 ) -> TypeTrace<'tcx> {
1517 cause: cause.clone(),
1518 values: Types(ExpectedFound::new(a_is_expected, a, b)),
1522 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1524 cause: ObligationCause::dummy(),
1525 values: Types(ExpectedFound {
1526 expected: tcx.types.err,
1527 found: tcx.types.err,
1533 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1534 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1535 write!(f, "TypeTrace({:?})", self.cause)
1539 impl<'tcx> SubregionOrigin<'tcx> {
1540 pub fn span(&self) -> Span {
1542 Subtype(ref a) => a.span(),
1543 InfStackClosure(a) => a,
1544 InvokeClosure(a) => a,
1545 DerefPointer(a) => a,
1546 FreeVariable(a, _) => a,
1548 RelateObjectBound(a) => a,
1549 RelateParamBound(a, _) => a,
1550 RelateRegionParamBound(a) => a,
1551 RelateDefaultParamBound(a, _) => a,
1553 ReborrowUpvar(a, _) => a,
1554 DataBorrowed(_, a) => a,
1555 ReferenceOutlivesReferent(_, a) => a,
1556 ParameterInScope(_, a) => a,
1557 ExprTypeIsNotInScope(_, a) => a,
1558 BindingTypeIsNotValidAtDecl(a) => a,
1565 SafeDestructor(a) => a,
1566 CompareImplMethodObligation { span, .. } => span,
1570 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1572 F: FnOnce() -> Self,
1575 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1576 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1579 traits::ObligationCauseCode::CompareImplMethodObligation {
1583 } => SubregionOrigin::CompareImplMethodObligation {
1595 impl RegionVariableOrigin {
1596 pub fn span(&self) -> Span {
1598 MiscVariable(a) => a,
1599 PatternRegion(a) => a,
1600 AddrOfRegion(a) => a,
1603 EarlyBoundRegion(a, ..) => a,
1604 LateBoundRegion(a, ..) => a,
1605 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1606 UpvarRegion(_, a) => a,
1607 NLL(..) => bug!("NLL variable used with `span`"),
1612 EnumTypeFoldableImpl! {
1613 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1614 (ValuePairs::Types)(a),
1615 (ValuePairs::Regions)(a),
1616 (ValuePairs::TraitRefs)(a),
1617 (ValuePairs::PolyTraitRefs)(a),
1621 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1625 "RegionObligation(sub_region={:?}, sup_type={:?})",
1626 self.sub_region, self.sup_type