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 infer::canonical::{Canonical, CanonicalVarValues};
24 use middle::free_region::RegionRelations;
25 use middle::lang_items;
27 use rustc_data_structures::unify as ut;
28 use session::config::BorrowckMode;
29 use std::cell::{Cell, Ref, RefCell, RefMut};
30 use std::collections::BTreeMap;
33 use syntax_pos::symbol::InternedString;
34 use syntax_pos::{self, Span};
35 use traits::{self, ObligationCause, PredicateObligations, TraitEngine};
36 use ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
37 use ty::fold::TypeFoldable;
38 use ty::relate::RelateResult;
39 use ty::subst::{Kind, Substs};
40 use ty::{self, GenericParamDefKind, Ty, TyCtxt};
41 use ty::{FloatVid, IntVid, TyVid};
42 use util::nodemap::FxHashMap;
44 use self::combine::CombineFields;
45 use self::higher_ranked::HrMatchResult;
46 use self::lexical_region_resolve::LexicalRegionResolutions;
47 use self::outlives::env::OutlivesEnvironment;
48 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
49 use self::region_constraints::{RegionConstraintCollector, RegionSnapshot};
50 use self::type_variable::TypeVariableOrigin;
51 use self::unify_key::ToType;
57 pub mod error_reporting;
63 mod lexical_region_resolve;
67 pub mod region_constraints;
70 pub mod type_variable;
75 pub struct InferOk<'tcx, T> {
77 pub obligations: PredicateObligations<'tcx>,
79 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
81 pub type Bound<T> = Option<T>;
82 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
83 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
85 /// A flag that is used to suppress region errors. This is normally
86 /// false, but sometimes -- when we are doing region checks that the
87 /// NLL borrow checker will also do -- it might be set to true.
88 #[derive(Copy, Clone, Default, Debug)]
89 pub struct SuppressRegionErrors {
93 impl SuppressRegionErrors {
94 pub fn suppressed(self) -> bool {
98 /// Indicates that the MIR borrowck will repeat these region
99 /// checks, so we should ignore errors if NLL is (unconditionally)
101 pub fn when_nll_is_enabled(tcx: TyCtxt<'_, '_, '_>) -> Self {
102 match tcx.borrowck_mode() {
103 // If we're on AST or Migrate mode, report AST region errors
104 BorrowckMode::Ast | BorrowckMode::Migrate => SuppressRegionErrors { suppressed: false },
106 // If we're on MIR or Compare mode, don't report AST region errors as they should
107 // be reported by NLL
108 BorrowckMode::Compare | BorrowckMode::Mir => SuppressRegionErrors { suppressed: true },
113 pub struct InferCtxt<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
114 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
116 /// During type-checking/inference of a body, `in_progress_tables`
117 /// contains a reference to the tables being built up, which are
118 /// used for reading closure kinds/signatures as they are inferred,
119 /// and for error reporting logic to read arbitrary node types.
120 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
122 // Cache for projections. This cache is snapshotted along with the
125 // Public so that `traits::project` can use it.
126 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
128 // We instantiate UnificationTable with bounds<Ty> because the
129 // types that might instantiate a general type variable have an
130 // order, represented by its upper and lower bounds.
131 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
133 // Map from integral variable to the kind of integer it represents
134 int_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::IntVid>>>,
136 // Map from floating variable to the kind of float it represents
137 float_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::FloatVid>>>,
139 // Tracks the set of region variables and the constraints between
140 // them. This is initially `Some(_)` but when
141 // `resolve_regions_and_report_errors` is invoked, this gets set
142 // to `None` -- further attempts to perform unification etc may
143 // fail if new region constraints would've been added.
144 region_constraints: RefCell<Option<RegionConstraintCollector<'tcx>>>,
146 // Once region inference is done, the values for each variable.
147 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
149 /// Caches the results of trait selection. This cache is used
150 /// for things that have to do with the parameters in scope.
151 pub selection_cache: traits::SelectionCache<'tcx>,
153 /// Caches the results of trait evaluation.
154 pub evaluation_cache: traits::EvaluationCache<'tcx>,
156 // the set of predicates on which errors have been reported, to
157 // avoid reporting the same error twice.
158 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
160 // When an error occurs, we want to avoid reporting "derived"
161 // errors that are due to this original failure. Normally, we
162 // handle this with the `err_count_on_creation` count, which
163 // basically just tracks how many errors were reported when we
164 // started type-checking a fn and checks to see if any new errors
165 // have been reported since then. Not great, but it works.
167 // However, when errors originated in other passes -- notably
168 // resolve -- this heuristic breaks down. Therefore, we have this
169 // auxiliary flag that one can set whenever one creates a
170 // type-error that is due to an error in a prior pass.
172 // Don't read this flag directly, call `is_tainted_by_errors()`
173 // and `set_tainted_by_errors()`.
174 tainted_by_errors_flag: Cell<bool>,
176 // Track how many errors were reported when this infcx is created.
177 // If the number of errors increases, that's also a sign (line
178 // `tained_by_errors`) to avoid reporting certain kinds of errors.
179 err_count_on_creation: usize,
181 // This flag is true while there is an active snapshot.
182 in_snapshot: Cell<bool>,
184 // A set of constraints that regionck must validate. Each
185 // constraint has the form `T:'a`, meaning "some type `T` must
186 // outlive the lifetime 'a". These constraints derive from
187 // instantiated type parameters. So if you had a struct defined
190 // struct Foo<T:'static> { ... }
192 // then in some expression `let x = Foo { ... }` it will
193 // instantiate the type parameter `T` with a fresh type `$0`. At
194 // the same time, it will record a region obligation of
195 // `$0:'static`. This will get checked later by regionck. (We
196 // can't generally check these things right away because we have
197 // to wait until types are resolved.)
199 // These are stored in a map keyed to the id of the innermost
200 // enclosing fn body / static initializer expression. This is
201 // because the location where the obligation was incurred can be
202 // relevant with respect to which sublifetime assumptions are in
203 // place. The reason that we store under the fn-id, and not
204 // something more fine-grained, is so that it is easier for
205 // regionck to be sure that it has found *all* the region
206 // obligations (otherwise, it's easy to fail to walk to a
207 // particular node-id).
209 // Before running `resolve_regions_and_report_errors`, the creator
210 // of the inference context is expected to invoke
211 // `process_region_obligations` (defined in `self::region_obligations`)
212 // for each body-id in this map, which will process the
213 // obligations within. This is expected to be done 'late enough'
214 // that all type inference variables have been bound and so forth.
215 pub region_obligations: RefCell<Vec<(ast::NodeId, RegionObligation<'tcx>)>>,
217 /// What is the innermost universe we have created? Starts out as
218 /// `UniverseIndex::root()` but grows from there as we enter
219 /// universal quantifiers.
221 /// NB: At present, we exclude the universal quantifiers on the
222 /// item we are type-checking, and just consider those names as
223 /// part of the root universe. So this would only get incremented
224 /// when we enter into a higher-ranked (`for<..>`) type or trait
226 universe: Cell<ty::UniverseIndex>,
229 /// A map returned by `replace_late_bound_regions_with_placeholders()`
230 /// indicating the placeholder region that each late-bound region was
232 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
234 /// See `error_reporting` module for more details
235 #[derive(Clone, Debug)]
236 pub enum ValuePairs<'tcx> {
237 Types(ExpectedFound<Ty<'tcx>>),
238 Regions(ExpectedFound<ty::Region<'tcx>>),
239 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
240 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
243 /// The trace designates the path through inference that we took to
244 /// encounter an error or subtyping constraint.
246 /// See `error_reporting` module for more details.
248 pub struct TypeTrace<'tcx> {
249 cause: ObligationCause<'tcx>,
250 values: ValuePairs<'tcx>,
253 /// The origin of a `r1 <= r2` constraint.
255 /// See `error_reporting` module for more details
256 #[derive(Clone, Debug)]
257 pub enum SubregionOrigin<'tcx> {
258 // Arose from a subtyping relation
259 Subtype(TypeTrace<'tcx>),
261 // Stack-allocated closures cannot outlive innermost loop
262 // or function so as to ensure we only require finite stack
263 InfStackClosure(Span),
265 // Invocation of closure must be within its lifetime
268 // Dereference of reference must be within its lifetime
271 // Closure bound must not outlive captured free variables
272 FreeVariable(Span, ast::NodeId),
274 // Index into slice must be within its lifetime
277 // When casting `&'a T` to an `&'b Trait` object,
278 // relating `'a` to `'b`
279 RelateObjectBound(Span),
281 // Some type parameter was instantiated with the given type,
282 // and that type must outlive some region.
283 RelateParamBound(Span, Ty<'tcx>),
285 // The given region parameter was instantiated with a region
286 // that must outlive some other region.
287 RelateRegionParamBound(Span),
289 // A bound placed on type parameters that states that must outlive
290 // the moment of their instantiation.
291 RelateDefaultParamBound(Span, Ty<'tcx>),
293 // Creating a pointer `b` to contents of another reference
296 // Creating a pointer `b` to contents of an upvar
297 ReborrowUpvar(Span, ty::UpvarId),
299 // Data with type `Ty<'tcx>` was borrowed
300 DataBorrowed(Ty<'tcx>, Span),
302 // (&'a &'b T) where a >= b
303 ReferenceOutlivesReferent(Ty<'tcx>, Span),
305 // Type or region parameters must be in scope.
306 ParameterInScope(ParameterOrigin, Span),
308 // The type T of an expression E must outlive the lifetime for E.
309 ExprTypeIsNotInScope(Ty<'tcx>, Span),
311 // A `ref b` whose region does not enclose the decl site
312 BindingTypeIsNotValidAtDecl(Span),
314 // Regions appearing in a method receiver must outlive method call
317 // Regions appearing in a function argument must outlive func call
320 // Region in return type of invoked fn must enclose call
323 // Operands must be in scope
326 // Region resulting from a `&` expr must enclose the `&` expr
329 // An auto-borrow that does not enclose the expr where it occurs
332 // Region constraint arriving from destructor safety
333 SafeDestructor(Span),
335 // Comparing the signature and requirements of an impl method against
336 // the containing trait.
337 CompareImplMethodObligation {
339 item_name: ast::Name,
340 impl_item_def_id: DefId,
341 trait_item_def_id: DefId,
345 /// Places that type/region parameters can appear.
346 #[derive(Clone, Copy, Debug)]
347 pub enum ParameterOrigin {
349 MethodCall, // foo.bar() <-- parameters on impl providing bar()
350 OverloadedOperator, // a + b when overloaded
351 OverloadedDeref, // *a when overloaded
354 /// Times when we replace late-bound regions with variables:
355 #[derive(Clone, Copy, Debug)]
356 pub enum LateBoundRegionConversionTime {
357 /// when a fn is called
360 /// when two higher-ranked types are compared
363 /// when projecting an associated type
364 AssocTypeProjection(DefId),
367 /// Reasons to create a region inference variable
369 /// See `error_reporting` module for more details
370 #[derive(Copy, Clone, Debug)]
371 pub enum RegionVariableOrigin {
372 // Region variables created for ill-categorized reasons,
373 // mostly indicates places in need of refactoring
376 // Regions created by a `&P` or `[...]` pattern
379 // Regions created by `&` operator
382 // Regions created as part of an autoref of a method receiver
385 // Regions created as part of an automatic coercion
388 // Region variables created as the values for early-bound regions
389 EarlyBoundRegion(Span, InternedString),
391 // Region variables created for bound regions
392 // in a function or method that is called
393 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
395 UpvarRegion(ty::UpvarId, Span),
397 BoundRegionInCoherence(ast::Name),
399 // This origin is used for the inference variables that we create
400 // during NLL region processing.
401 NLL(NLLRegionVariableOrigin),
404 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
405 pub enum NLLRegionVariableOrigin {
406 /// During NLL region processing, we create variables for free
407 /// regions that we encounter in the function signature and
408 /// elsewhere. This origin indices we've got one of those.
411 /// "Universal" instantiation of a higher-ranked region (e.g.,
412 /// from a `for<'a> T` binder). Meant to represent "any region".
413 Placeholder(ty::Placeholder),
418 impl NLLRegionVariableOrigin {
419 pub fn is_universal(self) -> bool {
421 NLLRegionVariableOrigin::FreeRegion => true,
422 NLLRegionVariableOrigin::Placeholder(..) => 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 /// Given a canonical value `C` as a starting point, create an
495 /// inference context that contains each of the bound values
496 /// within instantiated as a fresh variable. The `f` closure is
497 /// invoked with the new infcx, along with the instantiated value
498 /// `V` and a substitution `S`. This substitution `S` maps from
499 /// the bound values in `C` to their instantiated values in `V`
500 /// (in other words, `S(C) = V`).
501 pub fn enter_with_canonical<T, R>(
504 canonical: &Canonical<'tcx, T>,
505 f: impl for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
508 T: TypeFoldable<'tcx>,
512 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
513 f(infcx, value, subst)
517 pub fn enter<R>(&'tcx mut self, f: impl for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R) -> R {
518 let InferCtxtBuilder {
523 let in_progress_tables = fresh_tables.as_ref();
524 global_tcx.enter_local(arena, |tcx| {
528 projection_cache: RefCell::new(traits::ProjectionCache::new()),
529 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
530 int_unification_table: RefCell::new(ut::UnificationTable::new()),
531 float_unification_table: RefCell::new(ut::UnificationTable::new()),
532 region_constraints: RefCell::new(Some(RegionConstraintCollector::new())),
533 lexical_region_resolutions: RefCell::new(None),
534 selection_cache: traits::SelectionCache::new(),
535 evaluation_cache: traits::EvaluationCache::new(),
536 reported_trait_errors: RefCell::new(FxHashMap()),
537 tainted_by_errors_flag: Cell::new(false),
538 err_count_on_creation: tcx.sess.err_count(),
539 in_snapshot: Cell::new(false),
540 region_obligations: RefCell::new(vec![]),
541 universe: Cell::new(ty::UniverseIndex::ROOT),
547 impl<T> ExpectedFound<T> {
548 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
563 impl<'tcx, T> InferOk<'tcx, T> {
564 pub fn unit(self) -> InferOk<'tcx, ()> {
567 obligations: self.obligations,
571 /// Extract `value`, registering any obligations into `fulfill_cx`
572 pub fn into_value_registering_obligations(
574 infcx: &InferCtxt<'_, '_, 'tcx>,
575 fulfill_cx: &mut impl TraitEngine<'tcx>,
577 let InferOk { value, obligations } = self;
578 for obligation in obligations {
579 fulfill_cx.register_predicate_obligation(infcx, obligation);
585 impl<'tcx> InferOk<'tcx, ()> {
586 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
591 #[must_use = "once you start a snapshot, you should always consume it"]
592 pub struct CombinedSnapshot<'a, 'tcx: 'a> {
593 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
594 type_snapshot: type_variable::Snapshot<'tcx>,
595 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
596 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
597 region_constraints_snapshot: RegionSnapshot,
598 region_obligations_snapshot: usize,
599 universe: ty::UniverseIndex,
600 was_in_snapshot: bool,
601 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
604 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
605 pub fn is_in_snapshot(&self) -> bool {
606 self.in_snapshot.get()
609 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
610 t.fold_with(&mut self.freshener())
613 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
615 ty::Infer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
620 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
621 freshen::TypeFreshener::new(self)
624 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
625 use ty::error::UnconstrainedNumeric::Neither;
626 use ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
628 ty::Infer(ty::IntVar(vid)) => {
629 if self.int_unification_table
639 ty::Infer(ty::FloatVar(vid)) => {
640 if self.float_unification_table
654 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
655 let mut type_variables = self.type_variables.borrow_mut();
656 let mut int_unification_table = self.int_unification_table.borrow_mut();
657 let mut float_unification_table = self.float_unification_table.borrow_mut();
660 .unsolved_variables()
662 .map(|t| self.tcx.mk_var(t))
664 (0..int_unification_table.len())
665 .map(|i| ty::IntVid { index: i as u32 })
666 .filter(|&vid| int_unification_table.probe_value(vid).is_none())
667 .map(|v| self.tcx.mk_int_var(v)),
670 (0..float_unification_table.len())
671 .map(|i| ty::FloatVid { index: i as u32 })
672 .filter(|&vid| float_unification_table.probe_value(vid).is_none())
673 .map(|v| self.tcx.mk_float_var(v)),
680 trace: TypeTrace<'tcx>,
681 param_env: ty::ParamEnv<'tcx>,
682 ) -> CombineFields<'a, 'gcx, 'tcx> {
688 obligations: PredicateObligations::new(),
692 // Clear the "currently in a snapshot" flag, invoke the closure,
693 // then restore the flag to its original value. This flag is a
694 // debugging measure designed to detect cases where we start a
695 // snapshot, create type variables, and register obligations
696 // which may involve those type variables in the fulfillment cx,
697 // potentially leaving "dangling type variables" behind.
698 // In such cases, an assertion will fail when attempting to
699 // register obligations, within a snapshot. Very useful, much
700 // better than grovelling through megabytes of RUST_LOG output.
702 // HOWEVER, in some cases the flag is unhelpful. In particular, we
703 // sometimes create a "mini-fulfilment-cx" in which we enroll
704 // obligations. As long as this fulfillment cx is fully drained
705 // before we return, this is not a problem, as there won't be any
706 // escaping obligations in the main cx. In those cases, you can
707 // use this function.
708 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
710 F: FnOnce(&Self) -> R,
712 let flag = self.in_snapshot.get();
713 self.in_snapshot.set(false);
714 let result = func(self);
715 self.in_snapshot.set(flag);
719 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
720 debug!("start_snapshot()");
722 let in_snapshot = self.in_snapshot.get();
723 self.in_snapshot.set(true);
726 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
727 type_snapshot: self.type_variables.borrow_mut().snapshot(),
728 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
729 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
730 region_constraints_snapshot: self.borrow_region_constraints().start_snapshot(),
731 region_obligations_snapshot: self.region_obligations.borrow().len(),
732 universe: self.universe(),
733 was_in_snapshot: in_snapshot,
734 // Borrow tables "in progress" (i.e. during typeck)
735 // to ban writes from within a snapshot to them.
736 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
740 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
741 debug!("rollback_to(cause={})", cause);
742 let CombinedSnapshot {
743 projection_cache_snapshot,
747 region_constraints_snapshot,
748 region_obligations_snapshot,
754 self.in_snapshot.set(was_in_snapshot);
755 self.universe.set(universe);
757 self.projection_cache
759 .rollback_to(projection_cache_snapshot);
760 self.type_variables.borrow_mut().rollback_to(type_snapshot);
761 self.int_unification_table
763 .rollback_to(int_snapshot);
764 self.float_unification_table
766 .rollback_to(float_snapshot);
767 self.region_obligations
769 .truncate(region_obligations_snapshot);
770 self.borrow_region_constraints()
771 .rollback_to(region_constraints_snapshot);
774 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
775 debug!("commit_from()");
776 let CombinedSnapshot {
777 projection_cache_snapshot,
781 region_constraints_snapshot,
782 region_obligations_snapshot: _,
788 self.in_snapshot.set(was_in_snapshot);
790 self.projection_cache
792 .commit(&projection_cache_snapshot);
793 self.type_variables.borrow_mut().commit(type_snapshot);
794 self.int_unification_table.borrow_mut().commit(int_snapshot);
795 self.float_unification_table
797 .commit(float_snapshot);
798 self.borrow_region_constraints()
799 .commit(region_constraints_snapshot);
802 /// Execute `f` and commit the bindings
803 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
808 let snapshot = self.start_snapshot();
810 self.commit_from(snapshot);
814 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
815 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
817 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
819 debug!("commit_if_ok()");
820 let snapshot = self.start_snapshot();
821 let r = f(&snapshot);
822 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
825 self.commit_from(snapshot);
828 self.rollback_to("commit_if_ok -- error", snapshot);
834 // Execute `f` in a snapshot, and commit the bindings it creates
835 pub fn in_snapshot<T, F>(&self, f: F) -> T
837 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> T,
839 debug!("in_snapshot()");
840 let snapshot = self.start_snapshot();
841 let r = f(&snapshot);
842 self.commit_from(snapshot);
846 /// Execute `f` then unroll any bindings it creates
847 pub fn probe<R, F>(&self, f: F) -> R
849 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
852 let snapshot = self.start_snapshot();
853 let r = f(&snapshot);
854 self.rollback_to("probe", snapshot);
858 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
859 self.borrow_region_constraints().add_given(sub, sup);
862 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
864 T: at::ToTrace<'tcx>,
866 let origin = &ObligationCause::dummy();
868 self.at(origin, param_env)
870 .map(|InferOk { obligations: _, .. }| {
871 // Ignore obligations, since we are unrolling
872 // everything anyway.
877 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
879 T: at::ToTrace<'tcx>,
881 let origin = &ObligationCause::dummy();
883 self.at(origin, param_env)
885 .map(|InferOk { obligations: _, .. }| {
886 // Ignore obligations, since we are unrolling
887 // everything anyway.
894 origin: SubregionOrigin<'tcx>,
898 debug!("sub_regions({:?} <: {:?})", a, b);
899 self.borrow_region_constraints()
900 .make_subregion(origin, a, b);
903 pub fn subtype_predicate(
905 cause: &ObligationCause<'tcx>,
906 param_env: ty::ParamEnv<'tcx>,
907 predicate: &ty::PolySubtypePredicate<'tcx>,
908 ) -> Option<InferResult<'tcx, ()>> {
909 // Subtle: it's ok to skip the binder here and resolve because
910 // `shallow_resolve` just ignores anything that is not a type
911 // variable, and because type variable's can't (at present, at
912 // least) capture any of the things bound by this binder.
914 // Really, there is no *particular* reason to do this
915 // `shallow_resolve` here except as a
916 // micro-optimization. Naturally I could not
917 // resist. -nmatsakis
918 let two_unbound_type_vars = {
919 let a = self.shallow_resolve(predicate.skip_binder().a);
920 let b = self.shallow_resolve(predicate.skip_binder().b);
921 a.is_ty_var() && b.is_ty_var()
924 if two_unbound_type_vars {
925 // Two unbound type variables? Can't make progress.
929 Some(self.commit_if_ok(|snapshot| {
931 ty::SubtypePredicate {
937 ) = self.replace_late_bound_regions_with_placeholders(predicate);
939 let cause_span = cause.span;
940 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
941 self.leak_check(false, cause_span, &placeholder_map, snapshot)?;
942 self.pop_placeholders(placeholder_map, snapshot);
947 pub fn region_outlives_predicate(
949 cause: &traits::ObligationCause<'tcx>,
950 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
951 ) -> UnitResult<'tcx> {
952 self.commit_if_ok(|snapshot| {
953 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
954 self.replace_late_bound_regions_with_placeholders(predicate);
955 let origin = SubregionOrigin::from_obligation_cause(cause, || {
956 RelateRegionParamBound(cause.span)
958 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
959 self.leak_check(false, cause.span, &placeholder_map, snapshot)?;
960 Ok(self.pop_placeholders(placeholder_map, snapshot))
964 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
967 .new_var(self.universe(), diverging, origin)
970 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
971 self.tcx.mk_var(self.next_ty_var_id(false, origin))
974 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
975 self.tcx.mk_var(self.next_ty_var_id(true, origin))
978 pub fn next_int_var_id(&self) -> IntVid {
979 self.int_unification_table.borrow_mut().new_key(None)
982 pub fn next_float_var_id(&self) -> FloatVid {
983 self.float_unification_table.borrow_mut().new_key(None)
986 /// Create a fresh region variable with the next available index.
987 /// The variable will be created in the maximum universe created
988 /// thus far, allowing it to name any region created thus far.
989 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
990 self.next_region_var_in_universe(origin, self.universe())
993 /// Create a fresh region variable with the next available index
994 /// in the given universe; typically, you can use
995 /// `next_region_var` and just use the maximal universe.
996 pub fn next_region_var_in_universe(
998 origin: RegionVariableOrigin,
999 universe: ty::UniverseIndex,
1000 ) -> ty::Region<'tcx> {
1001 let region_var = self.borrow_region_constraints()
1002 .new_region_var(universe, origin);
1003 self.tcx.mk_region(ty::ReVar(region_var))
1006 /// Number of region variables created so far.
1007 pub fn num_region_vars(&self) -> usize {
1008 self.borrow_region_constraints().num_region_vars()
1011 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1012 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1013 self.next_region_var(RegionVariableOrigin::NLL(origin))
1016 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1017 pub fn next_nll_region_var_in_universe(
1019 origin: NLLRegionVariableOrigin,
1020 universe: ty::UniverseIndex,
1021 ) -> ty::Region<'tcx> {
1022 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1025 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> Kind<'tcx> {
1027 GenericParamDefKind::Lifetime => {
1028 // Create a region inference variable for the given
1029 // region parameter definition.
1030 self.next_region_var(EarlyBoundRegion(span, param.name))
1033 GenericParamDefKind::Type { .. } => {
1034 // Create a type inference variable for the given
1035 // type parameter definition. The substitutions are
1036 // for actual parameters that may be referred to by
1037 // the default of this type parameter, if it exists.
1038 // E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1039 // used in a path such as `Foo::<T, U>::new()` will
1040 // use an inference variable for `C` with `[T, U]`
1041 // as the substitutions for the default, `(T, U)`.
1042 let ty_var_id = self.type_variables.borrow_mut().new_var(
1045 TypeVariableOrigin::TypeParameterDefinition(span, param.name),
1048 self.tcx.mk_var(ty_var_id).into()
1053 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1054 /// type/region parameter to a fresh inference variable.
1055 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> &'tcx Substs<'tcx> {
1056 Substs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1059 /// True if errors have been reported since this infcx was
1060 /// created. This is sometimes used as a heuristic to skip
1061 /// reporting errors that often occur as a result of earlier
1062 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1063 /// inference variables, regionck errors).
1064 pub fn is_tainted_by_errors(&self) -> bool {
1066 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1067 tainted_by_errors_flag={})",
1068 self.tcx.sess.err_count(),
1069 self.err_count_on_creation,
1070 self.tainted_by_errors_flag.get()
1073 if self.tcx.sess.err_count() > self.err_count_on_creation {
1074 return true; // errors reported since this infcx was made
1076 self.tainted_by_errors_flag.get()
1079 /// Set the "tainted by errors" flag to true. We call this when we
1080 /// observe an error from a prior pass.
1081 pub fn set_tainted_by_errors(&self) {
1082 debug!("set_tainted_by_errors()");
1083 self.tainted_by_errors_flag.set(true)
1086 /// Process the region constraints and report any errors that
1087 /// result. After this, no more unification operations should be
1088 /// done -- or the compiler will panic -- but it is legal to use
1089 /// `resolve_type_vars_if_possible` as well as `fully_resolve`.
1090 pub fn resolve_regions_and_report_errors(
1092 region_context: DefId,
1093 region_map: ®ion::ScopeTree,
1094 outlives_env: &OutlivesEnvironment<'tcx>,
1095 suppress: SuppressRegionErrors,
1098 self.is_tainted_by_errors() || self.region_obligations.borrow().is_empty(),
1099 "region_obligations not empty: {:#?}",
1100 self.region_obligations.borrow()
1103 let region_rels = &RegionRelations::new(
1107 outlives_env.free_region_map(),
1109 let (var_infos, data) = self.region_constraints
1112 .expect("regions already resolved")
1113 .into_infos_and_data();
1114 let (lexical_region_resolutions, errors) =
1115 lexical_region_resolve::resolve(region_rels, var_infos, data);
1117 let old_value = self.lexical_region_resolutions
1118 .replace(Some(lexical_region_resolutions));
1119 assert!(old_value.is_none());
1121 if !self.is_tainted_by_errors() {
1122 // As a heuristic, just skip reporting region errors
1123 // altogether if other errors have been reported while
1124 // this infcx was in use. This is totally hokey but
1125 // otherwise we have a hard time separating legit region
1126 // errors from silly ones.
1127 self.report_region_errors(region_map, &errors, suppress);
1131 /// Obtains (and clears) the current set of region
1132 /// constraints. The inference context is still usable: further
1133 /// unifications will simply add new constraints.
1135 /// This method is not meant to be used with normal lexical region
1136 /// resolution. Rather, it is used in the NLL mode as a kind of
1137 /// interim hack: basically we run normal type-check and generate
1138 /// region constraints as normal, but then we take them and
1139 /// translate them into the form that the NLL solver
1140 /// understands. See the NLL module for mode details.
1141 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1143 self.region_obligations.borrow().is_empty(),
1144 "region_obligations not empty: {:#?}",
1145 self.region_obligations.borrow()
1148 self.borrow_region_constraints().take_and_reset_data()
1151 /// Gives temporary access to the region constraint data.
1152 #[allow(non_camel_case_types)] // bug with impl trait
1153 pub fn with_region_constraints<R>(
1155 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1157 let region_constraints = self.borrow_region_constraints();
1158 op(region_constraints.data())
1161 /// Takes ownership of the list of variable regions. This implies
1162 /// that all the region constriants have already been taken, and
1163 /// hence that `resolve_regions_and_report_errors` can never be
1164 /// called. This is used only during NLL processing to "hand off" ownership
1165 /// of the set of region vairables into the NLL region context.
1166 pub fn take_region_var_origins(&self) -> VarInfos {
1167 let (var_infos, data) = self.region_constraints
1170 .expect("regions already resolved")
1171 .into_infos_and_data();
1172 assert!(data.is_empty());
1176 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1177 self.resolve_type_vars_if_possible(&t).to_string()
1180 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1181 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1182 format!("({})", tstrs.join(", "))
1185 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1186 self.resolve_type_vars_if_possible(t).to_string()
1189 // We have this force-inlined variant of shallow_resolve() for the one
1190 // callsite that is extremely hot. All other callsites use the normal
1193 pub fn inlined_shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1195 ty::Infer(ty::TyVar(v)) => {
1196 // Not entirely obvious: if `typ` is a type variable,
1197 // it can be resolved to an int/float variable, which
1198 // can then be recursively resolved, hence the
1199 // recursion. Note though that we prevent type
1200 // variables from unifyxing to other type variables
1201 // directly (though they may be embedded
1202 // structurally), and we prevent cycles in any case,
1203 // so this recursion should always be of very limited
1209 .map(|t| self.shallow_resolve(t))
1213 ty::Infer(ty::IntVar(v)) => self.int_unification_table
1216 .map(|v| v.to_type(self.tcx))
1219 ty::Infer(ty::FloatVar(v)) => self.float_unification_table
1222 .map(|v| v.to_type(self.tcx))
1229 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1230 self.inlined_shallow_resolve(typ)
1233 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1235 T: TypeFoldable<'tcx>,
1238 * Where possible, replaces type/int/float variables in
1239 * `value` with their final value. Note that region variables
1240 * are unaffected. If a type variable has not been unified, it
1241 * is left as is. This is an idempotent operation that does
1242 * not affect inference state in any way and so you can do it
1246 if !value.needs_infer() {
1247 return value.clone(); // avoid duplicated subst-folding
1249 let mut r = resolve::OpportunisticTypeResolver::new(self);
1250 value.fold_with(&mut r)
1253 /// Returns true if `T` contains unresolved type variables. In the
1254 /// process of visiting `T`, this will resolve (where possible)
1255 /// type variables in `T`, but it never constructs the final,
1256 /// resolved type, so it's more efficient than
1257 /// `resolve_type_vars_if_possible()`.
1258 pub fn any_unresolved_type_vars<T>(&self, value: &T) -> bool
1260 T: TypeFoldable<'tcx>,
1262 let mut r = resolve::UnresolvedTypeFinder::new(self);
1263 value.visit_with(&mut r)
1266 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1268 T: TypeFoldable<'tcx>,
1270 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1271 value.fold_with(&mut r)
1274 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1276 * Attempts to resolve all type/region variables in
1277 * `value`. Region inference must have been run already (e.g.,
1278 * by calling `resolve_regions_and_report_errors`). If some
1279 * variable was never unified, an `Err` results.
1281 * This method is idempotent, but it not typically not invoked
1282 * except during the writeback phase.
1285 resolve::fully_resolve(self, value)
1288 // [Note-Type-error-reporting]
1289 // An invariant is that anytime the expected or actual type is Error (the special
1290 // error type, meaning that an error occurred when typechecking this expression),
1291 // this is a derived error. The error cascaded from another error (that was already
1292 // reported), so it's not useful to display it to the user.
1293 // The following methods implement this logic.
1294 // They check if either the actual or expected type is Error, and don't print the error
1295 // in this case. The typechecker should only ever report type errors involving mismatched
1296 // types using one of these methods, and should not call span_err directly for such
1299 pub fn type_error_struct_with_diag<M>(
1303 actual_ty: Ty<'tcx>,
1304 ) -> DiagnosticBuilder<'tcx>
1306 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1308 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1309 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1311 // Don't report an error if actual type is Error.
1312 if actual_ty.references_error() {
1313 return self.tcx.sess.diagnostic().struct_dummy();
1316 mk_diag(self.ty_to_string(actual_ty))
1319 pub fn report_mismatched_types(
1321 cause: &ObligationCause<'tcx>,
1324 err: TypeError<'tcx>,
1325 ) -> DiagnosticBuilder<'tcx> {
1326 let trace = TypeTrace::types(cause, true, expected, actual);
1327 self.report_and_explain_type_error(trace, &err)
1330 pub fn replace_late_bound_regions_with_fresh_var<T>(
1333 lbrct: LateBoundRegionConversionTime,
1334 value: &ty::Binder<T>,
1335 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1337 T: TypeFoldable<'tcx>,
1339 self.tcx.replace_late_bound_regions(value, |br| {
1340 self.next_region_var(LateBoundRegion(span, br, lbrct))
1344 /// Given a higher-ranked projection predicate like:
1346 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1348 /// and a target trait-ref like:
1350 /// <T as Fn<&'x u32>>
1352 /// find a substitution `S` for the higher-ranked regions (here,
1353 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1354 /// and then return the value (here, `&'a u32`) but with the
1355 /// substitution applied (hence, `&'x u32`).
1357 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1359 pub fn match_poly_projection_predicate(
1361 cause: ObligationCause<'tcx>,
1362 param_env: ty::ParamEnv<'tcx>,
1363 match_a: ty::PolyProjectionPredicate<'tcx>,
1364 match_b: ty::TraitRef<'tcx>,
1365 ) -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>> {
1366 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref(self.tcx), p.ty));
1367 let trace = TypeTrace {
1369 values: TraitRefs(ExpectedFound::new(
1371 match_pair.skip_binder().0,
1376 let mut combine = self.combine_fields(trace, param_env);
1377 let result = combine.higher_ranked_match(&match_pair, &match_b, true)?;
1380 obligations: combine.obligations,
1384 /// See `verify_generic_bound` method in `region_constraints`
1385 pub fn verify_generic_bound(
1387 origin: SubregionOrigin<'tcx>,
1388 kind: GenericKind<'tcx>,
1389 a: ty::Region<'tcx>,
1390 bound: VerifyBound<'tcx>,
1392 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1394 self.borrow_region_constraints()
1395 .verify_generic_bound(origin, kind, a, bound);
1398 pub fn type_moves_by_default(
1400 param_env: ty::ParamEnv<'tcx>,
1404 let ty = self.resolve_type_vars_if_possible(&ty);
1405 // Even if the type may have no inference variables, during
1406 // type-checking closure types are in local tables only.
1407 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1408 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1409 return ty.moves_by_default(self.tcx.global_tcx(), param_env, span);
1413 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1415 // this can get called from typeck (by euv), and moves_by_default
1416 // rightly refuses to work with inference variables, but
1417 // moves_by_default has a cache, which we want to use in other
1419 !traits::type_known_to_meet_bound(self, param_env, ty, copy_def_id, span)
1422 /// Obtains the latest type of the given closure; this may be a
1423 /// closure in the current function, in which case its
1424 /// `ClosureKind` may not yet be known.
1425 pub fn closure_kind(
1427 closure_def_id: DefId,
1428 closure_substs: ty::ClosureSubsts<'tcx>,
1429 ) -> Option<ty::ClosureKind> {
1430 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx);
1431 let closure_kind_ty = self.shallow_resolve(&closure_kind_ty);
1432 closure_kind_ty.to_opt_closure_kind()
1435 /// Obtain the signature of a closure. For closures, unlike
1436 /// `tcx.fn_sig(def_id)`, this method will work during the
1437 /// type-checking of the enclosing function and return the closure
1438 /// signature in its partially inferred state.
1442 substs: ty::ClosureSubsts<'tcx>,
1443 ) -> ty::PolyFnSig<'tcx> {
1444 let closure_sig_ty = substs.closure_sig_ty(def_id, self.tcx);
1445 let closure_sig_ty = self.shallow_resolve(&closure_sig_ty);
1446 closure_sig_ty.fn_sig(self.tcx)
1449 /// Normalizes associated types in `value`, potentially returning
1450 /// new obligations that must further be processed.
1451 pub fn partially_normalize_associated_types_in<T>(
1454 body_id: ast::NodeId,
1455 param_env: ty::ParamEnv<'tcx>,
1457 ) -> InferOk<'tcx, T>
1459 T: TypeFoldable<'tcx>,
1461 debug!("partially_normalize_associated_types_in(value={:?})", value);
1462 let mut selcx = traits::SelectionContext::new(self);
1463 let cause = ObligationCause::misc(span, body_id);
1464 let traits::Normalized { value, obligations } =
1465 traits::normalize(&mut selcx, param_env, cause, value);
1467 "partially_normalize_associated_types_in: result={:?} predicates={:?}",
1470 InferOk { value, obligations }
1473 pub fn borrow_region_constraints(&self) -> RefMut<'_, RegionConstraintCollector<'tcx>> {
1474 RefMut::map(self.region_constraints.borrow_mut(), |c| {
1475 c.as_mut().expect("region constraints already solved")
1479 /// Clears the selection, evaluation, and projection caches. This is useful when
1480 /// repeatedly attemping to select an Obligation while changing only
1481 /// its ParamEnv, since FulfillmentContext doesn't use 'probe'
1482 pub fn clear_caches(&self) {
1483 self.selection_cache.clear();
1484 self.evaluation_cache.clear();
1485 self.projection_cache.borrow_mut().clear();
1488 fn universe(&self) -> ty::UniverseIndex {
1492 /// Create and return a fresh universe that extends all previous
1493 /// universes. Updates `self.universe` to that new universe.
1494 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1495 let u = self.universe.get().next_universe();
1496 self.universe.set(u);
1501 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1502 pub fn span(&self) -> Span {
1507 cause: &ObligationCause<'tcx>,
1508 a_is_expected: bool,
1511 ) -> TypeTrace<'tcx> {
1513 cause: cause.clone(),
1514 values: Types(ExpectedFound::new(a_is_expected, a, b)),
1518 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1520 cause: ObligationCause::dummy(),
1521 values: Types(ExpectedFound {
1522 expected: tcx.types.err,
1523 found: tcx.types.err,
1529 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1531 write!(f, "TypeTrace({:?})", self.cause)
1535 impl<'tcx> SubregionOrigin<'tcx> {
1536 pub fn span(&self) -> Span {
1538 Subtype(ref a) => a.span(),
1539 InfStackClosure(a) => a,
1540 InvokeClosure(a) => a,
1541 DerefPointer(a) => a,
1542 FreeVariable(a, _) => a,
1544 RelateObjectBound(a) => a,
1545 RelateParamBound(a, _) => a,
1546 RelateRegionParamBound(a) => a,
1547 RelateDefaultParamBound(a, _) => a,
1549 ReborrowUpvar(a, _) => a,
1550 DataBorrowed(_, a) => a,
1551 ReferenceOutlivesReferent(_, a) => a,
1552 ParameterInScope(_, a) => a,
1553 ExprTypeIsNotInScope(_, a) => a,
1554 BindingTypeIsNotValidAtDecl(a) => a,
1561 SafeDestructor(a) => a,
1562 CompareImplMethodObligation { span, .. } => span,
1566 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1568 F: FnOnce() -> Self,
1571 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1572 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1575 traits::ObligationCauseCode::CompareImplMethodObligation {
1579 } => SubregionOrigin::CompareImplMethodObligation {
1591 impl RegionVariableOrigin {
1592 pub fn span(&self) -> Span {
1594 MiscVariable(a) => a,
1595 PatternRegion(a) => a,
1596 AddrOfRegion(a) => a,
1599 EarlyBoundRegion(a, ..) => a,
1600 LateBoundRegion(a, ..) => a,
1601 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1602 UpvarRegion(_, a) => a,
1603 NLL(..) => bug!("NLL variable used with `span`"),
1608 EnumTypeFoldableImpl! {
1609 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1610 (ValuePairs::Types)(a),
1611 (ValuePairs::Regions)(a),
1612 (ValuePairs::TraitRefs)(a),
1613 (ValuePairs::PolyTraitRefs)(a),
1617 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1618 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1621 "RegionObligation(sub_region={:?}, sup_type={:?})",
1622 self.sub_region, self.sup_type