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::LateBoundRegionConversionTime::*;
14 pub use self::RegionVariableOrigin::*;
15 pub use self::SubregionOrigin::*;
16 pub use self::ValuePairs::*;
17 pub use ty::IntVarValue;
18 pub use self::freshen::TypeFreshener;
19 pub use self::region_inference::{GenericKind, VerifyBound};
21 use hir::def_id::DefId;
22 use middle::free_region::{FreeRegionMap, RegionRelations};
24 use middle::lang_items;
25 use mir::tcx::LvalueTy;
26 use ty::subst::{Kind, Subst, Substs};
27 use ty::{TyVid, IntVid, FloatVid};
28 use ty::{self, Ty, TyCtxt};
29 use ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
30 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
31 use ty::relate::RelateResult;
32 use traits::{self, ObligationCause, PredicateObligations, Reveal};
33 use rustc_data_structures::unify::{self, UnificationTable};
34 use std::cell::{Cell, RefCell, Ref};
37 use errors::DiagnosticBuilder;
38 use syntax_pos::{self, Span, DUMMY_SP};
39 use util::nodemap::FxHashMap;
40 use arena::DroplessArena;
42 use self::combine::CombineFields;
43 use self::higher_ranked::HrMatchResult;
44 use self::region_inference::{RegionVarBindings, RegionSnapshot};
45 use self::type_variable::TypeVariableOrigin;
46 use self::unify_key::ToType;
51 pub mod error_reporting;
57 pub mod region_inference;
61 pub mod type_variable;
65 pub struct InferOk<'tcx, T> {
67 pub obligations: PredicateObligations<'tcx>,
69 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
71 pub type Bound<T> = Option<T>;
72 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
73 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
75 pub struct InferCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
76 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
78 /// During type-checking/inference of a body, `in_progress_tables`
79 /// contains a reference to the tables being built up, which are
80 /// used for reading closure kinds/signatures as they are inferred,
81 /// and for error reporting logic to read arbitrary node types.
82 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
84 // Cache for projections. This cache is snapshotted along with the
87 // Public so that `traits::project` can use it.
88 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
90 // We instantiate UnificationTable with bounds<Ty> because the
91 // types that might instantiate a general type variable have an
92 // order, represented by its upper and lower bounds.
93 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
95 // Map from integral variable to the kind of integer it represents
96 int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
98 // Map from floating variable to the kind of float it represents
99 float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
101 // For region variables.
102 region_vars: RegionVarBindings<'a, 'gcx, 'tcx>,
104 /// Caches the results of trait selection. This cache is used
105 /// for things that have to do with the parameters in scope.
106 pub selection_cache: traits::SelectionCache<'tcx>,
108 /// Caches the results of trait evaluation.
109 pub evaluation_cache: traits::EvaluationCache<'tcx>,
111 // the set of predicates on which errors have been reported, to
112 // avoid reporting the same error twice.
113 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
115 // When an error occurs, we want to avoid reporting "derived"
116 // errors that are due to this original failure. Normally, we
117 // handle this with the `err_count_on_creation` count, which
118 // basically just tracks how many errors were reported when we
119 // started type-checking a fn and checks to see if any new errors
120 // have been reported since then. Not great, but it works.
122 // However, when errors originated in other passes -- notably
123 // resolve -- this heuristic breaks down. Therefore, we have this
124 // auxiliary flag that one can set whenever one creates a
125 // type-error that is due to an error in a prior pass.
127 // Don't read this flag directly, call `is_tainted_by_errors()`
128 // and `set_tainted_by_errors()`.
129 tainted_by_errors_flag: Cell<bool>,
131 // Track how many errors were reported when this infcx is created.
132 // If the number of errors increases, that's also a sign (line
133 // `tained_by_errors`) to avoid reporting certain kinds of errors.
134 err_count_on_creation: usize,
136 // This flag is true while there is an active snapshot.
137 in_snapshot: Cell<bool>,
140 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
141 /// region that each late-bound region was replaced with.
142 pub type SkolemizationMap<'tcx> = FxHashMap<ty::BoundRegion, ty::Region<'tcx>>;
144 /// See `error_reporting` module for more details
145 #[derive(Clone, Debug)]
146 pub enum ValuePairs<'tcx> {
147 Types(ExpectedFound<Ty<'tcx>>),
148 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
149 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
152 /// The trace designates the path through inference that we took to
153 /// encounter an error or subtyping constraint.
155 /// See `error_reporting` module for more details.
157 pub struct TypeTrace<'tcx> {
158 cause: ObligationCause<'tcx>,
159 values: ValuePairs<'tcx>,
162 /// The origin of a `r1 <= r2` constraint.
164 /// See `error_reporting` module for more details
165 #[derive(Clone, Debug)]
166 pub enum SubregionOrigin<'tcx> {
167 // Arose from a subtyping relation
168 Subtype(TypeTrace<'tcx>),
170 // Stack-allocated closures cannot outlive innermost loop
171 // or function so as to ensure we only require finite stack
172 InfStackClosure(Span),
174 // Invocation of closure must be within its lifetime
177 // Dereference of reference must be within its lifetime
180 // Closure bound must not outlive captured free variables
181 FreeVariable(Span, ast::NodeId),
183 // Index into slice must be within its lifetime
186 // When casting `&'a T` to an `&'b Trait` object,
187 // relating `'a` to `'b`
188 RelateObjectBound(Span),
190 // Some type parameter was instantiated with the given type,
191 // and that type must outlive some region.
192 RelateParamBound(Span, Ty<'tcx>),
194 // The given region parameter was instantiated with a region
195 // that must outlive some other region.
196 RelateRegionParamBound(Span),
198 // A bound placed on type parameters that states that must outlive
199 // the moment of their instantiation.
200 RelateDefaultParamBound(Span, Ty<'tcx>),
202 // Creating a pointer `b` to contents of another reference
205 // Creating a pointer `b` to contents of an upvar
206 ReborrowUpvar(Span, ty::UpvarId),
208 // Data with type `Ty<'tcx>` was borrowed
209 DataBorrowed(Ty<'tcx>, Span),
211 // (&'a &'b T) where a >= b
212 ReferenceOutlivesReferent(Ty<'tcx>, Span),
214 // Type or region parameters must be in scope.
215 ParameterInScope(ParameterOrigin, Span),
217 // The type T of an expression E must outlive the lifetime for E.
218 ExprTypeIsNotInScope(Ty<'tcx>, Span),
220 // A `ref b` whose region does not enclose the decl site
221 BindingTypeIsNotValidAtDecl(Span),
223 // Regions appearing in a method receiver must outlive method call
226 // Regions appearing in a function argument must outlive func call
229 // Region in return type of invoked fn must enclose call
232 // Operands must be in scope
235 // Region resulting from a `&` expr must enclose the `&` expr
238 // An auto-borrow that does not enclose the expr where it occurs
241 // Region constraint arriving from destructor safety
242 SafeDestructor(Span),
244 // Comparing the signature and requirements of an impl method against
245 // the containing trait.
246 CompareImplMethodObligation {
248 item_name: ast::Name,
249 impl_item_def_id: DefId,
250 trait_item_def_id: DefId,
252 // this is `Some(_)` if this error arises from the bug fix for
253 // #18937. This is a temporary measure.
254 lint_id: Option<ast::NodeId>,
258 /// Places that type/region parameters can appear.
259 #[derive(Clone, Copy, Debug)]
260 pub enum ParameterOrigin {
262 MethodCall, // foo.bar() <-- parameters on impl providing bar()
263 OverloadedOperator, // a + b when overloaded
264 OverloadedDeref, // *a when overloaded
267 /// Times when we replace late-bound regions with variables:
268 #[derive(Clone, Copy, Debug)]
269 pub enum LateBoundRegionConversionTime {
270 /// when a fn is called
273 /// when two higher-ranked types are compared
276 /// when projecting an associated type
277 AssocTypeProjection(DefId),
280 /// Reasons to create a region inference variable
282 /// See `error_reporting` module for more details
283 #[derive(Clone, Debug)]
284 pub enum RegionVariableOrigin {
285 // Region variables created for ill-categorized reasons,
286 // mostly indicates places in need of refactoring
289 // Regions created by a `&P` or `[...]` pattern
292 // Regions created by `&` operator
295 // Regions created as part of an autoref of a method receiver
298 // Regions created as part of an automatic coercion
301 // Region variables created as the values for early-bound regions
302 EarlyBoundRegion(Span, ast::Name),
304 // Region variables created for bound regions
305 // in a function or method that is called
306 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
308 UpvarRegion(ty::UpvarId, Span),
310 BoundRegionInCoherence(ast::Name),
313 #[derive(Copy, Clone, Debug)]
314 pub enum FixupError {
315 UnresolvedIntTy(IntVid),
316 UnresolvedFloatTy(FloatVid),
320 impl fmt::Display for FixupError {
321 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
322 use self::FixupError::*;
325 UnresolvedIntTy(_) => {
326 write!(f, "cannot determine the type of this integer; \
327 add a suffix to specify the type explicitly")
329 UnresolvedFloatTy(_) => {
330 write!(f, "cannot determine the type of this number; \
331 add a suffix to specify the type explicitly")
333 UnresolvedTy(_) => write!(f, "unconstrained type")
338 /// Helper type of a temporary returned by tcx.infer_ctxt().
339 /// Necessary because we can't write the following bound:
340 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
341 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
342 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
343 arena: DroplessArena,
344 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
347 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
348 pub fn infer_ctxt(self) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
351 arena: DroplessArena::new(),
358 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
359 /// Used only by `rustc_typeck` during body type-checking/inference,
360 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
361 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
362 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
366 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
367 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
369 let InferCtxtBuilder {
374 let in_progress_tables = fresh_tables.as_ref();
375 global_tcx.enter_local(arena, |tcx| f(InferCtxt {
378 projection_cache: RefCell::new(traits::ProjectionCache::new()),
379 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
380 int_unification_table: RefCell::new(UnificationTable::new()),
381 float_unification_table: RefCell::new(UnificationTable::new()),
382 region_vars: RegionVarBindings::new(tcx),
383 selection_cache: traits::SelectionCache::new(),
384 evaluation_cache: traits::EvaluationCache::new(),
385 reported_trait_errors: RefCell::new(FxHashMap()),
386 tainted_by_errors_flag: Cell::new(false),
387 err_count_on_creation: tcx.sess.err_count(),
388 in_snapshot: Cell::new(false),
393 impl<T> ExpectedFound<T> {
394 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
396 ExpectedFound {expected: a, found: b}
398 ExpectedFound {expected: b, found: a}
403 impl<'tcx, T> InferOk<'tcx, T> {
404 pub fn unit(self) -> InferOk<'tcx, ()> {
405 InferOk { value: (), obligations: self.obligations }
409 #[must_use = "once you start a snapshot, you should always consume it"]
410 pub struct CombinedSnapshot<'a, 'tcx:'a> {
411 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
412 type_snapshot: type_variable::Snapshot,
413 int_snapshot: unify::Snapshot<ty::IntVid>,
414 float_snapshot: unify::Snapshot<ty::FloatVid>,
415 region_vars_snapshot: RegionSnapshot,
416 was_in_snapshot: bool,
417 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
420 /// Helper trait for shortening the lifetimes inside a
421 /// value for post-type-checking normalization.
422 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
423 fn trans_normalize<'a, 'tcx>(&self,
424 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
425 param_env: ty::ParamEnv<'tcx>)
429 macro_rules! items { ($($item:item)+) => ($($item)+) }
430 macro_rules! impl_trans_normalize {
431 ($lt_gcx:tt, $($ty:ty),+) => {
432 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
433 fn trans_normalize<'a, 'tcx>(&self,
434 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>,
435 param_env: ty::ParamEnv<'tcx>)
437 infcx.normalize_projections_in(param_env, self)
443 impl_trans_normalize!('gcx,
448 ty::ClosureSubsts<'gcx>,
449 ty::PolyTraitRef<'gcx>,
450 ty::ExistentialTraitRef<'gcx>
453 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
454 fn trans_normalize<'a, 'tcx>(&self,
455 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
456 param_env: ty::ParamEnv<'tcx>)
459 LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx, param_env) },
460 LvalueTy::Downcast { adt_def, substs, variant_index } => {
463 substs: substs.trans_normalize(infcx, param_env),
471 // NOTE: Callable from trans only!
472 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
473 /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
474 /// each time we erase them in translation, we need to normalize
476 pub fn erase_late_bound_regions_and_normalize<T>(self, value: &ty::Binder<T>)
478 where T: TransNormalize<'tcx>
480 assert!(!value.needs_subst());
481 let value = self.erase_late_bound_regions(value);
482 self.normalize_associated_type(&value)
485 /// Fully normalizes any associated types in `value`, using an
486 /// empty environment and `Reveal::All` mode (therefore, suitable
487 /// only for monomorphized code during trans, basically).
488 pub fn normalize_associated_type<T>(self, value: &T) -> T
489 where T: TransNormalize<'tcx>
491 debug!("normalize_associated_type(t={:?})", value);
493 let param_env = ty::ParamEnv::empty(Reveal::All);
494 let value = self.erase_regions(value);
496 if !value.has_projection_types() {
500 self.infer_ctxt().enter(|infcx| {
501 value.trans_normalize(&infcx, param_env)
505 /// Does a best-effort to normalize any associated types in
506 /// `value`; this includes revealing specializable types, so this
507 /// should be not be used during type-checking, but only during
508 /// optimization and code generation.
509 pub fn normalize_associated_type_in_env<T>(
510 self, value: &T, env: ty::ParamEnv<'tcx>
512 where T: TransNormalize<'tcx>
514 debug!("normalize_associated_type_in_env(t={:?})", value);
516 let value = self.erase_regions(value);
518 if !value.has_projection_types() {
522 self.infer_ctxt().enter(|infcx| {
523 value.trans_normalize(&infcx, env.reveal_all())
528 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
529 fn normalize_projections_in<T>(&self, param_env: ty::ParamEnv<'tcx>, value: &T) -> T::Lifted
530 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
532 let mut selcx = traits::SelectionContext::new(self);
533 let cause = traits::ObligationCause::dummy();
534 let traits::Normalized { value: result, obligations } =
535 traits::normalize(&mut selcx, param_env, cause, value);
537 debug!("normalize_projections_in: result={:?} obligations={:?}",
538 result, obligations);
540 let mut fulfill_cx = traits::FulfillmentContext::new();
542 for obligation in obligations {
543 fulfill_cx.register_predicate_obligation(self, obligation);
546 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
549 /// Finishes processes any obligations that remain in the
550 /// fulfillment context, and then returns the result with all type
551 /// variables removed and regions erased. Because this is intended
552 /// for use after type-check has completed, if any errors occur,
553 /// it will panic. It is used during normalization and other cases
554 /// where processing the obligations in `fulfill_cx` may cause
555 /// type inference variables that appear in `result` to be
556 /// unified, and hence we need to process those obligations to get
557 /// the complete picture of the type.
558 pub fn drain_fulfillment_cx_or_panic<T>(&self,
560 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
563 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
565 debug!("drain_fulfillment_cx_or_panic()");
567 // In principle, we only need to do this so long as `result`
568 // contains unbound type parameters. It could be a slight
569 // optimization to stop iterating early.
570 match fulfill_cx.select_all_or_error(self) {
573 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
578 let result = self.resolve_type_vars_if_possible(result);
579 let result = self.tcx.erase_regions(&result);
581 match self.tcx.lift_to_global(&result) {
582 Some(result) => result,
584 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
589 pub fn is_in_snapshot(&self) -> bool {
590 self.in_snapshot.get()
593 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
594 t.fold_with(&mut self.freshener())
597 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
599 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
604 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
605 freshen::TypeFreshener::new(self)
608 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
609 use ty::error::UnconstrainedNumeric::Neither;
610 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
612 ty::TyInfer(ty::IntVar(vid)) => {
613 if self.int_unification_table.borrow_mut().has_value(vid) {
619 ty::TyInfer(ty::FloatVar(vid)) => {
620 if self.float_unification_table.borrow_mut().has_value(vid) {
630 /// Returns a type variable's default fallback if any exists. A default
631 /// must be attached to the variable when created, if it is created
632 /// without a default, this will return None.
634 /// This code does not apply to integral or floating point variables,
635 /// only to use declared defaults.
637 /// See `new_ty_var_with_default` to create a type variable with a default.
638 /// See `type_variable::Default` for details about what a default entails.
639 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
641 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
646 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
647 let mut variables = Vec::new();
649 let unbound_ty_vars = self.type_variables
651 .unsolved_variables()
653 .map(|t| self.tcx.mk_var(t));
655 let unbound_int_vars = self.int_unification_table
657 .unsolved_variables()
659 .map(|v| self.tcx.mk_int_var(v));
661 let unbound_float_vars = self.float_unification_table
663 .unsolved_variables()
665 .map(|v| self.tcx.mk_float_var(v));
667 variables.extend(unbound_ty_vars);
668 variables.extend(unbound_int_vars);
669 variables.extend(unbound_float_vars);
674 fn combine_fields(&'a self, trace: TypeTrace<'tcx>, param_env: ty::ParamEnv<'tcx>)
675 -> CombineFields<'a, 'gcx, 'tcx> {
681 obligations: PredicateObligations::new(),
685 // Clear the "currently in a snapshot" flag, invoke the closure,
686 // then restore the flag to its original value. This flag is a
687 // debugging measure designed to detect cases where we start a
688 // snapshot, create type variables, and register obligations
689 // which may involve those type variables in the fulfillment cx,
690 // potentially leaving "dangling type variables" behind.
691 // In such cases, an assertion will fail when attempting to
692 // register obligations, within a snapshot. Very useful, much
693 // better than grovelling through megabytes of RUST_LOG output.
695 // HOWEVER, in some cases the flag is unhelpful. In particular, we
696 // sometimes create a "mini-fulfilment-cx" in which we enroll
697 // obligations. As long as this fulfillment cx is fully drained
698 // before we return, this is not a problem, as there won't be any
699 // escaping obligations in the main cx. In those cases, you can
700 // use this function.
701 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
702 where F: FnOnce(&Self) -> R
704 let flag = self.in_snapshot.get();
705 self.in_snapshot.set(false);
706 let result = func(self);
707 self.in_snapshot.set(flag);
711 fn start_snapshot<'b>(&'b self) -> CombinedSnapshot<'b, 'tcx> {
712 debug!("start_snapshot()");
714 let in_snapshot = self.in_snapshot.get();
715 self.in_snapshot.set(true);
718 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
719 type_snapshot: self.type_variables.borrow_mut().snapshot(),
720 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
721 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
722 region_vars_snapshot: self.region_vars.start_snapshot(),
723 was_in_snapshot: in_snapshot,
724 // Borrow tables "in progress" (i.e. during typeck)
725 // to ban writes from within a snapshot to them.
726 _in_progress_tables: self.in_progress_tables.map(|tables| {
732 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
733 debug!("rollback_to(cause={})", cause);
734 let CombinedSnapshot { projection_cache_snapshot,
738 region_vars_snapshot,
740 _in_progress_tables } = snapshot;
742 self.in_snapshot.set(was_in_snapshot);
744 self.projection_cache
746 .rollback_to(projection_cache_snapshot);
749 .rollback_to(type_snapshot);
750 self.int_unification_table
752 .rollback_to(int_snapshot);
753 self.float_unification_table
755 .rollback_to(float_snapshot);
757 .rollback_to(region_vars_snapshot);
760 fn commit_from(&self, snapshot: CombinedSnapshot) {
761 debug!("commit_from()");
762 let CombinedSnapshot { projection_cache_snapshot,
766 region_vars_snapshot,
768 _in_progress_tables } = snapshot;
770 self.in_snapshot.set(was_in_snapshot);
772 self.projection_cache
774 .commit(projection_cache_snapshot);
777 .commit(type_snapshot);
778 self.int_unification_table
780 .commit(int_snapshot);
781 self.float_unification_table
783 .commit(float_snapshot);
785 .commit(region_vars_snapshot);
788 /// Execute `f` and commit the bindings
789 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
793 let snapshot = self.start_snapshot();
795 self.commit_from(snapshot);
799 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
800 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
801 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
803 debug!("commit_if_ok()");
804 let snapshot = self.start_snapshot();
805 let r = f(&snapshot);
806 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
808 Ok(_) => { self.commit_from(snapshot); }
809 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
814 // Execute `f` in a snapshot, and commit the bindings it creates
815 pub fn in_snapshot<T, F>(&self, f: F) -> T where
816 F: FnOnce(&CombinedSnapshot) -> T
818 debug!("in_snapshot()");
819 let snapshot = self.start_snapshot();
820 let r = f(&snapshot);
821 self.commit_from(snapshot);
825 /// Execute `f` then unroll any bindings it creates
826 pub fn probe<R, F>(&self, f: F) -> R where
827 F: FnOnce(&CombinedSnapshot) -> R,
830 let snapshot = self.start_snapshot();
831 let r = f(&snapshot);
832 self.rollback_to("probe", snapshot);
836 pub fn add_given(&self,
837 sub: ty::Region<'tcx>,
840 self.region_vars.add_given(sub, sup);
843 pub fn can_sub<T>(&self,
844 param_env: ty::ParamEnv<'tcx>,
848 where T: at::ToTrace<'tcx>
850 let origin = &ObligationCause::dummy();
852 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
853 // Ignore obligations, since we are unrolling
854 // everything anyway.
859 pub fn can_eq<T>(&self,
860 param_env: ty::ParamEnv<'tcx>,
864 where T: at::ToTrace<'tcx>
866 let origin = &ObligationCause::dummy();
868 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
869 // Ignore obligations, since we are unrolling
870 // everything anyway.
875 pub fn sub_regions(&self,
876 origin: SubregionOrigin<'tcx>,
878 b: ty::Region<'tcx>) {
879 debug!("sub_regions({:?} <: {:?})", a, b);
880 self.region_vars.make_subregion(origin, a, b);
883 pub fn equality_predicate(&self,
884 cause: &ObligationCause<'tcx>,
885 param_env: ty::ParamEnv<'tcx>,
886 predicate: &ty::PolyEquatePredicate<'tcx>)
887 -> InferResult<'tcx, ()>
889 self.commit_if_ok(|snapshot| {
890 let (ty::EquatePredicate(a, b), skol_map) =
891 self.skolemize_late_bound_regions(predicate, snapshot);
892 let cause_span = cause.span;
893 let eqty_ok = self.at(cause, param_env).eq(b, a)?;
894 self.leak_check(false, cause_span, &skol_map, snapshot)?;
895 self.pop_skolemized(skol_map, snapshot);
900 pub fn subtype_predicate(&self,
901 cause: &ObligationCause<'tcx>,
902 param_env: ty::ParamEnv<'tcx>,
903 predicate: &ty::PolySubtypePredicate<'tcx>)
904 -> Option<InferResult<'tcx, ()>>
906 // Subtle: it's ok to skip the binder here and resolve because
907 // `shallow_resolve` just ignores anything that is not a type
908 // variable, and because type variable's can't (at present, at
909 // least) capture any of the things bound by this binder.
911 // Really, there is no *particular* reason to do this
912 // `shallow_resolve` here except as a
913 // micro-optimization. Naturally I could not
914 // resist. -nmatsakis
915 let two_unbound_type_vars = {
916 let a = self.shallow_resolve(predicate.skip_binder().a);
917 let b = self.shallow_resolve(predicate.skip_binder().b);
918 a.is_ty_var() && b.is_ty_var()
921 if two_unbound_type_vars {
922 // Two unbound type variables? Can't make progress.
926 Some(self.commit_if_ok(|snapshot| {
927 let (ty::SubtypePredicate { a_is_expected, a, b}, skol_map) =
928 self.skolemize_late_bound_regions(predicate, snapshot);
930 let cause_span = cause.span;
931 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
932 self.leak_check(false, cause_span, &skol_map, snapshot)?;
933 self.pop_skolemized(skol_map, snapshot);
938 pub fn region_outlives_predicate(&self,
939 cause: &traits::ObligationCause<'tcx>,
940 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
943 self.commit_if_ok(|snapshot| {
944 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
945 self.skolemize_late_bound_regions(predicate, snapshot);
947 SubregionOrigin::from_obligation_cause(cause,
948 || RelateRegionParamBound(cause.span));
949 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
950 self.leak_check(false, cause.span, &skol_map, snapshot)?;
951 Ok(self.pop_skolemized(skol_map, snapshot))
955 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
958 .new_var(diverging, origin, None)
961 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
962 self.tcx.mk_var(self.next_ty_var_id(false, origin))
965 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
966 self.tcx.mk_var(self.next_ty_var_id(true, origin))
969 pub fn next_int_var_id(&self) -> IntVid {
970 self.int_unification_table
975 pub fn next_float_var_id(&self) -> FloatVid {
976 self.float_unification_table
981 pub fn next_region_var(&self, origin: RegionVariableOrigin)
982 -> ty::Region<'tcx> {
983 self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
986 /// Create a region inference variable for the given
987 /// region parameter definition.
988 pub fn region_var_for_def(&self,
990 def: &ty::RegionParameterDef)
991 -> ty::Region<'tcx> {
992 self.next_region_var(EarlyBoundRegion(span, def.name))
995 /// Create a type inference variable for the given
996 /// type parameter definition. The substitutions are
997 /// for actual parameters that may be referred to by
998 /// the default of this type parameter, if it exists.
999 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1000 /// used in a path such as `Foo::<T, U>::new()` will
1001 /// use an inference variable for `C` with `[T, U]`
1002 /// as the substitutions for the default, `(T, U)`.
1003 pub fn type_var_for_def(&self,
1005 def: &ty::TypeParameterDef,
1006 substs: &[Kind<'tcx>])
1008 let default = if def.has_default {
1009 let default = self.tcx.type_of(def.def_id);
1010 Some(type_variable::Default {
1011 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1020 let ty_var_id = self.type_variables
1023 TypeVariableOrigin::TypeParameterDefinition(span, def.name),
1026 self.tcx.mk_var(ty_var_id)
1029 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1030 /// type/region parameter to a fresh inference variable.
1031 pub fn fresh_substs_for_item(&self,
1034 -> &'tcx Substs<'tcx> {
1035 Substs::for_item(self.tcx, def_id, |def, _| {
1036 self.region_var_for_def(span, def)
1038 self.type_var_for_def(span, def, substs)
1042 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region<'tcx> {
1043 self.region_vars.new_bound(debruijn)
1046 /// True if errors have been reported since this infcx was
1047 /// created. This is sometimes used as a heuristic to skip
1048 /// reporting errors that often occur as a result of earlier
1049 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1050 /// inference variables, regionck errors).
1051 pub fn is_tainted_by_errors(&self) -> bool {
1052 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1053 tainted_by_errors_flag={})",
1054 self.tcx.sess.err_count(),
1055 self.err_count_on_creation,
1056 self.tainted_by_errors_flag.get());
1058 if self.tcx.sess.err_count() > self.err_count_on_creation {
1059 return true; // errors reported since this infcx was made
1061 self.tainted_by_errors_flag.get()
1064 /// Set the "tainted by errors" flag to true. We call this when we
1065 /// observe an error from a prior pass.
1066 pub fn set_tainted_by_errors(&self) {
1067 debug!("set_tainted_by_errors()");
1068 self.tainted_by_errors_flag.set(true)
1071 pub fn resolve_regions_and_report_errors(&self,
1072 region_context: DefId,
1073 region_map: ®ion::ScopeTree,
1074 free_regions: &FreeRegionMap<'tcx>) {
1075 let region_rels = RegionRelations::new(self.tcx,
1079 let errors = self.region_vars.resolve_regions(®ion_rels);
1081 if !self.is_tainted_by_errors() {
1082 // As a heuristic, just skip reporting region errors
1083 // altogether if other errors have been reported while
1084 // this infcx was in use. This is totally hokey but
1085 // otherwise we have a hard time separating legit region
1086 // errors from silly ones.
1087 self.report_region_errors(region_map, &errors); // see error_reporting module
1091 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1092 self.resolve_type_vars_if_possible(&t).to_string()
1095 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1096 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1097 format!("({})", tstrs.join(", "))
1100 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1101 self.resolve_type_vars_if_possible(t).to_string()
1104 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1106 ty::TyInfer(ty::TyVar(v)) => {
1107 // Not entirely obvious: if `typ` is a type variable,
1108 // it can be resolved to an int/float variable, which
1109 // can then be recursively resolved, hence the
1110 // recursion. Note though that we prevent type
1111 // variables from unifying to other type variables
1112 // directly (though they may be embedded
1113 // structurally), and we prevent cycles in any case,
1114 // so this recursion should always be of very limited
1116 self.type_variables.borrow_mut()
1118 .map(|t| self.shallow_resolve(t))
1122 ty::TyInfer(ty::IntVar(v)) => {
1123 self.int_unification_table
1126 .map(|v| v.to_type(self.tcx))
1130 ty::TyInfer(ty::FloatVar(v)) => {
1131 self.float_unification_table
1134 .map(|v| v.to_type(self.tcx))
1144 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1145 where T: TypeFoldable<'tcx>
1148 * Where possible, replaces type/int/float variables in
1149 * `value` with their final value. Note that region variables
1150 * are unaffected. If a type variable has not been unified, it
1151 * is left as is. This is an idempotent operation that does
1152 * not affect inference state in any way and so you can do it
1156 if !value.needs_infer() {
1157 return value.clone(); // avoid duplicated subst-folding
1159 let mut r = resolve::OpportunisticTypeResolver::new(self);
1160 value.fold_with(&mut r)
1163 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1164 where T: TypeFoldable<'tcx>
1166 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1167 value.fold_with(&mut r)
1170 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1172 * Attempts to resolve all type/region variables in
1173 * `value`. Region inference must have been run already (e.g.,
1174 * by calling `resolve_regions_and_report_errors`). If some
1175 * variable was never unified, an `Err` results.
1177 * This method is idempotent, but it not typically not invoked
1178 * except during the writeback phase.
1181 resolve::fully_resolve(self, value)
1184 // [Note-Type-error-reporting]
1185 // An invariant is that anytime the expected or actual type is TyError (the special
1186 // error type, meaning that an error occurred when typechecking this expression),
1187 // this is a derived error. The error cascaded from another error (that was already
1188 // reported), so it's not useful to display it to the user.
1189 // The following methods implement this logic.
1190 // They check if either the actual or expected type is TyError, and don't print the error
1191 // in this case. The typechecker should only ever report type errors involving mismatched
1192 // types using one of these methods, and should not call span_err directly for such
1195 pub fn type_error_struct_with_diag<M>(&self,
1198 actual_ty: Ty<'tcx>)
1199 -> DiagnosticBuilder<'tcx>
1200 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1202 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1203 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1205 // Don't report an error if actual type is TyError.
1206 if actual_ty.references_error() {
1207 return self.tcx.sess.diagnostic().struct_dummy();
1210 mk_diag(self.ty_to_string(actual_ty))
1213 pub fn report_mismatched_types(&self,
1214 cause: &ObligationCause<'tcx>,
1217 err: TypeError<'tcx>)
1218 -> DiagnosticBuilder<'tcx> {
1219 let trace = TypeTrace::types(cause, true, expected, actual);
1220 self.report_and_explain_type_error(trace, &err)
1223 pub fn report_conflicting_default_types(&self,
1225 body_id: ast::NodeId,
1226 expected: type_variable::Default<'tcx>,
1227 actual: type_variable::Default<'tcx>) {
1228 let trace = TypeTrace {
1229 cause: ObligationCause::misc(span, body_id),
1230 values: Types(ExpectedFound {
1231 expected: expected.ty,
1236 self.report_and_explain_type_error(
1238 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1245 pub fn replace_late_bound_regions_with_fresh_var<T>(
1248 lbrct: LateBoundRegionConversionTime,
1249 value: &ty::Binder<T>)
1250 -> (T, FxHashMap<ty::BoundRegion, ty::Region<'tcx>>)
1251 where T : TypeFoldable<'tcx>
1253 self.tcx.replace_late_bound_regions(
1255 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1258 /// Given a higher-ranked projection predicate like:
1260 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1262 /// and a target trait-ref like:
1264 /// <T as Fn<&'x u32>>
1266 /// find a substitution `S` for the higher-ranked regions (here,
1267 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1268 /// and then return the value (here, `&'a u32`) but with the
1269 /// substitution applied (hence, `&'x u32`).
1271 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1273 pub fn match_poly_projection_predicate(&self,
1274 cause: ObligationCause<'tcx>,
1275 param_env: ty::ParamEnv<'tcx>,
1276 match_a: ty::PolyProjectionPredicate<'tcx>,
1277 match_b: ty::TraitRef<'tcx>)
1278 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1280 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref(self.tcx), p.ty));
1281 let trace = TypeTrace {
1283 values: TraitRefs(ExpectedFound::new(true, match_pair.skip_binder().0, match_b))
1286 let mut combine = self.combine_fields(trace, param_env);
1287 let result = combine.higher_ranked_match(&match_pair, &match_b, true)?;
1288 Ok(InferOk { value: result, obligations: combine.obligations })
1291 /// See `verify_generic_bound` method in `region_inference`
1292 pub fn verify_generic_bound(&self,
1293 origin: SubregionOrigin<'tcx>,
1294 kind: GenericKind<'tcx>,
1295 a: ty::Region<'tcx>,
1296 bound: VerifyBound<'tcx>) {
1297 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1302 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1305 pub fn type_moves_by_default(&self,
1306 param_env: ty::ParamEnv<'tcx>,
1310 let ty = self.resolve_type_vars_if_possible(&ty);
1311 // Even if the type may have no inference variables, during
1312 // type-checking closure types are in local tables only.
1313 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1314 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1315 return ty.moves_by_default(self.tcx.global_tcx(), param_env, span);
1319 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1321 // this can get called from typeck (by euv), and moves_by_default
1322 // rightly refuses to work with inference variables, but
1323 // moves_by_default has a cache, which we want to use in other
1325 !traits::type_known_to_meet_bound(self, param_env, ty, copy_def_id, span)
1328 pub fn closure_kind(&self,
1330 -> Option<ty::ClosureKind>
1332 if let Some(tables) = self.in_progress_tables {
1333 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1334 let hir_id = self.tcx.hir.node_to_hir_id(id);
1335 return tables.borrow()
1339 .map(|(kind, _)| kind);
1343 // During typeck, ALL closures are local. But afterwards,
1344 // during trans, we see closure ids from other traits.
1345 // That may require loading the closure data out of the
1347 Some(self.tcx.closure_kind(def_id))
1350 /// Obtain the signature of a function or closure.
1351 /// For closures, unlike `tcx.fn_sig(def_id)`, this method will
1352 /// work during the type-checking of the enclosing function and
1353 /// return the closure signature in its partially inferred state.
1354 pub fn fn_sig(&self, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1355 if let Some(tables) = self.in_progress_tables {
1356 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1357 let hir_id = self.tcx.hir.node_to_hir_id(id);
1358 if let Some(&ty) = tables.borrow().closure_tys().get(hir_id) {
1364 self.tcx.fn_sig(def_id)
1367 pub fn generator_sig(&self, def_id: DefId) -> Option<ty::PolyGenSig<'tcx>> {
1368 if let Some(tables) = self.in_progress_tables {
1369 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1370 let hir_id = self.tcx.hir.node_to_hir_id(id);
1371 if let Some(&ty) = tables.borrow().generator_sigs().get(hir_id) {
1372 return ty.map(|t| ty::Binder(t));
1377 self.tcx.generator_sig(def_id)
1381 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1382 pub fn span(&self) -> Span {
1386 pub fn types(cause: &ObligationCause<'tcx>,
1387 a_is_expected: bool,
1390 -> TypeTrace<'tcx> {
1392 cause: cause.clone(),
1393 values: Types(ExpectedFound::new(a_is_expected, a, b))
1397 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1399 cause: ObligationCause::dummy(),
1400 values: Types(ExpectedFound {
1401 expected: tcx.types.err,
1402 found: tcx.types.err,
1408 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1409 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1410 write!(f, "TypeTrace({:?})", self.cause)
1414 impl<'tcx> SubregionOrigin<'tcx> {
1415 pub fn span(&self) -> Span {
1417 Subtype(ref a) => a.span(),
1418 InfStackClosure(a) => a,
1419 InvokeClosure(a) => a,
1420 DerefPointer(a) => a,
1421 FreeVariable(a, _) => a,
1423 RelateObjectBound(a) => a,
1424 RelateParamBound(a, _) => a,
1425 RelateRegionParamBound(a) => a,
1426 RelateDefaultParamBound(a, _) => a,
1428 ReborrowUpvar(a, _) => a,
1429 DataBorrowed(_, a) => a,
1430 ReferenceOutlivesReferent(_, a) => a,
1431 ParameterInScope(_, a) => a,
1432 ExprTypeIsNotInScope(_, a) => a,
1433 BindingTypeIsNotValidAtDecl(a) => a,
1440 SafeDestructor(a) => a,
1441 CompareImplMethodObligation { span, .. } => span,
1445 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>,
1448 where F: FnOnce() -> Self
1451 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
1452 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span),
1454 traits::ObligationCauseCode::CompareImplMethodObligation { item_name,
1458 SubregionOrigin::CompareImplMethodObligation {
1471 impl RegionVariableOrigin {
1472 pub fn span(&self) -> Span {
1474 MiscVariable(a) => a,
1475 PatternRegion(a) => a,
1476 AddrOfRegion(a) => a,
1479 EarlyBoundRegion(a, ..) => a,
1480 LateBoundRegion(a, ..) => a,
1481 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1482 UpvarRegion(_, a) => a
1487 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1488 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1490 ValuePairs::Types(ref ef) => {
1491 ValuePairs::Types(ef.fold_with(folder))
1493 ValuePairs::TraitRefs(ref ef) => {
1494 ValuePairs::TraitRefs(ef.fold_with(folder))
1496 ValuePairs::PolyTraitRefs(ref ef) => {
1497 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1502 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1504 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1505 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1506 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1511 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1512 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1514 cause: self.cause.fold_with(folder),
1515 values: self.values.fold_with(folder)
1519 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1520 self.cause.visit_with(visitor) || self.values.visit_with(visitor)