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;
10 use crate::hir::def_id::DefId;
11 use crate::infer::canonical::{Canonical, CanonicalVarValues};
12 use crate::middle::free_region::RegionRelations;
13 use crate::middle::lang_items;
14 use crate::middle::region;
15 use crate::session::config::BorrowckMode;
16 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
17 use crate::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
18 use crate::ty::fold::TypeFoldable;
19 use crate::ty::relate::RelateResult;
20 use crate::ty::subst::{Kind, Substs};
21 use crate::ty::{self, GenericParamDefKind, Ty, TyCtxt, CtxtInterners};
22 use crate::ty::{FloatVid, IntVid, TyVid};
23 use crate::util::nodemap::FxHashMap;
25 use arena::SyncDroplessArena;
26 use errors::DiagnosticBuilder;
27 use rustc_data_structures::unify as ut;
28 use std::cell::{Cell, Ref, RefCell, RefMut};
29 use std::collections::BTreeMap;
32 use syntax_pos::symbol::InternedString;
35 use self::combine::CombineFields;
36 use self::lexical_region_resolve::LexicalRegionResolutions;
37 use self::outlives::env::OutlivesEnvironment;
38 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
39 use self::region_constraints::{RegionConstraintCollector, RegionSnapshot};
40 use self::type_variable::TypeVariableOrigin;
41 use self::unify_key::ToType;
47 pub mod error_reporting;
53 mod lexical_region_resolve;
58 pub mod region_constraints;
61 pub mod type_variable;
66 pub struct InferOk<'tcx, T> {
68 pub obligations: PredicateObligations<'tcx>,
70 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
72 pub type Bound<T> = Option<T>;
73 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
74 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
76 /// A flag that is used to suppress region errors. This is normally
77 /// false, but sometimes -- when we are doing region checks that the
78 /// NLL borrow checker will also do -- it might be set to true.
79 #[derive(Copy, Clone, Default, Debug)]
80 pub struct SuppressRegionErrors {
84 impl SuppressRegionErrors {
85 pub fn suppressed(self) -> bool {
89 /// Indicates that the MIR borrowck will repeat these region
90 /// checks, so we should ignore errors if NLL is (unconditionally)
92 pub fn when_nll_is_enabled(tcx: TyCtxt<'_, '_, '_>) -> Self {
93 match tcx.borrowck_mode() {
94 // If we're on AST or Migrate mode, report AST region errors
95 BorrowckMode::Ast | BorrowckMode::Migrate => SuppressRegionErrors { suppressed: false },
97 // If we're on MIR or Compare mode, don't report AST region errors as they should
99 BorrowckMode::Compare | BorrowckMode::Mir => SuppressRegionErrors { suppressed: true },
104 pub struct InferCtxt<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
105 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
107 /// During type-checking/inference of a body, `in_progress_tables`
108 /// contains a reference to the tables being built up, which are
109 /// used for reading closure kinds/signatures as they are inferred,
110 /// and for error reporting logic to read arbitrary node types.
111 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
113 // Cache for projections. This cache is snapshotted along with the
116 // Public so that `traits::project` can use it.
117 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
119 // We instantiate UnificationTable with bounds<Ty> because the
120 // types that might instantiate a general type variable have an
121 // order, represented by its upper and lower bounds.
122 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
124 // Map from integral variable to the kind of integer it represents
125 int_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::IntVid>>>,
127 // Map from floating variable to the kind of float it represents
128 float_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::FloatVid>>>,
130 // Tracks the set of region variables and the constraints between
131 // them. This is initially `Some(_)` but when
132 // `resolve_regions_and_report_errors` is invoked, this gets set
133 // to `None` -- further attempts to perform unification etc may
134 // fail if new region constraints would've been added.
135 region_constraints: RefCell<Option<RegionConstraintCollector<'tcx>>>,
137 // Once region inference is done, the values for each variable.
138 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
140 /// Caches the results of trait selection. This cache is used
141 /// for things that have to do with the parameters in scope.
142 pub selection_cache: traits::SelectionCache<'tcx>,
144 /// Caches the results of trait evaluation.
145 pub evaluation_cache: traits::EvaluationCache<'tcx>,
147 // the set of predicates on which errors have been reported, to
148 // avoid reporting the same error twice.
149 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
151 // When an error occurs, we want to avoid reporting "derived"
152 // errors that are due to this original failure. Normally, we
153 // handle this with the `err_count_on_creation` count, which
154 // basically just tracks how many errors were reported when we
155 // started type-checking a fn and checks to see if any new errors
156 // have been reported since then. Not great, but it works.
158 // However, when errors originated in other passes -- notably
159 // resolve -- this heuristic breaks down. Therefore, we have this
160 // auxiliary flag that one can set whenever one creates a
161 // type-error that is due to an error in a prior pass.
163 // Don't read this flag directly, call `is_tainted_by_errors()`
164 // and `set_tainted_by_errors()`.
165 tainted_by_errors_flag: Cell<bool>,
167 // Track how many errors were reported when this infcx is created.
168 // If the number of errors increases, that's also a sign (line
169 // `tained_by_errors`) to avoid reporting certain kinds of errors.
170 err_count_on_creation: usize,
172 // This flag is true while there is an active snapshot.
173 in_snapshot: Cell<bool>,
175 // A set of constraints that regionck must validate. Each
176 // constraint has the form `T:'a`, meaning "some type `T` must
177 // outlive the lifetime 'a". These constraints derive from
178 // instantiated type parameters. So if you had a struct defined
181 // struct Foo<T:'static> { ... }
183 // then in some expression `let x = Foo { ... }` it will
184 // instantiate the type parameter `T` with a fresh type `$0`. At
185 // the same time, it will record a region obligation of
186 // `$0:'static`. This will get checked later by regionck. (We
187 // can't generally check these things right away because we have
188 // to wait until types are resolved.)
190 // These are stored in a map keyed to the id of the innermost
191 // enclosing fn body / static initializer expression. This is
192 // because the location where the obligation was incurred can be
193 // relevant with respect to which sublifetime assumptions are in
194 // place. The reason that we store under the fn-id, and not
195 // something more fine-grained, is so that it is easier for
196 // regionck to be sure that it has found *all* the region
197 // obligations (otherwise, it's easy to fail to walk to a
198 // particular node-id).
200 // Before running `resolve_regions_and_report_errors`, the creator
201 // of the inference context is expected to invoke
202 // `process_region_obligations` (defined in `self::region_obligations`)
203 // for each body-id in this map, which will process the
204 // obligations within. This is expected to be done 'late enough'
205 // that all type inference variables have been bound and so forth.
206 pub region_obligations: RefCell<Vec<(ast::NodeId, RegionObligation<'tcx>)>>,
208 /// What is the innermost universe we have created? Starts out as
209 /// `UniverseIndex::root()` but grows from there as we enter
210 /// universal quantifiers.
212 /// N.B., at present, we exclude the universal quantifiers on the
213 /// item we are type-checking, and just consider those names as
214 /// part of the root universe. So this would only get incremented
215 /// when we enter into a higher-ranked (`for<..>`) type or trait
217 universe: Cell<ty::UniverseIndex>,
220 /// A map returned by `replace_bound_vars_with_placeholders()`
221 /// indicating the placeholder region that each late-bound region was
223 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
225 /// See the `error_reporting` module for more details.
226 #[derive(Clone, Debug, PartialEq, Eq)]
227 pub enum ValuePairs<'tcx> {
228 Types(ExpectedFound<Ty<'tcx>>),
229 Regions(ExpectedFound<ty::Region<'tcx>>),
230 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
231 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
234 /// The trace designates the path through inference that we took to
235 /// encounter an error or subtyping constraint.
237 /// See the `error_reporting` module for more details.
239 pub struct TypeTrace<'tcx> {
240 cause: ObligationCause<'tcx>,
241 values: ValuePairs<'tcx>,
244 /// The origin of a `r1 <= r2` constraint.
246 /// See `error_reporting` module for more details
247 #[derive(Clone, Debug)]
248 pub enum SubregionOrigin<'tcx> {
249 // Arose from a subtyping relation
250 Subtype(TypeTrace<'tcx>),
252 // Stack-allocated closures cannot outlive innermost loop
253 // or function so as to ensure we only require finite stack
254 InfStackClosure(Span),
256 // Invocation of closure must be within its lifetime
259 // Dereference of reference must be within its lifetime
262 // Closure bound must not outlive captured free variables
263 FreeVariable(Span, ast::NodeId),
265 // Index into slice must be within its lifetime
268 // When casting `&'a T` to an `&'b Trait` object,
269 // relating `'a` to `'b`
270 RelateObjectBound(Span),
272 // Some type parameter was instantiated with the given type,
273 // and that type must outlive some region.
274 RelateParamBound(Span, Ty<'tcx>),
276 // The given region parameter was instantiated with a region
277 // that must outlive some other region.
278 RelateRegionParamBound(Span),
280 // A bound placed on type parameters that states that must outlive
281 // the moment of their instantiation.
282 RelateDefaultParamBound(Span, Ty<'tcx>),
284 // Creating a pointer `b` to contents of another reference
287 // Creating a pointer `b` to contents of an upvar
288 ReborrowUpvar(Span, ty::UpvarId),
290 // Data with type `Ty<'tcx>` was borrowed
291 DataBorrowed(Ty<'tcx>, Span),
293 // (&'a &'b T) where a >= b
294 ReferenceOutlivesReferent(Ty<'tcx>, Span),
296 // Type or region parameters must be in scope.
297 ParameterInScope(ParameterOrigin, Span),
299 // The type T of an expression E must outlive the lifetime for E.
300 ExprTypeIsNotInScope(Ty<'tcx>, Span),
302 // A `ref b` whose region does not enclose the decl site
303 BindingTypeIsNotValidAtDecl(Span),
305 // Regions appearing in a method receiver must outlive method call
308 // Regions appearing in a function argument must outlive func call
311 // Region in return type of invoked fn must enclose call
314 // Operands must be in scope
317 // Region resulting from a `&` expr must enclose the `&` expr
320 // An auto-borrow that does not enclose the expr where it occurs
323 // Region constraint arriving from destructor safety
324 SafeDestructor(Span),
326 // Comparing the signature and requirements of an impl method against
327 // the containing trait.
328 CompareImplMethodObligation {
330 item_name: ast::Name,
331 impl_item_def_id: DefId,
332 trait_item_def_id: DefId,
336 /// Places that type/region parameters can appear.
337 #[derive(Clone, Copy, Debug)]
338 pub enum ParameterOrigin {
340 MethodCall, // foo.bar() <-- parameters on impl providing bar()
341 OverloadedOperator, // a + b when overloaded
342 OverloadedDeref, // *a when overloaded
345 /// Times when we replace late-bound regions with variables:
346 #[derive(Clone, Copy, Debug)]
347 pub enum LateBoundRegionConversionTime {
348 /// when a fn is called
351 /// when two higher-ranked types are compared
354 /// when projecting an associated type
355 AssocTypeProjection(DefId),
358 /// Reasons to create a region inference variable
360 /// See `error_reporting` module for more details
361 #[derive(Copy, Clone, Debug)]
362 pub enum RegionVariableOrigin {
363 // Region variables created for ill-categorized reasons,
364 // mostly indicates places in need of refactoring
367 // Regions created by a `&P` or `[...]` pattern
370 // Regions created by `&` operator
373 // Regions created as part of an autoref of a method receiver
376 // Regions created as part of an automatic coercion
379 // Region variables created as the values for early-bound regions
380 EarlyBoundRegion(Span, InternedString),
382 // Region variables created for bound regions
383 // in a function or method that is called
384 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
386 UpvarRegion(ty::UpvarId, Span),
388 BoundRegionInCoherence(ast::Name),
390 // This origin is used for the inference variables that we create
391 // during NLL region processing.
392 NLL(NLLRegionVariableOrigin),
395 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
396 pub enum NLLRegionVariableOrigin {
397 /// During NLL region processing, we create variables for free
398 /// regions that we encounter in the function signature and
399 /// elsewhere. This origin indices we've got one of those.
402 /// "Universal" instantiation of a higher-ranked region (e.g.,
403 /// from a `for<'a> T` binder). Meant to represent "any region".
404 Placeholder(ty::PlaceholderRegion),
409 impl NLLRegionVariableOrigin {
410 pub fn is_universal(self) -> bool {
412 NLLRegionVariableOrigin::FreeRegion => true,
413 NLLRegionVariableOrigin::Placeholder(..) => true,
414 NLLRegionVariableOrigin::Existential => false,
418 pub fn is_existential(self) -> bool {
423 #[derive(Copy, Clone, Debug)]
424 pub enum FixupError {
425 UnresolvedIntTy(IntVid),
426 UnresolvedFloatTy(FloatVid),
430 /// See the `region_obligations` field for more information.
432 pub struct RegionObligation<'tcx> {
433 pub sub_region: ty::Region<'tcx>,
434 pub sup_type: Ty<'tcx>,
435 pub origin: SubregionOrigin<'tcx>,
438 impl fmt::Display for FixupError {
439 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
440 use self::FixupError::*;
443 UnresolvedIntTy(_) => write!(
445 "cannot determine the type of this integer; \
446 add a suffix to specify the type explicitly"
448 UnresolvedFloatTy(_) => write!(
450 "cannot determine the type of this number; \
451 add a suffix to specify the type explicitly"
453 UnresolvedTy(_) => write!(f, "unconstrained type"),
458 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
459 /// Necessary because we can't write the following bound:
460 /// `F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>)`.
461 pub struct InferCtxtBuilder<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
462 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
463 arena: SyncDroplessArena,
464 interners: Option<CtxtInterners<'tcx>>,
465 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
468 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
469 pub fn infer_ctxt(self) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
472 arena: SyncDroplessArena::default(),
479 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
480 /// Used only by `rustc_typeck` during body type-checking/inference,
481 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
482 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
483 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
487 /// Given a canonical value `C` as a starting point, create an
488 /// inference context that contains each of the bound values
489 /// within instantiated as a fresh variable. The `f` closure is
490 /// invoked with the new infcx, along with the instantiated value
491 /// `V` and a substitution `S`. This substitution `S` maps from
492 /// the bound values in `C` to their instantiated values in `V`
493 /// (in other words, `S(C) = V`).
494 pub fn enter_with_canonical<T, R>(
497 canonical: &Canonical<'tcx, T>,
498 f: impl for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
501 T: TypeFoldable<'tcx>,
505 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
506 f(infcx, value, subst)
510 pub fn enter<R>(&'tcx mut self, f: impl for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R) -> R {
511 let InferCtxtBuilder {
517 let in_progress_tables = fresh_tables.as_ref();
518 // Check that we haven't entered before
519 assert!(interners.is_none());
520 global_tcx.enter_local(arena, interners, |tcx| {
524 projection_cache: Default::default(),
525 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
526 int_unification_table: RefCell::new(ut::UnificationTable::new()),
527 float_unification_table: RefCell::new(ut::UnificationTable::new()),
528 region_constraints: RefCell::new(Some(RegionConstraintCollector::new())),
529 lexical_region_resolutions: RefCell::new(None),
530 selection_cache: Default::default(),
531 evaluation_cache: Default::default(),
532 reported_trait_errors: Default::default(),
533 tainted_by_errors_flag: Cell::new(false),
534 err_count_on_creation: tcx.sess.err_count(),
535 in_snapshot: Cell::new(false),
536 region_obligations: RefCell::new(vec![]),
537 universe: Cell::new(ty::UniverseIndex::ROOT),
543 impl<T> ExpectedFound<T> {
544 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
559 impl<'tcx, T> InferOk<'tcx, T> {
560 pub fn unit(self) -> InferOk<'tcx, ()> {
563 obligations: self.obligations,
567 /// Extracts `value`, registering any obligations into `fulfill_cx`.
568 pub fn into_value_registering_obligations(
570 infcx: &InferCtxt<'_, '_, 'tcx>,
571 fulfill_cx: &mut dyn TraitEngine<'tcx>,
573 let InferOk { value, obligations } = self;
574 for obligation in obligations {
575 fulfill_cx.register_predicate_obligation(infcx, obligation);
581 impl<'tcx> InferOk<'tcx, ()> {
582 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
587 #[must_use = "once you start a snapshot, you should always consume it"]
588 pub struct CombinedSnapshot<'a, 'tcx: 'a> {
589 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
590 type_snapshot: type_variable::Snapshot<'tcx>,
591 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
592 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
593 region_constraints_snapshot: RegionSnapshot,
594 region_obligations_snapshot: usize,
595 universe: ty::UniverseIndex,
596 was_in_snapshot: bool,
597 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
600 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
601 pub fn is_in_snapshot(&self) -> bool {
602 self.in_snapshot.get()
605 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
606 t.fold_with(&mut self.freshener())
609 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
611 ty::Infer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
616 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
617 freshen::TypeFreshener::new(self)
620 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
621 use crate::ty::error::UnconstrainedNumeric::Neither;
622 use crate::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
624 ty::Infer(ty::IntVar(vid)) => {
625 if self.int_unification_table
635 ty::Infer(ty::FloatVar(vid)) => {
636 if self.float_unification_table
650 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
651 let mut type_variables = self.type_variables.borrow_mut();
652 let mut int_unification_table = self.int_unification_table.borrow_mut();
653 let mut float_unification_table = self.float_unification_table.borrow_mut();
656 .unsolved_variables()
658 .map(|t| self.tcx.mk_var(t))
660 (0..int_unification_table.len())
661 .map(|i| ty::IntVid { index: i as u32 })
662 .filter(|&vid| int_unification_table.probe_value(vid).is_none())
663 .map(|v| self.tcx.mk_int_var(v)),
666 (0..float_unification_table.len())
667 .map(|i| ty::FloatVid { index: i as u32 })
668 .filter(|&vid| float_unification_table.probe_value(vid).is_none())
669 .map(|v| self.tcx.mk_float_var(v)),
676 trace: TypeTrace<'tcx>,
677 param_env: ty::ParamEnv<'tcx>,
678 ) -> CombineFields<'a, 'gcx, 'tcx> {
684 obligations: PredicateObligations::new(),
688 // Clear the "currently in a snapshot" flag, invoke the closure,
689 // then restore the flag to its original value. This flag is a
690 // debugging measure designed to detect cases where we start a
691 // snapshot, create type variables, and register obligations
692 // which may involve those type variables in the fulfillment cx,
693 // potentially leaving "dangling type variables" behind.
694 // In such cases, an assertion will fail when attempting to
695 // register obligations, within a snapshot. Very useful, much
696 // better than grovelling through megabytes of RUST_LOG output.
698 // HOWEVER, in some cases the flag is unhelpful. In particular, we
699 // sometimes create a "mini-fulfilment-cx" in which we enroll
700 // obligations. As long as this fulfillment cx is fully drained
701 // before we return, this is not a problem, as there won't be any
702 // escaping obligations in the main cx. In those cases, you can
703 // use this function.
704 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
706 F: FnOnce(&Self) -> R,
708 let flag = self.in_snapshot.get();
709 self.in_snapshot.set(false);
710 let result = func(self);
711 self.in_snapshot.set(flag);
715 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
716 debug!("start_snapshot()");
718 let in_snapshot = self.in_snapshot.get();
719 self.in_snapshot.set(true);
722 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
723 type_snapshot: self.type_variables.borrow_mut().snapshot(),
724 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
725 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
726 region_constraints_snapshot: self.borrow_region_constraints().start_snapshot(),
727 region_obligations_snapshot: self.region_obligations.borrow().len(),
728 universe: self.universe(),
729 was_in_snapshot: in_snapshot,
730 // Borrow tables "in progress" (i.e., during typeck)
731 // to ban writes from within a snapshot to them.
732 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
736 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
737 debug!("rollback_to(cause={})", cause);
738 let CombinedSnapshot {
739 projection_cache_snapshot,
743 region_constraints_snapshot,
744 region_obligations_snapshot,
750 self.in_snapshot.set(was_in_snapshot);
751 self.universe.set(universe);
753 self.projection_cache
755 .rollback_to(projection_cache_snapshot);
756 self.type_variables.borrow_mut().rollback_to(type_snapshot);
757 self.int_unification_table
759 .rollback_to(int_snapshot);
760 self.float_unification_table
762 .rollback_to(float_snapshot);
763 self.region_obligations
765 .truncate(region_obligations_snapshot);
766 self.borrow_region_constraints()
767 .rollback_to(region_constraints_snapshot);
770 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
771 debug!("commit_from()");
772 let CombinedSnapshot {
773 projection_cache_snapshot,
777 region_constraints_snapshot,
778 region_obligations_snapshot: _,
784 self.in_snapshot.set(was_in_snapshot);
786 self.projection_cache
788 .commit(projection_cache_snapshot);
789 self.type_variables.borrow_mut().commit(type_snapshot);
790 self.int_unification_table.borrow_mut().commit(int_snapshot);
791 self.float_unification_table
793 .commit(float_snapshot);
794 self.borrow_region_constraints()
795 .commit(region_constraints_snapshot);
798 /// Executes `f` and commit the bindings.
799 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
804 let snapshot = self.start_snapshot();
806 self.commit_from(snapshot);
810 /// Executes `f` and commit the bindings if closure `f` returns `Ok(_)`.
811 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
813 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
815 debug!("commit_if_ok()");
816 let snapshot = self.start_snapshot();
817 let r = f(&snapshot);
818 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
821 self.commit_from(snapshot);
824 self.rollback_to("commit_if_ok -- error", snapshot);
830 // Execute `f` in a snapshot, and commit the bindings it creates
831 pub fn in_snapshot<T, F>(&self, f: F) -> T
833 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> T,
835 debug!("in_snapshot()");
836 let snapshot = self.start_snapshot();
837 let r = f(&snapshot);
838 self.commit_from(snapshot);
842 /// Executes `f` then unroll any bindings it creates.
843 pub fn probe<R, F>(&self, f: F) -> R
845 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
848 let snapshot = self.start_snapshot();
849 let r = f(&snapshot);
850 self.rollback_to("probe", snapshot);
854 /// Scan the constraints produced since `snapshot` began and returns:
856 /// - None -- if none of them involve "region outlives" constraints
857 /// - Some(true) -- if there are `'a: 'b` constraints where `'a` or `'b` is a placehodler
858 /// - Some(false) -- if there are `'a: 'b` constraints but none involve placeholders
859 pub fn region_constraints_added_in_snapshot(
861 snapshot: &CombinedSnapshot<'a, 'tcx>,
863 self.borrow_region_constraints().region_constraints_added_in_snapshot(
864 &snapshot.region_constraints_snapshot,
868 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
869 self.borrow_region_constraints().add_given(sub, sup);
872 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
874 T: at::ToTrace<'tcx>,
876 let origin = &ObligationCause::dummy();
878 self.at(origin, param_env)
880 .map(|InferOk { obligations: _, .. }| {
881 // Ignore obligations, since we are unrolling
882 // everything anyway.
887 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
889 T: at::ToTrace<'tcx>,
891 let origin = &ObligationCause::dummy();
893 self.at(origin, param_env)
895 .map(|InferOk { obligations: _, .. }| {
896 // Ignore obligations, since we are unrolling
897 // everything anyway.
904 origin: SubregionOrigin<'tcx>,
908 debug!("sub_regions({:?} <: {:?})", a, b);
909 self.borrow_region_constraints()
910 .make_subregion(origin, a, b);
913 pub fn subtype_predicate(
915 cause: &ObligationCause<'tcx>,
916 param_env: ty::ParamEnv<'tcx>,
917 predicate: &ty::PolySubtypePredicate<'tcx>,
918 ) -> Option<InferResult<'tcx, ()>> {
919 // Subtle: it's ok to skip the binder here and resolve because
920 // `shallow_resolve` just ignores anything that is not a type
921 // variable, and because type variable's can't (at present, at
922 // least) capture any of the things bound by this binder.
924 // Really, there is no *particular* reason to do this
925 // `shallow_resolve` here except as a
926 // micro-optimization. Naturally I could not
927 // resist. -nmatsakis
928 let two_unbound_type_vars = {
929 let a = self.shallow_resolve(predicate.skip_binder().a);
930 let b = self.shallow_resolve(predicate.skip_binder().b);
931 a.is_ty_var() && b.is_ty_var()
934 if two_unbound_type_vars {
935 // Two unbound type variables? Can't make progress.
940 ty::SubtypePredicate {
946 ) = self.replace_bound_vars_with_placeholders(predicate);
949 self.at(cause, param_env)
950 .sub_exp(a_is_expected, a, b)
951 .map(|ok| ok.unit()),
955 pub fn region_outlives_predicate(
957 cause: &traits::ObligationCause<'tcx>,
958 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
960 let (ty::OutlivesPredicate(r_a, r_b), _) =
961 self.replace_bound_vars_with_placeholders(predicate);
963 SubregionOrigin::from_obligation_cause(cause, || RelateRegionParamBound(cause.span));
964 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
967 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
970 .new_var(self.universe(), diverging, origin)
973 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
974 self.tcx.mk_var(self.next_ty_var_id(false, origin))
977 pub fn next_ty_var_in_universe(
979 origin: TypeVariableOrigin,
980 universe: ty::UniverseIndex
982 let vid = self.type_variables
984 .new_var(universe, false, origin);
988 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
989 self.tcx.mk_var(self.next_ty_var_id(true, origin))
992 pub fn next_int_var_id(&self) -> IntVid {
993 self.int_unification_table.borrow_mut().new_key(None)
996 pub fn next_float_var_id(&self) -> FloatVid {
997 self.float_unification_table.borrow_mut().new_key(None)
1000 /// Creates a fresh region variable with the next available index.
1001 /// The variable will be created in the maximum universe created
1002 /// thus far, allowing it to name any region created thus far.
1003 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1004 self.next_region_var_in_universe(origin, self.universe())
1007 /// Creates a fresh region variable with the next available index
1008 /// in the given universe; typically, you can use
1009 /// `next_region_var` and just use the maximal universe.
1010 pub fn next_region_var_in_universe(
1012 origin: RegionVariableOrigin,
1013 universe: ty::UniverseIndex,
1014 ) -> ty::Region<'tcx> {
1015 let region_var = self.borrow_region_constraints()
1016 .new_region_var(universe, origin);
1017 self.tcx.mk_region(ty::ReVar(region_var))
1020 /// Number of region variables created so far.
1021 pub fn num_region_vars(&self) -> usize {
1022 self.borrow_region_constraints().num_region_vars()
1025 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1026 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1027 self.next_region_var(RegionVariableOrigin::NLL(origin))
1030 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1031 pub fn next_nll_region_var_in_universe(
1033 origin: NLLRegionVariableOrigin,
1034 universe: ty::UniverseIndex,
1035 ) -> ty::Region<'tcx> {
1036 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1039 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> Kind<'tcx> {
1041 GenericParamDefKind::Lifetime => {
1042 // Create a region inference variable for the given
1043 // region parameter definition.
1044 self.next_region_var(EarlyBoundRegion(span, param.name))
1047 GenericParamDefKind::Type { .. } => {
1048 // Create a type inference variable for the given
1049 // type parameter definition. The substitutions are
1050 // for actual parameters that may be referred to by
1051 // the default of this type parameter, if it exists.
1052 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1053 // used in a path such as `Foo::<T, U>::new()` will
1054 // use an inference variable for `C` with `[T, U]`
1055 // as the substitutions for the default, `(T, U)`.
1056 let ty_var_id = self.type_variables.borrow_mut().new_var(
1059 TypeVariableOrigin::TypeParameterDefinition(span, param.name),
1062 self.tcx.mk_var(ty_var_id).into()
1067 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1068 /// type/region parameter to a fresh inference variable.
1069 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> &'tcx Substs<'tcx> {
1070 Substs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1073 /// Returns `true` if errors have been reported since this infcx was
1074 /// created. This is sometimes used as a heuristic to skip
1075 /// reporting errors that often occur as a result of earlier
1076 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1077 /// inference variables, regionck errors).
1078 pub fn is_tainted_by_errors(&self) -> bool {
1080 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1081 tainted_by_errors_flag={})",
1082 self.tcx.sess.err_count(),
1083 self.err_count_on_creation,
1084 self.tainted_by_errors_flag.get()
1087 if self.tcx.sess.err_count() > self.err_count_on_creation {
1088 return true; // errors reported since this infcx was made
1090 self.tainted_by_errors_flag.get()
1093 /// Set the "tainted by errors" flag to true. We call this when we
1094 /// observe an error from a prior pass.
1095 pub fn set_tainted_by_errors(&self) {
1096 debug!("set_tainted_by_errors()");
1097 self.tainted_by_errors_flag.set(true)
1100 /// Process the region constraints and report any errors that
1101 /// result. After this, no more unification operations should be
1102 /// done -- or the compiler will panic -- but it is legal to use
1103 /// `resolve_type_vars_if_possible` as well as `fully_resolve`.
1104 pub fn resolve_regions_and_report_errors(
1106 region_context: DefId,
1107 region_map: ®ion::ScopeTree,
1108 outlives_env: &OutlivesEnvironment<'tcx>,
1109 suppress: SuppressRegionErrors,
1112 self.is_tainted_by_errors() || self.region_obligations.borrow().is_empty(),
1113 "region_obligations not empty: {:#?}",
1114 self.region_obligations.borrow()
1117 let region_rels = &RegionRelations::new(
1121 outlives_env.free_region_map(),
1123 let (var_infos, data) = self.region_constraints
1126 .expect("regions already resolved")
1127 .into_infos_and_data();
1128 let (lexical_region_resolutions, errors) =
1129 lexical_region_resolve::resolve(region_rels, var_infos, data);
1131 let old_value = self.lexical_region_resolutions
1132 .replace(Some(lexical_region_resolutions));
1133 assert!(old_value.is_none());
1135 if !self.is_tainted_by_errors() {
1136 // As a heuristic, just skip reporting region errors
1137 // altogether if other errors have been reported while
1138 // this infcx was in use. This is totally hokey but
1139 // otherwise we have a hard time separating legit region
1140 // errors from silly ones.
1141 self.report_region_errors(region_map, &errors, suppress);
1145 /// Obtains (and clears) the current set of region
1146 /// constraints. The inference context is still usable: further
1147 /// unifications will simply add new constraints.
1149 /// This method is not meant to be used with normal lexical region
1150 /// resolution. Rather, it is used in the NLL mode as a kind of
1151 /// interim hack: basically we run normal type-check and generate
1152 /// region constraints as normal, but then we take them and
1153 /// translate them into the form that the NLL solver
1154 /// understands. See the NLL module for mode details.
1155 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1157 self.region_obligations.borrow().is_empty(),
1158 "region_obligations not empty: {:#?}",
1159 self.region_obligations.borrow()
1162 self.borrow_region_constraints().take_and_reset_data()
1165 /// Gives temporary access to the region constraint data.
1166 #[allow(non_camel_case_types)] // bug with impl trait
1167 pub fn with_region_constraints<R>(
1169 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1171 let region_constraints = self.borrow_region_constraints();
1172 op(region_constraints.data())
1175 /// Takes ownership of the list of variable regions. This implies
1176 /// that all the region constraints have already been taken, and
1177 /// hence that `resolve_regions_and_report_errors` can never be
1178 /// called. This is used only during NLL processing to "hand off" ownership
1179 /// of the set of region variables into the NLL region context.
1180 pub fn take_region_var_origins(&self) -> VarInfos {
1181 let (var_infos, data) = self.region_constraints
1184 .expect("regions already resolved")
1185 .into_infos_and_data();
1186 assert!(data.is_empty());
1190 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1191 self.resolve_type_vars_if_possible(&t).to_string()
1194 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1195 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1196 format!("({})", tstrs.join(", "))
1199 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1200 self.resolve_type_vars_if_possible(t).to_string()
1203 // We have this force-inlined variant of shallow_resolve() for the one
1204 // callsite that is extremely hot. All other callsites use the normal
1207 pub fn inlined_shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1209 ty::Infer(ty::TyVar(v)) => {
1210 // Not entirely obvious: if `typ` is a type variable,
1211 // it can be resolved to an int/float variable, which
1212 // can then be recursively resolved, hence the
1213 // recursion. Note though that we prevent type
1214 // variables from unifyxing to other type variables
1215 // directly (though they may be embedded
1216 // structurally), and we prevent cycles in any case,
1217 // so this recursion should always be of very limited
1223 .map(|t| self.shallow_resolve(t))
1227 ty::Infer(ty::IntVar(v)) => self.int_unification_table
1230 .map(|v| v.to_type(self.tcx))
1233 ty::Infer(ty::FloatVar(v)) => self.float_unification_table
1236 .map(|v| v.to_type(self.tcx))
1243 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1244 /// universe index of `TyVar(vid)`.
1245 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1246 use self::type_variable::TypeVariableValue;
1248 match self.type_variables.borrow_mut().probe(vid) {
1249 TypeVariableValue::Known { value } => Ok(value),
1250 TypeVariableValue::Unknown { universe } => Err(universe),
1254 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1255 self.inlined_shallow_resolve(typ)
1258 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1259 self.type_variables.borrow_mut().root_var(var)
1262 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1264 T: TypeFoldable<'tcx>,
1267 * Where possible, replaces type/int/float variables in
1268 * `value` with their final value. Note that region variables
1269 * are unaffected. If a type variable has not been unified, it
1270 * is left as is. This is an idempotent operation that does
1271 * not affect inference state in any way and so you can do it
1275 if !value.needs_infer() {
1276 return value.clone(); // avoid duplicated subst-folding
1278 let mut r = resolve::OpportunisticTypeResolver::new(self);
1279 value.fold_with(&mut r)
1282 /// Returns `true` if `T` contains unresolved type variables. In the
1283 /// process of visiting `T`, this will resolve (where possible)
1284 /// type variables in `T`, but it never constructs the final,
1285 /// resolved type, so it's more efficient than
1286 /// `resolve_type_vars_if_possible()`.
1287 pub fn any_unresolved_type_vars<T>(&self, value: &T) -> bool
1289 T: TypeFoldable<'tcx>,
1291 let mut r = resolve::UnresolvedTypeFinder::new(self);
1292 value.visit_with(&mut r)
1295 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1297 * Attempts to resolve all type/region variables in
1298 * `value`. Region inference must have been run already (e.g.,
1299 * by calling `resolve_regions_and_report_errors`). If some
1300 * variable was never unified, an `Err` results.
1302 * This method is idempotent, but it not typically not invoked
1303 * except during the writeback phase.
1306 resolve::fully_resolve(self, value)
1309 // [Note-Type-error-reporting]
1310 // An invariant is that anytime the expected or actual type is Error (the special
1311 // error type, meaning that an error occurred when typechecking this expression),
1312 // this is a derived error. The error cascaded from another error (that was already
1313 // reported), so it's not useful to display it to the user.
1314 // The following methods implement this logic.
1315 // They check if either the actual or expected type is Error, and don't print the error
1316 // in this case. The typechecker should only ever report type errors involving mismatched
1317 // types using one of these methods, and should not call span_err directly for such
1320 pub fn type_error_struct_with_diag<M>(
1324 actual_ty: Ty<'tcx>,
1325 ) -> DiagnosticBuilder<'tcx>
1327 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1329 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1330 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1332 // Don't report an error if actual type is `Error`.
1333 if actual_ty.references_error() {
1334 return self.tcx.sess.diagnostic().struct_dummy();
1337 mk_diag(self.ty_to_string(actual_ty))
1340 pub fn report_mismatched_types(
1342 cause: &ObligationCause<'tcx>,
1345 err: TypeError<'tcx>,
1346 ) -> DiagnosticBuilder<'tcx> {
1347 let trace = TypeTrace::types(cause, true, expected, actual);
1348 self.report_and_explain_type_error(trace, &err)
1351 pub fn replace_bound_vars_with_fresh_vars<T>(
1354 lbrct: LateBoundRegionConversionTime,
1355 value: &ty::Binder<T>
1356 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1358 T: TypeFoldable<'tcx>
1360 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1361 let fld_t = |_| self.next_ty_var(TypeVariableOrigin::MiscVariable(span));
1362 self.tcx.replace_bound_vars(value, fld_r, fld_t)
1365 /// See the [`region_constraints::verify_generic_bound`] method.
1366 pub fn verify_generic_bound(
1368 origin: SubregionOrigin<'tcx>,
1369 kind: GenericKind<'tcx>,
1370 a: ty::Region<'tcx>,
1371 bound: VerifyBound<'tcx>,
1373 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1375 self.borrow_region_constraints()
1376 .verify_generic_bound(origin, kind, a, bound);
1379 pub fn type_is_copy_modulo_regions(
1381 param_env: ty::ParamEnv<'tcx>,
1385 let ty = self.resolve_type_vars_if_possible(&ty);
1387 // Even if the type may have no inference variables, during
1388 // type-checking closure types are in local tables only.
1389 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1390 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1391 return ty.is_copy_modulo_regions(self.tcx.global_tcx(), param_env, span);
1395 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1397 // this can get called from typeck (by euv), and moves_by_default
1398 // rightly refuses to work with inference variables, but
1399 // moves_by_default has a cache, which we want to use in other
1401 traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id, span)
1404 /// Obtains the latest type of the given closure; this may be a
1405 /// closure in the current function, in which case its
1406 /// `ClosureKind` may not yet be known.
1407 pub fn closure_kind(
1409 closure_def_id: DefId,
1410 closure_substs: ty::ClosureSubsts<'tcx>,
1411 ) -> Option<ty::ClosureKind> {
1412 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx);
1413 let closure_kind_ty = self.shallow_resolve(&closure_kind_ty);
1414 closure_kind_ty.to_opt_closure_kind()
1417 /// Obtain the signature of a closure. For closures, unlike
1418 /// `tcx.fn_sig(def_id)`, this method will work during the
1419 /// type-checking of the enclosing function and return the closure
1420 /// signature in its partially inferred state.
1424 substs: ty::ClosureSubsts<'tcx>,
1425 ) -> ty::PolyFnSig<'tcx> {
1426 let closure_sig_ty = substs.closure_sig_ty(def_id, self.tcx);
1427 let closure_sig_ty = self.shallow_resolve(&closure_sig_ty);
1428 closure_sig_ty.fn_sig(self.tcx)
1431 /// Normalizes associated types in `value`, potentially returning
1432 /// new obligations that must further be processed.
1433 pub fn partially_normalize_associated_types_in<T>(
1436 body_id: ast::NodeId,
1437 param_env: ty::ParamEnv<'tcx>,
1439 ) -> InferOk<'tcx, T>
1441 T: TypeFoldable<'tcx>,
1443 debug!("partially_normalize_associated_types_in(value={:?})", value);
1444 let mut selcx = traits::SelectionContext::new(self);
1445 let cause = ObligationCause::misc(span, body_id);
1446 let traits::Normalized { value, obligations } =
1447 traits::normalize(&mut selcx, param_env, cause, value);
1449 "partially_normalize_associated_types_in: result={:?} predicates={:?}",
1452 InferOk { value, obligations }
1455 pub fn borrow_region_constraints(&self) -> RefMut<'_, RegionConstraintCollector<'tcx>> {
1456 RefMut::map(self.region_constraints.borrow_mut(), |c| {
1457 c.as_mut().expect("region constraints already solved")
1461 /// Clears the selection, evaluation, and projection caches. This is useful when
1462 /// repeatedly attempting to select an `Obligation` while changing only
1463 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1464 pub fn clear_caches(&self) {
1465 self.selection_cache.clear();
1466 self.evaluation_cache.clear();
1467 self.projection_cache.borrow_mut().clear();
1470 fn universe(&self) -> ty::UniverseIndex {
1474 /// Creates and return a fresh universe that extends all previous
1475 /// universes. Updates `self.universe` to that new universe.
1476 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1477 let u = self.universe.get().next_universe();
1478 self.universe.set(u);
1483 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1484 pub fn span(&self) -> Span {
1489 cause: &ObligationCause<'tcx>,
1490 a_is_expected: bool,
1493 ) -> TypeTrace<'tcx> {
1495 cause: cause.clone(),
1496 values: Types(ExpectedFound::new(a_is_expected, a, b)),
1500 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1502 cause: ObligationCause::dummy(),
1503 values: Types(ExpectedFound {
1504 expected: tcx.types.err,
1505 found: tcx.types.err,
1511 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1512 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1513 write!(f, "TypeTrace({:?})", self.cause)
1517 impl<'tcx> SubregionOrigin<'tcx> {
1518 pub fn span(&self) -> Span {
1520 Subtype(ref a) => a.span(),
1521 InfStackClosure(a) => a,
1522 InvokeClosure(a) => a,
1523 DerefPointer(a) => a,
1524 FreeVariable(a, _) => a,
1526 RelateObjectBound(a) => a,
1527 RelateParamBound(a, _) => a,
1528 RelateRegionParamBound(a) => a,
1529 RelateDefaultParamBound(a, _) => a,
1531 ReborrowUpvar(a, _) => a,
1532 DataBorrowed(_, a) => a,
1533 ReferenceOutlivesReferent(_, a) => a,
1534 ParameterInScope(_, a) => a,
1535 ExprTypeIsNotInScope(_, a) => a,
1536 BindingTypeIsNotValidAtDecl(a) => a,
1543 SafeDestructor(a) => a,
1544 CompareImplMethodObligation { span, .. } => span,
1548 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1550 F: FnOnce() -> Self,
1553 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1554 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1557 traits::ObligationCauseCode::CompareImplMethodObligation {
1561 } => SubregionOrigin::CompareImplMethodObligation {
1573 impl RegionVariableOrigin {
1574 pub fn span(&self) -> Span {
1576 MiscVariable(a) => a,
1577 PatternRegion(a) => a,
1578 AddrOfRegion(a) => a,
1581 EarlyBoundRegion(a, ..) => a,
1582 LateBoundRegion(a, ..) => a,
1583 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1584 UpvarRegion(_, a) => a,
1585 NLL(..) => bug!("NLL variable used with `span`"),
1590 EnumTypeFoldableImpl! {
1591 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1592 (ValuePairs::Types)(a),
1593 (ValuePairs::Regions)(a),
1594 (ValuePairs::TraitRefs)(a),
1595 (ValuePairs::PolyTraitRefs)(a),
1599 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1603 "RegionObligation(sub_region={:?}, sup_type={:?})",
1604 self.sub_region, self.sup_type