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;
68 pub mod region_constraints;
71 pub mod type_variable;
76 pub struct InferOk<'tcx, T> {
78 pub obligations: PredicateObligations<'tcx>,
80 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
82 pub type Bound<T> = Option<T>;
83 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
84 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
86 /// A flag that is used to suppress region errors. This is normally
87 /// false, but sometimes -- when we are doing region checks that the
88 /// NLL borrow checker will also do -- it might be set to true.
89 #[derive(Copy, Clone, Default, Debug)]
90 pub struct SuppressRegionErrors {
94 impl SuppressRegionErrors {
95 pub fn suppressed(self) -> bool {
99 /// Indicates that the MIR borrowck will repeat these region
100 /// checks, so we should ignore errors if NLL is (unconditionally)
102 pub fn when_nll_is_enabled(tcx: TyCtxt<'_, '_, '_>) -> Self {
103 match tcx.borrowck_mode() {
104 // If we're on AST or Migrate mode, report AST region errors
105 BorrowckMode::Ast | BorrowckMode::Migrate => SuppressRegionErrors { suppressed: false },
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 { suppressed: true },
114 pub struct InferCtxt<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
115 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
117 /// During type-checking/inference of a body, `in_progress_tables`
118 /// contains a reference to the tables being built up, which are
119 /// used for reading closure kinds/signatures as they are inferred,
120 /// and for error reporting logic to read arbitrary node types.
121 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
123 // Cache for projections. This cache is snapshotted along with the
126 // Public so that `traits::project` can use it.
127 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
129 // We instantiate UnificationTable with bounds<Ty> because the
130 // types that might instantiate a general type variable have an
131 // order, represented by its upper and lower bounds.
132 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
134 // Map from integral variable to the kind of integer it represents
135 int_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::IntVid>>>,
137 // Map from floating variable to the kind of float it represents
138 float_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::FloatVid>>>,
140 // Tracks the set of region variables and the constraints between
141 // them. This is initially `Some(_)` but when
142 // `resolve_regions_and_report_errors` is invoked, this gets set
143 // to `None` -- further attempts to perform unification etc may
144 // fail if new region constraints would've been added.
145 region_constraints: RefCell<Option<RegionConstraintCollector<'tcx>>>,
147 // Once region inference is done, the values for each variable.
148 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
150 /// Caches the results of trait selection. This cache is used
151 /// for things that have to do with the parameters in scope.
152 pub selection_cache: traits::SelectionCache<'tcx>,
154 /// Caches the results of trait evaluation.
155 pub evaluation_cache: traits::EvaluationCache<'tcx>,
157 // the set of predicates on which errors have been reported, to
158 // avoid reporting the same error twice.
159 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
161 // When an error occurs, we want to avoid reporting "derived"
162 // errors that are due to this original failure. Normally, we
163 // handle this with the `err_count_on_creation` count, which
164 // basically just tracks how many errors were reported when we
165 // started type-checking a fn and checks to see if any new errors
166 // have been reported since then. Not great, but it works.
168 // However, when errors originated in other passes -- notably
169 // resolve -- this heuristic breaks down. Therefore, we have this
170 // auxiliary flag that one can set whenever one creates a
171 // type-error that is due to an error in a prior pass.
173 // Don't read this flag directly, call `is_tainted_by_errors()`
174 // and `set_tainted_by_errors()`.
175 tainted_by_errors_flag: Cell<bool>,
177 // Track how many errors were reported when this infcx is created.
178 // If the number of errors increases, that's also a sign (line
179 // `tained_by_errors`) to avoid reporting certain kinds of errors.
180 err_count_on_creation: usize,
182 // This flag is true while there is an active snapshot.
183 in_snapshot: Cell<bool>,
185 // A set of constraints that regionck must validate. Each
186 // constraint has the form `T:'a`, meaning "some type `T` must
187 // outlive the lifetime 'a". These constraints derive from
188 // instantiated type parameters. So if you had a struct defined
191 // struct Foo<T:'static> { ... }
193 // then in some expression `let x = Foo { ... }` it will
194 // instantiate the type parameter `T` with a fresh type `$0`. At
195 // the same time, it will record a region obligation of
196 // `$0:'static`. This will get checked later by regionck. (We
197 // can't generally check these things right away because we have
198 // to wait until types are resolved.)
200 // These are stored in a map keyed to the id of the innermost
201 // enclosing fn body / static initializer expression. This is
202 // because the location where the obligation was incurred can be
203 // relevant with respect to which sublifetime assumptions are in
204 // place. The reason that we store under the fn-id, and not
205 // something more fine-grained, is so that it is easier for
206 // regionck to be sure that it has found *all* the region
207 // obligations (otherwise, it's easy to fail to walk to a
208 // particular node-id).
210 // Before running `resolve_regions_and_report_errors`, the creator
211 // of the inference context is expected to invoke
212 // `process_region_obligations` (defined in `self::region_obligations`)
213 // for each body-id in this map, which will process the
214 // obligations within. This is expected to be done 'late enough'
215 // that all type inference variables have been bound and so forth.
216 pub region_obligations: RefCell<Vec<(ast::NodeId, RegionObligation<'tcx>)>>,
218 /// What is the innermost universe we have created? Starts out as
219 /// `UniverseIndex::root()` but grows from there as we enter
220 /// universal quantifiers.
222 /// N.B., at present, we exclude the universal quantifiers on the
223 /// item we are type-checking, and just consider those names as
224 /// part of the root universe. So this would only get incremented
225 /// when we enter into a higher-ranked (`for<..>`) type or trait
227 universe: Cell<ty::UniverseIndex>,
230 /// A map returned by `replace_bound_vars_with_placeholders()`
231 /// indicating the placeholder region that each late-bound region was
233 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
235 /// See `error_reporting` module for more details
236 #[derive(Clone, Debug)]
237 pub enum ValuePairs<'tcx> {
238 Types(ExpectedFound<Ty<'tcx>>),
239 Regions(ExpectedFound<ty::Region<'tcx>>),
240 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
241 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
244 /// The trace designates the path through inference that we took to
245 /// encounter an error or subtyping constraint.
247 /// See `error_reporting` module for more details.
249 pub struct TypeTrace<'tcx> {
250 cause: ObligationCause<'tcx>,
251 values: ValuePairs<'tcx>,
254 /// The origin of a `r1 <= r2` constraint.
256 /// See `error_reporting` module for more details
257 #[derive(Clone, Debug)]
258 pub enum SubregionOrigin<'tcx> {
259 // Arose from a subtyping relation
260 Subtype(TypeTrace<'tcx>),
262 // Stack-allocated closures cannot outlive innermost loop
263 // or function so as to ensure we only require finite stack
264 InfStackClosure(Span),
266 // Invocation of closure must be within its lifetime
269 // Dereference of reference must be within its lifetime
272 // Closure bound must not outlive captured free variables
273 FreeVariable(Span, ast::NodeId),
275 // Index into slice must be within its lifetime
278 // When casting `&'a T` to an `&'b Trait` object,
279 // relating `'a` to `'b`
280 RelateObjectBound(Span),
282 // Some type parameter was instantiated with the given type,
283 // and that type must outlive some region.
284 RelateParamBound(Span, Ty<'tcx>),
286 // The given region parameter was instantiated with a region
287 // that must outlive some other region.
288 RelateRegionParamBound(Span),
290 // A bound placed on type parameters that states that must outlive
291 // the moment of their instantiation.
292 RelateDefaultParamBound(Span, Ty<'tcx>),
294 // Creating a pointer `b` to contents of another reference
297 // Creating a pointer `b` to contents of an upvar
298 ReborrowUpvar(Span, ty::UpvarId),
300 // Data with type `Ty<'tcx>` was borrowed
301 DataBorrowed(Ty<'tcx>, Span),
303 // (&'a &'b T) where a >= b
304 ReferenceOutlivesReferent(Ty<'tcx>, Span),
306 // Type or region parameters must be in scope.
307 ParameterInScope(ParameterOrigin, Span),
309 // The type T of an expression E must outlive the lifetime for E.
310 ExprTypeIsNotInScope(Ty<'tcx>, Span),
312 // A `ref b` whose region does not enclose the decl site
313 BindingTypeIsNotValidAtDecl(Span),
315 // Regions appearing in a method receiver must outlive method call
318 // Regions appearing in a function argument must outlive func call
321 // Region in return type of invoked fn must enclose call
324 // Operands must be in scope
327 // Region resulting from a `&` expr must enclose the `&` expr
330 // An auto-borrow that does not enclose the expr where it occurs
333 // Region constraint arriving from destructor safety
334 SafeDestructor(Span),
336 // Comparing the signature and requirements of an impl method against
337 // the containing trait.
338 CompareImplMethodObligation {
340 item_name: ast::Name,
341 impl_item_def_id: DefId,
342 trait_item_def_id: DefId,
346 /// Places that type/region parameters can appear.
347 #[derive(Clone, Copy, Debug)]
348 pub enum ParameterOrigin {
350 MethodCall, // foo.bar() <-- parameters on impl providing bar()
351 OverloadedOperator, // a + b when overloaded
352 OverloadedDeref, // *a when overloaded
355 /// Times when we replace late-bound regions with variables:
356 #[derive(Clone, Copy, Debug)]
357 pub enum LateBoundRegionConversionTime {
358 /// when a fn is called
361 /// when two higher-ranked types are compared
364 /// when projecting an associated type
365 AssocTypeProjection(DefId),
368 /// Reasons to create a region inference variable
370 /// See `error_reporting` module for more details
371 #[derive(Copy, Clone, Debug)]
372 pub enum RegionVariableOrigin {
373 // Region variables created for ill-categorized reasons,
374 // mostly indicates places in need of refactoring
377 // Regions created by a `&P` or `[...]` pattern
380 // Regions created by `&` operator
383 // Regions created as part of an autoref of a method receiver
386 // Regions created as part of an automatic coercion
389 // Region variables created as the values for early-bound regions
390 EarlyBoundRegion(Span, InternedString),
392 // Region variables created for bound regions
393 // in a function or method that is called
394 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
396 UpvarRegion(ty::UpvarId, Span),
398 BoundRegionInCoherence(ast::Name),
400 // This origin is used for the inference variables that we create
401 // during NLL region processing.
402 NLL(NLLRegionVariableOrigin),
405 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
406 pub enum NLLRegionVariableOrigin {
407 /// During NLL region processing, we create variables for free
408 /// regions that we encounter in the function signature and
409 /// elsewhere. This origin indices we've got one of those.
412 /// "Universal" instantiation of a higher-ranked region (e.g.,
413 /// from a `for<'a> T` binder). Meant to represent "any region".
414 Placeholder(ty::PlaceholderRegion),
419 impl NLLRegionVariableOrigin {
420 pub fn is_universal(self) -> bool {
422 NLLRegionVariableOrigin::FreeRegion => true,
423 NLLRegionVariableOrigin::Placeholder(..) => true,
424 NLLRegionVariableOrigin::Existential => false,
428 pub fn is_existential(self) -> bool {
433 #[derive(Copy, Clone, Debug)]
434 pub enum FixupError {
435 UnresolvedIntTy(IntVid),
436 UnresolvedFloatTy(FloatVid),
440 /// See the `region_obligations` field for more information.
442 pub struct RegionObligation<'tcx> {
443 pub sub_region: ty::Region<'tcx>,
444 pub sup_type: Ty<'tcx>,
445 pub origin: SubregionOrigin<'tcx>,
448 impl fmt::Display for FixupError {
449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
450 use self::FixupError::*;
453 UnresolvedIntTy(_) => write!(
455 "cannot determine the type of this integer; \
456 add a suffix to specify the type explicitly"
458 UnresolvedFloatTy(_) => write!(
460 "cannot determine the type of this number; \
461 add a suffix to specify the type explicitly"
463 UnresolvedTy(_) => write!(f, "unconstrained type"),
468 /// Helper type of a temporary returned by tcx.infer_ctxt().
469 /// Necessary because we can't write the following bound:
470 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
471 pub struct InferCtxtBuilder<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
472 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
473 arena: SyncDroplessArena,
474 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
477 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
478 pub fn infer_ctxt(self) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
481 arena: SyncDroplessArena::default(),
487 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
488 /// Used only by `rustc_typeck` during body type-checking/inference,
489 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
490 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
491 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
495 /// Given a canonical value `C` as a starting point, create an
496 /// inference context that contains each of the bound values
497 /// within instantiated as a fresh variable. The `f` closure is
498 /// invoked with the new infcx, along with the instantiated value
499 /// `V` and a substitution `S`. This substitution `S` maps from
500 /// the bound values in `C` to their instantiated values in `V`
501 /// (in other words, `S(C) = V`).
502 pub fn enter_with_canonical<T, R>(
505 canonical: &Canonical<'tcx, T>,
506 f: impl for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
509 T: TypeFoldable<'tcx>,
513 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
514 f(infcx, value, subst)
518 pub fn enter<R>(&'tcx mut self, f: impl for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R) -> R {
519 let InferCtxtBuilder {
524 let in_progress_tables = fresh_tables.as_ref();
525 global_tcx.enter_local(arena, |tcx| {
529 projection_cache: Default::default(),
530 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
531 int_unification_table: RefCell::new(ut::UnificationTable::new()),
532 float_unification_table: RefCell::new(ut::UnificationTable::new()),
533 region_constraints: RefCell::new(Some(RegionConstraintCollector::new())),
534 lexical_region_resolutions: RefCell::new(None),
535 selection_cache: Default::default(),
536 evaluation_cache: Default::default(),
537 reported_trait_errors: Default::default(),
538 tainted_by_errors_flag: Cell::new(false),
539 err_count_on_creation: tcx.sess.err_count(),
540 in_snapshot: Cell::new(false),
541 region_obligations: RefCell::new(vec![]),
542 universe: Cell::new(ty::UniverseIndex::ROOT),
548 impl<T> ExpectedFound<T> {
549 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
564 impl<'tcx, T> InferOk<'tcx, T> {
565 pub fn unit(self) -> InferOk<'tcx, ()> {
568 obligations: self.obligations,
572 /// Extract `value`, registering any obligations into `fulfill_cx`
573 pub fn into_value_registering_obligations(
575 infcx: &InferCtxt<'_, '_, 'tcx>,
576 fulfill_cx: &mut impl TraitEngine<'tcx>,
578 let InferOk { value, obligations } = self;
579 for obligation in obligations {
580 fulfill_cx.register_predicate_obligation(infcx, obligation);
586 impl<'tcx> InferOk<'tcx, ()> {
587 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
592 #[must_use = "once you start a snapshot, you should always consume it"]
593 pub struct CombinedSnapshot<'a, 'tcx: 'a> {
594 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
595 type_snapshot: type_variable::Snapshot<'tcx>,
596 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
597 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
598 region_constraints_snapshot: RegionSnapshot,
599 region_obligations_snapshot: usize,
600 universe: ty::UniverseIndex,
601 was_in_snapshot: bool,
602 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
605 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
606 pub fn is_in_snapshot(&self) -> bool {
607 self.in_snapshot.get()
610 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
611 t.fold_with(&mut self.freshener())
614 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
616 ty::Infer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
621 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
622 freshen::TypeFreshener::new(self)
625 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
626 use ty::error::UnconstrainedNumeric::Neither;
627 use ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
629 ty::Infer(ty::IntVar(vid)) => {
630 if self.int_unification_table
640 ty::Infer(ty::FloatVar(vid)) => {
641 if self.float_unification_table
655 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
656 let mut type_variables = self.type_variables.borrow_mut();
657 let mut int_unification_table = self.int_unification_table.borrow_mut();
658 let mut float_unification_table = self.float_unification_table.borrow_mut();
661 .unsolved_variables()
663 .map(|t| self.tcx.mk_var(t))
665 (0..int_unification_table.len())
666 .map(|i| ty::IntVid { index: i as u32 })
667 .filter(|&vid| int_unification_table.probe_value(vid).is_none())
668 .map(|v| self.tcx.mk_int_var(v)),
671 (0..float_unification_table.len())
672 .map(|i| ty::FloatVid { index: i as u32 })
673 .filter(|&vid| float_unification_table.probe_value(vid).is_none())
674 .map(|v| self.tcx.mk_float_var(v)),
681 trace: TypeTrace<'tcx>,
682 param_env: ty::ParamEnv<'tcx>,
683 ) -> CombineFields<'a, 'gcx, 'tcx> {
689 obligations: PredicateObligations::new(),
693 // Clear the "currently in a snapshot" flag, invoke the closure,
694 // then restore the flag to its original value. This flag is a
695 // debugging measure designed to detect cases where we start a
696 // snapshot, create type variables, and register obligations
697 // which may involve those type variables in the fulfillment cx,
698 // potentially leaving "dangling type variables" behind.
699 // In such cases, an assertion will fail when attempting to
700 // register obligations, within a snapshot. Very useful, much
701 // better than grovelling through megabytes of RUST_LOG output.
703 // HOWEVER, in some cases the flag is unhelpful. In particular, we
704 // sometimes create a "mini-fulfilment-cx" in which we enroll
705 // obligations. As long as this fulfillment cx is fully drained
706 // before we return, this is not a problem, as there won't be any
707 // escaping obligations in the main cx. In those cases, you can
708 // use this function.
709 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
711 F: FnOnce(&Self) -> R,
713 let flag = self.in_snapshot.get();
714 self.in_snapshot.set(false);
715 let result = func(self);
716 self.in_snapshot.set(flag);
720 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
721 debug!("start_snapshot()");
723 let in_snapshot = self.in_snapshot.get();
724 self.in_snapshot.set(true);
727 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
728 type_snapshot: self.type_variables.borrow_mut().snapshot(),
729 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
730 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
731 region_constraints_snapshot: self.borrow_region_constraints().start_snapshot(),
732 region_obligations_snapshot: self.region_obligations.borrow().len(),
733 universe: self.universe(),
734 was_in_snapshot: in_snapshot,
735 // Borrow tables "in progress" (i.e., during typeck)
736 // to ban writes from within a snapshot to them.
737 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
741 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
742 debug!("rollback_to(cause={})", cause);
743 let CombinedSnapshot {
744 projection_cache_snapshot,
748 region_constraints_snapshot,
749 region_obligations_snapshot,
755 self.in_snapshot.set(was_in_snapshot);
756 self.universe.set(universe);
758 self.projection_cache
760 .rollback_to(projection_cache_snapshot);
761 self.type_variables.borrow_mut().rollback_to(type_snapshot);
762 self.int_unification_table
764 .rollback_to(int_snapshot);
765 self.float_unification_table
767 .rollback_to(float_snapshot);
768 self.region_obligations
770 .truncate(region_obligations_snapshot);
771 self.borrow_region_constraints()
772 .rollback_to(region_constraints_snapshot);
775 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
776 debug!("commit_from()");
777 let CombinedSnapshot {
778 projection_cache_snapshot,
782 region_constraints_snapshot,
783 region_obligations_snapshot: _,
789 self.in_snapshot.set(was_in_snapshot);
791 self.projection_cache
793 .commit(projection_cache_snapshot);
794 self.type_variables.borrow_mut().commit(type_snapshot);
795 self.int_unification_table.borrow_mut().commit(int_snapshot);
796 self.float_unification_table
798 .commit(float_snapshot);
799 self.borrow_region_constraints()
800 .commit(region_constraints_snapshot);
803 /// Execute `f` and commit the bindings
804 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
809 let snapshot = self.start_snapshot();
811 self.commit_from(snapshot);
815 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
816 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
818 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
820 debug!("commit_if_ok()");
821 let snapshot = self.start_snapshot();
822 let r = f(&snapshot);
823 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
826 self.commit_from(snapshot);
829 self.rollback_to("commit_if_ok -- error", snapshot);
835 // Execute `f` in a snapshot, and commit the bindings it creates
836 pub fn in_snapshot<T, F>(&self, f: F) -> T
838 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> T,
840 debug!("in_snapshot()");
841 let snapshot = self.start_snapshot();
842 let r = f(&snapshot);
843 self.commit_from(snapshot);
847 /// Execute `f` then unroll any bindings it creates
848 pub fn probe<R, F>(&self, f: F) -> R
850 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
853 let snapshot = self.start_snapshot();
854 let r = f(&snapshot);
855 self.rollback_to("probe", snapshot);
859 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
860 self.borrow_region_constraints().add_given(sub, sup);
863 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
865 T: at::ToTrace<'tcx>,
867 let origin = &ObligationCause::dummy();
869 self.at(origin, param_env)
871 .map(|InferOk { obligations: _, .. }| {
872 // Ignore obligations, since we are unrolling
873 // everything anyway.
878 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
880 T: at::ToTrace<'tcx>,
882 let origin = &ObligationCause::dummy();
884 self.at(origin, param_env)
886 .map(|InferOk { obligations: _, .. }| {
887 // Ignore obligations, since we are unrolling
888 // everything anyway.
895 origin: SubregionOrigin<'tcx>,
899 debug!("sub_regions({:?} <: {:?})", a, b);
900 self.borrow_region_constraints()
901 .make_subregion(origin, a, b);
904 pub fn subtype_predicate(
906 cause: &ObligationCause<'tcx>,
907 param_env: ty::ParamEnv<'tcx>,
908 predicate: &ty::PolySubtypePredicate<'tcx>,
909 ) -> Option<InferResult<'tcx, ()>> {
910 // Subtle: it's ok to skip the binder here and resolve because
911 // `shallow_resolve` just ignores anything that is not a type
912 // variable, and because type variable's can't (at present, at
913 // least) capture any of the things bound by this binder.
915 // Really, there is no *particular* reason to do this
916 // `shallow_resolve` here except as a
917 // micro-optimization. Naturally I could not
918 // resist. -nmatsakis
919 let two_unbound_type_vars = {
920 let a = self.shallow_resolve(predicate.skip_binder().a);
921 let b = self.shallow_resolve(predicate.skip_binder().b);
922 a.is_ty_var() && b.is_ty_var()
925 if two_unbound_type_vars {
926 // Two unbound type variables? Can't make progress.
930 Some(self.commit_if_ok(|snapshot| {
932 ty::SubtypePredicate {
938 ) = self.replace_bound_vars_with_placeholders(predicate);
940 let cause_span = cause.span;
941 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
942 self.leak_check(false, cause_span, &placeholder_map, snapshot)?;
943 self.pop_placeholders(placeholder_map, snapshot);
948 pub fn region_outlives_predicate(
950 cause: &traits::ObligationCause<'tcx>,
951 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
952 ) -> UnitResult<'tcx> {
953 self.commit_if_ok(|snapshot| {
954 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
955 self.replace_bound_vars_with_placeholders(predicate);
956 let origin = SubregionOrigin::from_obligation_cause(cause, || {
957 RelateRegionParamBound(cause.span)
959 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
960 self.leak_check(false, cause.span, &placeholder_map, snapshot)?;
961 Ok(self.pop_placeholders(placeholder_map, snapshot))
965 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
968 .new_var(self.universe(), diverging, origin)
971 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
972 self.tcx.mk_var(self.next_ty_var_id(false, origin))
975 pub fn next_ty_var_in_universe(
977 origin: TypeVariableOrigin,
978 universe: ty::UniverseIndex
980 let vid = self.type_variables
982 .new_var(universe, false, origin);
986 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
987 self.tcx.mk_var(self.next_ty_var_id(true, origin))
990 pub fn next_int_var_id(&self) -> IntVid {
991 self.int_unification_table.borrow_mut().new_key(None)
994 pub fn next_float_var_id(&self) -> FloatVid {
995 self.float_unification_table.borrow_mut().new_key(None)
998 /// Create a fresh region variable with the next available index.
999 /// The variable will be created in the maximum universe created
1000 /// thus far, allowing it to name any region created thus far.
1001 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1002 self.next_region_var_in_universe(origin, self.universe())
1005 /// Create a fresh region variable with the next available index
1006 /// in the given universe; typically, you can use
1007 /// `next_region_var` and just use the maximal universe.
1008 pub fn next_region_var_in_universe(
1010 origin: RegionVariableOrigin,
1011 universe: ty::UniverseIndex,
1012 ) -> ty::Region<'tcx> {
1013 let region_var = self.borrow_region_constraints()
1014 .new_region_var(universe, origin);
1015 self.tcx.mk_region(ty::ReVar(region_var))
1018 /// Number of region variables created so far.
1019 pub fn num_region_vars(&self) -> usize {
1020 self.borrow_region_constraints().num_region_vars()
1023 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1024 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1025 self.next_region_var(RegionVariableOrigin::NLL(origin))
1028 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1029 pub fn next_nll_region_var_in_universe(
1031 origin: NLLRegionVariableOrigin,
1032 universe: ty::UniverseIndex,
1033 ) -> ty::Region<'tcx> {
1034 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1037 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> Kind<'tcx> {
1039 GenericParamDefKind::Lifetime => {
1040 // Create a region inference variable for the given
1041 // region parameter definition.
1042 self.next_region_var(EarlyBoundRegion(span, param.name))
1045 GenericParamDefKind::Type { .. } => {
1046 // Create a type inference variable for the given
1047 // type parameter definition. The substitutions are
1048 // for actual parameters that may be referred to by
1049 // the default of this type parameter, if it exists.
1050 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1051 // used in a path such as `Foo::<T, U>::new()` will
1052 // use an inference variable for `C` with `[T, U]`
1053 // as the substitutions for the default, `(T, U)`.
1054 let ty_var_id = self.type_variables.borrow_mut().new_var(
1057 TypeVariableOrigin::TypeParameterDefinition(span, param.name),
1060 self.tcx.mk_var(ty_var_id).into()
1065 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1066 /// type/region parameter to a fresh inference variable.
1067 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> &'tcx Substs<'tcx> {
1068 Substs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1071 /// True if errors have been reported since this infcx was
1072 /// created. This is sometimes used as a heuristic to skip
1073 /// reporting errors that often occur as a result of earlier
1074 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1075 /// inference variables, regionck errors).
1076 pub fn is_tainted_by_errors(&self) -> bool {
1078 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1079 tainted_by_errors_flag={})",
1080 self.tcx.sess.err_count(),
1081 self.err_count_on_creation,
1082 self.tainted_by_errors_flag.get()
1085 if self.tcx.sess.err_count() > self.err_count_on_creation {
1086 return true; // errors reported since this infcx was made
1088 self.tainted_by_errors_flag.get()
1091 /// Set the "tainted by errors" flag to true. We call this when we
1092 /// observe an error from a prior pass.
1093 pub fn set_tainted_by_errors(&self) {
1094 debug!("set_tainted_by_errors()");
1095 self.tainted_by_errors_flag.set(true)
1098 /// Process the region constraints and report any errors that
1099 /// result. After this, no more unification operations should be
1100 /// done -- or the compiler will panic -- but it is legal to use
1101 /// `resolve_type_vars_if_possible` as well as `fully_resolve`.
1102 pub fn resolve_regions_and_report_errors(
1104 region_context: DefId,
1105 region_map: ®ion::ScopeTree,
1106 outlives_env: &OutlivesEnvironment<'tcx>,
1107 suppress: SuppressRegionErrors,
1110 self.is_tainted_by_errors() || self.region_obligations.borrow().is_empty(),
1111 "region_obligations not empty: {:#?}",
1112 self.region_obligations.borrow()
1115 let region_rels = &RegionRelations::new(
1119 outlives_env.free_region_map(),
1121 let (var_infos, data) = self.region_constraints
1124 .expect("regions already resolved")
1125 .into_infos_and_data();
1126 let (lexical_region_resolutions, errors) =
1127 lexical_region_resolve::resolve(region_rels, var_infos, data);
1129 let old_value = self.lexical_region_resolutions
1130 .replace(Some(lexical_region_resolutions));
1131 assert!(old_value.is_none());
1133 if !self.is_tainted_by_errors() {
1134 // As a heuristic, just skip reporting region errors
1135 // altogether if other errors have been reported while
1136 // this infcx was in use. This is totally hokey but
1137 // otherwise we have a hard time separating legit region
1138 // errors from silly ones.
1139 self.report_region_errors(region_map, &errors, suppress);
1143 /// Obtains (and clears) the current set of region
1144 /// constraints. The inference context is still usable: further
1145 /// unifications will simply add new constraints.
1147 /// This method is not meant to be used with normal lexical region
1148 /// resolution. Rather, it is used in the NLL mode as a kind of
1149 /// interim hack: basically we run normal type-check and generate
1150 /// region constraints as normal, but then we take them and
1151 /// translate them into the form that the NLL solver
1152 /// understands. See the NLL module for mode details.
1153 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1155 self.region_obligations.borrow().is_empty(),
1156 "region_obligations not empty: {:#?}",
1157 self.region_obligations.borrow()
1160 self.borrow_region_constraints().take_and_reset_data()
1163 /// Gives temporary access to the region constraint data.
1164 #[allow(non_camel_case_types)] // bug with impl trait
1165 pub fn with_region_constraints<R>(
1167 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1169 let region_constraints = self.borrow_region_constraints();
1170 op(region_constraints.data())
1173 /// Takes ownership of the list of variable regions. This implies
1174 /// that all the region constraints have already been taken, and
1175 /// hence that `resolve_regions_and_report_errors` can never be
1176 /// called. This is used only during NLL processing to "hand off" ownership
1177 /// of the set of region variables into the NLL region context.
1178 pub fn take_region_var_origins(&self) -> VarInfos {
1179 let (var_infos, data) = self.region_constraints
1182 .expect("regions already resolved")
1183 .into_infos_and_data();
1184 assert!(data.is_empty());
1188 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1189 self.resolve_type_vars_if_possible(&t).to_string()
1192 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1193 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1194 format!("({})", tstrs.join(", "))
1197 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1198 self.resolve_type_vars_if_possible(t).to_string()
1201 // We have this force-inlined variant of shallow_resolve() for the one
1202 // callsite that is extremely hot. All other callsites use the normal
1205 pub fn inlined_shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1207 ty::Infer(ty::TyVar(v)) => {
1208 // Not entirely obvious: if `typ` is a type variable,
1209 // it can be resolved to an int/float variable, which
1210 // can then be recursively resolved, hence the
1211 // recursion. Note though that we prevent type
1212 // variables from unifyxing to other type variables
1213 // directly (though they may be embedded
1214 // structurally), and we prevent cycles in any case,
1215 // so this recursion should always be of very limited
1221 .map(|t| self.shallow_resolve(t))
1225 ty::Infer(ty::IntVar(v)) => self.int_unification_table
1228 .map(|v| v.to_type(self.tcx))
1231 ty::Infer(ty::FloatVar(v)) => self.float_unification_table
1234 .map(|v| v.to_type(self.tcx))
1241 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1242 /// universe index of `TyVar(vid)`.
1243 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1244 use self::type_variable::TypeVariableValue;
1246 match self.type_variables.borrow_mut().probe(vid) {
1247 TypeVariableValue::Known { value } => Ok(value),
1248 TypeVariableValue::Unknown { universe } => Err(universe),
1252 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1253 self.inlined_shallow_resolve(typ)
1256 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1258 T: TypeFoldable<'tcx>,
1261 * Where possible, replaces type/int/float variables in
1262 * `value` with their final value. Note that region variables
1263 * are unaffected. If a type variable has not been unified, it
1264 * is left as is. This is an idempotent operation that does
1265 * not affect inference state in any way and so you can do it
1269 if !value.needs_infer() {
1270 return value.clone(); // avoid duplicated subst-folding
1272 let mut r = resolve::OpportunisticTypeResolver::new(self);
1273 value.fold_with(&mut r)
1276 /// Returns true if `T` contains unresolved type variables. In the
1277 /// process of visiting `T`, this will resolve (where possible)
1278 /// type variables in `T`, but it never constructs the final,
1279 /// resolved type, so it's more efficient than
1280 /// `resolve_type_vars_if_possible()`.
1281 pub fn any_unresolved_type_vars<T>(&self, value: &T) -> bool
1283 T: TypeFoldable<'tcx>,
1285 let mut r = resolve::UnresolvedTypeFinder::new(self);
1286 value.visit_with(&mut r)
1289 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1291 T: TypeFoldable<'tcx>,
1293 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1294 value.fold_with(&mut r)
1297 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1299 * Attempts to resolve all type/region variables in
1300 * `value`. Region inference must have been run already (e.g.,
1301 * by calling `resolve_regions_and_report_errors`). If some
1302 * variable was never unified, an `Err` results.
1304 * This method is idempotent, but it not typically not invoked
1305 * except during the writeback phase.
1308 resolve::fully_resolve(self, value)
1311 // [Note-Type-error-reporting]
1312 // An invariant is that anytime the expected or actual type is Error (the special
1313 // error type, meaning that an error occurred when typechecking this expression),
1314 // this is a derived error. The error cascaded from another error (that was already
1315 // reported), so it's not useful to display it to the user.
1316 // The following methods implement this logic.
1317 // They check if either the actual or expected type is Error, and don't print the error
1318 // in this case. The typechecker should only ever report type errors involving mismatched
1319 // types using one of these methods, and should not call span_err directly for such
1322 pub fn type_error_struct_with_diag<M>(
1326 actual_ty: Ty<'tcx>,
1327 ) -> DiagnosticBuilder<'tcx>
1329 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1331 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1332 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1334 // Don't report an error if actual type is `Error`.
1335 if actual_ty.references_error() {
1336 return self.tcx.sess.diagnostic().struct_dummy();
1339 mk_diag(self.ty_to_string(actual_ty))
1342 pub fn report_mismatched_types(
1344 cause: &ObligationCause<'tcx>,
1347 err: TypeError<'tcx>,
1348 ) -> DiagnosticBuilder<'tcx> {
1349 let trace = TypeTrace::types(cause, true, expected, actual);
1350 self.report_and_explain_type_error(trace, &err)
1353 pub fn replace_bound_vars_with_fresh_vars<T>(
1356 lbrct: LateBoundRegionConversionTime,
1357 value: &ty::Binder<T>
1358 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1360 T: TypeFoldable<'tcx>
1362 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1363 let fld_t = |_| self.next_ty_var(TypeVariableOrigin::MiscVariable(span));
1364 self.tcx.replace_bound_vars(value, fld_r, fld_t)
1367 /// Given a higher-ranked projection predicate like:
1369 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1371 /// and a target trait-ref like:
1373 /// <T as Fn<&'x u32>>
1375 /// find a substitution `S` for the higher-ranked regions (here,
1376 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1377 /// and then return the value (here, `&'a u32`) but with the
1378 /// substitution applied (hence, `&'x u32`).
1380 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1382 pub fn match_poly_projection_predicate(
1384 cause: ObligationCause<'tcx>,
1385 param_env: ty::ParamEnv<'tcx>,
1386 match_a: ty::PolyProjectionPredicate<'tcx>,
1387 match_b: ty::TraitRef<'tcx>,
1388 ) -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>> {
1389 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref(self.tcx), p.ty));
1390 let trace = TypeTrace {
1392 values: TraitRefs(ExpectedFound::new(
1394 match_pair.skip_binder().0,
1399 let mut combine = self.combine_fields(trace, param_env);
1400 let result = combine.higher_ranked_match(&match_pair, &match_b, true)?;
1403 obligations: combine.obligations,
1407 /// See `verify_generic_bound` method in `region_constraints`
1408 pub fn verify_generic_bound(
1410 origin: SubregionOrigin<'tcx>,
1411 kind: GenericKind<'tcx>,
1412 a: ty::Region<'tcx>,
1413 bound: VerifyBound<'tcx>,
1415 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1417 self.borrow_region_constraints()
1418 .verify_generic_bound(origin, kind, a, bound);
1421 pub fn type_moves_by_default(
1423 param_env: ty::ParamEnv<'tcx>,
1427 let ty = self.resolve_type_vars_if_possible(&ty);
1428 // Even if the type may have no inference variables, during
1429 // type-checking closure types are in local tables only.
1430 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1431 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1432 return ty.moves_by_default(self.tcx.global_tcx(), param_env, span);
1436 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1438 // this can get called from typeck (by euv), and moves_by_default
1439 // rightly refuses to work with inference variables, but
1440 // moves_by_default has a cache, which we want to use in other
1442 !traits::type_known_to_meet_bound(self, param_env, ty, copy_def_id, span)
1445 /// Obtains the latest type of the given closure; this may be a
1446 /// closure in the current function, in which case its
1447 /// `ClosureKind` may not yet be known.
1448 pub fn closure_kind(
1450 closure_def_id: DefId,
1451 closure_substs: ty::ClosureSubsts<'tcx>,
1452 ) -> Option<ty::ClosureKind> {
1453 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx);
1454 let closure_kind_ty = self.shallow_resolve(&closure_kind_ty);
1455 closure_kind_ty.to_opt_closure_kind()
1458 /// Obtain the signature of a closure. For closures, unlike
1459 /// `tcx.fn_sig(def_id)`, this method will work during the
1460 /// type-checking of the enclosing function and return the closure
1461 /// signature in its partially inferred state.
1465 substs: ty::ClosureSubsts<'tcx>,
1466 ) -> ty::PolyFnSig<'tcx> {
1467 let closure_sig_ty = substs.closure_sig_ty(def_id, self.tcx);
1468 let closure_sig_ty = self.shallow_resolve(&closure_sig_ty);
1469 closure_sig_ty.fn_sig(self.tcx)
1472 /// Normalizes associated types in `value`, potentially returning
1473 /// new obligations that must further be processed.
1474 pub fn partially_normalize_associated_types_in<T>(
1477 body_id: ast::NodeId,
1478 param_env: ty::ParamEnv<'tcx>,
1480 ) -> InferOk<'tcx, T>
1482 T: TypeFoldable<'tcx>,
1484 debug!("partially_normalize_associated_types_in(value={:?})", value);
1485 let mut selcx = traits::SelectionContext::new(self);
1486 let cause = ObligationCause::misc(span, body_id);
1487 let traits::Normalized { value, obligations } =
1488 traits::normalize(&mut selcx, param_env, cause, value);
1490 "partially_normalize_associated_types_in: result={:?} predicates={:?}",
1493 InferOk { value, obligations }
1496 pub fn borrow_region_constraints(&self) -> RefMut<'_, RegionConstraintCollector<'tcx>> {
1497 RefMut::map(self.region_constraints.borrow_mut(), |c| {
1498 c.as_mut().expect("region constraints already solved")
1502 /// Clears the selection, evaluation, and projection caches. This is useful when
1503 /// repeatedly attempting to select an Obligation while changing only
1504 /// its ParamEnv, since FulfillmentContext doesn't use 'probe'
1505 pub fn clear_caches(&self) {
1506 self.selection_cache.clear();
1507 self.evaluation_cache.clear();
1508 self.projection_cache.borrow_mut().clear();
1511 fn universe(&self) -> ty::UniverseIndex {
1515 /// Create and return a fresh universe that extends all previous
1516 /// universes. Updates `self.universe` to that new universe.
1517 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1518 let u = self.universe.get().next_universe();
1519 self.universe.set(u);
1524 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1525 pub fn span(&self) -> Span {
1530 cause: &ObligationCause<'tcx>,
1531 a_is_expected: bool,
1534 ) -> TypeTrace<'tcx> {
1536 cause: cause.clone(),
1537 values: Types(ExpectedFound::new(a_is_expected, a, b)),
1541 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1543 cause: ObligationCause::dummy(),
1544 values: Types(ExpectedFound {
1545 expected: tcx.types.err,
1546 found: tcx.types.err,
1552 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1554 write!(f, "TypeTrace({:?})", self.cause)
1558 impl<'tcx> SubregionOrigin<'tcx> {
1559 pub fn span(&self) -> Span {
1561 Subtype(ref a) => a.span(),
1562 InfStackClosure(a) => a,
1563 InvokeClosure(a) => a,
1564 DerefPointer(a) => a,
1565 FreeVariable(a, _) => a,
1567 RelateObjectBound(a) => a,
1568 RelateParamBound(a, _) => a,
1569 RelateRegionParamBound(a) => a,
1570 RelateDefaultParamBound(a, _) => a,
1572 ReborrowUpvar(a, _) => a,
1573 DataBorrowed(_, a) => a,
1574 ReferenceOutlivesReferent(_, a) => a,
1575 ParameterInScope(_, a) => a,
1576 ExprTypeIsNotInScope(_, a) => a,
1577 BindingTypeIsNotValidAtDecl(a) => a,
1584 SafeDestructor(a) => a,
1585 CompareImplMethodObligation { span, .. } => span,
1589 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1591 F: FnOnce() -> Self,
1594 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1595 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1598 traits::ObligationCauseCode::CompareImplMethodObligation {
1602 } => SubregionOrigin::CompareImplMethodObligation {
1614 impl RegionVariableOrigin {
1615 pub fn span(&self) -> Span {
1617 MiscVariable(a) => a,
1618 PatternRegion(a) => a,
1619 AddrOfRegion(a) => a,
1622 EarlyBoundRegion(a, ..) => a,
1623 LateBoundRegion(a, ..) => a,
1624 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1625 UpvarRegion(_, a) => a,
1626 NLL(..) => bug!("NLL variable used with `span`"),
1631 EnumTypeFoldableImpl! {
1632 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1633 (ValuePairs::Types)(a),
1634 (ValuePairs::Regions)(a),
1635 (ValuePairs::TraitRefs)(a),
1636 (ValuePairs::PolyTraitRefs)(a),
1640 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1641 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1644 "RegionObligation(sub_region={:?}, sup_type={:?})",
1645 self.sub_region, self.sup_type