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 arena::SyncDroplessArena;
11 use crate::errors::DiagnosticBuilder;
12 use crate::hir::def_id::DefId;
13 use crate::infer::canonical::{Canonical, CanonicalVarValues};
14 use crate::middle::free_region::RegionRelations;
15 use crate::middle::lang_items;
16 use crate::middle::region;
17 use rustc_data_structures::unify as ut;
18 use crate::session::config::BorrowckMode;
19 use std::cell::{Cell, Ref, RefCell, RefMut};
20 use std::collections::BTreeMap;
23 use syntax_pos::symbol::InternedString;
24 use syntax_pos::{self, Span};
25 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
26 use crate::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
27 use crate::ty::fold::TypeFoldable;
28 use crate::ty::relate::RelateResult;
29 use crate::ty::subst::{Kind, Substs};
30 use crate::ty::{self, GenericParamDefKind, Ty, TyCtxt, CtxtInterners};
31 use crate::ty::{FloatVid, IntVid, TyVid};
32 use crate::util::nodemap::FxHashMap;
34 use self::combine::CombineFields;
35 use self::lexical_region_resolve::LexicalRegionResolutions;
36 use self::outlives::env::OutlivesEnvironment;
37 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
38 use self::region_constraints::{RegionConstraintCollector, RegionSnapshot};
39 use self::type_variable::TypeVariableOrigin;
40 use self::unify_key::ToType;
46 pub mod error_reporting;
52 mod lexical_region_resolve;
57 pub mod region_constraints;
60 pub mod type_variable;
65 pub struct InferOk<'tcx, T> {
67 pub obligations: PredicateObligations<'tcx>,
69 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
71 pub type Bound<T> = Option<T>;
72 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
73 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
75 /// A flag that is used to suppress region errors. This is normally
76 /// false, but sometimes -- when we are doing region checks that the
77 /// NLL borrow checker will also do -- it might be set to true.
78 #[derive(Copy, Clone, Default, Debug)]
79 pub struct SuppressRegionErrors {
83 impl SuppressRegionErrors {
84 pub fn suppressed(self) -> bool {
88 /// Indicates that the MIR borrowck will repeat these region
89 /// checks, so we should ignore errors if NLL is (unconditionally)
91 pub fn when_nll_is_enabled(tcx: TyCtxt<'_, '_, '_>) -> Self {
92 match tcx.borrowck_mode() {
93 // If we're on AST or Migrate mode, report AST region errors
94 BorrowckMode::Ast | BorrowckMode::Migrate => SuppressRegionErrors { suppressed: false },
96 // If we're on MIR or Compare mode, don't report AST region errors as they should
98 BorrowckMode::Compare | BorrowckMode::Mir => SuppressRegionErrors { suppressed: true },
103 pub struct InferCtxt<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
104 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
106 /// During type-checking/inference of a body, `in_progress_tables`
107 /// contains a reference to the tables being built up, which are
108 /// used for reading closure kinds/signatures as they are inferred,
109 /// and for error reporting logic to read arbitrary node types.
110 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
112 // Cache for projections. This cache is snapshotted along with the
115 // Public so that `traits::project` can use it.
116 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
118 // We instantiate UnificationTable with bounds<Ty> because the
119 // types that might instantiate a general type variable have an
120 // order, represented by its upper and lower bounds.
121 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
123 // Map from integral variable to the kind of integer it represents
124 int_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::IntVid>>>,
126 // Map from floating variable to the kind of float it represents
127 float_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::FloatVid>>>,
129 // Tracks the set of region variables and the constraints between
130 // them. This is initially `Some(_)` but when
131 // `resolve_regions_and_report_errors` is invoked, this gets set
132 // to `None` -- further attempts to perform unification etc may
133 // fail if new region constraints would've been added.
134 region_constraints: RefCell<Option<RegionConstraintCollector<'tcx>>>,
136 // Once region inference is done, the values for each variable.
137 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
139 /// Caches the results of trait selection. This cache is used
140 /// for things that have to do with the parameters in scope.
141 pub selection_cache: traits::SelectionCache<'tcx>,
143 /// Caches the results of trait evaluation.
144 pub evaluation_cache: traits::EvaluationCache<'tcx>,
146 // the set of predicates on which errors have been reported, to
147 // avoid reporting the same error twice.
148 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
150 // When an error occurs, we want to avoid reporting "derived"
151 // errors that are due to this original failure. Normally, we
152 // handle this with the `err_count_on_creation` count, which
153 // basically just tracks how many errors were reported when we
154 // started type-checking a fn and checks to see if any new errors
155 // have been reported since then. Not great, but it works.
157 // However, when errors originated in other passes -- notably
158 // resolve -- this heuristic breaks down. Therefore, we have this
159 // auxiliary flag that one can set whenever one creates a
160 // type-error that is due to an error in a prior pass.
162 // Don't read this flag directly, call `is_tainted_by_errors()`
163 // and `set_tainted_by_errors()`.
164 tainted_by_errors_flag: Cell<bool>,
166 // Track how many errors were reported when this infcx is created.
167 // If the number of errors increases, that's also a sign (line
168 // `tained_by_errors`) to avoid reporting certain kinds of errors.
169 err_count_on_creation: usize,
171 // This flag is true while there is an active snapshot.
172 in_snapshot: Cell<bool>,
174 // A set of constraints that regionck must validate. Each
175 // constraint has the form `T:'a`, meaning "some type `T` must
176 // outlive the lifetime 'a". These constraints derive from
177 // instantiated type parameters. So if you had a struct defined
180 // struct Foo<T:'static> { ... }
182 // then in some expression `let x = Foo { ... }` it will
183 // instantiate the type parameter `T` with a fresh type `$0`. At
184 // the same time, it will record a region obligation of
185 // `$0:'static`. This will get checked later by regionck. (We
186 // can't generally check these things right away because we have
187 // to wait until types are resolved.)
189 // These are stored in a map keyed to the id of the innermost
190 // enclosing fn body / static initializer expression. This is
191 // because the location where the obligation was incurred can be
192 // relevant with respect to which sublifetime assumptions are in
193 // place. The reason that we store under the fn-id, and not
194 // something more fine-grained, is so that it is easier for
195 // regionck to be sure that it has found *all* the region
196 // obligations (otherwise, it's easy to fail to walk to a
197 // particular node-id).
199 // Before running `resolve_regions_and_report_errors`, the creator
200 // of the inference context is expected to invoke
201 // `process_region_obligations` (defined in `self::region_obligations`)
202 // for each body-id in this map, which will process the
203 // obligations within. This is expected to be done 'late enough'
204 // that all type inference variables have been bound and so forth.
205 pub region_obligations: RefCell<Vec<(ast::NodeId, RegionObligation<'tcx>)>>,
207 /// What is the innermost universe we have created? Starts out as
208 /// `UniverseIndex::root()` but grows from there as we enter
209 /// universal quantifiers.
211 /// N.B., at present, we exclude the universal quantifiers on the
212 /// item we are type-checking, and just consider those names as
213 /// part of the root universe. So this would only get incremented
214 /// when we enter into a higher-ranked (`for<..>`) type or trait
216 universe: Cell<ty::UniverseIndex>,
219 /// A map returned by `replace_bound_vars_with_placeholders()`
220 /// indicating the placeholder region that each late-bound region was
222 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
224 /// See the `error_reporting` module for more details.
225 #[derive(Clone, Debug, PartialEq, Eq)]
226 pub enum ValuePairs<'tcx> {
227 Types(ExpectedFound<Ty<'tcx>>),
228 Regions(ExpectedFound<ty::Region<'tcx>>),
229 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
230 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
233 /// The trace designates the path through inference that we took to
234 /// encounter an error or subtyping constraint.
236 /// See the `error_reporting` module for more details.
238 pub struct TypeTrace<'tcx> {
239 cause: ObligationCause<'tcx>,
240 values: ValuePairs<'tcx>,
243 /// The origin of a `r1 <= r2` constraint.
245 /// See `error_reporting` module for more details
246 #[derive(Clone, Debug)]
247 pub enum SubregionOrigin<'tcx> {
248 // Arose from a subtyping relation
249 Subtype(TypeTrace<'tcx>),
251 // Stack-allocated closures cannot outlive innermost loop
252 // or function so as to ensure we only require finite stack
253 InfStackClosure(Span),
255 // Invocation of closure must be within its lifetime
258 // Dereference of reference must be within its lifetime
261 // Closure bound must not outlive captured free variables
262 FreeVariable(Span, ast::NodeId),
264 // Index into slice must be within its lifetime
267 // When casting `&'a T` to an `&'b Trait` object,
268 // relating `'a` to `'b`
269 RelateObjectBound(Span),
271 // Some type parameter was instantiated with the given type,
272 // and that type must outlive some region.
273 RelateParamBound(Span, Ty<'tcx>),
275 // The given region parameter was instantiated with a region
276 // that must outlive some other region.
277 RelateRegionParamBound(Span),
279 // A bound placed on type parameters that states that must outlive
280 // the moment of their instantiation.
281 RelateDefaultParamBound(Span, Ty<'tcx>),
283 // Creating a pointer `b` to contents of another reference
286 // Creating a pointer `b` to contents of an upvar
287 ReborrowUpvar(Span, ty::UpvarId),
289 // Data with type `Ty<'tcx>` was borrowed
290 DataBorrowed(Ty<'tcx>, Span),
292 // (&'a &'b T) where a >= b
293 ReferenceOutlivesReferent(Ty<'tcx>, Span),
295 // Type or region parameters must be in scope.
296 ParameterInScope(ParameterOrigin, Span),
298 // The type T of an expression E must outlive the lifetime for E.
299 ExprTypeIsNotInScope(Ty<'tcx>, Span),
301 // A `ref b` whose region does not enclose the decl site
302 BindingTypeIsNotValidAtDecl(Span),
304 // Regions appearing in a method receiver must outlive method call
307 // Regions appearing in a function argument must outlive func call
310 // Region in return type of invoked fn must enclose call
313 // Operands must be in scope
316 // Region resulting from a `&` expr must enclose the `&` expr
319 // An auto-borrow that does not enclose the expr where it occurs
322 // Region constraint arriving from destructor safety
323 SafeDestructor(Span),
325 // Comparing the signature and requirements of an impl method against
326 // the containing trait.
327 CompareImplMethodObligation {
329 item_name: ast::Name,
330 impl_item_def_id: DefId,
331 trait_item_def_id: DefId,
335 /// Places that type/region parameters can appear.
336 #[derive(Clone, Copy, Debug)]
337 pub enum ParameterOrigin {
339 MethodCall, // foo.bar() <-- parameters on impl providing bar()
340 OverloadedOperator, // a + b when overloaded
341 OverloadedDeref, // *a when overloaded
344 /// Times when we replace late-bound regions with variables:
345 #[derive(Clone, Copy, Debug)]
346 pub enum LateBoundRegionConversionTime {
347 /// when a fn is called
350 /// when two higher-ranked types are compared
353 /// when projecting an associated type
354 AssocTypeProjection(DefId),
357 /// Reasons to create a region inference variable
359 /// See `error_reporting` module for more details
360 #[derive(Copy, Clone, Debug)]
361 pub enum RegionVariableOrigin {
362 // Region variables created for ill-categorized reasons,
363 // mostly indicates places in need of refactoring
366 // Regions created by a `&P` or `[...]` pattern
369 // Regions created by `&` operator
372 // Regions created as part of an autoref of a method receiver
375 // Regions created as part of an automatic coercion
378 // Region variables created as the values for early-bound regions
379 EarlyBoundRegion(Span, InternedString),
381 // Region variables created for bound regions
382 // in a function or method that is called
383 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
385 UpvarRegion(ty::UpvarId, Span),
387 BoundRegionInCoherence(ast::Name),
389 // This origin is used for the inference variables that we create
390 // during NLL region processing.
391 NLL(NLLRegionVariableOrigin),
394 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
395 pub enum NLLRegionVariableOrigin {
396 /// During NLL region processing, we create variables for free
397 /// regions that we encounter in the function signature and
398 /// elsewhere. This origin indices we've got one of those.
401 /// "Universal" instantiation of a higher-ranked region (e.g.,
402 /// from a `for<'a> T` binder). Meant to represent "any region".
403 Placeholder(ty::PlaceholderRegion),
408 impl NLLRegionVariableOrigin {
409 pub fn is_universal(self) -> bool {
411 NLLRegionVariableOrigin::FreeRegion => true,
412 NLLRegionVariableOrigin::Placeholder(..) => true,
413 NLLRegionVariableOrigin::Existential => false,
417 pub fn is_existential(self) -> bool {
422 #[derive(Copy, Clone, Debug)]
423 pub enum FixupError {
424 UnresolvedIntTy(IntVid),
425 UnresolvedFloatTy(FloatVid),
429 /// See the `region_obligations` field for more information.
431 pub struct RegionObligation<'tcx> {
432 pub sub_region: ty::Region<'tcx>,
433 pub sup_type: Ty<'tcx>,
434 pub origin: SubregionOrigin<'tcx>,
437 impl fmt::Display for FixupError {
438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
439 use self::FixupError::*;
442 UnresolvedIntTy(_) => write!(
444 "cannot determine the type of this integer; \
445 add a suffix to specify the type explicitly"
447 UnresolvedFloatTy(_) => write!(
449 "cannot determine the type of this number; \
450 add a suffix to specify the type explicitly"
452 UnresolvedTy(_) => write!(f, "unconstrained type"),
457 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
458 /// Necessary because we can't write the following bound:
459 /// `F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>)`.
460 pub struct InferCtxtBuilder<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
461 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
462 arena: SyncDroplessArena,
463 interners: Option<CtxtInterners<'tcx>>,
464 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
467 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
468 pub fn infer_ctxt(self) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
471 arena: SyncDroplessArena::default(),
478 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
479 /// Used only by `rustc_typeck` during body type-checking/inference,
480 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
481 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
482 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
486 /// Given a canonical value `C` as a starting point, create an
487 /// inference context that contains each of the bound values
488 /// within instantiated as a fresh variable. The `f` closure is
489 /// invoked with the new infcx, along with the instantiated value
490 /// `V` and a substitution `S`. This substitution `S` maps from
491 /// the bound values in `C` to their instantiated values in `V`
492 /// (in other words, `S(C) = V`).
493 pub fn enter_with_canonical<T, R>(
496 canonical: &Canonical<'tcx, T>,
497 f: impl for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
500 T: TypeFoldable<'tcx>,
504 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
505 f(infcx, value, subst)
509 pub fn enter<R>(&'tcx mut self, f: impl for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R) -> R {
510 let InferCtxtBuilder {
516 let in_progress_tables = fresh_tables.as_ref();
517 // Check that we haven't entered before
518 assert!(interners.is_none());
519 global_tcx.enter_local(arena, interners, |tcx| {
523 projection_cache: Default::default(),
524 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
525 int_unification_table: RefCell::new(ut::UnificationTable::new()),
526 float_unification_table: RefCell::new(ut::UnificationTable::new()),
527 region_constraints: RefCell::new(Some(RegionConstraintCollector::new())),
528 lexical_region_resolutions: RefCell::new(None),
529 selection_cache: Default::default(),
530 evaluation_cache: Default::default(),
531 reported_trait_errors: Default::default(),
532 tainted_by_errors_flag: Cell::new(false),
533 err_count_on_creation: tcx.sess.err_count(),
534 in_snapshot: Cell::new(false),
535 region_obligations: RefCell::new(vec![]),
536 universe: Cell::new(ty::UniverseIndex::ROOT),
542 impl<T> ExpectedFound<T> {
543 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
558 impl<'tcx, T> InferOk<'tcx, T> {
559 pub fn unit(self) -> InferOk<'tcx, ()> {
562 obligations: self.obligations,
566 /// Extracts `value`, registering any obligations into `fulfill_cx`.
567 pub fn into_value_registering_obligations(
569 infcx: &InferCtxt<'_, '_, 'tcx>,
570 fulfill_cx: &mut dyn TraitEngine<'tcx>,
572 let InferOk { value, obligations } = self;
573 for obligation in obligations {
574 fulfill_cx.register_predicate_obligation(infcx, obligation);
580 impl<'tcx> InferOk<'tcx, ()> {
581 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
586 #[must_use = "once you start a snapshot, you should always consume it"]
587 pub struct CombinedSnapshot<'a, 'tcx: 'a> {
588 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
589 type_snapshot: type_variable::Snapshot<'tcx>,
590 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
591 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
592 region_constraints_snapshot: RegionSnapshot,
593 region_obligations_snapshot: usize,
594 universe: ty::UniverseIndex,
595 was_in_snapshot: bool,
596 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
599 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
600 pub fn is_in_snapshot(&self) -> bool {
601 self.in_snapshot.get()
604 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
605 t.fold_with(&mut self.freshener())
608 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
610 ty::Infer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
615 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
616 freshen::TypeFreshener::new(self)
619 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
620 use crate::ty::error::UnconstrainedNumeric::Neither;
621 use crate::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
623 ty::Infer(ty::IntVar(vid)) => {
624 if self.int_unification_table
634 ty::Infer(ty::FloatVar(vid)) => {
635 if self.float_unification_table
649 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
650 let mut type_variables = self.type_variables.borrow_mut();
651 let mut int_unification_table = self.int_unification_table.borrow_mut();
652 let mut float_unification_table = self.float_unification_table.borrow_mut();
655 .unsolved_variables()
657 .map(|t| self.tcx.mk_var(t))
659 (0..int_unification_table.len())
660 .map(|i| ty::IntVid { index: i as u32 })
661 .filter(|&vid| int_unification_table.probe_value(vid).is_none())
662 .map(|v| self.tcx.mk_int_var(v)),
665 (0..float_unification_table.len())
666 .map(|i| ty::FloatVid { index: i as u32 })
667 .filter(|&vid| float_unification_table.probe_value(vid).is_none())
668 .map(|v| self.tcx.mk_float_var(v)),
675 trace: TypeTrace<'tcx>,
676 param_env: ty::ParamEnv<'tcx>,
677 ) -> CombineFields<'a, 'gcx, 'tcx> {
683 obligations: PredicateObligations::new(),
687 // Clear the "currently in a snapshot" flag, invoke the closure,
688 // then restore the flag to its original value. This flag is a
689 // debugging measure designed to detect cases where we start a
690 // snapshot, create type variables, and register obligations
691 // which may involve those type variables in the fulfillment cx,
692 // potentially leaving "dangling type variables" behind.
693 // In such cases, an assertion will fail when attempting to
694 // register obligations, within a snapshot. Very useful, much
695 // better than grovelling through megabytes of RUST_LOG output.
697 // HOWEVER, in some cases the flag is unhelpful. In particular, we
698 // sometimes create a "mini-fulfilment-cx" in which we enroll
699 // obligations. As long as this fulfillment cx is fully drained
700 // before we return, this is not a problem, as there won't be any
701 // escaping obligations in the main cx. In those cases, you can
702 // use this function.
703 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
705 F: FnOnce(&Self) -> R,
707 let flag = self.in_snapshot.get();
708 self.in_snapshot.set(false);
709 let result = func(self);
710 self.in_snapshot.set(flag);
714 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
715 debug!("start_snapshot()");
717 let in_snapshot = self.in_snapshot.get();
718 self.in_snapshot.set(true);
721 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
722 type_snapshot: self.type_variables.borrow_mut().snapshot(),
723 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
724 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
725 region_constraints_snapshot: self.borrow_region_constraints().start_snapshot(),
726 region_obligations_snapshot: self.region_obligations.borrow().len(),
727 universe: self.universe(),
728 was_in_snapshot: in_snapshot,
729 // Borrow tables "in progress" (i.e., during typeck)
730 // to ban writes from within a snapshot to them.
731 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
735 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
736 debug!("rollback_to(cause={})", cause);
737 let CombinedSnapshot {
738 projection_cache_snapshot,
742 region_constraints_snapshot,
743 region_obligations_snapshot,
749 self.in_snapshot.set(was_in_snapshot);
750 self.universe.set(universe);
752 self.projection_cache
754 .rollback_to(projection_cache_snapshot);
755 self.type_variables.borrow_mut().rollback_to(type_snapshot);
756 self.int_unification_table
758 .rollback_to(int_snapshot);
759 self.float_unification_table
761 .rollback_to(float_snapshot);
762 self.region_obligations
764 .truncate(region_obligations_snapshot);
765 self.borrow_region_constraints()
766 .rollback_to(region_constraints_snapshot);
769 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
770 debug!("commit_from()");
771 let CombinedSnapshot {
772 projection_cache_snapshot,
776 region_constraints_snapshot,
777 region_obligations_snapshot: _,
783 self.in_snapshot.set(was_in_snapshot);
785 self.projection_cache
787 .commit(projection_cache_snapshot);
788 self.type_variables.borrow_mut().commit(type_snapshot);
789 self.int_unification_table.borrow_mut().commit(int_snapshot);
790 self.float_unification_table
792 .commit(float_snapshot);
793 self.borrow_region_constraints()
794 .commit(region_constraints_snapshot);
797 /// Executes `f` and commit the bindings.
798 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
803 let snapshot = self.start_snapshot();
805 self.commit_from(snapshot);
809 /// Executes `f` and commit the bindings if closure `f` returns `Ok(_)`.
810 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
812 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
814 debug!("commit_if_ok()");
815 let snapshot = self.start_snapshot();
816 let r = f(&snapshot);
817 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
820 self.commit_from(snapshot);
823 self.rollback_to("commit_if_ok -- error", snapshot);
829 // Execute `f` in a snapshot, and commit the bindings it creates
830 pub fn in_snapshot<T, F>(&self, f: F) -> T
832 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> T,
834 debug!("in_snapshot()");
835 let snapshot = self.start_snapshot();
836 let r = f(&snapshot);
837 self.commit_from(snapshot);
841 /// Executes `f` then unroll any bindings it creates.
842 pub fn probe<R, F>(&self, f: F) -> R
844 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
847 let snapshot = self.start_snapshot();
848 let r = f(&snapshot);
849 self.rollback_to("probe", snapshot);
853 /// Scan the constraints produced since `snapshot` began and returns:
855 /// - None -- if none of them involve "region outlives" constraints
856 /// - Some(true) -- if there are `'a: 'b` constraints where `'a` or `'b` is a placehodler
857 /// - Some(false) -- if there are `'a: 'b` constraints but none involve placeholders
858 pub fn region_constraints_added_in_snapshot(
860 snapshot: &CombinedSnapshot<'a, 'tcx>,
862 self.borrow_region_constraints().region_constraints_added_in_snapshot(
863 &snapshot.region_constraints_snapshot,
867 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
868 self.borrow_region_constraints().add_given(sub, sup);
871 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
873 T: at::ToTrace<'tcx>,
875 let origin = &ObligationCause::dummy();
877 self.at(origin, param_env)
879 .map(|InferOk { obligations: _, .. }| {
880 // Ignore obligations, since we are unrolling
881 // everything anyway.
886 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
888 T: at::ToTrace<'tcx>,
890 let origin = &ObligationCause::dummy();
892 self.at(origin, param_env)
894 .map(|InferOk { obligations: _, .. }| {
895 // Ignore obligations, since we are unrolling
896 // everything anyway.
903 origin: SubregionOrigin<'tcx>,
907 debug!("sub_regions({:?} <: {:?})", a, b);
908 self.borrow_region_constraints()
909 .make_subregion(origin, a, b);
912 pub fn subtype_predicate(
914 cause: &ObligationCause<'tcx>,
915 param_env: ty::ParamEnv<'tcx>,
916 predicate: &ty::PolySubtypePredicate<'tcx>,
917 ) -> Option<InferResult<'tcx, ()>> {
918 // Subtle: it's ok to skip the binder here and resolve because
919 // `shallow_resolve` just ignores anything that is not a type
920 // variable, and because type variable's can't (at present, at
921 // least) capture any of the things bound by this binder.
923 // Really, there is no *particular* reason to do this
924 // `shallow_resolve` here except as a
925 // micro-optimization. Naturally I could not
926 // resist. -nmatsakis
927 let two_unbound_type_vars = {
928 let a = self.shallow_resolve(predicate.skip_binder().a);
929 let b = self.shallow_resolve(predicate.skip_binder().b);
930 a.is_ty_var() && b.is_ty_var()
933 if two_unbound_type_vars {
934 // Two unbound type variables? Can't make progress.
939 ty::SubtypePredicate {
945 ) = self.replace_bound_vars_with_placeholders(predicate);
948 self.at(cause, param_env)
949 .sub_exp(a_is_expected, a, b)
950 .map(|ok| ok.unit()),
954 pub fn region_outlives_predicate(
956 cause: &traits::ObligationCause<'tcx>,
957 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
959 let (ty::OutlivesPredicate(r_a, r_b), _) =
960 self.replace_bound_vars_with_placeholders(predicate);
962 SubregionOrigin::from_obligation_cause(cause, || RelateRegionParamBound(cause.span));
963 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
966 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
969 .new_var(self.universe(), diverging, origin)
972 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
973 self.tcx.mk_var(self.next_ty_var_id(false, origin))
976 pub fn next_ty_var_in_universe(
978 origin: TypeVariableOrigin,
979 universe: ty::UniverseIndex
981 let vid = self.type_variables
983 .new_var(universe, false, origin);
987 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
988 self.tcx.mk_var(self.next_ty_var_id(true, origin))
991 pub fn next_int_var_id(&self) -> IntVid {
992 self.int_unification_table.borrow_mut().new_key(None)
995 pub fn next_float_var_id(&self) -> FloatVid {
996 self.float_unification_table.borrow_mut().new_key(None)
999 /// Creates a fresh region variable with the next available index.
1000 /// The variable will be created in the maximum universe created
1001 /// thus far, allowing it to name any region created thus far.
1002 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1003 self.next_region_var_in_universe(origin, self.universe())
1006 /// Creates a fresh region variable with the next available index
1007 /// in the given universe; typically, you can use
1008 /// `next_region_var` and just use the maximal universe.
1009 pub fn next_region_var_in_universe(
1011 origin: RegionVariableOrigin,
1012 universe: ty::UniverseIndex,
1013 ) -> ty::Region<'tcx> {
1014 let region_var = self.borrow_region_constraints()
1015 .new_region_var(universe, origin);
1016 self.tcx.mk_region(ty::ReVar(region_var))
1019 /// Number of region variables created so far.
1020 pub fn num_region_vars(&self) -> usize {
1021 self.borrow_region_constraints().num_region_vars()
1024 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1025 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1026 self.next_region_var(RegionVariableOrigin::NLL(origin))
1029 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1030 pub fn next_nll_region_var_in_universe(
1032 origin: NLLRegionVariableOrigin,
1033 universe: ty::UniverseIndex,
1034 ) -> ty::Region<'tcx> {
1035 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1038 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> Kind<'tcx> {
1040 GenericParamDefKind::Lifetime => {
1041 // Create a region inference variable for the given
1042 // region parameter definition.
1043 self.next_region_var(EarlyBoundRegion(span, param.name))
1046 GenericParamDefKind::Type { .. } => {
1047 // Create a type inference variable for the given
1048 // type parameter definition. The substitutions are
1049 // for actual parameters that may be referred to by
1050 // the default of this type parameter, if it exists.
1051 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1052 // used in a path such as `Foo::<T, U>::new()` will
1053 // use an inference variable for `C` with `[T, U]`
1054 // as the substitutions for the default, `(T, U)`.
1055 let ty_var_id = self.type_variables.borrow_mut().new_var(
1058 TypeVariableOrigin::TypeParameterDefinition(span, param.name),
1061 self.tcx.mk_var(ty_var_id).into()
1066 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1067 /// type/region parameter to a fresh inference variable.
1068 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> &'tcx Substs<'tcx> {
1069 Substs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1072 /// Returns `true` if errors have been reported since this infcx was
1073 /// created. This is sometimes used as a heuristic to skip
1074 /// reporting errors that often occur as a result of earlier
1075 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1076 /// inference variables, regionck errors).
1077 pub fn is_tainted_by_errors(&self) -> bool {
1079 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1080 tainted_by_errors_flag={})",
1081 self.tcx.sess.err_count(),
1082 self.err_count_on_creation,
1083 self.tainted_by_errors_flag.get()
1086 if self.tcx.sess.err_count() > self.err_count_on_creation {
1087 return true; // errors reported since this infcx was made
1089 self.tainted_by_errors_flag.get()
1092 /// Set the "tainted by errors" flag to true. We call this when we
1093 /// observe an error from a prior pass.
1094 pub fn set_tainted_by_errors(&self) {
1095 debug!("set_tainted_by_errors()");
1096 self.tainted_by_errors_flag.set(true)
1099 /// Process the region constraints and report any errors that
1100 /// result. After this, no more unification operations should be
1101 /// done -- or the compiler will panic -- but it is legal to use
1102 /// `resolve_type_vars_if_possible` as well as `fully_resolve`.
1103 pub fn resolve_regions_and_report_errors(
1105 region_context: DefId,
1106 region_map: ®ion::ScopeTree,
1107 outlives_env: &OutlivesEnvironment<'tcx>,
1108 suppress: SuppressRegionErrors,
1111 self.is_tainted_by_errors() || self.region_obligations.borrow().is_empty(),
1112 "region_obligations not empty: {:#?}",
1113 self.region_obligations.borrow()
1116 let region_rels = &RegionRelations::new(
1120 outlives_env.free_region_map(),
1122 let (var_infos, data) = self.region_constraints
1125 .expect("regions already resolved")
1126 .into_infos_and_data();
1127 let (lexical_region_resolutions, errors) =
1128 lexical_region_resolve::resolve(region_rels, var_infos, data);
1130 let old_value = self.lexical_region_resolutions
1131 .replace(Some(lexical_region_resolutions));
1132 assert!(old_value.is_none());
1134 if !self.is_tainted_by_errors() {
1135 // As a heuristic, just skip reporting region errors
1136 // altogether if other errors have been reported while
1137 // this infcx was in use. This is totally hokey but
1138 // otherwise we have a hard time separating legit region
1139 // errors from silly ones.
1140 self.report_region_errors(region_map, &errors, suppress);
1144 /// Obtains (and clears) the current set of region
1145 /// constraints. The inference context is still usable: further
1146 /// unifications will simply add new constraints.
1148 /// This method is not meant to be used with normal lexical region
1149 /// resolution. Rather, it is used in the NLL mode as a kind of
1150 /// interim hack: basically we run normal type-check and generate
1151 /// region constraints as normal, but then we take them and
1152 /// translate them into the form that the NLL solver
1153 /// understands. See the NLL module for mode details.
1154 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1156 self.region_obligations.borrow().is_empty(),
1157 "region_obligations not empty: {:#?}",
1158 self.region_obligations.borrow()
1161 self.borrow_region_constraints().take_and_reset_data()
1164 /// Gives temporary access to the region constraint data.
1165 #[allow(non_camel_case_types)] // bug with impl trait
1166 pub fn with_region_constraints<R>(
1168 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1170 let region_constraints = self.borrow_region_constraints();
1171 op(region_constraints.data())
1174 /// Takes ownership of the list of variable regions. This implies
1175 /// that all the region constraints have already been taken, and
1176 /// hence that `resolve_regions_and_report_errors` can never be
1177 /// called. This is used only during NLL processing to "hand off" ownership
1178 /// of the set of region variables into the NLL region context.
1179 pub fn take_region_var_origins(&self) -> VarInfos {
1180 let (var_infos, data) = self.region_constraints
1183 .expect("regions already resolved")
1184 .into_infos_and_data();
1185 assert!(data.is_empty());
1189 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1190 self.resolve_type_vars_if_possible(&t).to_string()
1193 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1194 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1195 format!("({})", tstrs.join(", "))
1198 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1199 self.resolve_type_vars_if_possible(t).to_string()
1202 // We have this force-inlined variant of shallow_resolve() for the one
1203 // callsite that is extremely hot. All other callsites use the normal
1206 pub fn inlined_shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1208 ty::Infer(ty::TyVar(v)) => {
1209 // Not entirely obvious: if `typ` is a type variable,
1210 // it can be resolved to an int/float variable, which
1211 // can then be recursively resolved, hence the
1212 // recursion. Note though that we prevent type
1213 // variables from unifyxing to other type variables
1214 // directly (though they may be embedded
1215 // structurally), and we prevent cycles in any case,
1216 // so this recursion should always be of very limited
1222 .map(|t| self.shallow_resolve(t))
1226 ty::Infer(ty::IntVar(v)) => self.int_unification_table
1229 .map(|v| v.to_type(self.tcx))
1232 ty::Infer(ty::FloatVar(v)) => self.float_unification_table
1235 .map(|v| v.to_type(self.tcx))
1242 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1243 /// universe index of `TyVar(vid)`.
1244 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1245 use self::type_variable::TypeVariableValue;
1247 match self.type_variables.borrow_mut().probe(vid) {
1248 TypeVariableValue::Known { value } => Ok(value),
1249 TypeVariableValue::Unknown { universe } => Err(universe),
1253 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1254 self.inlined_shallow_resolve(typ)
1257 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1258 self.type_variables.borrow_mut().root_var(var)
1261 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1263 T: TypeFoldable<'tcx>,
1266 * Where possible, replaces type/int/float variables in
1267 * `value` with their final value. Note that region variables
1268 * are unaffected. If a type variable has not been unified, it
1269 * is left as is. This is an idempotent operation that does
1270 * not affect inference state in any way and so you can do it
1274 if !value.needs_infer() {
1275 return value.clone(); // avoid duplicated subst-folding
1277 let mut r = resolve::OpportunisticTypeResolver::new(self);
1278 value.fold_with(&mut r)
1281 /// Returns `true` if `T` contains unresolved type variables. In the
1282 /// process of visiting `T`, this will resolve (where possible)
1283 /// type variables in `T`, but it never constructs the final,
1284 /// resolved type, so it's more efficient than
1285 /// `resolve_type_vars_if_possible()`.
1286 pub fn any_unresolved_type_vars<T>(&self, value: &T) -> bool
1288 T: TypeFoldable<'tcx>,
1290 let mut r = resolve::UnresolvedTypeFinder::new(self);
1291 value.visit_with(&mut r)
1294 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1296 * Attempts to resolve all type/region variables in
1297 * `value`. Region inference must have been run already (e.g.,
1298 * by calling `resolve_regions_and_report_errors`). If some
1299 * variable was never unified, an `Err` results.
1301 * This method is idempotent, but it not typically not invoked
1302 * except during the writeback phase.
1305 resolve::fully_resolve(self, value)
1308 // [Note-Type-error-reporting]
1309 // An invariant is that anytime the expected or actual type is Error (the special
1310 // error type, meaning that an error occurred when typechecking this expression),
1311 // this is a derived error. The error cascaded from another error (that was already
1312 // reported), so it's not useful to display it to the user.
1313 // The following methods implement this logic.
1314 // They check if either the actual or expected type is Error, and don't print the error
1315 // in this case. The typechecker should only ever report type errors involving mismatched
1316 // types using one of these methods, and should not call span_err directly for such
1319 pub fn type_error_struct_with_diag<M>(
1323 actual_ty: Ty<'tcx>,
1324 ) -> DiagnosticBuilder<'tcx>
1326 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1328 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1329 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1331 // Don't report an error if actual type is `Error`.
1332 if actual_ty.references_error() {
1333 return self.tcx.sess.diagnostic().struct_dummy();
1336 mk_diag(self.ty_to_string(actual_ty))
1339 pub fn report_mismatched_types(
1341 cause: &ObligationCause<'tcx>,
1344 err: TypeError<'tcx>,
1345 ) -> DiagnosticBuilder<'tcx> {
1346 let trace = TypeTrace::types(cause, true, expected, actual);
1347 self.report_and_explain_type_error(trace, &err)
1350 pub fn replace_bound_vars_with_fresh_vars<T>(
1353 lbrct: LateBoundRegionConversionTime,
1354 value: &ty::Binder<T>
1355 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1357 T: TypeFoldable<'tcx>
1359 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1360 let fld_t = |_| self.next_ty_var(TypeVariableOrigin::MiscVariable(span));
1361 self.tcx.replace_bound_vars(value, fld_r, fld_t)
1364 /// See the [`region_constraints::verify_generic_bound`] method.
1365 pub fn verify_generic_bound(
1367 origin: SubregionOrigin<'tcx>,
1368 kind: GenericKind<'tcx>,
1369 a: ty::Region<'tcx>,
1370 bound: VerifyBound<'tcx>,
1372 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1374 self.borrow_region_constraints()
1375 .verify_generic_bound(origin, kind, a, bound);
1378 pub fn type_is_copy_modulo_regions(
1380 param_env: ty::ParamEnv<'tcx>,
1384 let ty = self.resolve_type_vars_if_possible(&ty);
1386 // Even if the type may have no inference variables, during
1387 // type-checking closure types are in local tables only.
1388 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1389 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1390 return ty.is_copy_modulo_regions(self.tcx.global_tcx(), param_env, span);
1394 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1396 // this can get called from typeck (by euv), and moves_by_default
1397 // rightly refuses to work with inference variables, but
1398 // moves_by_default has a cache, which we want to use in other
1400 traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id, span)
1403 /// Obtains the latest type of the given closure; this may be a
1404 /// closure in the current function, in which case its
1405 /// `ClosureKind` may not yet be known.
1406 pub fn closure_kind(
1408 closure_def_id: DefId,
1409 closure_substs: ty::ClosureSubsts<'tcx>,
1410 ) -> Option<ty::ClosureKind> {
1411 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx);
1412 let closure_kind_ty = self.shallow_resolve(&closure_kind_ty);
1413 closure_kind_ty.to_opt_closure_kind()
1416 /// Obtain the signature of a closure. For closures, unlike
1417 /// `tcx.fn_sig(def_id)`, this method will work during the
1418 /// type-checking of the enclosing function and return the closure
1419 /// signature in its partially inferred state.
1423 substs: ty::ClosureSubsts<'tcx>,
1424 ) -> ty::PolyFnSig<'tcx> {
1425 let closure_sig_ty = substs.closure_sig_ty(def_id, self.tcx);
1426 let closure_sig_ty = self.shallow_resolve(&closure_sig_ty);
1427 closure_sig_ty.fn_sig(self.tcx)
1430 /// Normalizes associated types in `value`, potentially returning
1431 /// new obligations that must further be processed.
1432 pub fn partially_normalize_associated_types_in<T>(
1435 body_id: ast::NodeId,
1436 param_env: ty::ParamEnv<'tcx>,
1438 ) -> InferOk<'tcx, T>
1440 T: TypeFoldable<'tcx>,
1442 debug!("partially_normalize_associated_types_in(value={:?})", value);
1443 let mut selcx = traits::SelectionContext::new(self);
1444 let cause = ObligationCause::misc(span, body_id);
1445 let traits::Normalized { value, obligations } =
1446 traits::normalize(&mut selcx, param_env, cause, value);
1448 "partially_normalize_associated_types_in: result={:?} predicates={:?}",
1451 InferOk { value, obligations }
1454 pub fn borrow_region_constraints(&self) -> RefMut<'_, RegionConstraintCollector<'tcx>> {
1455 RefMut::map(self.region_constraints.borrow_mut(), |c| {
1456 c.as_mut().expect("region constraints already solved")
1460 /// Clears the selection, evaluation, and projection caches. This is useful when
1461 /// repeatedly attempting to select an `Obligation` while changing only
1462 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1463 pub fn clear_caches(&self) {
1464 self.selection_cache.clear();
1465 self.evaluation_cache.clear();
1466 self.projection_cache.borrow_mut().clear();
1469 fn universe(&self) -> ty::UniverseIndex {
1473 /// Creates and return a fresh universe that extends all previous
1474 /// universes. Updates `self.universe` to that new universe.
1475 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1476 let u = self.universe.get().next_universe();
1477 self.universe.set(u);
1482 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1483 pub fn span(&self) -> Span {
1488 cause: &ObligationCause<'tcx>,
1489 a_is_expected: bool,
1492 ) -> TypeTrace<'tcx> {
1494 cause: cause.clone(),
1495 values: Types(ExpectedFound::new(a_is_expected, a, b)),
1499 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1501 cause: ObligationCause::dummy(),
1502 values: Types(ExpectedFound {
1503 expected: tcx.types.err,
1504 found: tcx.types.err,
1510 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1512 write!(f, "TypeTrace({:?})", self.cause)
1516 impl<'tcx> SubregionOrigin<'tcx> {
1517 pub fn span(&self) -> Span {
1519 Subtype(ref a) => a.span(),
1520 InfStackClosure(a) => a,
1521 InvokeClosure(a) => a,
1522 DerefPointer(a) => a,
1523 FreeVariable(a, _) => a,
1525 RelateObjectBound(a) => a,
1526 RelateParamBound(a, _) => a,
1527 RelateRegionParamBound(a) => a,
1528 RelateDefaultParamBound(a, _) => a,
1530 ReborrowUpvar(a, _) => a,
1531 DataBorrowed(_, a) => a,
1532 ReferenceOutlivesReferent(_, a) => a,
1533 ParameterInScope(_, a) => a,
1534 ExprTypeIsNotInScope(_, a) => a,
1535 BindingTypeIsNotValidAtDecl(a) => a,
1542 SafeDestructor(a) => a,
1543 CompareImplMethodObligation { span, .. } => span,
1547 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1549 F: FnOnce() -> Self,
1552 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1553 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1556 traits::ObligationCauseCode::CompareImplMethodObligation {
1560 } => SubregionOrigin::CompareImplMethodObligation {
1572 impl RegionVariableOrigin {
1573 pub fn span(&self) -> Span {
1575 MiscVariable(a) => a,
1576 PatternRegion(a) => a,
1577 AddrOfRegion(a) => a,
1580 EarlyBoundRegion(a, ..) => a,
1581 LateBoundRegion(a, ..) => a,
1582 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1583 UpvarRegion(_, a) => a,
1584 NLL(..) => bug!("NLL variable used with `span`"),
1589 EnumTypeFoldableImpl! {
1590 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1591 (ValuePairs::Types)(a),
1592 (ValuePairs::Regions)(a),
1593 (ValuePairs::TraitRefs)(a),
1594 (ValuePairs::PolyTraitRefs)(a),
1598 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1599 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1602 "RegionObligation(sub_region={:?}, sup_type={:?})",
1603 self.sub_region, self.sup_type