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 pub fn normalizing_infer_ctxt(self, projection_mode: Reveal)
472 -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
475 arenas: ty::CtxtArenas::new(),
478 projection_mode: projection_mode,
482 /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
483 /// for MemCategorizationContext/ExprUseVisitor.
484 /// If any inference functionality is used, ICEs will occur.
485 pub fn borrowck_fake_infer_ctxt(self, param_env: ty::ParameterEnvironment<'gcx>)
486 -> InferCtxt<'a, 'gcx, 'gcx> {
489 tables: InferTables::Global(&self.tables),
490 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
491 int_unification_table: RefCell::new(UnificationTable::new()),
492 float_unification_table: RefCell::new(UnificationTable::new()),
493 region_vars: RegionVarBindings::new(self),
494 parameter_environment: param_env,
495 selection_cache: traits::SelectionCache::new(),
496 evaluation_cache: traits::EvaluationCache::new(),
497 projection_cache: RefCell::new(traits::ProjectionCache::new()),
498 reported_trait_errors: RefCell::new(FnvHashSet()),
499 projection_mode: Reveal::NotSpecializable,
500 tainted_by_errors_flag: Cell::new(false),
501 err_count_on_creation: self.sess.err_count(),
502 obligations_in_snapshot: Cell::new(false),
507 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
508 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
509 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
511 let InferCtxtBuilder {
518 let tables = if let Some(ref tables) = *tables {
519 InferTables::Local(tables)
521 InferTables::Global(&global_tcx.tables)
523 let param_env = param_env.take().unwrap_or_else(|| {
524 global_tcx.empty_parameter_environment()
526 global_tcx.enter_local(arenas, |tcx| f(InferCtxt {
529 projection_cache: RefCell::new(traits::ProjectionCache::new()),
530 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
531 int_unification_table: RefCell::new(UnificationTable::new()),
532 float_unification_table: RefCell::new(UnificationTable::new()),
533 region_vars: RegionVarBindings::new(tcx),
534 parameter_environment: param_env,
535 selection_cache: traits::SelectionCache::new(),
536 evaluation_cache: traits::EvaluationCache::new(),
537 reported_trait_errors: RefCell::new(FnvHashSet()),
538 projection_mode: projection_mode,
539 tainted_by_errors_flag: Cell::new(false),
540 err_count_on_creation: tcx.sess.err_count(),
541 obligations_in_snapshot: Cell::new(false),
546 impl<T> ExpectedFound<T> {
547 fn new(a_is_expected: bool, a: T, b: T) -> Self {
549 ExpectedFound {expected: a, found: b}
551 ExpectedFound {expected: b, found: a}
556 impl<'tcx, T> InferOk<'tcx, T> {
557 pub fn unit(self) -> InferOk<'tcx, ()> {
558 InferOk { value: (), obligations: self.obligations }
562 #[must_use = "once you start a snapshot, you should always consume it"]
563 pub struct CombinedSnapshot {
564 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
565 type_snapshot: type_variable::Snapshot,
566 int_snapshot: unify::Snapshot<ty::IntVid>,
567 float_snapshot: unify::Snapshot<ty::FloatVid>,
568 region_vars_snapshot: RegionSnapshot,
569 obligations_in_snapshot: bool,
572 /// Helper trait for shortening the lifetimes inside a
573 /// value for post-type-checking normalization.
574 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
575 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self;
578 macro_rules! items { ($($item:item)+) => ($($item)+) }
579 macro_rules! impl_trans_normalize {
580 ($lt_gcx:tt, $($ty:ty),+) => {
581 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
582 fn trans_normalize<'a, 'tcx>(&self,
583 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>)
585 infcx.normalize_projections_in(self)
591 impl_trans_normalize!('gcx,
595 &'gcx ty::BareFnTy<'gcx>,
596 ty::ClosureSubsts<'gcx>,
597 ty::PolyTraitRef<'gcx>
600 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
601 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self {
603 LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx) },
604 LvalueTy::Downcast { adt_def, substs, variant_index } => {
607 substs: substs.trans_normalize(infcx),
608 variant_index: variant_index
615 // NOTE: Callable from trans only!
616 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
617 pub fn normalize_associated_type<T>(self, value: &T) -> T
618 where T: TransNormalize<'tcx>
620 debug!("normalize_associated_type(t={:?})", value);
622 let value = self.erase_regions(value);
624 if !value.has_projection_types() {
628 self.infer_ctxt(None, None, Reveal::All).enter(|infcx| {
629 value.trans_normalize(&infcx)
633 pub fn normalize_associated_type_in_env<T>(
634 self, value: &T, env: &'a ty::ParameterEnvironment<'tcx>
636 where T: TransNormalize<'tcx>
638 debug!("normalize_associated_type_in_env(t={:?})", value);
640 let value = self.erase_regions(value);
642 if !value.has_projection_types() {
646 self.infer_ctxt(None, Some(env.clone()), Reveal::All).enter(|infcx| {
647 value.trans_normalize(&infcx)
652 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
653 fn normalize_projections_in<T>(&self, value: &T) -> T::Lifted
654 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
656 let mut selcx = traits::SelectionContext::new(self);
657 let cause = traits::ObligationCause::dummy();
658 let traits::Normalized { value: result, obligations } =
659 traits::normalize(&mut selcx, cause, value);
661 debug!("normalize_projections_in: result={:?} obligations={:?}",
662 result, obligations);
664 let mut fulfill_cx = traits::FulfillmentContext::new();
666 for obligation in obligations {
667 fulfill_cx.register_predicate_obligation(self, obligation);
670 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
673 /// Finishes processes any obligations that remain in the
674 /// fulfillment context, and then returns the result with all type
675 /// variables removed and regions erased. Because this is intended
676 /// for use after type-check has completed, if any errors occur,
677 /// it will panic. It is used during normalization and other cases
678 /// where processing the obligations in `fulfill_cx` may cause
679 /// type inference variables that appear in `result` to be
680 /// unified, and hence we need to process those obligations to get
681 /// the complete picture of the type.
682 pub fn drain_fulfillment_cx_or_panic<T>(&self,
684 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
687 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
689 debug!("drain_fulfillment_cx_or_panic()");
691 // In principle, we only need to do this so long as `result`
692 // contains unbound type parameters. It could be a slight
693 // optimization to stop iterating early.
694 match fulfill_cx.select_all_or_error(self) {
697 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
702 let result = self.resolve_type_vars_if_possible(result);
703 let result = self.tcx.erase_regions(&result);
705 match self.tcx.lift_to_global(&result) {
706 Some(result) => result,
708 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
713 pub fn projection_mode(&self) -> Reveal {
717 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
718 t.fold_with(&mut self.freshener())
721 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
723 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
728 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
729 freshen::TypeFreshener::new(self)
732 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
733 use ty::error::UnconstrainedNumeric::Neither;
734 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
736 ty::TyInfer(ty::IntVar(vid)) => {
737 if self.int_unification_table.borrow_mut().has_value(vid) {
743 ty::TyInfer(ty::FloatVar(vid)) => {
744 if self.float_unification_table.borrow_mut().has_value(vid) {
754 /// Returns a type variable's default fallback if any exists. A default
755 /// must be attached to the variable when created, if it is created
756 /// without a default, this will return None.
758 /// This code does not apply to integral or floating point variables,
759 /// only to use declared defaults.
761 /// See `new_ty_var_with_default` to create a type variable with a default.
762 /// See `type_variable::Default` for details about what a default entails.
763 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
765 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
770 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
771 let mut variables = Vec::new();
773 let unbound_ty_vars = self.type_variables
775 .unsolved_variables()
777 .map(|t| self.tcx.mk_var(t));
779 let unbound_int_vars = self.int_unification_table
781 .unsolved_variables()
783 .map(|v| self.tcx.mk_int_var(v));
785 let unbound_float_vars = self.float_unification_table
787 .unsolved_variables()
789 .map(|v| self.tcx.mk_float_var(v));
791 variables.extend(unbound_ty_vars);
792 variables.extend(unbound_int_vars);
793 variables.extend(unbound_float_vars);
798 fn combine_fields(&'a self, trace: TypeTrace<'tcx>)
799 -> CombineFields<'a, 'gcx, 'tcx> {
804 obligations: PredicateObligations::new(),
808 pub fn equate<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
809 -> InferResult<'tcx, T>
810 where T: Relate<'tcx>
812 let mut fields = self.combine_fields(trace);
813 let result = fields.equate(a_is_expected).relate(a, b);
814 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
817 pub fn sub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
818 -> InferResult<'tcx, T>
819 where T: Relate<'tcx>
821 let mut fields = self.combine_fields(trace);
822 let result = fields.sub(a_is_expected).relate(a, b);
823 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
826 pub fn lub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
827 -> InferResult<'tcx, T>
828 where T: Relate<'tcx>
830 let mut fields = self.combine_fields(trace);
831 let result = fields.lub(a_is_expected).relate(a, b);
832 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
835 pub fn glb<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
836 -> InferResult<'tcx, T>
837 where T: Relate<'tcx>
839 let mut fields = self.combine_fields(trace);
840 let result = fields.glb(a_is_expected).relate(a, b);
841 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
844 fn start_snapshot(&self) -> CombinedSnapshot {
845 debug!("start_snapshot()");
847 let obligations_in_snapshot = self.obligations_in_snapshot.get();
848 self.obligations_in_snapshot.set(false);
851 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
852 type_snapshot: self.type_variables.borrow_mut().snapshot(),
853 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
854 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
855 region_vars_snapshot: self.region_vars.start_snapshot(),
856 obligations_in_snapshot: obligations_in_snapshot,
860 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
861 debug!("rollback_to(cause={})", cause);
862 let CombinedSnapshot { projection_cache_snapshot,
866 region_vars_snapshot,
867 obligations_in_snapshot } = snapshot;
869 assert!(!self.obligations_in_snapshot.get());
870 self.obligations_in_snapshot.set(obligations_in_snapshot);
872 self.projection_cache
874 .rollback_to(projection_cache_snapshot);
877 .rollback_to(type_snapshot);
878 self.int_unification_table
880 .rollback_to(int_snapshot);
881 self.float_unification_table
883 .rollback_to(float_snapshot);
885 .rollback_to(region_vars_snapshot);
888 fn commit_from(&self, snapshot: CombinedSnapshot) {
889 debug!("commit_from()");
890 let CombinedSnapshot { projection_cache_snapshot,
894 region_vars_snapshot,
895 obligations_in_snapshot } = snapshot;
897 self.obligations_in_snapshot.set(obligations_in_snapshot);
899 self.projection_cache
901 .commit(projection_cache_snapshot);
904 .commit(type_snapshot);
905 self.int_unification_table
907 .commit(int_snapshot);
908 self.float_unification_table
910 .commit(float_snapshot);
912 .commit(region_vars_snapshot);
915 /// Execute `f` and commit the bindings
916 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
920 let snapshot = self.start_snapshot();
922 self.commit_from(snapshot);
926 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
927 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
928 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
930 debug!("commit_if_ok()");
931 let snapshot = self.start_snapshot();
932 let r = f(&snapshot);
933 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
935 Ok(_) => { self.commit_from(snapshot); }
936 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
941 // Execute `f` in a snapshot, and commit the bindings it creates
942 pub fn in_snapshot<T, F>(&self, f: F) -> T where
943 F: FnOnce(&CombinedSnapshot) -> T
945 debug!("in_snapshot()");
946 let snapshot = self.start_snapshot();
947 let r = f(&snapshot);
948 self.commit_from(snapshot);
952 /// Execute `f` and commit only the region bindings if successful.
953 /// The function f must be very careful not to leak any non-region
954 /// variables that get created.
955 pub fn commit_regions_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
956 F: FnOnce() -> Result<T, E>
958 debug!("commit_regions_if_ok()");
959 let CombinedSnapshot { projection_cache_snapshot,
963 region_vars_snapshot,
964 obligations_in_snapshot } = self.start_snapshot();
966 let r = self.commit_if_ok(|_| f());
968 debug!("commit_regions_if_ok: rolling back everything but regions");
970 assert!(!self.obligations_in_snapshot.get());
971 self.obligations_in_snapshot.set(obligations_in_snapshot);
973 // Roll back any non-region bindings - they should be resolved
974 // inside `f`, with, e.g. `resolve_type_vars_if_possible`.
975 self.projection_cache
977 .rollback_to(projection_cache_snapshot);
980 .rollback_to(type_snapshot);
981 self.int_unification_table
983 .rollback_to(int_snapshot);
984 self.float_unification_table
986 .rollback_to(float_snapshot);
988 // Commit region vars that may escape through resolved types.
990 .commit(region_vars_snapshot);
995 /// Execute `f` then unroll any bindings it creates
996 pub fn probe<R, F>(&self, f: F) -> R where
997 F: FnOnce(&CombinedSnapshot) -> R,
1000 let snapshot = self.start_snapshot();
1001 let r = f(&snapshot);
1002 self.rollback_to("probe", snapshot);
1006 pub fn add_given(&self,
1007 sub: ty::FreeRegion,
1010 self.region_vars.add_given(sub, sup);
1013 pub fn sub_types(&self,
1014 a_is_expected: bool,
1018 -> InferResult<'tcx, ()>
1020 debug!("sub_types({:?} <: {:?})", a, b);
1021 self.commit_if_ok(|_| {
1022 let trace = TypeTrace::types(origin, a_is_expected, a, b);
1023 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1027 pub fn can_sub_types(&self,
1033 let origin = TypeOrigin::Misc(syntax_pos::DUMMY_SP);
1034 let trace = TypeTrace::types(origin, true, a, b);
1035 self.sub(true, trace, &a, &b).map(|_| ())
1039 pub fn eq_types(&self,
1040 a_is_expected: bool,
1044 -> InferResult<'tcx, ()>
1046 self.commit_if_ok(|_| {
1047 let trace = TypeTrace::types(origin, a_is_expected, a, b);
1048 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1052 pub fn eq_trait_refs(&self,
1053 a_is_expected: bool,
1055 a: ty::TraitRef<'tcx>,
1056 b: ty::TraitRef<'tcx>)
1057 -> InferResult<'tcx, ()>
1059 debug!("eq_trait_refs({:?} = {:?})", a, b);
1060 self.commit_if_ok(|_| {
1061 let trace = TypeTrace {
1063 values: TraitRefs(ExpectedFound::new(a_is_expected, a, b))
1065 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1069 pub fn eq_impl_headers(&self,
1070 a_is_expected: bool,
1072 a: &ty::ImplHeader<'tcx>,
1073 b: &ty::ImplHeader<'tcx>)
1074 -> InferResult<'tcx, ()>
1076 debug!("eq_impl_header({:?} = {:?})", a, b);
1077 match (a.trait_ref, b.trait_ref) {
1078 (Some(a_ref), Some(b_ref)) => self.eq_trait_refs(a_is_expected, origin, a_ref, b_ref),
1079 (None, None) => self.eq_types(a_is_expected, origin, a.self_ty, b.self_ty),
1080 _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
1084 pub fn sub_poly_trait_refs(&self,
1085 a_is_expected: bool,
1087 a: ty::PolyTraitRef<'tcx>,
1088 b: ty::PolyTraitRef<'tcx>)
1089 -> InferResult<'tcx, ()>
1091 debug!("sub_poly_trait_refs({:?} <: {:?})", a, b);
1092 self.commit_if_ok(|_| {
1093 let trace = TypeTrace {
1095 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b))
1097 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1101 pub fn sub_regions(&self,
1102 origin: SubregionOrigin<'tcx>,
1103 a: &'tcx ty::Region,
1104 b: &'tcx ty::Region) {
1105 debug!("sub_regions({:?} <: {:?})", a, b);
1106 self.region_vars.make_subregion(origin, a, b);
1109 pub fn equality_predicate(&self,
1111 predicate: &ty::PolyEquatePredicate<'tcx>)
1112 -> InferResult<'tcx, ()>
1114 self.commit_if_ok(|snapshot| {
1115 let (ty::EquatePredicate(a, b), skol_map) =
1116 self.skolemize_late_bound_regions(predicate, snapshot);
1117 let origin = TypeOrigin::EquatePredicate(span);
1118 let eqty_ok = self.eq_types(false, origin, a, b)?;
1119 self.leak_check(false, span, &skol_map, snapshot)?;
1120 self.pop_skolemized(skol_map, snapshot);
1125 pub fn region_outlives_predicate(&self,
1127 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1130 self.commit_if_ok(|snapshot| {
1131 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1132 self.skolemize_late_bound_regions(predicate, snapshot);
1133 let origin = RelateRegionParamBound(span);
1134 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1135 self.leak_check(false, span, &skol_map, snapshot)?;
1136 Ok(self.pop_skolemized(skol_map, snapshot))
1140 pub fn next_ty_var_id(&self, diverging: bool) -> TyVid {
1143 .new_var(diverging, None)
1146 pub fn next_ty_var(&self) -> Ty<'tcx> {
1147 self.tcx.mk_var(self.next_ty_var_id(false))
1150 pub fn next_diverging_ty_var(&self) -> Ty<'tcx> {
1151 self.tcx.mk_var(self.next_ty_var_id(true))
1154 pub fn next_ty_vars(&self, n: usize) -> Vec<Ty<'tcx>> {
1155 (0..n).map(|_i| self.next_ty_var()).collect()
1158 pub fn next_int_var_id(&self) -> IntVid {
1159 self.int_unification_table
1164 pub fn next_float_var_id(&self) -> FloatVid {
1165 self.float_unification_table
1170 pub fn next_region_var(&self, origin: RegionVariableOrigin)
1171 -> &'tcx ty::Region {
1172 self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
1175 /// Create a region inference variable for the given
1176 /// region parameter definition.
1177 pub fn region_var_for_def(&self,
1179 def: &ty::RegionParameterDef)
1180 -> &'tcx ty::Region {
1181 self.next_region_var(EarlyBoundRegion(span, def.name))
1184 /// Create a type inference variable for the given
1185 /// type parameter definition. The substitutions are
1186 /// for actual parameters that may be referred to by
1187 /// the default of this type parameter, if it exists.
1188 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1189 /// used in a path such as `Foo::<T, U>::new()` will
1190 /// use an inference variable for `C` with `[T, U]`
1191 /// as the substitutions for the default, `(T, U)`.
1192 pub fn type_var_for_def(&self,
1194 def: &ty::TypeParameterDef<'tcx>,
1195 substs: &Substs<'tcx>)
1197 let default = def.default.map(|default| {
1198 type_variable::Default {
1199 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1201 def_id: def.default_def_id
1206 let ty_var_id = self.type_variables
1208 .new_var(false, default);
1210 self.tcx.mk_var(ty_var_id)
1213 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1214 /// type/region parameter to a fresh inference variable.
1215 pub fn fresh_substs_for_item(&self,
1218 -> &'tcx Substs<'tcx> {
1219 Substs::for_item(self.tcx, def_id, |def, _| {
1220 self.region_var_for_def(span, def)
1222 self.type_var_for_def(span, def, substs)
1226 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> &'tcx ty::Region {
1227 self.region_vars.new_bound(debruijn)
1230 /// Apply `adjustment` to the type of `expr`
1231 pub fn adjust_expr_ty(&self,
1233 adjustment: Option<&adjustment::AutoAdjustment<'tcx>>)
1236 let raw_ty = self.expr_ty(expr);
1237 let raw_ty = self.shallow_resolve(raw_ty);
1238 let resolve_ty = |ty: Ty<'tcx>| self.resolve_type_vars_if_possible(&ty);
1239 raw_ty.adjust(self.tcx,
1243 |method_call| self.tables
1247 .map(|method| resolve_ty(method.ty)))
1250 /// True if errors have been reported since this infcx was
1251 /// created. This is sometimes used as a heuristic to skip
1252 /// reporting errors that often occur as a result of earlier
1253 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1254 /// inference variables, regionck errors).
1255 pub fn is_tainted_by_errors(&self) -> bool {
1256 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1257 tainted_by_errors_flag={})",
1258 self.tcx.sess.err_count(),
1259 self.err_count_on_creation,
1260 self.tainted_by_errors_flag.get());
1262 if self.tcx.sess.err_count() > self.err_count_on_creation {
1263 return true; // errors reported since this infcx was made
1265 self.tainted_by_errors_flag.get()
1268 /// Set the "tainted by errors" flag to true. We call this when we
1269 /// observe an error from a prior pass.
1270 pub fn set_tainted_by_errors(&self) {
1271 debug!("set_tainted_by_errors()");
1272 self.tainted_by_errors_flag.set(true)
1275 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1276 match self.tables.borrow().node_types.get(&id) {
1279 None if self.is_tainted_by_errors() =>
1282 bug!("no type for node {}: {} in fcx",
1283 id, self.tcx.map.node_to_string(id));
1288 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1289 match self.tables.borrow().node_types.get(&ex.id) {
1292 bug!("no type for expr in fcx");
1297 pub fn resolve_regions_and_report_errors(&self,
1298 free_regions: &FreeRegionMap,
1299 subject_node_id: ast::NodeId) {
1300 let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1301 if !self.is_tainted_by_errors() {
1302 // As a heuristic, just skip reporting region errors
1303 // altogether if other errors have been reported while
1304 // this infcx was in use. This is totally hokey but
1305 // otherwise we have a hard time separating legit region
1306 // errors from silly ones.
1307 self.report_region_errors(&errors); // see error_reporting.rs
1311 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1312 self.resolve_type_vars_if_possible(&t).to_string()
1315 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1316 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1317 format!("({})", tstrs.join(", "))
1320 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1321 self.resolve_type_vars_if_possible(t).to_string()
1324 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1326 ty::TyInfer(ty::TyVar(v)) => {
1327 // Not entirely obvious: if `typ` is a type variable,
1328 // it can be resolved to an int/float variable, which
1329 // can then be recursively resolved, hence the
1330 // recursion. Note though that we prevent type
1331 // variables from unifying to other type variables
1332 // directly (though they may be embedded
1333 // structurally), and we prevent cycles in any case,
1334 // so this recursion should always be of very limited
1336 self.type_variables.borrow_mut()
1338 .map(|t| self.shallow_resolve(t))
1342 ty::TyInfer(ty::IntVar(v)) => {
1343 self.int_unification_table
1346 .map(|v| v.to_type(self.tcx))
1350 ty::TyInfer(ty::FloatVar(v)) => {
1351 self.float_unification_table
1354 .map(|v| v.to_type(self.tcx))
1364 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1365 where T: TypeFoldable<'tcx>
1368 * Where possible, replaces type/int/float variables in
1369 * `value` with their final value. Note that region variables
1370 * are unaffected. If a type variable has not been unified, it
1371 * is left as is. This is an idempotent operation that does
1372 * not affect inference state in any way and so you can do it
1376 if !value.needs_infer() {
1377 return value.clone(); // avoid duplicated subst-folding
1379 let mut r = resolve::OpportunisticTypeResolver::new(self);
1380 value.fold_with(&mut r)
1383 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1384 where T: TypeFoldable<'tcx>
1386 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1387 value.fold_with(&mut r)
1390 /// Resolves all type variables in `t` and then, if any were left
1391 /// unresolved, substitutes an error type. This is used after the
1392 /// main checking when doing a second pass before writeback. The
1393 /// justification is that writeback will produce an error for
1394 /// these unconstrained type variables.
1395 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1396 let ty = self.resolve_type_vars_if_possible(t);
1397 if ty.references_error() || ty.is_ty_var() {
1398 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1405 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1407 * Attempts to resolve all type/region variables in
1408 * `value`. Region inference must have been run already (e.g.,
1409 * by calling `resolve_regions_and_report_errors`). If some
1410 * variable was never unified, an `Err` results.
1412 * This method is idempotent, but it not typically not invoked
1413 * except during the writeback phase.
1416 resolve::fully_resolve(self, value)
1419 // [Note-Type-error-reporting]
1420 // An invariant is that anytime the expected or actual type is TyError (the special
1421 // error type, meaning that an error occurred when typechecking this expression),
1422 // this is a derived error. The error cascaded from another error (that was already
1423 // reported), so it's not useful to display it to the user.
1424 // The following methods implement this logic.
1425 // They check if either the actual or expected type is TyError, and don't print the error
1426 // in this case. The typechecker should only ever report type errors involving mismatched
1427 // types using one of these methods, and should not call span_err directly for such
1430 pub fn type_error_message<M>(&self,
1433 actual_ty: Ty<'tcx>)
1434 where M: FnOnce(String) -> String,
1436 self.type_error_struct(sp, mk_msg, actual_ty).emit();
1439 // FIXME: this results in errors without an error code. Deprecate?
1440 pub fn type_error_struct<M>(&self,
1443 actual_ty: Ty<'tcx>)
1444 -> DiagnosticBuilder<'tcx>
1445 where M: FnOnce(String) -> String,
1447 self.type_error_struct_with_diag(sp, |actual_ty| {
1448 self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1452 pub fn type_error_struct_with_diag<M>(&self,
1455 actual_ty: Ty<'tcx>)
1456 -> DiagnosticBuilder<'tcx>
1457 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1459 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1460 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1462 // Don't report an error if actual type is TyError.
1463 if actual_ty.references_error() {
1464 return self.tcx.sess.diagnostic().struct_dummy();
1467 mk_diag(self.ty_to_string(actual_ty))
1470 pub fn report_mismatched_types(&self,
1474 err: TypeError<'tcx>) {
1475 let trace = TypeTrace {
1477 values: Types(ExpectedFound {
1482 self.report_and_explain_type_error(trace, &err).emit();
1485 pub fn report_conflicting_default_types(&self,
1487 expected: type_variable::Default<'tcx>,
1488 actual: type_variable::Default<'tcx>) {
1489 let trace = TypeTrace {
1490 origin: TypeOrigin::Misc(span),
1491 values: Types(ExpectedFound {
1492 expected: expected.ty,
1497 self.report_and_explain_type_error(
1499 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1506 pub fn replace_late_bound_regions_with_fresh_var<T>(
1509 lbrct: LateBoundRegionConversionTime,
1510 value: &ty::Binder<T>)
1511 -> (T, FnvHashMap<ty::BoundRegion, &'tcx ty::Region>)
1512 where T : TypeFoldable<'tcx>
1514 self.tcx.replace_late_bound_regions(
1516 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1519 /// Given a higher-ranked projection predicate like:
1521 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1523 /// and a target trait-ref like:
1525 /// <T as Fn<&'x u32>>
1527 /// find a substitution `S` for the higher-ranked regions (here,
1528 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1529 /// and then return the value (here, `&'a u32`) but with the
1530 /// substitution applied (hence, `&'x u32`).
1532 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1534 pub fn match_poly_projection_predicate(&self,
1536 match_a: ty::PolyProjectionPredicate<'tcx>,
1537 match_b: ty::TraitRef<'tcx>)
1538 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1540 let span = origin.span();
1541 let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1542 let trace = TypeTrace {
1544 values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1547 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1548 let mut combine = self.combine_fields(trace);
1549 let result = combine.higher_ranked_match(span, &match_pair, &match_b, true)?;
1550 Ok(InferOk { value: result, obligations: combine.obligations })
1553 /// See `verify_generic_bound` method in `region_inference`
1554 pub fn verify_generic_bound(&self,
1555 origin: SubregionOrigin<'tcx>,
1556 kind: GenericKind<'tcx>,
1557 a: &'tcx ty::Region,
1558 bound: VerifyBound<'tcx>) {
1559 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1564 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1567 pub fn can_equate<T>(&self, a: &T, b: &T) -> UnitResult<'tcx>
1568 where T: Relate<'tcx> + fmt::Debug
1570 debug!("can_equate({:?}, {:?})", a, b);
1572 // Gin up a dummy trace, since this won't be committed
1573 // anyhow. We should make this typetrace stuff more
1574 // generic so we don't have to do anything quite this
1576 self.equate(true, TypeTrace::dummy(self.tcx), a, b)
1580 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1581 let ty = self.node_type(id);
1582 self.resolve_type_vars_or_error(&ty)
1585 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1586 let ty = self.adjust_expr_ty(expr, self.tables.borrow().adjustments.get(&expr.id));
1587 self.resolve_type_vars_or_error(&ty)
1590 pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1591 let ty = self.resolve_type_vars_if_possible(&ty);
1592 if let Some(ty) = self.tcx.lift_to_global(&ty) {
1593 // Even if the type may have no inference variables, during
1594 // type-checking closure types are in local tables only.
1595 let local_closures = match self.tables {
1596 InferTables::Local(_) => ty.has_closure_types(),
1597 InferTables::Global(_) => false
1599 if !local_closures {
1600 return ty.moves_by_default(self.tcx.global_tcx(), self.param_env(), span);
1604 // this can get called from typeck (by euv), and moves_by_default
1605 // rightly refuses to work with inference variables, but
1606 // moves_by_default has a cache, which we want to use in other
1608 !traits::type_known_to_meet_builtin_bound(self, ty, ty::BoundCopy, span)
1611 pub fn node_method_ty(&self, method_call: ty::MethodCall)
1612 -> Option<Ty<'tcx>> {
1617 .map(|method| method.ty)
1618 .map(|ty| self.resolve_type_vars_if_possible(&ty))
1621 pub fn node_method_id(&self, method_call: ty::MethodCall)
1627 .map(|method| method.def_id)
1630 pub fn adjustments(&self) -> Ref<NodeMap<adjustment::AutoAdjustment<'tcx>>> {
1631 fn project_adjustments<'a, 'tcx>(tables: &'a ty::Tables<'tcx>)
1632 -> &'a NodeMap<adjustment::AutoAdjustment<'tcx>> {
1636 Ref::map(self.tables.borrow(), project_adjustments)
1639 pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1640 self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1643 pub fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<CodeExtent> {
1644 self.tcx.region_maps.temporary_scope(rvalue_id)
1647 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
1648 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1651 pub fn param_env(&self) -> &ty::ParameterEnvironment<'gcx> {
1652 &self.parameter_environment
1655 pub fn closure_kind(&self,
1657 -> Option<ty::ClosureKind>
1659 if def_id.is_local() {
1660 self.tables.borrow().closure_kinds.get(&def_id).cloned()
1662 // During typeck, ALL closures are local. But afterwards,
1663 // during trans, we see closure ids from other traits.
1664 // That may require loading the closure data out of the
1666 Some(self.tcx.closure_kind(def_id))
1670 pub fn closure_type(&self,
1672 substs: ty::ClosureSubsts<'tcx>)
1673 -> ty::ClosureTy<'tcx>
1675 if let InferTables::Local(tables) = self.tables {
1676 if let Some(ty) = tables.borrow().closure_tys.get(&def_id) {
1677 return ty.subst(self.tcx, substs.func_substs);
1681 let closure_ty = self.tcx.closure_type(def_id, substs);
1686 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1687 pub fn span(&self) -> Span {
1691 pub fn types(origin: TypeOrigin,
1692 a_is_expected: bool,
1695 -> TypeTrace<'tcx> {
1698 values: Types(ExpectedFound::new(a_is_expected, a, b))
1702 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1704 origin: TypeOrigin::Misc(syntax_pos::DUMMY_SP),
1705 values: Types(ExpectedFound {
1706 expected: tcx.types.err,
1707 found: tcx.types.err,
1713 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1714 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1715 write!(f, "TypeTrace({:?})", self.origin)
1720 pub fn span(&self) -> Span {
1722 TypeOrigin::MethodCompatCheck(span) => span,
1723 TypeOrigin::ExprAssignable(span) => span,
1724 TypeOrigin::Misc(span) => span,
1725 TypeOrigin::RelateOutputImplTypes(span) => span,
1726 TypeOrigin::MatchExpressionArm(match_span, _, _) => match_span,
1727 TypeOrigin::IfExpression(span) => span,
1728 TypeOrigin::IfExpressionWithNoElse(span) => span,
1729 TypeOrigin::RangeExpression(span) => span,
1730 TypeOrigin::EquatePredicate(span) => span,
1731 TypeOrigin::MainFunctionType(span) => span,
1732 TypeOrigin::StartFunctionType(span) => span,
1733 TypeOrigin::IntrinsicType(span) => span,
1734 TypeOrigin::MethodReceiver(span) => span,
1739 impl<'tcx> SubregionOrigin<'tcx> {
1740 pub fn span(&self) -> Span {
1742 Subtype(ref a) => a.span(),
1743 InfStackClosure(a) => a,
1744 InvokeClosure(a) => a,
1745 DerefPointer(a) => a,
1746 FreeVariable(a, _) => a,
1748 RelateObjectBound(a) => a,
1749 RelateParamBound(a, _) => a,
1750 RelateRegionParamBound(a) => a,
1751 RelateDefaultParamBound(a, _) => a,
1753 ReborrowUpvar(a, _) => a,
1754 DataBorrowed(_, a) => a,
1755 ReferenceOutlivesReferent(_, a) => a,
1756 ParameterInScope(_, a) => a,
1757 ExprTypeIsNotInScope(_, a) => a,
1758 BindingTypeIsNotValidAtDecl(a) => a,
1765 SafeDestructor(a) => a,
1770 impl RegionVariableOrigin {
1771 pub fn span(&self) -> Span {
1773 MiscVariable(a) => a,
1774 PatternRegion(a) => a,
1775 AddrOfRegion(a) => a,
1778 EarlyBoundRegion(a, _) => a,
1779 LateBoundRegion(a, _, _) => a,
1780 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1781 UpvarRegion(_, a) => a
1786 impl<'tcx> TypeFoldable<'tcx> for TypeOrigin {
1787 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _folder: &mut F) -> Self {
1791 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> bool {
1796 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1797 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1799 ValuePairs::Types(ref ef) => {
1800 ValuePairs::Types(ef.fold_with(folder))
1802 ValuePairs::TraitRefs(ref ef) => {
1803 ValuePairs::TraitRefs(ef.fold_with(folder))
1805 ValuePairs::PolyTraitRefs(ref ef) => {
1806 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1811 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1813 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1814 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1815 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1820 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1821 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1823 origin: self.origin.fold_with(folder),
1824 values: self.values.fold_with(folder)
1828 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1829 self.origin.visit_with(visitor) || self.values.visit_with(visitor)