1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See the Book for more information.
13 pub use self::freshen::TypeFreshener;
14 pub use self::LateBoundRegionConversionTime::*;
15 pub use self::RegionVariableOrigin::*;
16 pub use self::SubregionOrigin::*;
17 pub use self::ValuePairs::*;
18 pub use ty::IntVarValue;
20 use arena::SyncDroplessArena;
21 use errors::DiagnosticBuilder;
22 use hir::def_id::DefId;
23 use middle::free_region::RegionRelations;
24 use middle::lang_items;
26 use rustc_data_structures::unify as ut;
27 use session::config::BorrowckMode;
28 use std::cell::{Cell, Ref, RefCell, RefMut};
29 use std::collections::BTreeMap;
32 use syntax_pos::symbol::InternedString;
33 use syntax_pos::{self, Span};
34 use traits::{self, ObligationCause, PredicateObligations, TraitEngine};
35 use ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
36 use ty::fold::TypeFoldable;
37 use ty::relate::RelateResult;
38 use ty::subst::{Kind, Substs};
39 use ty::{self, GenericParamDefKind, Ty, TyCtxt};
40 use ty::{FloatVid, IntVid, TyVid};
41 use util::nodemap::FxHashMap;
43 use self::combine::CombineFields;
44 use self::higher_ranked::HrMatchResult;
45 use self::lexical_region_resolve::LexicalRegionResolutions;
46 use self::outlives::env::OutlivesEnvironment;
47 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
48 use self::region_constraints::{RegionConstraintCollector, RegionSnapshot};
49 use self::type_variable::TypeVariableOrigin;
50 use self::unify_key::ToType;
57 pub mod error_reporting;
63 mod lexical_region_resolve;
66 pub mod region_constraints;
69 pub mod type_variable;
74 pub struct InferOk<'tcx, T> {
76 pub obligations: PredicateObligations<'tcx>,
78 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
80 pub type Bound<T> = Option<T>;
81 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
82 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
84 /// A flag that is used to suppress region errors. This is normally
85 /// false, but sometimes -- when we are doing region checks that the
86 /// NLL borrow checker will also do -- it might be set to true.
87 #[derive(Copy, Clone, Default, Debug)]
88 pub struct SuppressRegionErrors {
92 impl SuppressRegionErrors {
93 pub fn suppressed(self) -> bool {
97 /// Indicates that the MIR borrowck will repeat these region
98 /// checks, so we should ignore errors if NLL is (unconditionally)
100 pub fn when_nll_is_enabled(tcx: TyCtxt<'_, '_, '_>) -> Self {
101 match tcx.borrowck_mode() {
102 // If we're on AST or Migrate mode, report AST region errors
103 BorrowckMode::Ast | BorrowckMode::Migrate => SuppressRegionErrors {
107 // If we're on MIR or Compare mode, don't report AST region errors as they should
108 // be reported by NLL
109 BorrowckMode::Compare | BorrowckMode::Mir => SuppressRegionErrors {
116 pub struct InferCtxt<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
117 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
119 /// During type-checking/inference of a body, `in_progress_tables`
120 /// contains a reference to the tables being built up, which are
121 /// used for reading closure kinds/signatures as they are inferred,
122 /// and for error reporting logic to read arbitrary node types.
123 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
125 // Cache for projections. This cache is snapshotted along with the
128 // Public so that `traits::project` can use it.
129 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
131 // We instantiate UnificationTable with bounds<Ty> because the
132 // types that might instantiate a general type variable have an
133 // order, represented by its upper and lower bounds.
134 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
136 // Map from integral variable to the kind of integer it represents
137 int_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::IntVid>>>,
139 // Map from floating variable to the kind of float it represents
140 float_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::FloatVid>>>,
142 // Tracks the set of region variables and the constraints between
143 // them. This is initially `Some(_)` but when
144 // `resolve_regions_and_report_errors` is invoked, this gets set
145 // to `None` -- further attempts to perform unification etc may
146 // fail if new region constraints would've been added.
147 region_constraints: RefCell<Option<RegionConstraintCollector<'tcx>>>,
149 // Once region inference is done, the values for each variable.
150 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
152 /// Caches the results of trait selection. This cache is used
153 /// for things that have to do with the parameters in scope.
154 pub selection_cache: traits::SelectionCache<'tcx>,
156 /// Caches the results of trait evaluation.
157 pub evaluation_cache: traits::EvaluationCache<'tcx>,
159 // the set of predicates on which errors have been reported, to
160 // avoid reporting the same error twice.
161 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
163 // When an error occurs, we want to avoid reporting "derived"
164 // errors that are due to this original failure. Normally, we
165 // handle this with the `err_count_on_creation` count, which
166 // basically just tracks how many errors were reported when we
167 // started type-checking a fn and checks to see if any new errors
168 // have been reported since then. Not great, but it works.
170 // However, when errors originated in other passes -- notably
171 // resolve -- this heuristic breaks down. Therefore, we have this
172 // auxiliary flag that one can set whenever one creates a
173 // type-error that is due to an error in a prior pass.
175 // Don't read this flag directly, call `is_tainted_by_errors()`
176 // and `set_tainted_by_errors()`.
177 tainted_by_errors_flag: Cell<bool>,
179 // Track how many errors were reported when this infcx is created.
180 // If the number of errors increases, that's also a sign (line
181 // `tained_by_errors`) to avoid reporting certain kinds of errors.
182 err_count_on_creation: usize,
184 // This flag is true while there is an active snapshot.
185 in_snapshot: Cell<bool>,
187 // A set of constraints that regionck must validate. Each
188 // constraint has the form `T:'a`, meaning "some type `T` must
189 // outlive the lifetime 'a". These constraints derive from
190 // instantiated type parameters. So if you had a struct defined
193 // struct Foo<T:'static> { ... }
195 // then in some expression `let x = Foo { ... }` it will
196 // instantiate the type parameter `T` with a fresh type `$0`. At
197 // the same time, it will record a region obligation of
198 // `$0:'static`. This will get checked later by regionck. (We
199 // can't generally check these things right away because we have
200 // to wait until types are resolved.)
202 // These are stored in a map keyed to the id of the innermost
203 // enclosing fn body / static initializer expression. This is
204 // because the location where the obligation was incurred can be
205 // relevant with respect to which sublifetime assumptions are in
206 // place. The reason that we store under the fn-id, and not
207 // something more fine-grained, is so that it is easier for
208 // regionck to be sure that it has found *all* the region
209 // obligations (otherwise, it's easy to fail to walk to a
210 // particular node-id).
212 // Before running `resolve_regions_and_report_errors`, the creator
213 // of the inference context is expected to invoke
214 // `process_region_obligations` (defined in `self::region_obligations`)
215 // for each body-id in this map, which will process the
216 // obligations within. This is expected to be done 'late enough'
217 // that all type inference variables have been bound and so forth.
218 pub region_obligations: RefCell<Vec<(ast::NodeId, RegionObligation<'tcx>)>>,
220 /// What is the innermost universe we have created? Starts out as
221 /// `UniverseIndex::root()` but grows from there as we enter
222 /// universal quantifiers.
224 /// NB: At present, we exclude the universal quantifiers on the
225 /// item we are type-checking, and just consider those names as
226 /// part of the root universe. So this would only get incremented
227 /// when we enter into a higher-ranked (`for<..>`) type or trait
229 universe: Cell<ty::UniverseIndex>,
232 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
233 /// region that each late-bound region was replaced with.
234 pub type SkolemizationMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
236 /// See `error_reporting` module for more details
237 #[derive(Clone, Debug)]
238 pub enum ValuePairs<'tcx> {
239 Types(ExpectedFound<Ty<'tcx>>),
240 Regions(ExpectedFound<ty::Region<'tcx>>),
241 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
242 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
245 /// The trace designates the path through inference that we took to
246 /// encounter an error or subtyping constraint.
248 /// See `error_reporting` module for more details.
250 pub struct TypeTrace<'tcx> {
251 cause: ObligationCause<'tcx>,
252 values: ValuePairs<'tcx>,
255 /// The origin of a `r1 <= r2` constraint.
257 /// See `error_reporting` module for more details
258 #[derive(Clone, Debug)]
259 pub enum SubregionOrigin<'tcx> {
260 // Arose from a subtyping relation
261 Subtype(TypeTrace<'tcx>),
263 // Stack-allocated closures cannot outlive innermost loop
264 // or function so as to ensure we only require finite stack
265 InfStackClosure(Span),
267 // Invocation of closure must be within its lifetime
270 // Dereference of reference must be within its lifetime
273 // Closure bound must not outlive captured free variables
274 FreeVariable(Span, ast::NodeId),
276 // Index into slice must be within its lifetime
279 // When casting `&'a T` to an `&'b Trait` object,
280 // relating `'a` to `'b`
281 RelateObjectBound(Span),
283 // Some type parameter was instantiated with the given type,
284 // and that type must outlive some region.
285 RelateParamBound(Span, Ty<'tcx>),
287 // The given region parameter was instantiated with a region
288 // that must outlive some other region.
289 RelateRegionParamBound(Span),
291 // A bound placed on type parameters that states that must outlive
292 // the moment of their instantiation.
293 RelateDefaultParamBound(Span, Ty<'tcx>),
295 // Creating a pointer `b` to contents of another reference
298 // Creating a pointer `b` to contents of an upvar
299 ReborrowUpvar(Span, ty::UpvarId),
301 // Data with type `Ty<'tcx>` was borrowed
302 DataBorrowed(Ty<'tcx>, Span),
304 // (&'a &'b T) where a >= b
305 ReferenceOutlivesReferent(Ty<'tcx>, Span),
307 // Type or region parameters must be in scope.
308 ParameterInScope(ParameterOrigin, Span),
310 // The type T of an expression E must outlive the lifetime for E.
311 ExprTypeIsNotInScope(Ty<'tcx>, Span),
313 // A `ref b` whose region does not enclose the decl site
314 BindingTypeIsNotValidAtDecl(Span),
316 // Regions appearing in a method receiver must outlive method call
319 // Regions appearing in a function argument must outlive func call
322 // Region in return type of invoked fn must enclose call
325 // Operands must be in scope
328 // Region resulting from a `&` expr must enclose the `&` expr
331 // An auto-borrow that does not enclose the expr where it occurs
334 // Region constraint arriving from destructor safety
335 SafeDestructor(Span),
337 // Comparing the signature and requirements of an impl method against
338 // the containing trait.
339 CompareImplMethodObligation {
341 item_name: ast::Name,
342 impl_item_def_id: DefId,
343 trait_item_def_id: DefId,
347 /// Places that type/region parameters can appear.
348 #[derive(Clone, Copy, Debug)]
349 pub enum ParameterOrigin {
351 MethodCall, // foo.bar() <-- parameters on impl providing bar()
352 OverloadedOperator, // a + b when overloaded
353 OverloadedDeref, // *a when overloaded
356 /// Times when we replace late-bound regions with variables:
357 #[derive(Clone, Copy, Debug)]
358 pub enum LateBoundRegionConversionTime {
359 /// when a fn is called
362 /// when two higher-ranked types are compared
365 /// when projecting an associated type
366 AssocTypeProjection(DefId),
369 /// Reasons to create a region inference variable
371 /// See `error_reporting` module for more details
372 #[derive(Copy, Clone, Debug)]
373 pub enum RegionVariableOrigin {
374 // Region variables created for ill-categorized reasons,
375 // mostly indicates places in need of refactoring
378 // Regions created by a `&P` or `[...]` pattern
381 // Regions created by `&` operator
384 // Regions created as part of an autoref of a method receiver
387 // Regions created as part of an automatic coercion
390 // Region variables created as the values for early-bound regions
391 EarlyBoundRegion(Span, InternedString),
393 // Region variables created for bound regions
394 // in a function or method that is called
395 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
397 UpvarRegion(ty::UpvarId, Span),
399 BoundRegionInCoherence(ast::Name),
401 // This origin is used for the inference variables that we create
402 // during NLL region processing.
403 NLL(NLLRegionVariableOrigin),
406 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
407 pub enum NLLRegionVariableOrigin {
408 // During NLL region processing, we create variables for free
409 // regions that we encounter in the function signature and
410 // elsewhere. This origin indices we've got one of those.
413 BoundRegion(ty::UniverseIndex),
418 impl NLLRegionVariableOrigin {
419 pub fn is_universal(self) -> bool {
421 NLLRegionVariableOrigin::FreeRegion => true,
422 NLLRegionVariableOrigin::BoundRegion(..) => true,
423 NLLRegionVariableOrigin::Existential => false,
427 pub fn is_existential(self) -> bool {
432 #[derive(Copy, Clone, Debug)]
433 pub enum FixupError {
434 UnresolvedIntTy(IntVid),
435 UnresolvedFloatTy(FloatVid),
439 /// See the `region_obligations` field for more information.
441 pub struct RegionObligation<'tcx> {
442 pub sub_region: ty::Region<'tcx>,
443 pub sup_type: Ty<'tcx>,
444 pub origin: SubregionOrigin<'tcx>,
447 impl fmt::Display for FixupError {
448 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449 use self::FixupError::*;
452 UnresolvedIntTy(_) => write!(
454 "cannot determine the type of this integer; \
455 add a suffix to specify the type explicitly"
457 UnresolvedFloatTy(_) => write!(
459 "cannot determine the type of this number; \
460 add a suffix to specify the type explicitly"
462 UnresolvedTy(_) => write!(f, "unconstrained type"),
467 /// Helper type of a temporary returned by tcx.infer_ctxt().
468 /// Necessary because we can't write the following bound:
469 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
470 pub struct InferCtxtBuilder<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
471 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
472 arena: SyncDroplessArena,
473 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
476 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
477 pub fn infer_ctxt(self) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
480 arena: SyncDroplessArena::new(),
486 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
487 /// Used only by `rustc_typeck` during body type-checking/inference,
488 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
489 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
490 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
494 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
496 F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R,
498 let InferCtxtBuilder {
503 let in_progress_tables = fresh_tables.as_ref();
504 global_tcx.enter_local(arena, |tcx| {
508 projection_cache: RefCell::new(traits::ProjectionCache::new()),
509 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
510 int_unification_table: RefCell::new(ut::UnificationTable::new()),
511 float_unification_table: RefCell::new(ut::UnificationTable::new()),
512 region_constraints: RefCell::new(Some(RegionConstraintCollector::new())),
513 lexical_region_resolutions: RefCell::new(None),
514 selection_cache: traits::SelectionCache::new(),
515 evaluation_cache: traits::EvaluationCache::new(),
516 reported_trait_errors: RefCell::new(FxHashMap()),
517 tainted_by_errors_flag: Cell::new(false),
518 err_count_on_creation: tcx.sess.err_count(),
519 in_snapshot: Cell::new(false),
520 region_obligations: RefCell::new(vec![]),
521 universe: Cell::new(ty::UniverseIndex::ROOT),
527 impl<T> ExpectedFound<T> {
528 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
543 impl<'tcx, T> InferOk<'tcx, T> {
544 pub fn unit(self) -> InferOk<'tcx, ()> {
547 obligations: self.obligations,
551 /// Extract `value`, registering any obligations into `fulfill_cx`
552 pub fn into_value_registering_obligations(
554 infcx: &InferCtxt<'_, '_, 'tcx>,
555 fulfill_cx: &mut impl TraitEngine<'tcx>,
557 let InferOk { value, obligations } = self;
558 for obligation in obligations {
559 fulfill_cx.register_predicate_obligation(infcx, obligation);
565 impl<'tcx> InferOk<'tcx, ()> {
566 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
571 #[must_use = "once you start a snapshot, you should always consume it"]
572 pub struct CombinedSnapshot<'a, 'tcx: 'a> {
573 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
574 type_snapshot: type_variable::Snapshot<'tcx>,
575 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
576 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
577 region_constraints_snapshot: RegionSnapshot,
578 region_obligations_snapshot: usize,
579 universe: ty::UniverseIndex,
580 was_in_snapshot: bool,
581 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
584 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
585 pub fn is_in_snapshot(&self) -> bool {
586 self.in_snapshot.get()
589 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
590 t.fold_with(&mut self.freshener())
593 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
595 ty::Infer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
600 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
601 freshen::TypeFreshener::new(self)
604 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
605 use ty::error::UnconstrainedNumeric::Neither;
606 use ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
608 ty::Infer(ty::IntVar(vid)) => {
609 if self.int_unification_table
619 ty::Infer(ty::FloatVar(vid)) => {
620 if self.float_unification_table
634 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
635 let mut type_variables = self.type_variables.borrow_mut();
636 let mut int_unification_table = self.int_unification_table.borrow_mut();
637 let mut float_unification_table = self.float_unification_table.borrow_mut();
640 .unsolved_variables()
642 .map(|t| self.tcx.mk_var(t))
644 (0..int_unification_table.len())
645 .map(|i| ty::IntVid { index: i as u32 })
646 .filter(|&vid| int_unification_table.probe_value(vid).is_none())
647 .map(|v| self.tcx.mk_int_var(v)),
650 (0..float_unification_table.len())
651 .map(|i| ty::FloatVid { index: i as u32 })
652 .filter(|&vid| float_unification_table.probe_value(vid).is_none())
653 .map(|v| self.tcx.mk_float_var(v)),
660 trace: TypeTrace<'tcx>,
661 param_env: ty::ParamEnv<'tcx>,
662 ) -> CombineFields<'a, 'gcx, 'tcx> {
668 obligations: PredicateObligations::new(),
672 // Clear the "currently in a snapshot" flag, invoke the closure,
673 // then restore the flag to its original value. This flag is a
674 // debugging measure designed to detect cases where we start a
675 // snapshot, create type variables, and register obligations
676 // which may involve those type variables in the fulfillment cx,
677 // potentially leaving "dangling type variables" behind.
678 // In such cases, an assertion will fail when attempting to
679 // register obligations, within a snapshot. Very useful, much
680 // better than grovelling through megabytes of RUST_LOG output.
682 // HOWEVER, in some cases the flag is unhelpful. In particular, we
683 // sometimes create a "mini-fulfilment-cx" in which we enroll
684 // obligations. As long as this fulfillment cx is fully drained
685 // before we return, this is not a problem, as there won't be any
686 // escaping obligations in the main cx. In those cases, you can
687 // use this function.
688 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
690 F: FnOnce(&Self) -> R,
692 let flag = self.in_snapshot.get();
693 self.in_snapshot.set(false);
694 let result = func(self);
695 self.in_snapshot.set(flag);
699 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
700 debug!("start_snapshot()");
702 let in_snapshot = self.in_snapshot.get();
703 self.in_snapshot.set(true);
706 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
707 type_snapshot: self.type_variables.borrow_mut().snapshot(),
708 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
709 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
710 region_constraints_snapshot: self.borrow_region_constraints().start_snapshot(),
711 region_obligations_snapshot: self.region_obligations.borrow().len(),
712 universe: self.universe(),
713 was_in_snapshot: in_snapshot,
714 // Borrow tables "in progress" (i.e. during typeck)
715 // to ban writes from within a snapshot to them.
716 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
720 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
721 debug!("rollback_to(cause={})", cause);
722 let CombinedSnapshot {
723 projection_cache_snapshot,
727 region_constraints_snapshot,
728 region_obligations_snapshot,
734 self.in_snapshot.set(was_in_snapshot);
735 self.universe.set(universe);
737 self.projection_cache
739 .rollback_to(projection_cache_snapshot);
740 self.type_variables.borrow_mut().rollback_to(type_snapshot);
741 self.int_unification_table
743 .rollback_to(int_snapshot);
744 self.float_unification_table
746 .rollback_to(float_snapshot);
747 self.region_obligations
749 .truncate(region_obligations_snapshot);
750 self.borrow_region_constraints()
751 .rollback_to(region_constraints_snapshot);
754 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
755 debug!("commit_from()");
756 let CombinedSnapshot {
757 projection_cache_snapshot,
761 region_constraints_snapshot,
762 region_obligations_snapshot: _,
768 self.in_snapshot.set(was_in_snapshot);
770 self.projection_cache
772 .commit(&projection_cache_snapshot);
773 self.type_variables.borrow_mut().commit(type_snapshot);
774 self.int_unification_table.borrow_mut().commit(int_snapshot);
775 self.float_unification_table
777 .commit(float_snapshot);
778 self.borrow_region_constraints()
779 .commit(region_constraints_snapshot);
782 /// Execute `f` and commit the bindings
783 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
788 let snapshot = self.start_snapshot();
790 self.commit_from(snapshot);
794 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
795 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
797 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
799 debug!("commit_if_ok()");
800 let snapshot = self.start_snapshot();
801 let r = f(&snapshot);
802 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
805 self.commit_from(snapshot);
808 self.rollback_to("commit_if_ok -- error", snapshot);
814 // Execute `f` in a snapshot, and commit the bindings it creates
815 pub fn in_snapshot<T, F>(&self, f: F) -> T
817 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> T,
819 debug!("in_snapshot()");
820 let snapshot = self.start_snapshot();
821 let r = f(&snapshot);
822 self.commit_from(snapshot);
826 /// Execute `f` then unroll any bindings it creates
827 pub fn probe<R, F>(&self, f: F) -> R
829 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
832 let snapshot = self.start_snapshot();
833 let r = f(&snapshot);
834 self.rollback_to("probe", snapshot);
838 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
839 self.borrow_region_constraints().add_given(sub, sup);
842 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
844 T: at::ToTrace<'tcx>,
846 let origin = &ObligationCause::dummy();
848 self.at(origin, param_env)
850 .map(|InferOk { obligations: _, .. }| {
851 // Ignore obligations, since we are unrolling
852 // everything anyway.
857 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
859 T: at::ToTrace<'tcx>,
861 let origin = &ObligationCause::dummy();
863 self.at(origin, param_env)
865 .map(|InferOk { obligations: _, .. }| {
866 // Ignore obligations, since we are unrolling
867 // everything anyway.
874 origin: SubregionOrigin<'tcx>,
878 debug!("sub_regions({:?} <: {:?})", a, b);
879 self.borrow_region_constraints()
880 .make_subregion(origin, a, b);
883 pub fn subtype_predicate(
885 cause: &ObligationCause<'tcx>,
886 param_env: ty::ParamEnv<'tcx>,
887 predicate: &ty::PolySubtypePredicate<'tcx>,
888 ) -> Option<InferResult<'tcx, ()>> {
889 // Subtle: it's ok to skip the binder here and resolve because
890 // `shallow_resolve` just ignores anything that is not a type
891 // variable, and because type variable's can't (at present, at
892 // least) capture any of the things bound by this binder.
894 // Really, there is no *particular* reason to do this
895 // `shallow_resolve` here except as a
896 // micro-optimization. Naturally I could not
897 // resist. -nmatsakis
898 let two_unbound_type_vars = {
899 let a = self.shallow_resolve(predicate.skip_binder().a);
900 let b = self.shallow_resolve(predicate.skip_binder().b);
901 a.is_ty_var() && b.is_ty_var()
904 if two_unbound_type_vars {
905 // Two unbound type variables? Can't make progress.
909 Some(self.commit_if_ok(|snapshot| {
911 ty::SubtypePredicate {
917 ) = self.skolemize_late_bound_regions(predicate);
919 let cause_span = cause.span;
920 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
921 self.leak_check(false, cause_span, &skol_map, snapshot)?;
922 self.pop_skolemized(skol_map, snapshot);
927 pub fn region_outlives_predicate(
929 cause: &traits::ObligationCause<'tcx>,
930 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
931 ) -> UnitResult<'tcx> {
932 self.commit_if_ok(|snapshot| {
933 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
934 self.skolemize_late_bound_regions(predicate);
935 let origin = SubregionOrigin::from_obligation_cause(cause, || {
936 RelateRegionParamBound(cause.span)
938 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
939 self.leak_check(false, cause.span, &skol_map, snapshot)?;
940 Ok(self.pop_skolemized(skol_map, snapshot))
944 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
947 .new_var(self.universe(), diverging, origin)
950 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
951 self.tcx.mk_var(self.next_ty_var_id(false, origin))
954 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
955 self.tcx.mk_var(self.next_ty_var_id(true, origin))
958 pub fn next_int_var_id(&self) -> IntVid {
959 self.int_unification_table.borrow_mut().new_key(None)
962 pub fn next_float_var_id(&self) -> FloatVid {
963 self.float_unification_table.borrow_mut().new_key(None)
966 /// Create a fresh region variable with the next available index.
967 /// The variable will be created in the maximum universe created
968 /// thus far, allowing it to name any region created thus far.
969 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
970 self.next_region_var_in_universe(origin, self.universe())
973 /// Create a fresh region variable with the next available index
974 /// in the given universe; typically, you can use
975 /// `next_region_var` and just use the maximal universe.
976 pub fn next_region_var_in_universe(
978 origin: RegionVariableOrigin,
979 universe: ty::UniverseIndex,
980 ) -> ty::Region<'tcx> {
981 let region_var = self.borrow_region_constraints()
982 .new_region_var(universe, origin);
983 self.tcx.mk_region(ty::ReVar(region_var))
986 /// Number of region variables created so far.
987 pub fn num_region_vars(&self) -> usize {
988 self.borrow_region_constraints().num_region_vars()
991 /// Just a convenient wrapper of `next_region_var` for using during NLL.
992 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
993 self.next_region_var(RegionVariableOrigin::NLL(origin))
996 /// Just a convenient wrapper of `next_region_var` for using during NLL.
997 pub fn next_nll_region_var_in_universe(
999 origin: NLLRegionVariableOrigin,
1000 universe: ty::UniverseIndex,
1001 ) -> ty::Region<'tcx> {
1002 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1005 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> Kind<'tcx> {
1007 GenericParamDefKind::Lifetime => {
1008 // Create a region inference variable for the given
1009 // region parameter definition.
1010 self.next_region_var(EarlyBoundRegion(span, param.name))
1013 GenericParamDefKind::Type { .. } => {
1014 // Create a type inference variable for the given
1015 // type parameter definition. The substitutions are
1016 // for actual parameters that may be referred to by
1017 // the default of this type parameter, if it exists.
1018 // E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1019 // used in a path such as `Foo::<T, U>::new()` will
1020 // use an inference variable for `C` with `[T, U]`
1021 // as the substitutions for the default, `(T, U)`.
1022 let ty_var_id = self.type_variables.borrow_mut().new_var(
1025 TypeVariableOrigin::TypeParameterDefinition(span, param.name),
1028 self.tcx.mk_var(ty_var_id).into()
1033 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1034 /// type/region parameter to a fresh inference variable.
1035 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> &'tcx Substs<'tcx> {
1036 Substs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1039 /// True if errors have been reported since this infcx was
1040 /// created. This is sometimes used as a heuristic to skip
1041 /// reporting errors that often occur as a result of earlier
1042 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1043 /// inference variables, regionck errors).
1044 pub fn is_tainted_by_errors(&self) -> bool {
1046 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1047 tainted_by_errors_flag={})",
1048 self.tcx.sess.err_count(),
1049 self.err_count_on_creation,
1050 self.tainted_by_errors_flag.get()
1053 if self.tcx.sess.err_count() > self.err_count_on_creation {
1054 return true; // errors reported since this infcx was made
1056 self.tainted_by_errors_flag.get()
1059 /// Set the "tainted by errors" flag to true. We call this when we
1060 /// observe an error from a prior pass.
1061 pub fn set_tainted_by_errors(&self) {
1062 debug!("set_tainted_by_errors()");
1063 self.tainted_by_errors_flag.set(true)
1066 /// Process the region constraints and report any errors that
1067 /// result. After this, no more unification operations should be
1068 /// done -- or the compiler will panic -- but it is legal to use
1069 /// `resolve_type_vars_if_possible` as well as `fully_resolve`.
1070 pub fn resolve_regions_and_report_errors(
1072 region_context: DefId,
1073 region_map: ®ion::ScopeTree,
1074 outlives_env: &OutlivesEnvironment<'tcx>,
1075 suppress: SuppressRegionErrors,
1078 self.is_tainted_by_errors() || self.region_obligations.borrow().is_empty(),
1079 "region_obligations not empty: {:#?}",
1080 self.region_obligations.borrow()
1083 let region_rels = &RegionRelations::new(
1087 outlives_env.free_region_map(),
1089 let (var_infos, data) = self.region_constraints
1092 .expect("regions already resolved")
1093 .into_infos_and_data();
1094 let (lexical_region_resolutions, errors) =
1095 lexical_region_resolve::resolve(region_rels, var_infos, data);
1097 let old_value = self.lexical_region_resolutions
1098 .replace(Some(lexical_region_resolutions));
1099 assert!(old_value.is_none());
1101 if !self.is_tainted_by_errors() {
1102 // As a heuristic, just skip reporting region errors
1103 // altogether if other errors have been reported while
1104 // this infcx was in use. This is totally hokey but
1105 // otherwise we have a hard time separating legit region
1106 // errors from silly ones.
1107 self.report_region_errors(region_map, &errors, suppress);
1111 /// Obtains (and clears) the current set of region
1112 /// constraints. The inference context is still usable: further
1113 /// unifications will simply add new constraints.
1115 /// This method is not meant to be used with normal lexical region
1116 /// resolution. Rather, it is used in the NLL mode as a kind of
1117 /// interim hack: basically we run normal type-check and generate
1118 /// region constraints as normal, but then we take them and
1119 /// translate them into the form that the NLL solver
1120 /// understands. See the NLL module for mode details.
1121 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1123 self.region_obligations.borrow().is_empty(),
1124 "region_obligations not empty: {:#?}",
1125 self.region_obligations.borrow()
1128 self.borrow_region_constraints().take_and_reset_data()
1131 /// Gives temporary access to the region constraint data.
1132 #[allow(non_camel_case_types)] // bug with impl trait
1133 pub fn with_region_constraints<R>(
1135 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1137 let region_constraints = self.borrow_region_constraints();
1138 op(region_constraints.data())
1141 /// Takes ownership of the list of variable regions. This implies
1142 /// that all the region constriants have already been taken, and
1143 /// hence that `resolve_regions_and_report_errors` can never be
1144 /// called. This is used only during NLL processing to "hand off" ownership
1145 /// of the set of region vairables into the NLL region context.
1146 pub fn take_region_var_origins(&self) -> VarInfos {
1147 let (var_infos, data) = self.region_constraints
1150 .expect("regions already resolved")
1151 .into_infos_and_data();
1152 assert!(data.is_empty());
1156 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1157 self.resolve_type_vars_if_possible(&t).to_string()
1160 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1161 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1162 format!("({})", tstrs.join(", "))
1165 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1166 self.resolve_type_vars_if_possible(t).to_string()
1169 // We have this force-inlined variant of shallow_resolve() for the one
1170 // callsite that is extremely hot. All other callsites use the normal
1173 pub fn inlined_shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1175 ty::Infer(ty::TyVar(v)) => {
1176 // Not entirely obvious: if `typ` is a type variable,
1177 // it can be resolved to an int/float variable, which
1178 // can then be recursively resolved, hence the
1179 // recursion. Note though that we prevent type
1180 // variables from unifyxing to other type variables
1181 // directly (though they may be embedded
1182 // structurally), and we prevent cycles in any case,
1183 // so this recursion should always be of very limited
1189 .map(|t| self.shallow_resolve(t))
1193 ty::Infer(ty::IntVar(v)) => self.int_unification_table
1196 .map(|v| v.to_type(self.tcx))
1199 ty::Infer(ty::FloatVar(v)) => self.float_unification_table
1202 .map(|v| v.to_type(self.tcx))
1209 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1210 self.inlined_shallow_resolve(typ)
1213 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1215 T: TypeFoldable<'tcx>,
1218 * Where possible, replaces type/int/float variables in
1219 * `value` with their final value. Note that region variables
1220 * are unaffected. If a type variable has not been unified, it
1221 * is left as is. This is an idempotent operation that does
1222 * not affect inference state in any way and so you can do it
1226 if !value.needs_infer() {
1227 return value.clone(); // avoid duplicated subst-folding
1229 let mut r = resolve::OpportunisticTypeResolver::new(self);
1230 value.fold_with(&mut r)
1233 /// Returns true if `T` contains unresolved type variables. In the
1234 /// process of visiting `T`, this will resolve (where possible)
1235 /// type variables in `T`, but it never constructs the final,
1236 /// resolved type, so it's more efficient than
1237 /// `resolve_type_vars_if_possible()`.
1238 pub fn any_unresolved_type_vars<T>(&self, value: &T) -> bool
1240 T: TypeFoldable<'tcx>,
1242 let mut r = resolve::UnresolvedTypeFinder::new(self);
1243 value.visit_with(&mut r)
1246 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1248 T: TypeFoldable<'tcx>,
1250 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1251 value.fold_with(&mut r)
1254 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1256 * Attempts to resolve all type/region variables in
1257 * `value`. Region inference must have been run already (e.g.,
1258 * by calling `resolve_regions_and_report_errors`). If some
1259 * variable was never unified, an `Err` results.
1261 * This method is idempotent, but it not typically not invoked
1262 * except during the writeback phase.
1265 resolve::fully_resolve(self, value)
1268 // [Note-Type-error-reporting]
1269 // An invariant is that anytime the expected or actual type is Error (the special
1270 // error type, meaning that an error occurred when typechecking this expression),
1271 // this is a derived error. The error cascaded from another error (that was already
1272 // reported), so it's not useful to display it to the user.
1273 // The following methods implement this logic.
1274 // They check if either the actual or expected type is Error, and don't print the error
1275 // in this case. The typechecker should only ever report type errors involving mismatched
1276 // types using one of these methods, and should not call span_err directly for such
1279 pub fn type_error_struct_with_diag<M>(
1283 actual_ty: Ty<'tcx>,
1284 ) -> DiagnosticBuilder<'tcx>
1286 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1288 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1289 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1291 // Don't report an error if actual type is Error.
1292 if actual_ty.references_error() {
1293 return self.tcx.sess.diagnostic().struct_dummy();
1296 mk_diag(self.ty_to_string(actual_ty))
1299 pub fn report_mismatched_types(
1301 cause: &ObligationCause<'tcx>,
1304 err: TypeError<'tcx>,
1305 ) -> DiagnosticBuilder<'tcx> {
1306 let trace = TypeTrace::types(cause, true, expected, actual);
1307 self.report_and_explain_type_error(trace, &err)
1310 pub fn replace_late_bound_regions_with_fresh_var<T>(
1313 lbrct: LateBoundRegionConversionTime,
1314 value: &ty::Binder<T>,
1315 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1317 T: TypeFoldable<'tcx>,
1319 self.tcx.replace_late_bound_regions(value, |br| {
1320 self.next_region_var(LateBoundRegion(span, br, lbrct))
1324 /// Given a higher-ranked projection predicate like:
1326 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1328 /// and a target trait-ref like:
1330 /// <T as Fn<&'x u32>>
1332 /// find a substitution `S` for the higher-ranked regions (here,
1333 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1334 /// and then return the value (here, `&'a u32`) but with the
1335 /// substitution applied (hence, `&'x u32`).
1337 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1339 pub fn match_poly_projection_predicate(
1341 cause: ObligationCause<'tcx>,
1342 param_env: ty::ParamEnv<'tcx>,
1343 match_a: ty::PolyProjectionPredicate<'tcx>,
1344 match_b: ty::TraitRef<'tcx>,
1345 ) -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>> {
1346 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref(self.tcx), p.ty));
1347 let trace = TypeTrace {
1349 values: TraitRefs(ExpectedFound::new(
1351 match_pair.skip_binder().0,
1356 let mut combine = self.combine_fields(trace, param_env);
1357 let result = combine.higher_ranked_match(&match_pair, &match_b, true)?;
1360 obligations: combine.obligations,
1364 /// See `verify_generic_bound` method in `region_constraints`
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_moves_by_default(
1380 param_env: ty::ParamEnv<'tcx>,
1384 let ty = self.resolve_type_vars_if_possible(&ty);
1385 // Even if the type may have no inference variables, during
1386 // type-checking closure types are in local tables only.
1387 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1388 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1389 return ty.moves_by_default(self.tcx.global_tcx(), param_env, span);
1393 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1395 // this can get called from typeck (by euv), and moves_by_default
1396 // rightly refuses to work with inference variables, but
1397 // moves_by_default has a cache, which we want to use in other
1399 !traits::type_known_to_meet_bound(self, param_env, ty, copy_def_id, span)
1402 /// Obtains the latest type of the given closure; this may be a
1403 /// closure in the current function, in which case its
1404 /// `ClosureKind` may not yet be known.
1405 pub fn closure_kind(
1407 closure_def_id: DefId,
1408 closure_substs: ty::ClosureSubsts<'tcx>,
1409 ) -> Option<ty::ClosureKind> {
1410 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx);
1411 let closure_kind_ty = self.shallow_resolve(&closure_kind_ty);
1412 closure_kind_ty.to_opt_closure_kind()
1415 /// Obtain the signature of a closure. For closures, unlike
1416 /// `tcx.fn_sig(def_id)`, this method will work during the
1417 /// type-checking of the enclosing function and return the closure
1418 /// signature in its partially inferred state.
1422 substs: ty::ClosureSubsts<'tcx>,
1423 ) -> ty::PolyFnSig<'tcx> {
1424 let closure_sig_ty = substs.closure_sig_ty(def_id, self.tcx);
1425 let closure_sig_ty = self.shallow_resolve(&closure_sig_ty);
1426 closure_sig_ty.fn_sig(self.tcx)
1429 /// Normalizes associated types in `value`, potentially returning
1430 /// new obligations that must further be processed.
1431 pub fn partially_normalize_associated_types_in<T>(
1434 body_id: ast::NodeId,
1435 param_env: ty::ParamEnv<'tcx>,
1437 ) -> InferOk<'tcx, T>
1439 T: TypeFoldable<'tcx>,
1441 debug!("partially_normalize_associated_types_in(value={:?})", value);
1442 let mut selcx = traits::SelectionContext::new(self);
1443 let cause = ObligationCause::misc(span, body_id);
1444 let traits::Normalized { value, obligations } =
1445 traits::normalize(&mut selcx, param_env, cause, value);
1447 "partially_normalize_associated_types_in: result={:?} predicates={:?}",
1450 InferOk { value, obligations }
1453 pub fn borrow_region_constraints(&self) -> RefMut<'_, RegionConstraintCollector<'tcx>> {
1454 RefMut::map(self.region_constraints.borrow_mut(), |c| {
1455 c.as_mut().expect("region constraints already solved")
1459 /// Clears the selection, evaluation, and projection caches. This is useful when
1460 /// repeatedly attemping to select an Obligation while changing only
1461 /// its ParamEnv, since FulfillmentContext doesn't use 'probe'
1462 pub fn clear_caches(&self) {
1463 self.selection_cache.clear();
1464 self.evaluation_cache.clear();
1465 self.projection_cache.borrow_mut().clear();
1468 fn universe(&self) -> ty::UniverseIndex {
1472 /// Create and return a new subunivese of the current universe;
1473 /// update `self.universe` to that new subuniverse. At present,
1474 /// used only in the NLL subtyping code, which uses the new
1475 /// universe-based scheme instead of the more limited leak-check
1477 pub fn create_subuniverse(&self) -> ty::UniverseIndex {
1478 let u = self.universe.get().subuniverse();
1479 self.universe.set(u);
1484 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1485 pub fn span(&self) -> Span {
1490 cause: &ObligationCause<'tcx>,
1491 a_is_expected: bool,
1494 ) -> TypeTrace<'tcx> {
1496 cause: cause.clone(),
1497 values: Types(ExpectedFound::new(a_is_expected, a, b)),
1501 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1503 cause: ObligationCause::dummy(),
1504 values: Types(ExpectedFound {
1505 expected: tcx.types.err,
1506 found: tcx.types.err,
1512 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1514 write!(f, "TypeTrace({:?})", self.cause)
1518 impl<'tcx> SubregionOrigin<'tcx> {
1519 pub fn span(&self) -> Span {
1521 Subtype(ref a) => a.span(),
1522 InfStackClosure(a) => a,
1523 InvokeClosure(a) => a,
1524 DerefPointer(a) => a,
1525 FreeVariable(a, _) => a,
1527 RelateObjectBound(a) => a,
1528 RelateParamBound(a, _) => a,
1529 RelateRegionParamBound(a) => a,
1530 RelateDefaultParamBound(a, _) => a,
1532 ReborrowUpvar(a, _) => a,
1533 DataBorrowed(_, a) => a,
1534 ReferenceOutlivesReferent(_, a) => a,
1535 ParameterInScope(_, a) => a,
1536 ExprTypeIsNotInScope(_, a) => a,
1537 BindingTypeIsNotValidAtDecl(a) => a,
1544 SafeDestructor(a) => a,
1545 CompareImplMethodObligation { span, .. } => span,
1549 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1551 F: FnOnce() -> Self,
1554 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1555 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1558 traits::ObligationCauseCode::CompareImplMethodObligation {
1562 } => SubregionOrigin::CompareImplMethodObligation {
1574 impl RegionVariableOrigin {
1575 pub fn span(&self) -> Span {
1577 MiscVariable(a) => a,
1578 PatternRegion(a) => a,
1579 AddrOfRegion(a) => a,
1582 EarlyBoundRegion(a, ..) => a,
1583 LateBoundRegion(a, ..) => a,
1584 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1585 UpvarRegion(_, a) => a,
1586 NLL(..) => bug!("NLL variable used with `span`"),
1591 EnumTypeFoldableImpl! {
1592 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1593 (ValuePairs::Types)(a),
1594 (ValuePairs::Regions)(a),
1595 (ValuePairs::TraitRefs)(a),
1596 (ValuePairs::PolyTraitRefs)(a),
1600 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1604 "RegionObligation(sub_region={:?}, sup_type={:?})",
1605 self.sub_region, self.sup_type