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;
23 use middle::free_region::FreeRegionMap;
24 use middle::mem_categorization as mc;
25 use middle::mem_categorization::McResult;
26 use middle::region::CodeExtent;
27 use mir::tcx::LvalueTy;
28 use ty::subst::{Subst, Substs};
30 use ty::{TyVid, IntVid, FloatVid};
31 use ty::{self, Ty, TyCtxt};
32 use ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
33 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
34 use ty::relate::{Relate, RelateResult, TypeRelation};
35 use traits::{self, PredicateObligations, Reveal};
36 use rustc_data_structures::unify::{self, UnificationTable};
37 use std::cell::{Cell, RefCell, Ref, RefMut};
40 use errors::DiagnosticBuilder;
41 use syntax_pos::{self, Span, DUMMY_SP};
42 use util::nodemap::{FnvHashMap, FnvHashSet, NodeMap};
44 use self::combine::CombineFields;
45 use self::higher_ranked::HrMatchResult;
46 use self::region_inference::{RegionVarBindings, RegionSnapshot};
47 use self::unify_key::ToType;
52 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 /// A version of &ty::Tables which can be global or local.
76 /// Only the local version supports borrow_mut.
77 #[derive(Copy, Clone)]
78 pub enum InferTables<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
79 Global(&'a RefCell<ty::Tables<'gcx>>),
80 Local(&'a RefCell<ty::Tables<'tcx>>)
83 impl<'a, 'gcx, 'tcx> InferTables<'a, 'gcx, 'tcx> {
84 pub fn borrow(self) -> Ref<'a, ty::Tables<'tcx>> {
86 InferTables::Global(tables) => tables.borrow(),
87 InferTables::Local(tables) => tables.borrow()
91 pub fn borrow_mut(self) -> RefMut<'a, ty::Tables<'tcx>> {
93 InferTables::Global(_) => {
94 bug!("InferTables: infcx.tables.borrow_mut() outside of type-checking");
96 InferTables::Local(tables) => tables.borrow_mut()
101 pub struct InferCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
102 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
104 pub tables: InferTables<'a, 'gcx, 'tcx>,
106 // Cache for projections. This cache is snapshotted along with the
109 // Public so that `traits::project` can use it.
110 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
112 // We instantiate UnificationTable with bounds<Ty> because the
113 // types that might instantiate a general type variable have an
114 // order, represented by its upper and lower bounds.
115 type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
117 // Map from integral variable to the kind of integer it represents
118 int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
120 // Map from floating variable to the kind of float it represents
121 float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
123 // For region variables.
124 region_vars: RegionVarBindings<'a, 'gcx, 'tcx>,
126 pub parameter_environment: ty::ParameterEnvironment<'gcx>,
128 /// Caches the results of trait selection. This cache is used
129 /// for things that have to do with the parameters in scope.
130 pub selection_cache: traits::SelectionCache<'tcx>,
132 /// Caches the results of trait evaluation.
133 pub evaluation_cache: traits::EvaluationCache<'tcx>,
135 // the set of predicates on which errors have been reported, to
136 // avoid reporting the same error twice.
137 pub reported_trait_errors: RefCell<FnvHashSet<traits::TraitErrorKey<'tcx>>>,
139 // Sadly, the behavior of projection varies a bit depending on the
140 // stage of compilation. The specifics are given in the
141 // documentation for `Reveal`.
142 projection_mode: Reveal,
144 // When an error occurs, we want to avoid reporting "derived"
145 // errors that are due to this original failure. Normally, we
146 // handle this with the `err_count_on_creation` count, which
147 // basically just tracks how many errors were reported when we
148 // started type-checking a fn and checks to see if any new errors
149 // have been reported since then. Not great, but it works.
151 // However, when errors originated in other passes -- notably
152 // resolve -- this heuristic breaks down. Therefore, we have this
153 // auxiliary flag that one can set whenever one creates a
154 // type-error that is due to an error in a prior pass.
156 // Don't read this flag directly, call `is_tainted_by_errors()`
157 // and `set_tainted_by_errors()`.
158 tainted_by_errors_flag: Cell<bool>,
160 // Track how many errors were reported when this infcx is created.
161 // If the number of errors increases, that's also a sign (line
162 // `tained_by_errors`) to avoid reporting certain kinds of errors.
163 err_count_on_creation: usize,
165 // This flag is used for debugging, and is set to true if there are
166 // any obligations set during the current snapshot. In that case, the
167 // snapshot can't be rolled back.
168 pub obligations_in_snapshot: Cell<bool>,
171 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
172 /// region that each late-bound region was replaced with.
173 pub type SkolemizationMap<'tcx> = FnvHashMap<ty::BoundRegion, &'tcx ty::Region>;
175 /// Why did we require that the two types be related?
177 /// See `error_reporting.rs` for more details
178 #[derive(Clone, Copy, Debug)]
179 pub enum TypeOrigin {
180 // Not yet categorized in a better way
183 // Checking that method of impl is compatible with trait
184 MethodCompatCheck(Span),
186 // Checking that this expression can be assigned where it needs to be
187 // FIXME(eddyb) #11161 is the original Expr required?
188 ExprAssignable(Span),
190 // Relating trait type parameters to those found in impl etc
191 RelateOutputImplTypes(Span),
193 // Computing common supertype in the arms of a match expression
194 MatchExpressionArm(Span, Span, hir::MatchSource),
196 // Computing common supertype in an if expression
199 // Computing common supertype of an if expression with no else counter-part
200 IfExpressionWithNoElse(Span),
202 // Computing common supertype in a range expression
203 RangeExpression(Span),
206 EquatePredicate(Span),
208 // `main` has wrong type
209 MainFunctionType(Span),
211 // `start` has wrong type
212 StartFunctionType(Span),
214 // intrinsic has wrong type
218 MethodReceiver(Span),
222 fn as_failure_str(&self) -> &'static str {
224 &TypeOrigin::Misc(_) |
225 &TypeOrigin::RelateOutputImplTypes(_) |
226 &TypeOrigin::ExprAssignable(_) => "mismatched types",
227 &TypeOrigin::MethodCompatCheck(_) => "method not compatible with trait",
228 &TypeOrigin::MatchExpressionArm(_, _, source) => match source {
229 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
230 _ => "match arms have incompatible types",
232 &TypeOrigin::IfExpression(_) => "if and else have incompatible types",
233 &TypeOrigin::IfExpressionWithNoElse(_) => "if may be missing an else clause",
234 &TypeOrigin::RangeExpression(_) => "start and end of range have incompatible types",
235 &TypeOrigin::EquatePredicate(_) => "equality predicate not satisfied",
236 &TypeOrigin::MainFunctionType(_) => "main function has wrong type",
237 &TypeOrigin::StartFunctionType(_) => "start function has wrong type",
238 &TypeOrigin::IntrinsicType(_) => "intrinsic has wrong type",
239 &TypeOrigin::MethodReceiver(_) => "mismatched method receiver",
243 fn as_requirement_str(&self) -> &'static str {
245 &TypeOrigin::Misc(_) => "types are compatible",
246 &TypeOrigin::MethodCompatCheck(_) => "method type is compatible with trait",
247 &TypeOrigin::ExprAssignable(_) => "expression is assignable",
248 &TypeOrigin::RelateOutputImplTypes(_) => {
249 "trait type parameters matches those specified on the impl"
251 &TypeOrigin::MatchExpressionArm(_, _, _) => "match arms have compatible types",
252 &TypeOrigin::IfExpression(_) => "if and else have compatible types",
253 &TypeOrigin::IfExpressionWithNoElse(_) => "if missing an else returns ()",
254 &TypeOrigin::RangeExpression(_) => "start and end of range have compatible types",
255 &TypeOrigin::EquatePredicate(_) => "equality where clause is satisfied",
256 &TypeOrigin::MainFunctionType(_) => "`main` function has the correct type",
257 &TypeOrigin::StartFunctionType(_) => "`start` function has the correct type",
258 &TypeOrigin::IntrinsicType(_) => "intrinsic has the correct type",
259 &TypeOrigin::MethodReceiver(_) => "method receiver has the correct type",
264 /// See `error_reporting.rs` for more details
265 #[derive(Clone, Debug)]
266 pub enum ValuePairs<'tcx> {
267 Types(ExpectedFound<Ty<'tcx>>),
268 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
269 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
272 /// The trace designates the path through inference that we took to
273 /// encounter an error or subtyping constraint.
275 /// See `error_reporting.rs` for more details.
277 pub struct TypeTrace<'tcx> {
279 values: ValuePairs<'tcx>,
282 /// The origin of a `r1 <= r2` constraint.
284 /// See `error_reporting.rs` for more details
285 #[derive(Clone, Debug)]
286 pub enum SubregionOrigin<'tcx> {
287 // Arose from a subtyping relation
288 Subtype(TypeTrace<'tcx>),
290 // Stack-allocated closures cannot outlive innermost loop
291 // or function so as to ensure we only require finite stack
292 InfStackClosure(Span),
294 // Invocation of closure must be within its lifetime
297 // Dereference of reference must be within its lifetime
300 // Closure bound must not outlive captured free variables
301 FreeVariable(Span, ast::NodeId),
303 // Index into slice must be within its lifetime
306 // When casting `&'a T` to an `&'b Trait` object,
307 // relating `'a` to `'b`
308 RelateObjectBound(Span),
310 // Some type parameter was instantiated with the given type,
311 // and that type must outlive some region.
312 RelateParamBound(Span, Ty<'tcx>),
314 // The given region parameter was instantiated with a region
315 // that must outlive some other region.
316 RelateRegionParamBound(Span),
318 // A bound placed on type parameters that states that must outlive
319 // the moment of their instantiation.
320 RelateDefaultParamBound(Span, Ty<'tcx>),
322 // Creating a pointer `b` to contents of another reference
325 // Creating a pointer `b` to contents of an upvar
326 ReborrowUpvar(Span, ty::UpvarId),
328 // Data with type `Ty<'tcx>` was borrowed
329 DataBorrowed(Ty<'tcx>, Span),
331 // (&'a &'b T) where a >= b
332 ReferenceOutlivesReferent(Ty<'tcx>, Span),
334 // Type or region parameters must be in scope.
335 ParameterInScope(ParameterOrigin, Span),
337 // The type T of an expression E must outlive the lifetime for E.
338 ExprTypeIsNotInScope(Ty<'tcx>, Span),
340 // A `ref b` whose region does not enclose the decl site
341 BindingTypeIsNotValidAtDecl(Span),
343 // Regions appearing in a method receiver must outlive method call
346 // Regions appearing in a function argument must outlive func call
349 // Region in return type of invoked fn must enclose call
352 // Operands must be in scope
355 // Region resulting from a `&` expr must enclose the `&` expr
358 // An auto-borrow that does not enclose the expr where it occurs
361 // Region constraint arriving from destructor safety
362 SafeDestructor(Span),
365 /// Places that type/region parameters can appear.
366 #[derive(Clone, Copy, Debug)]
367 pub enum ParameterOrigin {
369 MethodCall, // foo.bar() <-- parameters on impl providing bar()
370 OverloadedOperator, // a + b when overloaded
371 OverloadedDeref, // *a when overloaded
374 /// Times when we replace late-bound regions with variables:
375 #[derive(Clone, Copy, Debug)]
376 pub enum LateBoundRegionConversionTime {
377 /// when a fn is called
380 /// when two higher-ranked types are compared
383 /// when projecting an associated type
384 AssocTypeProjection(ast::Name),
387 /// Reasons to create a region inference variable
389 /// See `error_reporting.rs` for more details
390 #[derive(Clone, Debug)]
391 pub enum RegionVariableOrigin {
392 // Region variables created for ill-categorized reasons,
393 // mostly indicates places in need of refactoring
396 // Regions created by a `&P` or `[...]` pattern
399 // Regions created by `&` operator
402 // Regions created as part of an autoref of a method receiver
405 // Regions created as part of an automatic coercion
408 // Region variables created as the values for early-bound regions
409 EarlyBoundRegion(Span, ast::Name),
411 // Region variables created for bound regions
412 // in a function or method that is called
413 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
415 UpvarRegion(ty::UpvarId, Span),
417 BoundRegionInCoherence(ast::Name),
420 #[derive(Copy, Clone, Debug)]
421 pub enum FixupError {
422 UnresolvedIntTy(IntVid),
423 UnresolvedFloatTy(FloatVid),
427 impl fmt::Display for FixupError {
428 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
429 use self::FixupError::*;
432 UnresolvedIntTy(_) => {
433 write!(f, "cannot determine the type of this integer; \
434 add a suffix to specify the type explicitly")
436 UnresolvedFloatTy(_) => {
437 write!(f, "cannot determine the type of this number; \
438 add a suffix to specify the type explicitly")
440 UnresolvedTy(_) => write!(f, "unconstrained type")
445 /// Helper type of a temporary returned by tcx.infer_ctxt(...).
446 /// Necessary because we can't write the following bound:
447 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
448 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
449 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
450 arenas: ty::CtxtArenas<'tcx>,
451 tables: Option<RefCell<ty::Tables<'tcx>>>,
452 param_env: Option<ty::ParameterEnvironment<'gcx>>,
453 projection_mode: Reveal,
456 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
457 pub fn infer_ctxt(self,
458 tables: Option<ty::Tables<'tcx>>,
459 param_env: Option<ty::ParameterEnvironment<'gcx>>,
460 projection_mode: Reveal)
461 -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
464 arenas: ty::CtxtArenas::new(),
465 tables: tables.map(RefCell::new),
466 param_env: param_env,
467 projection_mode: projection_mode,
471 /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
472 /// for MemCategorizationContext/ExprUseVisitor.
473 /// If any inference functionality is used, ICEs will occur.
474 pub fn borrowck_fake_infer_ctxt(self, param_env: ty::ParameterEnvironment<'gcx>)
475 -> InferCtxt<'a, 'gcx, 'gcx> {
478 tables: InferTables::Global(&self.tables),
479 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
480 int_unification_table: RefCell::new(UnificationTable::new()),
481 float_unification_table: RefCell::new(UnificationTable::new()),
482 region_vars: RegionVarBindings::new(self),
483 parameter_environment: param_env,
484 selection_cache: traits::SelectionCache::new(),
485 evaluation_cache: traits::EvaluationCache::new(),
486 projection_cache: RefCell::new(traits::ProjectionCache::new()),
487 reported_trait_errors: RefCell::new(FnvHashSet()),
488 projection_mode: Reveal::NotSpecializable,
489 tainted_by_errors_flag: Cell::new(false),
490 err_count_on_creation: self.sess.err_count(),
491 obligations_in_snapshot: Cell::new(false),
496 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
497 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
498 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
500 let InferCtxtBuilder {
507 let tables = if let Some(ref tables) = *tables {
508 InferTables::Local(tables)
510 InferTables::Global(&global_tcx.tables)
512 let param_env = param_env.take().unwrap_or_else(|| {
513 global_tcx.empty_parameter_environment()
515 global_tcx.enter_local(arenas, |tcx| f(InferCtxt {
518 projection_cache: RefCell::new(traits::ProjectionCache::new()),
519 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
520 int_unification_table: RefCell::new(UnificationTable::new()),
521 float_unification_table: RefCell::new(UnificationTable::new()),
522 region_vars: RegionVarBindings::new(tcx),
523 parameter_environment: param_env,
524 selection_cache: traits::SelectionCache::new(),
525 evaluation_cache: traits::EvaluationCache::new(),
526 reported_trait_errors: RefCell::new(FnvHashSet()),
527 projection_mode: projection_mode,
528 tainted_by_errors_flag: Cell::new(false),
529 err_count_on_creation: tcx.sess.err_count(),
530 obligations_in_snapshot: Cell::new(false),
535 impl<T> ExpectedFound<T> {
536 fn new(a_is_expected: bool, a: T, b: T) -> Self {
538 ExpectedFound {expected: a, found: b}
540 ExpectedFound {expected: b, found: a}
545 impl<'tcx, T> InferOk<'tcx, T> {
546 pub fn unit(self) -> InferOk<'tcx, ()> {
547 InferOk { value: (), obligations: self.obligations }
551 #[must_use = "once you start a snapshot, you should always consume it"]
552 pub struct CombinedSnapshot {
553 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
554 type_snapshot: type_variable::Snapshot,
555 int_snapshot: unify::Snapshot<ty::IntVid>,
556 float_snapshot: unify::Snapshot<ty::FloatVid>,
557 region_vars_snapshot: RegionSnapshot,
558 obligations_in_snapshot: bool,
561 /// Helper trait for shortening the lifetimes inside a
562 /// value for post-type-checking normalization.
563 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
564 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self;
567 macro_rules! items { ($($item:item)+) => ($($item)+) }
568 macro_rules! impl_trans_normalize {
569 ($lt_gcx:tt, $($ty:ty),+) => {
570 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
571 fn trans_normalize<'a, 'tcx>(&self,
572 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>)
574 infcx.normalize_projections_in(self)
580 impl_trans_normalize!('gcx,
584 &'gcx ty::BareFnTy<'gcx>,
585 ty::ClosureSubsts<'gcx>,
586 ty::PolyTraitRef<'gcx>
589 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
590 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self {
592 LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx) },
593 LvalueTy::Downcast { adt_def, substs, variant_index } => {
596 substs: substs.trans_normalize(infcx),
597 variant_index: variant_index
604 // NOTE: Callable from trans only!
605 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
606 pub fn normalize_associated_type<T>(self, value: &T) -> T
607 where T: TransNormalize<'tcx>
609 debug!("normalize_associated_type(t={:?})", value);
611 let value = self.erase_regions(value);
613 if !value.has_projection_types() {
617 self.infer_ctxt(None, None, Reveal::All).enter(|infcx| {
618 value.trans_normalize(&infcx)
622 pub fn normalize_associated_type_in_env<T>(
623 self, value: &T, env: &'a ty::ParameterEnvironment<'tcx>
625 where T: TransNormalize<'tcx>
627 debug!("normalize_associated_type_in_env(t={:?})", value);
629 let value = self.erase_regions(value);
631 if !value.has_projection_types() {
635 self.infer_ctxt(None, Some(env.clone()), Reveal::All).enter(|infcx| {
636 value.trans_normalize(&infcx)
641 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
642 fn normalize_projections_in<T>(&self, value: &T) -> T::Lifted
643 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
645 let mut selcx = traits::SelectionContext::new(self);
646 let cause = traits::ObligationCause::dummy();
647 let traits::Normalized { value: result, obligations } =
648 traits::normalize(&mut selcx, cause, value);
650 debug!("normalize_projections_in: result={:?} obligations={:?}",
651 result, obligations);
653 let mut fulfill_cx = traits::FulfillmentContext::new();
655 for obligation in obligations {
656 fulfill_cx.register_predicate_obligation(self, obligation);
659 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
662 /// Finishes processes any obligations that remain in the
663 /// fulfillment context, and then returns the result with all type
664 /// variables removed and regions erased. Because this is intended
665 /// for use after type-check has completed, if any errors occur,
666 /// it will panic. It is used during normalization and other cases
667 /// where processing the obligations in `fulfill_cx` may cause
668 /// type inference variables that appear in `result` to be
669 /// unified, and hence we need to process those obligations to get
670 /// the complete picture of the type.
671 pub fn drain_fulfillment_cx_or_panic<T>(&self,
673 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
676 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
678 debug!("drain_fulfillment_cx_or_panic()");
680 // In principle, we only need to do this so long as `result`
681 // contains unbound type parameters. It could be a slight
682 // optimization to stop iterating early.
683 match fulfill_cx.select_all_or_error(self) {
686 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
691 let result = self.resolve_type_vars_if_possible(result);
692 let result = self.tcx.erase_regions(&result);
694 match self.tcx.lift_to_global(&result) {
695 Some(result) => result,
697 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
702 pub fn projection_mode(&self) -> Reveal {
706 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
707 t.fold_with(&mut self.freshener())
710 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
712 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
717 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
718 freshen::TypeFreshener::new(self)
721 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
722 use ty::error::UnconstrainedNumeric::Neither;
723 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
725 ty::TyInfer(ty::IntVar(vid)) => {
726 if self.int_unification_table.borrow_mut().has_value(vid) {
732 ty::TyInfer(ty::FloatVar(vid)) => {
733 if self.float_unification_table.borrow_mut().has_value(vid) {
743 /// Returns a type variable's default fallback if any exists. A default
744 /// must be attached to the variable when created, if it is created
745 /// without a default, this will return None.
747 /// This code does not apply to integral or floating point variables,
748 /// only to use declared defaults.
750 /// See `new_ty_var_with_default` to create a type variable with a default.
751 /// See `type_variable::Default` for details about what a default entails.
752 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
754 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
759 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
760 let mut variables = Vec::new();
762 let unbound_ty_vars = self.type_variables
764 .unsolved_variables()
766 .map(|t| self.tcx.mk_var(t));
768 let unbound_int_vars = self.int_unification_table
770 .unsolved_variables()
772 .map(|v| self.tcx.mk_int_var(v));
774 let unbound_float_vars = self.float_unification_table
776 .unsolved_variables()
778 .map(|v| self.tcx.mk_float_var(v));
780 variables.extend(unbound_ty_vars);
781 variables.extend(unbound_int_vars);
782 variables.extend(unbound_float_vars);
787 fn combine_fields(&'a self, trace: TypeTrace<'tcx>)
788 -> CombineFields<'a, 'gcx, 'tcx> {
793 obligations: PredicateObligations::new(),
797 pub fn equate<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
798 -> InferResult<'tcx, T>
799 where T: Relate<'tcx>
801 let mut fields = self.combine_fields(trace);
802 let result = fields.equate(a_is_expected).relate(a, b);
803 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
806 pub fn sub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
807 -> InferResult<'tcx, T>
808 where T: Relate<'tcx>
810 let mut fields = self.combine_fields(trace);
811 let result = fields.sub(a_is_expected).relate(a, b);
812 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
815 pub fn lub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
816 -> InferResult<'tcx, T>
817 where T: Relate<'tcx>
819 let mut fields = self.combine_fields(trace);
820 let result = fields.lub(a_is_expected).relate(a, b);
821 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
824 pub fn glb<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
825 -> InferResult<'tcx, T>
826 where T: Relate<'tcx>
828 let mut fields = self.combine_fields(trace);
829 let result = fields.glb(a_is_expected).relate(a, b);
830 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
833 fn start_snapshot(&self) -> CombinedSnapshot {
834 debug!("start_snapshot()");
836 let obligations_in_snapshot = self.obligations_in_snapshot.get();
837 self.obligations_in_snapshot.set(false);
840 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
841 type_snapshot: self.type_variables.borrow_mut().snapshot(),
842 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
843 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
844 region_vars_snapshot: self.region_vars.start_snapshot(),
845 obligations_in_snapshot: obligations_in_snapshot,
849 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
850 debug!("rollback_to(cause={})", cause);
851 let CombinedSnapshot { projection_cache_snapshot,
855 region_vars_snapshot,
856 obligations_in_snapshot } = snapshot;
858 assert!(!self.obligations_in_snapshot.get());
859 self.obligations_in_snapshot.set(obligations_in_snapshot);
861 self.projection_cache
863 .rollback_to(projection_cache_snapshot);
866 .rollback_to(type_snapshot);
867 self.int_unification_table
869 .rollback_to(int_snapshot);
870 self.float_unification_table
872 .rollback_to(float_snapshot);
874 .rollback_to(region_vars_snapshot);
877 fn commit_from(&self, snapshot: CombinedSnapshot) {
878 debug!("commit_from()");
879 let CombinedSnapshot { projection_cache_snapshot,
883 region_vars_snapshot,
884 obligations_in_snapshot } = snapshot;
886 self.obligations_in_snapshot.set(obligations_in_snapshot);
888 self.projection_cache
890 .commit(projection_cache_snapshot);
893 .commit(type_snapshot);
894 self.int_unification_table
896 .commit(int_snapshot);
897 self.float_unification_table
899 .commit(float_snapshot);
901 .commit(region_vars_snapshot);
904 /// Execute `f` and commit the bindings
905 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
909 let snapshot = self.start_snapshot();
911 self.commit_from(snapshot);
915 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
916 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
917 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
919 debug!("commit_if_ok()");
920 let snapshot = self.start_snapshot();
921 let r = f(&snapshot);
922 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
924 Ok(_) => { self.commit_from(snapshot); }
925 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
930 // Execute `f` in a snapshot, and commit the bindings it creates
931 pub fn in_snapshot<T, F>(&self, f: F) -> T where
932 F: FnOnce(&CombinedSnapshot) -> T
934 debug!("in_snapshot()");
935 let snapshot = self.start_snapshot();
936 let r = f(&snapshot);
937 self.commit_from(snapshot);
941 /// Execute `f` and commit only the region bindings if successful.
942 /// The function f must be very careful not to leak any non-region
943 /// variables that get created.
944 pub fn commit_regions_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
945 F: FnOnce() -> Result<T, E>
947 debug!("commit_regions_if_ok()");
948 let CombinedSnapshot { projection_cache_snapshot,
952 region_vars_snapshot,
953 obligations_in_snapshot } = self.start_snapshot();
955 let r = self.commit_if_ok(|_| f());
957 debug!("commit_regions_if_ok: rolling back everything but regions");
959 assert!(!self.obligations_in_snapshot.get());
960 self.obligations_in_snapshot.set(obligations_in_snapshot);
962 // Roll back any non-region bindings - they should be resolved
963 // inside `f`, with, e.g. `resolve_type_vars_if_possible`.
964 self.projection_cache
966 .rollback_to(projection_cache_snapshot);
969 .rollback_to(type_snapshot);
970 self.int_unification_table
972 .rollback_to(int_snapshot);
973 self.float_unification_table
975 .rollback_to(float_snapshot);
977 // Commit region vars that may escape through resolved types.
979 .commit(region_vars_snapshot);
984 /// Execute `f` then unroll any bindings it creates
985 pub fn probe<R, F>(&self, f: F) -> R where
986 F: FnOnce(&CombinedSnapshot) -> R,
989 let snapshot = self.start_snapshot();
990 let r = f(&snapshot);
991 self.rollback_to("probe", snapshot);
995 pub fn add_given(&self,
999 self.region_vars.add_given(sub, sup);
1002 pub fn sub_types(&self,
1003 a_is_expected: bool,
1007 -> InferResult<'tcx, ()>
1009 debug!("sub_types({:?} <: {:?})", a, b);
1010 self.commit_if_ok(|_| {
1011 let trace = TypeTrace::types(origin, a_is_expected, a, b);
1012 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1016 pub fn can_sub_types(&self,
1022 let origin = TypeOrigin::Misc(syntax_pos::DUMMY_SP);
1023 let trace = TypeTrace::types(origin, true, a, b);
1024 self.sub(true, trace, &a, &b).map(|_| ())
1028 pub fn eq_types(&self,
1029 a_is_expected: bool,
1033 -> InferResult<'tcx, ()>
1035 self.commit_if_ok(|_| {
1036 let trace = TypeTrace::types(origin, a_is_expected, a, b);
1037 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1041 pub fn eq_trait_refs(&self,
1042 a_is_expected: bool,
1044 a: ty::TraitRef<'tcx>,
1045 b: ty::TraitRef<'tcx>)
1046 -> InferResult<'tcx, ()>
1048 debug!("eq_trait_refs({:?} = {:?})", a, b);
1049 self.commit_if_ok(|_| {
1050 let trace = TypeTrace {
1052 values: TraitRefs(ExpectedFound::new(a_is_expected, a, b))
1054 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1058 pub fn eq_impl_headers(&self,
1059 a_is_expected: bool,
1061 a: &ty::ImplHeader<'tcx>,
1062 b: &ty::ImplHeader<'tcx>)
1063 -> InferResult<'tcx, ()>
1065 debug!("eq_impl_header({:?} = {:?})", a, b);
1066 match (a.trait_ref, b.trait_ref) {
1067 (Some(a_ref), Some(b_ref)) => self.eq_trait_refs(a_is_expected, origin, a_ref, b_ref),
1068 (None, None) => self.eq_types(a_is_expected, origin, a.self_ty, b.self_ty),
1069 _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
1073 pub fn sub_poly_trait_refs(&self,
1074 a_is_expected: bool,
1076 a: ty::PolyTraitRef<'tcx>,
1077 b: ty::PolyTraitRef<'tcx>)
1078 -> InferResult<'tcx, ()>
1080 debug!("sub_poly_trait_refs({:?} <: {:?})", a, b);
1081 self.commit_if_ok(|_| {
1082 let trace = TypeTrace {
1084 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b))
1086 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1090 pub fn sub_regions(&self,
1091 origin: SubregionOrigin<'tcx>,
1092 a: &'tcx ty::Region,
1093 b: &'tcx ty::Region) {
1094 debug!("sub_regions({:?} <: {:?})", a, b);
1095 self.region_vars.make_subregion(origin, a, b);
1098 pub fn equality_predicate(&self,
1100 predicate: &ty::PolyEquatePredicate<'tcx>)
1101 -> InferResult<'tcx, ()>
1103 self.commit_if_ok(|snapshot| {
1104 let (ty::EquatePredicate(a, b), skol_map) =
1105 self.skolemize_late_bound_regions(predicate, snapshot);
1106 let origin = TypeOrigin::EquatePredicate(span);
1107 let eqty_ok = self.eq_types(false, origin, a, b)?;
1108 self.leak_check(false, span, &skol_map, snapshot)?;
1109 self.pop_skolemized(skol_map, snapshot);
1114 pub fn region_outlives_predicate(&self,
1116 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1119 self.commit_if_ok(|snapshot| {
1120 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1121 self.skolemize_late_bound_regions(predicate, snapshot);
1122 let origin = RelateRegionParamBound(span);
1123 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1124 self.leak_check(false, span, &skol_map, snapshot)?;
1125 Ok(self.pop_skolemized(skol_map, snapshot))
1129 pub fn next_ty_var_id(&self, diverging: bool) -> TyVid {
1132 .new_var(diverging, None)
1135 pub fn next_ty_var(&self) -> Ty<'tcx> {
1136 self.tcx.mk_var(self.next_ty_var_id(false))
1139 pub fn next_diverging_ty_var(&self) -> Ty<'tcx> {
1140 self.tcx.mk_var(self.next_ty_var_id(true))
1143 pub fn next_ty_vars(&self, n: usize) -> Vec<Ty<'tcx>> {
1144 (0..n).map(|_i| self.next_ty_var()).collect()
1147 pub fn next_int_var_id(&self) -> IntVid {
1148 self.int_unification_table
1153 pub fn next_float_var_id(&self) -> FloatVid {
1154 self.float_unification_table
1159 pub fn next_region_var(&self, origin: RegionVariableOrigin)
1160 -> &'tcx ty::Region {
1161 self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
1164 /// Create a region inference variable for the given
1165 /// region parameter definition.
1166 pub fn region_var_for_def(&self,
1168 def: &ty::RegionParameterDef)
1169 -> &'tcx ty::Region {
1170 self.next_region_var(EarlyBoundRegion(span, def.name))
1173 /// Create a type inference variable for the given
1174 /// type parameter definition. The substitutions are
1175 /// for actual parameters that may be referred to by
1176 /// the default of this type parameter, if it exists.
1177 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1178 /// used in a path such as `Foo::<T, U>::new()` will
1179 /// use an inference variable for `C` with `[T, U]`
1180 /// as the substitutions for the default, `(T, U)`.
1181 pub fn type_var_for_def(&self,
1183 def: &ty::TypeParameterDef<'tcx>,
1184 substs: &Substs<'tcx>)
1186 let default = def.default.map(|default| {
1187 type_variable::Default {
1188 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1190 def_id: def.default_def_id
1195 let ty_var_id = self.type_variables
1197 .new_var(false, default);
1199 self.tcx.mk_var(ty_var_id)
1202 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1203 /// type/region parameter to a fresh inference variable.
1204 pub fn fresh_substs_for_item(&self,
1207 -> &'tcx Substs<'tcx> {
1208 Substs::for_item(self.tcx, def_id, |def, _| {
1209 self.region_var_for_def(span, def)
1211 self.type_var_for_def(span, def, substs)
1215 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> &'tcx ty::Region {
1216 self.region_vars.new_bound(debruijn)
1219 /// Apply `adjustment` to the type of `expr`
1220 pub fn adjust_expr_ty(&self,
1222 adjustment: Option<&adjustment::AutoAdjustment<'tcx>>)
1225 let raw_ty = self.expr_ty(expr);
1226 let raw_ty = self.shallow_resolve(raw_ty);
1227 let resolve_ty = |ty: Ty<'tcx>| self.resolve_type_vars_if_possible(&ty);
1228 raw_ty.adjust(self.tcx,
1232 |method_call| self.tables
1236 .map(|method| resolve_ty(method.ty)))
1239 /// True if errors have been reported since this infcx was
1240 /// created. This is sometimes used as a heuristic to skip
1241 /// reporting errors that often occur as a result of earlier
1242 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1243 /// inference variables, regionck errors).
1244 pub fn is_tainted_by_errors(&self) -> bool {
1245 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1246 tainted_by_errors_flag={})",
1247 self.tcx.sess.err_count(),
1248 self.err_count_on_creation,
1249 self.tainted_by_errors_flag.get());
1251 if self.tcx.sess.err_count() > self.err_count_on_creation {
1252 return true; // errors reported since this infcx was made
1254 self.tainted_by_errors_flag.get()
1257 /// Set the "tainted by errors" flag to true. We call this when we
1258 /// observe an error from a prior pass.
1259 pub fn set_tainted_by_errors(&self) {
1260 debug!("set_tainted_by_errors()");
1261 self.tainted_by_errors_flag.set(true)
1264 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1265 match self.tables.borrow().node_types.get(&id) {
1268 None if self.is_tainted_by_errors() =>
1271 bug!("no type for node {}: {} in fcx",
1272 id, self.tcx.map.node_to_string(id));
1277 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1278 match self.tables.borrow().node_types.get(&ex.id) {
1281 bug!("no type for expr in fcx");
1286 pub fn resolve_regions_and_report_errors(&self,
1287 free_regions: &FreeRegionMap,
1288 subject_node_id: ast::NodeId) {
1289 let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1290 if !self.is_tainted_by_errors() {
1291 // As a heuristic, just skip reporting region errors
1292 // altogether if other errors have been reported while
1293 // this infcx was in use. This is totally hokey but
1294 // otherwise we have a hard time separating legit region
1295 // errors from silly ones.
1296 self.report_region_errors(&errors); // see error_reporting.rs
1300 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1301 self.resolve_type_vars_if_possible(&t).to_string()
1304 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1305 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1306 format!("({})", tstrs.join(", "))
1309 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1310 self.resolve_type_vars_if_possible(t).to_string()
1313 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1315 ty::TyInfer(ty::TyVar(v)) => {
1316 // Not entirely obvious: if `typ` is a type variable,
1317 // it can be resolved to an int/float variable, which
1318 // can then be recursively resolved, hence the
1319 // recursion. Note though that we prevent type
1320 // variables from unifying to other type variables
1321 // directly (though they may be embedded
1322 // structurally), and we prevent cycles in any case,
1323 // so this recursion should always be of very limited
1325 self.type_variables.borrow_mut()
1327 .map(|t| self.shallow_resolve(t))
1331 ty::TyInfer(ty::IntVar(v)) => {
1332 self.int_unification_table
1335 .map(|v| v.to_type(self.tcx))
1339 ty::TyInfer(ty::FloatVar(v)) => {
1340 self.float_unification_table
1343 .map(|v| v.to_type(self.tcx))
1353 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1354 where T: TypeFoldable<'tcx>
1357 * Where possible, replaces type/int/float variables in
1358 * `value` with their final value. Note that region variables
1359 * are unaffected. If a type variable has not been unified, it
1360 * is left as is. This is an idempotent operation that does
1361 * not affect inference state in any way and so you can do it
1365 if !value.needs_infer() {
1366 return value.clone(); // avoid duplicated subst-folding
1368 let mut r = resolve::OpportunisticTypeResolver::new(self);
1369 value.fold_with(&mut r)
1372 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1373 where T: TypeFoldable<'tcx>
1375 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1376 value.fold_with(&mut r)
1379 /// Resolves all type variables in `t` and then, if any were left
1380 /// unresolved, substitutes an error type. This is used after the
1381 /// main checking when doing a second pass before writeback. The
1382 /// justification is that writeback will produce an error for
1383 /// these unconstrained type variables.
1384 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1385 let ty = self.resolve_type_vars_if_possible(t);
1386 if ty.references_error() || ty.is_ty_var() {
1387 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1394 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1396 * Attempts to resolve all type/region variables in
1397 * `value`. Region inference must have been run already (e.g.,
1398 * by calling `resolve_regions_and_report_errors`). If some
1399 * variable was never unified, an `Err` results.
1401 * This method is idempotent, but it not typically not invoked
1402 * except during the writeback phase.
1405 resolve::fully_resolve(self, value)
1408 // [Note-Type-error-reporting]
1409 // An invariant is that anytime the expected or actual type is TyError (the special
1410 // error type, meaning that an error occurred when typechecking this expression),
1411 // this is a derived error. The error cascaded from another error (that was already
1412 // reported), so it's not useful to display it to the user.
1413 // The following methods implement this logic.
1414 // They check if either the actual or expected type is TyError, and don't print the error
1415 // in this case. The typechecker should only ever report type errors involving mismatched
1416 // types using one of these methods, and should not call span_err directly for such
1419 pub fn type_error_message<M>(&self,
1422 actual_ty: Ty<'tcx>)
1423 where M: FnOnce(String) -> String,
1425 self.type_error_struct(sp, mk_msg, actual_ty).emit();
1428 // FIXME: this results in errors without an error code. Deprecate?
1429 pub fn type_error_struct<M>(&self,
1432 actual_ty: Ty<'tcx>)
1433 -> DiagnosticBuilder<'tcx>
1434 where M: FnOnce(String) -> String,
1436 self.type_error_struct_with_diag(sp, |actual_ty| {
1437 self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1441 pub fn type_error_struct_with_diag<M>(&self,
1444 actual_ty: Ty<'tcx>)
1445 -> DiagnosticBuilder<'tcx>
1446 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1448 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1449 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1451 // Don't report an error if actual type is TyError.
1452 if actual_ty.references_error() {
1453 return self.tcx.sess.diagnostic().struct_dummy();
1456 mk_diag(self.ty_to_string(actual_ty))
1459 pub fn report_mismatched_types(&self,
1463 err: TypeError<'tcx>) {
1464 let trace = TypeTrace {
1466 values: Types(ExpectedFound {
1471 self.report_and_explain_type_error(trace, &err).emit();
1474 pub fn report_conflicting_default_types(&self,
1476 expected: type_variable::Default<'tcx>,
1477 actual: type_variable::Default<'tcx>) {
1478 let trace = TypeTrace {
1479 origin: TypeOrigin::Misc(span),
1480 values: Types(ExpectedFound {
1481 expected: expected.ty,
1486 self.report_and_explain_type_error(
1488 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1495 pub fn replace_late_bound_regions_with_fresh_var<T>(
1498 lbrct: LateBoundRegionConversionTime,
1499 value: &ty::Binder<T>)
1500 -> (T, FnvHashMap<ty::BoundRegion, &'tcx ty::Region>)
1501 where T : TypeFoldable<'tcx>
1503 self.tcx.replace_late_bound_regions(
1505 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1508 /// Given a higher-ranked projection predicate like:
1510 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1512 /// and a target trait-ref like:
1514 /// <T as Fn<&'x u32>>
1516 /// find a substitution `S` for the higher-ranked regions (here,
1517 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1518 /// and then return the value (here, `&'a u32`) but with the
1519 /// substitution applied (hence, `&'x u32`).
1521 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1523 pub fn match_poly_projection_predicate(&self,
1525 match_a: ty::PolyProjectionPredicate<'tcx>,
1526 match_b: ty::TraitRef<'tcx>)
1527 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1529 let span = origin.span();
1530 let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1531 let trace = TypeTrace {
1533 values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1536 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1537 let mut combine = self.combine_fields(trace);
1538 let result = combine.higher_ranked_match(span, &match_pair, &match_b, true)?;
1539 Ok(InferOk { value: result, obligations: combine.obligations })
1542 /// See `verify_generic_bound` method in `region_inference`
1543 pub fn verify_generic_bound(&self,
1544 origin: SubregionOrigin<'tcx>,
1545 kind: GenericKind<'tcx>,
1546 a: &'tcx ty::Region,
1547 bound: VerifyBound<'tcx>) {
1548 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1553 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1556 pub fn can_equate<T>(&self, a: &T, b: &T) -> UnitResult<'tcx>
1557 where T: Relate<'tcx> + fmt::Debug
1559 debug!("can_equate({:?}, {:?})", a, b);
1561 // Gin up a dummy trace, since this won't be committed
1562 // anyhow. We should make this typetrace stuff more
1563 // generic so we don't have to do anything quite this
1565 self.equate(true, TypeTrace::dummy(self.tcx), a, b)
1569 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1570 let ty = self.node_type(id);
1571 self.resolve_type_vars_or_error(&ty)
1574 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1575 let ty = self.adjust_expr_ty(expr, self.tables.borrow().adjustments.get(&expr.id));
1576 self.resolve_type_vars_or_error(&ty)
1579 pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1580 let ty = self.resolve_type_vars_if_possible(&ty);
1581 if let Some(ty) = self.tcx.lift_to_global(&ty) {
1582 // Even if the type may have no inference variables, during
1583 // type-checking closure types are in local tables only.
1584 let local_closures = match self.tables {
1585 InferTables::Local(_) => ty.has_closure_types(),
1586 InferTables::Global(_) => false
1588 if !local_closures {
1589 return ty.moves_by_default(self.tcx.global_tcx(), self.param_env(), span);
1593 // this can get called from typeck (by euv), and moves_by_default
1594 // rightly refuses to work with inference variables, but
1595 // moves_by_default has a cache, which we want to use in other
1597 !traits::type_known_to_meet_builtin_bound(self, ty, ty::BoundCopy, span)
1600 pub fn node_method_ty(&self, method_call: ty::MethodCall)
1601 -> Option<Ty<'tcx>> {
1606 .map(|method| method.ty)
1607 .map(|ty| self.resolve_type_vars_if_possible(&ty))
1610 pub fn node_method_id(&self, method_call: ty::MethodCall)
1616 .map(|method| method.def_id)
1619 pub fn adjustments(&self) -> Ref<NodeMap<adjustment::AutoAdjustment<'tcx>>> {
1620 fn project_adjustments<'a, 'tcx>(tables: &'a ty::Tables<'tcx>)
1621 -> &'a NodeMap<adjustment::AutoAdjustment<'tcx>> {
1625 Ref::map(self.tables.borrow(), project_adjustments)
1628 pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1629 self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1632 pub fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<CodeExtent> {
1633 self.tcx.region_maps.temporary_scope(rvalue_id)
1636 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
1637 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1640 pub fn param_env(&self) -> &ty::ParameterEnvironment<'gcx> {
1641 &self.parameter_environment
1644 pub fn closure_kind(&self,
1646 -> Option<ty::ClosureKind>
1648 if def_id.is_local() {
1649 self.tables.borrow().closure_kinds.get(&def_id).cloned()
1651 // During typeck, ALL closures are local. But afterwards,
1652 // during trans, we see closure ids from other traits.
1653 // That may require loading the closure data out of the
1655 Some(self.tcx.closure_kind(def_id))
1659 pub fn closure_type(&self,
1661 substs: ty::ClosureSubsts<'tcx>)
1662 -> ty::ClosureTy<'tcx>
1664 if let InferTables::Local(tables) = self.tables {
1665 if let Some(ty) = tables.borrow().closure_tys.get(&def_id) {
1666 return ty.subst(self.tcx, substs.func_substs);
1670 let closure_ty = self.tcx.closure_type(def_id, substs);
1675 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1676 pub fn span(&self) -> Span {
1680 pub fn types(origin: TypeOrigin,
1681 a_is_expected: bool,
1684 -> TypeTrace<'tcx> {
1687 values: Types(ExpectedFound::new(a_is_expected, a, b))
1691 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1693 origin: TypeOrigin::Misc(syntax_pos::DUMMY_SP),
1694 values: Types(ExpectedFound {
1695 expected: tcx.types.err,
1696 found: tcx.types.err,
1702 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1703 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1704 write!(f, "TypeTrace({:?})", self.origin)
1709 pub fn span(&self) -> Span {
1711 TypeOrigin::MethodCompatCheck(span) => span,
1712 TypeOrigin::ExprAssignable(span) => span,
1713 TypeOrigin::Misc(span) => span,
1714 TypeOrigin::RelateOutputImplTypes(span) => span,
1715 TypeOrigin::MatchExpressionArm(match_span, _, _) => match_span,
1716 TypeOrigin::IfExpression(span) => span,
1717 TypeOrigin::IfExpressionWithNoElse(span) => span,
1718 TypeOrigin::RangeExpression(span) => span,
1719 TypeOrigin::EquatePredicate(span) => span,
1720 TypeOrigin::MainFunctionType(span) => span,
1721 TypeOrigin::StartFunctionType(span) => span,
1722 TypeOrigin::IntrinsicType(span) => span,
1723 TypeOrigin::MethodReceiver(span) => span,
1728 impl<'tcx> SubregionOrigin<'tcx> {
1729 pub fn span(&self) -> Span {
1731 Subtype(ref a) => a.span(),
1732 InfStackClosure(a) => a,
1733 InvokeClosure(a) => a,
1734 DerefPointer(a) => a,
1735 FreeVariable(a, _) => a,
1737 RelateObjectBound(a) => a,
1738 RelateParamBound(a, _) => a,
1739 RelateRegionParamBound(a) => a,
1740 RelateDefaultParamBound(a, _) => a,
1742 ReborrowUpvar(a, _) => a,
1743 DataBorrowed(_, a) => a,
1744 ReferenceOutlivesReferent(_, a) => a,
1745 ParameterInScope(_, a) => a,
1746 ExprTypeIsNotInScope(_, a) => a,
1747 BindingTypeIsNotValidAtDecl(a) => a,
1754 SafeDestructor(a) => a,
1759 impl RegionVariableOrigin {
1760 pub fn span(&self) -> Span {
1762 MiscVariable(a) => a,
1763 PatternRegion(a) => a,
1764 AddrOfRegion(a) => a,
1767 EarlyBoundRegion(a, _) => a,
1768 LateBoundRegion(a, _, _) => a,
1769 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1770 UpvarRegion(_, a) => a
1775 impl<'tcx> TypeFoldable<'tcx> for TypeOrigin {
1776 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _folder: &mut F) -> Self {
1780 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> bool {
1785 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1786 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1788 ValuePairs::Types(ref ef) => {
1789 ValuePairs::Types(ef.fold_with(folder))
1791 ValuePairs::TraitRefs(ref ef) => {
1792 ValuePairs::TraitRefs(ef.fold_with(folder))
1794 ValuePairs::PolyTraitRefs(ref ef) => {
1795 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1800 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1802 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1803 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1804 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1809 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1810 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1812 origin: self.origin.fold_with(folder),
1813 values: self.values.fold_with(folder)
1817 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1818 self.origin.visit_with(visitor) || self.values.visit_with(visitor)