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;
29 use ty::subst::Substs;
32 use ty::{TyVid, IntVid, FloatVid};
33 use ty::{self, Ty, TyCtxt};
34 use ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
35 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
36 use ty::relate::{Relate, RelateResult, TypeRelation};
37 use traits::{self, PredicateObligations, ProjectionMode};
38 use rustc_data_structures::unify::{self, UnificationTable};
39 use std::cell::{Cell, RefCell, Ref, RefMut};
42 use errors::DiagnosticBuilder;
43 use syntax_pos::{self, Span, DUMMY_SP};
44 use util::nodemap::{FnvHashMap, FnvHashSet, NodeMap};
46 use self::combine::CombineFields;
47 use self::higher_ranked::HrMatchResult;
48 use self::region_inference::{RegionVarBindings, RegionSnapshot};
49 use self::unify_key::ToType;
54 pub mod error_reporting;
59 pub mod region_inference;
63 pub mod type_variable;
67 pub struct InferOk<'tcx, T> {
69 pub obligations: PredicateObligations<'tcx>,
71 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
73 pub type Bound<T> = Option<T>;
74 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
75 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
77 /// A version of &ty::Tables which can be global or local.
78 /// Only the local version supports borrow_mut.
79 #[derive(Copy, Clone)]
80 pub enum InferTables<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
81 Global(&'a RefCell<ty::Tables<'gcx>>),
82 Local(&'a RefCell<ty::Tables<'tcx>>)
85 impl<'a, 'gcx, 'tcx> InferTables<'a, 'gcx, 'tcx> {
86 pub fn borrow(self) -> Ref<'a, ty::Tables<'tcx>> {
88 InferTables::Global(tables) => tables.borrow(),
89 InferTables::Local(tables) => tables.borrow()
93 pub fn borrow_mut(self) -> RefMut<'a, ty::Tables<'tcx>> {
95 InferTables::Global(_) => {
96 bug!("InferTables: infcx.tables.borrow_mut() outside of type-checking");
98 InferTables::Local(tables) => tables.borrow_mut()
103 pub struct InferCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
104 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
106 pub tables: InferTables<'a, 'gcx, 'tcx>,
108 // Cache for projections. This cache is snapshotted along with the
111 // Public so that `traits::project` can use it.
112 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
114 // We instantiate UnificationTable with bounds<Ty> because the
115 // types that might instantiate a general type variable have an
116 // order, represented by its upper and lower bounds.
117 type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
119 // Map from integral variable to the kind of integer it represents
120 int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
122 // Map from floating variable to the kind of float it represents
123 float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
125 // For region variables.
126 region_vars: RegionVarBindings<'a, 'gcx, 'tcx>,
128 pub parameter_environment: ty::ParameterEnvironment<'gcx>,
130 /// Caches the results of trait selection. This cache is used
131 /// for things that have to do with the parameters in scope.
132 pub selection_cache: traits::SelectionCache<'tcx>,
134 /// Caches the results of trait evaluation.
135 pub evaluation_cache: traits::EvaluationCache<'tcx>,
137 // the set of predicates on which errors have been reported, to
138 // avoid reporting the same error twice.
139 pub reported_trait_errors: RefCell<FnvHashSet<traits::TraitErrorKey<'tcx>>>,
141 // This is a temporary field used for toggling on normalization in the inference context,
142 // as we move towards the approach described here:
143 // https://internals.rust-lang.org/t/flattening-the-contexts-for-fun-and-profit/2293
144 // At a point sometime in the future normalization will be done by the typing context
148 // Sadly, the behavior of projection varies a bit depending on the
149 // stage of compilation. The specifics are given in the
150 // documentation for `ProjectionMode`.
151 projection_mode: ProjectionMode,
153 // When an error occurs, we want to avoid reporting "derived"
154 // errors that are due to this original failure. Normally, we
155 // handle this with the `err_count_on_creation` count, which
156 // basically just tracks how many errors were reported when we
157 // started type-checking a fn and checks to see if any new errors
158 // have been reported since then. Not great, but it works.
160 // However, when errors originated in other passes -- notably
161 // resolve -- this heuristic breaks down. Therefore, we have this
162 // auxiliary flag that one can set whenever one creates a
163 // type-error that is due to an error in a prior pass.
165 // Don't read this flag directly, call `is_tainted_by_errors()`
166 // and `set_tainted_by_errors()`.
167 tainted_by_errors_flag: Cell<bool>,
169 // Track how many errors were reported when this infcx is created.
170 // If the number of errors increases, that's also a sign (line
171 // `tained_by_errors`) to avoid reporting certain kinds of errors.
172 err_count_on_creation: usize,
174 // This flag is used for debugging, and is set to true if there are
175 // any obligations set during the current snapshot. In that case, the
176 // snapshot can't be rolled back.
177 pub obligations_in_snapshot: Cell<bool>,
180 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
181 /// region that each late-bound region was replaced with.
182 pub type SkolemizationMap = FnvHashMap<ty::BoundRegion, ty::Region>;
184 /// Why did we require that the two types be related?
186 /// See `error_reporting.rs` for more details
187 #[derive(Clone, Copy, Debug)]
188 pub enum TypeOrigin {
189 // Not yet categorized in a better way
192 // Checking that method of impl is compatible with trait
193 MethodCompatCheck(Span),
195 // Checking that this expression can be assigned where it needs to be
196 // FIXME(eddyb) #11161 is the original Expr required?
197 ExprAssignable(Span),
199 // Relating trait refs when resolving vtables
200 RelateTraitRefs(Span),
202 // Relating self types when resolving vtables
203 RelateSelfType(Span),
205 // Relating trait type parameters to those found in impl etc
206 RelateOutputImplTypes(Span),
208 // Computing common supertype in the arms of a match expression
209 MatchExpressionArm(Span, Span, hir::MatchSource),
211 // Computing common supertype in an if expression
214 // Computing common supertype of an if expression with no else counter-part
215 IfExpressionWithNoElse(Span),
217 // Computing common supertype in a range expression
218 RangeExpression(Span),
221 EquatePredicate(Span),
223 // `main` has wrong type
224 MainFunctionType(Span),
226 // `start` has wrong type
227 StartFunctionType(Span),
229 // intrinsic has wrong type
234 fn as_failure_str(&self) -> &'static str {
236 &TypeOrigin::Misc(_) |
237 &TypeOrigin::RelateSelfType(_) |
238 &TypeOrigin::RelateOutputImplTypes(_) |
239 &TypeOrigin::ExprAssignable(_) => "mismatched types",
240 &TypeOrigin::RelateTraitRefs(_) => "mismatched traits",
241 &TypeOrigin::MethodCompatCheck(_) => "method not compatible with trait",
242 &TypeOrigin::MatchExpressionArm(_, _, source) => match source {
243 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
244 _ => "match arms have incompatible types",
246 &TypeOrigin::IfExpression(_) => "if and else have incompatible types",
247 &TypeOrigin::IfExpressionWithNoElse(_) => "if may be missing an else clause",
248 &TypeOrigin::RangeExpression(_) => "start and end of range have incompatible types",
249 &TypeOrigin::EquatePredicate(_) => "equality predicate not satisfied",
250 &TypeOrigin::MainFunctionType(_) => "main function has wrong type",
251 &TypeOrigin::StartFunctionType(_) => "start function has wrong type",
252 &TypeOrigin::IntrinsicType(_) => "intrinsic has wrong type",
256 fn as_requirement_str(&self) -> &'static str {
258 &TypeOrigin::Misc(_) => "types are compatible",
259 &TypeOrigin::MethodCompatCheck(_) => "method type is compatible with trait",
260 &TypeOrigin::ExprAssignable(_) => "expression is assignable",
261 &TypeOrigin::RelateTraitRefs(_) => "traits are compatible",
262 &TypeOrigin::RelateSelfType(_) => "self type matches impl self type",
263 &TypeOrigin::RelateOutputImplTypes(_) => {
264 "trait type parameters matches those specified on the impl"
266 &TypeOrigin::MatchExpressionArm(_, _, _) => "match arms have compatible types",
267 &TypeOrigin::IfExpression(_) => "if and else have compatible types",
268 &TypeOrigin::IfExpressionWithNoElse(_) => "if missing an else returns ()",
269 &TypeOrigin::RangeExpression(_) => "start and end of range have compatible types",
270 &TypeOrigin::EquatePredicate(_) => "equality where clause is satisfied",
271 &TypeOrigin::MainFunctionType(_) => "`main` function has the correct type",
272 &TypeOrigin::StartFunctionType(_) => "`start` function has the correct type",
273 &TypeOrigin::IntrinsicType(_) => "intrinsic has the correct type",
278 /// See `error_reporting.rs` for more details
279 #[derive(Clone, Debug)]
280 pub enum ValuePairs<'tcx> {
281 Types(ExpectedFound<Ty<'tcx>>),
282 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
283 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
286 /// The trace designates the path through inference that we took to
287 /// encounter an error or subtyping constraint.
289 /// See `error_reporting.rs` for more details.
291 pub struct TypeTrace<'tcx> {
293 values: ValuePairs<'tcx>,
296 /// The origin of a `r1 <= r2` constraint.
298 /// See `error_reporting.rs` for more details
299 #[derive(Clone, Debug)]
300 pub enum SubregionOrigin<'tcx> {
301 // Arose from a subtyping relation
302 Subtype(TypeTrace<'tcx>),
304 // Stack-allocated closures cannot outlive innermost loop
305 // or function so as to ensure we only require finite stack
306 InfStackClosure(Span),
308 // Invocation of closure must be within its lifetime
311 // Dereference of reference must be within its lifetime
314 // Closure bound must not outlive captured free variables
315 FreeVariable(Span, ast::NodeId),
317 // Index into slice must be within its lifetime
320 // When casting `&'a T` to an `&'b Trait` object,
321 // relating `'a` to `'b`
322 RelateObjectBound(Span),
324 // Some type parameter was instantiated with the given type,
325 // and that type must outlive some region.
326 RelateParamBound(Span, Ty<'tcx>),
328 // The given region parameter was instantiated with a region
329 // that must outlive some other region.
330 RelateRegionParamBound(Span),
332 // A bound placed on type parameters that states that must outlive
333 // the moment of their instantiation.
334 RelateDefaultParamBound(Span, Ty<'tcx>),
336 // Creating a pointer `b` to contents of another reference
339 // Creating a pointer `b` to contents of an upvar
340 ReborrowUpvar(Span, ty::UpvarId),
342 // Data with type `Ty<'tcx>` was borrowed
343 DataBorrowed(Ty<'tcx>, Span),
345 // (&'a &'b T) where a >= b
346 ReferenceOutlivesReferent(Ty<'tcx>, Span),
348 // Type or region parameters must be in scope.
349 ParameterInScope(ParameterOrigin, Span),
351 // The type T of an expression E must outlive the lifetime for E.
352 ExprTypeIsNotInScope(Ty<'tcx>, Span),
354 // A `ref b` whose region does not enclose the decl site
355 BindingTypeIsNotValidAtDecl(Span),
357 // Regions appearing in a method receiver must outlive method call
360 // Regions appearing in a function argument must outlive func call
363 // Region in return type of invoked fn must enclose call
366 // Operands must be in scope
369 // Region resulting from a `&` expr must enclose the `&` expr
372 // An auto-borrow that does not enclose the expr where it occurs
375 // Region constraint arriving from destructor safety
376 SafeDestructor(Span),
379 /// Places that type/region parameters can appear.
380 #[derive(Clone, Copy, Debug)]
381 pub enum ParameterOrigin {
383 MethodCall, // foo.bar() <-- parameters on impl providing bar()
384 OverloadedOperator, // a + b when overloaded
385 OverloadedDeref, // *a when overloaded
388 /// Times when we replace late-bound regions with variables:
389 #[derive(Clone, Copy, Debug)]
390 pub enum LateBoundRegionConversionTime {
391 /// when a fn is called
394 /// when two higher-ranked types are compared
397 /// when projecting an associated type
398 AssocTypeProjection(ast::Name),
401 /// Reasons to create a region inference variable
403 /// See `error_reporting.rs` for more details
404 #[derive(Clone, Debug)]
405 pub enum RegionVariableOrigin {
406 // Region variables created for ill-categorized reasons,
407 // mostly indicates places in need of refactoring
410 // Regions created by a `&P` or `[...]` pattern
413 // Regions created by `&` operator
416 // Regions created as part of an autoref of a method receiver
419 // Regions created as part of an automatic coercion
422 // Region variables created as the values for early-bound regions
423 EarlyBoundRegion(Span, ast::Name),
425 // Region variables created for bound regions
426 // in a function or method that is called
427 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
429 UpvarRegion(ty::UpvarId, Span),
431 BoundRegionInCoherence(ast::Name),
434 #[derive(Copy, Clone, Debug)]
435 pub enum FixupError {
436 UnresolvedIntTy(IntVid),
437 UnresolvedFloatTy(FloatVid),
441 impl fmt::Display for FixupError {
442 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
443 use self::FixupError::*;
446 UnresolvedIntTy(_) => {
447 write!(f, "cannot determine the type of this integer; \
448 add a suffix to specify the type explicitly")
450 UnresolvedFloatTy(_) => {
451 write!(f, "cannot determine the type of this number; \
452 add a suffix to specify the type explicitly")
454 UnresolvedTy(_) => write!(f, "unconstrained type")
459 /// Helper type of a temporary returned by tcx.infer_ctxt(...).
460 /// Necessary because we can't write the following bound:
461 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
462 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
463 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
464 arenas: ty::CtxtArenas<'tcx>,
465 tables: Option<RefCell<ty::Tables<'tcx>>>,
466 param_env: Option<ty::ParameterEnvironment<'gcx>>,
467 projection_mode: ProjectionMode,
471 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
472 pub fn infer_ctxt(self,
473 tables: Option<ty::Tables<'tcx>>,
474 param_env: Option<ty::ParameterEnvironment<'gcx>>,
475 projection_mode: ProjectionMode)
476 -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
479 arenas: ty::CtxtArenas::new(),
480 tables: tables.map(RefCell::new),
481 param_env: param_env,
482 projection_mode: projection_mode,
487 pub fn normalizing_infer_ctxt(self, projection_mode: ProjectionMode)
488 -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
491 arenas: ty::CtxtArenas::new(),
494 projection_mode: projection_mode,
499 /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
500 /// for MemCategorizationContext/ExprUseVisitor.
501 /// If any inference functionality is used, ICEs will occur.
502 pub fn borrowck_fake_infer_ctxt(self, param_env: ty::ParameterEnvironment<'gcx>)
503 -> InferCtxt<'a, 'gcx, 'gcx> {
506 tables: InferTables::Global(&self.tables),
507 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
508 int_unification_table: RefCell::new(UnificationTable::new()),
509 float_unification_table: RefCell::new(UnificationTable::new()),
510 region_vars: RegionVarBindings::new(self),
511 parameter_environment: param_env,
512 selection_cache: traits::SelectionCache::new(),
513 evaluation_cache: traits::EvaluationCache::new(),
514 projection_cache: RefCell::new(traits::ProjectionCache::new()),
515 reported_trait_errors: RefCell::new(FnvHashSet()),
517 projection_mode: ProjectionMode::AnyFinal,
518 tainted_by_errors_flag: Cell::new(false),
519 err_count_on_creation: self.sess.err_count(),
520 obligations_in_snapshot: Cell::new(false),
525 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
526 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
527 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
529 let InferCtxtBuilder {
537 let tables = if let Some(ref tables) = *tables {
538 InferTables::Local(tables)
540 InferTables::Global(&global_tcx.tables)
542 let param_env = param_env.take().unwrap_or_else(|| {
543 global_tcx.empty_parameter_environment()
545 global_tcx.enter_local(arenas, |tcx| f(InferCtxt {
548 projection_cache: RefCell::new(traits::ProjectionCache::new()),
549 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
550 int_unification_table: RefCell::new(UnificationTable::new()),
551 float_unification_table: RefCell::new(UnificationTable::new()),
552 region_vars: RegionVarBindings::new(tcx),
553 parameter_environment: param_env,
554 selection_cache: traits::SelectionCache::new(),
555 evaluation_cache: traits::EvaluationCache::new(),
556 reported_trait_errors: RefCell::new(FnvHashSet()),
557 normalize: normalize,
558 projection_mode: projection_mode,
559 tainted_by_errors_flag: Cell::new(false),
560 err_count_on_creation: tcx.sess.err_count(),
561 obligations_in_snapshot: Cell::new(false),
566 impl<T> ExpectedFound<T> {
567 fn new(a_is_expected: bool, a: T, b: T) -> Self {
569 ExpectedFound {expected: a, found: b}
571 ExpectedFound {expected: b, found: a}
576 impl<'tcx, T> InferOk<'tcx, T> {
577 pub fn unit(self) -> InferOk<'tcx, ()> {
578 InferOk { value: (), obligations: self.obligations }
582 #[must_use = "once you start a snapshot, you should always consume it"]
583 pub struct CombinedSnapshot {
584 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
585 type_snapshot: type_variable::Snapshot,
586 int_snapshot: unify::Snapshot<ty::IntVid>,
587 float_snapshot: unify::Snapshot<ty::FloatVid>,
588 region_vars_snapshot: RegionSnapshot,
589 obligations_in_snapshot: bool,
592 /// Helper trait for shortening the lifetimes inside a
593 /// value for post-type-checking normalization.
594 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
595 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self;
598 macro_rules! items { ($($item:item)+) => ($($item)+) }
599 macro_rules! impl_trans_normalize {
600 ($lt_gcx:tt, $($ty:ty),+) => {
601 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
602 fn trans_normalize<'a, 'tcx>(&self,
603 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>)
605 infcx.normalize_projections_in(self)
611 impl_trans_normalize!('gcx,
616 &'gcx ty::BareFnTy<'gcx>,
617 ty::ClosureSubsts<'gcx>,
618 ty::PolyTraitRef<'gcx>
621 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
622 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self {
624 LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx) },
625 LvalueTy::Downcast { adt_def, substs, variant_index } => {
628 substs: substs.trans_normalize(infcx),
629 variant_index: variant_index
636 // NOTE: Callable from trans only!
637 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
638 pub fn normalize_associated_type<T>(self, value: &T) -> T
639 where T: TransNormalize<'tcx>
641 debug!("normalize_associated_type(t={:?})", value);
643 let value = self.erase_regions(value);
645 if !value.has_projection_types() {
649 self.infer_ctxt(None, None, ProjectionMode::Any).enter(|infcx| {
650 value.trans_normalize(&infcx)
654 pub fn normalize_associated_type_in_env<T>(
655 self, value: &T, env: &'a ty::ParameterEnvironment<'tcx>
657 where T: TransNormalize<'tcx>
659 debug!("normalize_associated_type_in_env(t={:?})", value);
661 let value = self.erase_regions(value);
663 if !value.has_projection_types() {
667 self.infer_ctxt(None, Some(env.clone()), ProjectionMode::Any).enter(|infcx| {
668 value.trans_normalize(&infcx)
673 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
674 fn normalize_projections_in<T>(&self, value: &T) -> T::Lifted
675 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
677 let mut selcx = traits::SelectionContext::new(self);
678 let cause = traits::ObligationCause::dummy();
679 let traits::Normalized { value: result, obligations } =
680 traits::normalize(&mut selcx, cause, value);
682 debug!("normalize_projections_in: result={:?} obligations={:?}",
683 result, obligations);
685 let mut fulfill_cx = traits::FulfillmentContext::new();
687 for obligation in obligations {
688 fulfill_cx.register_predicate_obligation(self, obligation);
691 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
694 pub fn drain_fulfillment_cx_or_panic<T>(&self,
696 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
699 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
701 debug!("drain_fulfillment_cx_or_panic()");
703 let when = "resolving bounds after type-checking";
704 let v = match self.drain_fulfillment_cx(fulfill_cx, result) {
707 span_bug!(span, "Encountered errors `{:?}` {}", errors, when);
711 match self.tcx.lift_to_global(&v) {
714 span_bug!(span, "Uninferred types/regions in `{:?}` {}", v, when);
719 /// Finishes processes any obligations that remain in the fulfillment
720 /// context, and then "freshens" and returns `result`. This is
721 /// primarily used during normalization and other cases where
722 /// processing the obligations in `fulfill_cx` may cause type
723 /// inference variables that appear in `result` to be unified, and
724 /// hence we need to process those obligations to get the complete
725 /// picture of the type.
726 pub fn drain_fulfillment_cx<T>(&self,
727 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
729 -> Result<T,Vec<traits::FulfillmentError<'tcx>>>
730 where T : TypeFoldable<'tcx>
732 debug!("drain_fulfillment_cx(result={:?})",
735 // In principle, we only need to do this so long as `result`
736 // contains unbound type parameters. It could be a slight
737 // optimization to stop iterating early.
738 fulfill_cx.select_all_or_error(self)?;
740 let result = self.resolve_type_vars_if_possible(result);
741 Ok(self.tcx.erase_regions(&result))
744 pub fn projection_mode(&self) -> ProjectionMode {
748 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
749 t.fold_with(&mut self.freshener())
752 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
754 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
759 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
760 freshen::TypeFreshener::new(self)
763 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
764 use ty::error::UnconstrainedNumeric::Neither;
765 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
767 ty::TyInfer(ty::IntVar(vid)) => {
768 if self.int_unification_table.borrow_mut().has_value(vid) {
774 ty::TyInfer(ty::FloatVar(vid)) => {
775 if self.float_unification_table.borrow_mut().has_value(vid) {
785 /// Returns a type variable's default fallback if any exists. A default
786 /// must be attached to the variable when created, if it is created
787 /// without a default, this will return None.
789 /// This code does not apply to integral or floating point variables,
790 /// only to use declared defaults.
792 /// See `new_ty_var_with_default` to create a type variable with a default.
793 /// See `type_variable::Default` for details about what a default entails.
794 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
796 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
801 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
802 let mut variables = Vec::new();
804 let unbound_ty_vars = self.type_variables
806 .unsolved_variables()
808 .map(|t| self.tcx.mk_var(t));
810 let unbound_int_vars = self.int_unification_table
812 .unsolved_variables()
814 .map(|v| self.tcx.mk_int_var(v));
816 let unbound_float_vars = self.float_unification_table
818 .unsolved_variables()
820 .map(|v| self.tcx.mk_float_var(v));
822 variables.extend(unbound_ty_vars);
823 variables.extend(unbound_int_vars);
824 variables.extend(unbound_float_vars);
829 fn combine_fields(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
830 -> CombineFields<'a, 'gcx, 'tcx> {
833 a_is_expected: a_is_expected,
836 obligations: PredicateObligations::new(),
840 pub fn equate<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
841 -> InferResult<'tcx, T>
842 where T: Relate<'tcx>
844 let mut equate = self.combine_fields(a_is_expected, trace).equate();
845 let result = equate.relate(a, b);
846 result.map(|t| InferOk { value: t, obligations: equate.obligations() })
849 pub fn sub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
850 -> InferResult<'tcx, T>
851 where T: Relate<'tcx>
853 let mut sub = self.combine_fields(a_is_expected, trace).sub();
854 let result = sub.relate(a, b);
855 result.map(|t| InferOk { value: t, obligations: sub.obligations() })
858 pub fn lub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
859 -> InferResult<'tcx, T>
860 where T: Relate<'tcx>
862 let mut lub = self.combine_fields(a_is_expected, trace).lub();
863 let result = lub.relate(a, b);
864 result.map(|t| InferOk { value: t, obligations: lub.obligations() })
867 pub fn glb<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
868 -> InferResult<'tcx, T>
869 where T: Relate<'tcx>
871 let mut glb = self.combine_fields(a_is_expected, trace).glb();
872 let result = glb.relate(a, b);
873 result.map(|t| InferOk { value: t, obligations: glb.obligations() })
876 fn start_snapshot(&self) -> CombinedSnapshot {
877 debug!("start_snapshot()");
879 let obligations_in_snapshot = self.obligations_in_snapshot.get();
880 self.obligations_in_snapshot.set(false);
883 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
884 type_snapshot: self.type_variables.borrow_mut().snapshot(),
885 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
886 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
887 region_vars_snapshot: self.region_vars.start_snapshot(),
888 obligations_in_snapshot: obligations_in_snapshot,
892 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
893 debug!("rollback_to(cause={})", cause);
894 let CombinedSnapshot { projection_cache_snapshot,
898 region_vars_snapshot,
899 obligations_in_snapshot } = snapshot;
901 assert!(!self.obligations_in_snapshot.get());
902 self.obligations_in_snapshot.set(obligations_in_snapshot);
904 self.projection_cache
906 .rollback_to(projection_cache_snapshot);
909 .rollback_to(type_snapshot);
910 self.int_unification_table
912 .rollback_to(int_snapshot);
913 self.float_unification_table
915 .rollback_to(float_snapshot);
917 .rollback_to(region_vars_snapshot);
920 fn commit_from(&self, snapshot: CombinedSnapshot) {
921 debug!("commit_from()");
922 let CombinedSnapshot { projection_cache_snapshot,
926 region_vars_snapshot,
927 obligations_in_snapshot } = snapshot;
929 self.obligations_in_snapshot.set(obligations_in_snapshot);
931 self.projection_cache
933 .commit(projection_cache_snapshot);
936 .commit(type_snapshot);
937 self.int_unification_table
939 .commit(int_snapshot);
940 self.float_unification_table
942 .commit(float_snapshot);
944 .commit(region_vars_snapshot);
947 /// Execute `f` and commit the bindings
948 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
952 let snapshot = self.start_snapshot();
954 self.commit_from(snapshot);
958 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
959 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
960 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
962 debug!("commit_if_ok()");
963 let snapshot = self.start_snapshot();
964 let r = f(&snapshot);
965 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
967 Ok(_) => { self.commit_from(snapshot); }
968 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
973 // Execute `f` in a snapshot, and commit the bindings it creates
974 pub fn in_snapshot<T, F>(&self, f: F) -> T where
975 F: FnOnce(&CombinedSnapshot) -> T
977 debug!("in_snapshot()");
978 let snapshot = self.start_snapshot();
979 let r = f(&snapshot);
980 self.commit_from(snapshot);
984 /// Execute `f` and commit only the region bindings if successful.
985 /// The function f must be very careful not to leak any non-region
986 /// variables that get created.
987 pub fn commit_regions_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
988 F: FnOnce() -> Result<T, E>
990 debug!("commit_regions_if_ok()");
991 let CombinedSnapshot { projection_cache_snapshot,
995 region_vars_snapshot,
996 obligations_in_snapshot } = self.start_snapshot();
998 let r = self.commit_if_ok(|_| f());
1000 debug!("commit_regions_if_ok: rolling back everything but regions");
1002 assert!(!self.obligations_in_snapshot.get());
1003 self.obligations_in_snapshot.set(obligations_in_snapshot);
1005 // Roll back any non-region bindings - they should be resolved
1006 // inside `f`, with, e.g. `resolve_type_vars_if_possible`.
1007 self.projection_cache
1009 .rollback_to(projection_cache_snapshot);
1012 .rollback_to(type_snapshot);
1013 self.int_unification_table
1015 .rollback_to(int_snapshot);
1016 self.float_unification_table
1018 .rollback_to(float_snapshot);
1020 // Commit region vars that may escape through resolved types.
1022 .commit(region_vars_snapshot);
1027 /// Execute `f` then unroll any bindings it creates
1028 pub fn probe<R, F>(&self, f: F) -> R where
1029 F: FnOnce(&CombinedSnapshot) -> R,
1032 let snapshot = self.start_snapshot();
1033 let r = f(&snapshot);
1034 self.rollback_to("probe", snapshot);
1038 pub fn add_given(&self,
1039 sub: ty::FreeRegion,
1042 self.region_vars.add_given(sub, sup);
1045 pub fn sub_types(&self,
1046 a_is_expected: bool,
1050 -> InferResult<'tcx, ()>
1052 debug!("sub_types({:?} <: {:?})", a, b);
1053 self.commit_if_ok(|_| {
1054 let trace = TypeTrace::types(origin, a_is_expected, a, b);
1055 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1059 pub fn can_sub_types(&self,
1065 let origin = TypeOrigin::Misc(syntax_pos::DUMMY_SP);
1066 let trace = TypeTrace::types(origin, true, a, b);
1067 self.sub(true, trace, &a, &b).map(|_| ())
1071 pub fn eq_types(&self,
1072 a_is_expected: bool,
1076 -> InferResult<'tcx, ()>
1078 self.commit_if_ok(|_| {
1079 let trace = TypeTrace::types(origin, a_is_expected, a, b);
1080 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1084 pub fn eq_trait_refs(&self,
1085 a_is_expected: bool,
1087 a: ty::TraitRef<'tcx>,
1088 b: ty::TraitRef<'tcx>)
1089 -> InferResult<'tcx, ()>
1091 debug!("eq_trait_refs({:?} = {:?})", a, b);
1092 self.commit_if_ok(|_| {
1093 let trace = TypeTrace {
1095 values: TraitRefs(ExpectedFound::new(a_is_expected, a, b))
1097 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1101 pub fn eq_impl_headers(&self,
1102 a_is_expected: bool,
1104 a: &ty::ImplHeader<'tcx>,
1105 b: &ty::ImplHeader<'tcx>)
1106 -> InferResult<'tcx, ()>
1108 debug!("eq_impl_header({:?} = {:?})", a, b);
1109 match (a.trait_ref, b.trait_ref) {
1110 (Some(a_ref), Some(b_ref)) => self.eq_trait_refs(a_is_expected, origin, a_ref, b_ref),
1111 (None, None) => self.eq_types(a_is_expected, origin, a.self_ty, b.self_ty),
1112 _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
1116 pub fn sub_poly_trait_refs(&self,
1117 a_is_expected: bool,
1119 a: ty::PolyTraitRef<'tcx>,
1120 b: ty::PolyTraitRef<'tcx>)
1121 -> InferResult<'tcx, ()>
1123 debug!("sub_poly_trait_refs({:?} <: {:?})", a, b);
1124 self.commit_if_ok(|_| {
1125 let trace = TypeTrace {
1127 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b))
1129 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1133 pub fn sub_regions(&self,
1134 origin: SubregionOrigin<'tcx>,
1137 debug!("sub_regions({:?} <: {:?})", a, b);
1138 self.region_vars.make_subregion(origin, a, b);
1141 pub fn equality_predicate(&self,
1143 predicate: &ty::PolyEquatePredicate<'tcx>)
1144 -> InferResult<'tcx, ()>
1146 self.commit_if_ok(|snapshot| {
1147 let (ty::EquatePredicate(a, b), skol_map) =
1148 self.skolemize_late_bound_regions(predicate, snapshot);
1149 let origin = TypeOrigin::EquatePredicate(span);
1150 let eqty_ok = self.eq_types(false, origin, a, b)?;
1151 self.leak_check(false, span, &skol_map, snapshot)?;
1152 self.pop_skolemized(skol_map, snapshot);
1157 pub fn region_outlives_predicate(&self,
1159 predicate: &ty::PolyRegionOutlivesPredicate)
1162 self.commit_if_ok(|snapshot| {
1163 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1164 self.skolemize_late_bound_regions(predicate, snapshot);
1165 let origin = RelateRegionParamBound(span);
1166 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1167 self.leak_check(false, span, &skol_map, snapshot)?;
1168 Ok(self.pop_skolemized(skol_map, snapshot))
1172 pub fn next_ty_var_id(&self, diverging: bool) -> TyVid {
1175 .new_var(diverging, None)
1178 pub fn next_ty_var(&self) -> Ty<'tcx> {
1179 self.tcx.mk_var(self.next_ty_var_id(false))
1182 pub fn next_ty_var_with_default(&self,
1183 default: Option<type_variable::Default<'tcx>>) -> Ty<'tcx> {
1184 let ty_var_id = self.type_variables
1186 .new_var(false, default);
1188 self.tcx.mk_var(ty_var_id)
1191 pub fn next_diverging_ty_var(&self) -> Ty<'tcx> {
1192 self.tcx.mk_var(self.next_ty_var_id(true))
1195 pub fn next_ty_vars(&self, n: usize) -> Vec<Ty<'tcx>> {
1196 (0..n).map(|_i| self.next_ty_var()).collect()
1199 pub fn next_int_var_id(&self) -> IntVid {
1200 self.int_unification_table
1205 pub fn next_float_var_id(&self) -> FloatVid {
1206 self.float_unification_table
1211 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region {
1212 ty::ReVar(self.region_vars.new_region_var(origin))
1215 pub fn region_vars_for_defs(&self,
1217 defs: &[ty::RegionParameterDef])
1218 -> Vec<ty::Region> {
1220 .map(|d| self.next_region_var(EarlyBoundRegion(span, d.name)))
1224 // We have to take `&mut Substs` in order to provide the correct substitutions for defaults
1225 // along the way, for this reason we don't return them.
1226 pub fn type_vars_for_defs(&self,
1228 space: subst::ParamSpace,
1229 substs: &mut Substs<'tcx>,
1230 defs: &[ty::TypeParameterDef<'tcx>]) {
1232 for def in defs.iter() {
1233 let default = def.default.map(|default| {
1234 type_variable::Default {
1235 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1237 def_id: def.default_def_id
1241 let ty_var = self.next_ty_var_with_default(default);
1242 substs.types.push(space, ty_var);
1246 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1247 /// type/region parameter to a fresh inference variable.
1248 pub fn fresh_substs_for_generics(&self,
1250 generics: &ty::Generics<'tcx>)
1251 -> &'tcx subst::Substs<'tcx>
1253 let type_params = subst::VecPerParamSpace::empty();
1256 generics.regions.map(
1257 |d| self.next_region_var(EarlyBoundRegion(span, d.name)));
1259 let mut substs = subst::Substs::new(type_params, region_params);
1261 for space in subst::ParamSpace::all().iter() {
1262 self.type_vars_for_defs(
1266 generics.types.get_slice(*space));
1269 self.tcx.mk_substs(substs)
1272 /// Given a set of generics defined on a trait, returns a substitution mapping each output
1273 /// type/region parameter to a fresh inference variable, and mapping the self type to
1275 pub fn fresh_substs_for_trait(&self,
1277 generics: &ty::Generics<'tcx>,
1279 -> subst::Substs<'tcx>
1282 assert!(generics.types.len(subst::SelfSpace) == 1);
1283 assert!(generics.types.len(subst::FnSpace) == 0);
1284 assert!(generics.regions.len(subst::SelfSpace) == 0);
1285 assert!(generics.regions.len(subst::FnSpace) == 0);
1287 let type_params = Vec::new();
1289 let region_param_defs = generics.regions.get_slice(subst::TypeSpace);
1290 let regions = self.region_vars_for_defs(span, region_param_defs);
1292 let mut substs = subst::Substs::new_trait(type_params, regions, self_ty);
1294 let type_parameter_defs = generics.types.get_slice(subst::TypeSpace);
1295 self.type_vars_for_defs(span, subst::TypeSpace, &mut substs, type_parameter_defs);
1300 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region {
1301 self.region_vars.new_bound(debruijn)
1304 /// Apply `adjustment` to the type of `expr`
1305 pub fn adjust_expr_ty(&self,
1307 adjustment: Option<&adjustment::AutoAdjustment<'tcx>>)
1310 let raw_ty = self.expr_ty(expr);
1311 let raw_ty = self.shallow_resolve(raw_ty);
1312 let resolve_ty = |ty: Ty<'tcx>| self.resolve_type_vars_if_possible(&ty);
1313 raw_ty.adjust(self.tcx,
1317 |method_call| self.tables
1321 .map(|method| resolve_ty(method.ty)))
1324 /// True if errors have been reported since this infcx was
1325 /// created. This is sometimes used as a heuristic to skip
1326 /// reporting errors that often occur as a result of earlier
1327 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1328 /// inference variables, regionck errors).
1329 pub fn is_tainted_by_errors(&self) -> bool {
1330 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1331 tainted_by_errors_flag={})",
1332 self.tcx.sess.err_count(),
1333 self.err_count_on_creation,
1334 self.tainted_by_errors_flag.get());
1336 if self.tcx.sess.err_count() > self.err_count_on_creation {
1337 return true; // errors reported since this infcx was made
1339 self.tainted_by_errors_flag.get()
1342 /// Set the "tainted by errors" flag to true. We call this when we
1343 /// observe an error from a prior pass.
1344 pub fn set_tainted_by_errors(&self) {
1345 debug!("set_tainted_by_errors()");
1346 self.tainted_by_errors_flag.set(true)
1349 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1350 match self.tables.borrow().node_types.get(&id) {
1353 None if self.is_tainted_by_errors() =>
1356 bug!("no type for node {}: {} in fcx",
1357 id, self.tcx.map.node_to_string(id));
1362 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1363 match self.tables.borrow().node_types.get(&ex.id) {
1366 bug!("no type for expr in fcx");
1371 pub fn resolve_regions_and_report_errors(&self,
1372 free_regions: &FreeRegionMap,
1373 subject_node_id: ast::NodeId) {
1374 let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1375 if !self.is_tainted_by_errors() {
1376 // As a heuristic, just skip reporting region errors
1377 // altogether if other errors have been reported while
1378 // this infcx was in use. This is totally hokey but
1379 // otherwise we have a hard time separating legit region
1380 // errors from silly ones.
1381 self.report_region_errors(&errors); // see error_reporting.rs
1385 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1386 self.resolve_type_vars_if_possible(&t).to_string()
1389 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1390 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1391 format!("({})", tstrs.join(", "))
1394 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1395 self.resolve_type_vars_if_possible(t).to_string()
1398 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1400 ty::TyInfer(ty::TyVar(v)) => {
1401 // Not entirely obvious: if `typ` is a type variable,
1402 // it can be resolved to an int/float variable, which
1403 // can then be recursively resolved, hence the
1404 // recursion. Note though that we prevent type
1405 // variables from unifying to other type variables
1406 // directly (though they may be embedded
1407 // structurally), and we prevent cycles in any case,
1408 // so this recursion should always be of very limited
1410 self.type_variables.borrow_mut()
1412 .map(|t| self.shallow_resolve(t))
1416 ty::TyInfer(ty::IntVar(v)) => {
1417 self.int_unification_table
1420 .map(|v| v.to_type(self.tcx))
1424 ty::TyInfer(ty::FloatVar(v)) => {
1425 self.float_unification_table
1428 .map(|v| v.to_type(self.tcx))
1438 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1439 where T: TypeFoldable<'tcx>
1442 * Where possible, replaces type/int/float variables in
1443 * `value` with their final value. Note that region variables
1444 * are unaffected. If a type variable has not been unified, it
1445 * is left as is. This is an idempotent operation that does
1446 * not affect inference state in any way and so you can do it
1450 if !value.needs_infer() {
1451 return value.clone(); // avoid duplicated subst-folding
1453 let mut r = resolve::OpportunisticTypeResolver::new(self);
1454 value.fold_with(&mut r)
1457 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1458 where T: TypeFoldable<'tcx>
1460 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1461 value.fold_with(&mut r)
1464 /// Resolves all type variables in `t` and then, if any were left
1465 /// unresolved, substitutes an error type. This is used after the
1466 /// main checking when doing a second pass before writeback. The
1467 /// justification is that writeback will produce an error for
1468 /// these unconstrained type variables.
1469 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1470 let ty = self.resolve_type_vars_if_possible(t);
1471 if ty.references_error() || ty.is_ty_var() {
1472 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1479 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1481 * Attempts to resolve all type/region variables in
1482 * `value`. Region inference must have been run already (e.g.,
1483 * by calling `resolve_regions_and_report_errors`). If some
1484 * variable was never unified, an `Err` results.
1486 * This method is idempotent, but it not typically not invoked
1487 * except during the writeback phase.
1490 resolve::fully_resolve(self, value)
1493 // [Note-Type-error-reporting]
1494 // An invariant is that anytime the expected or actual type is TyError (the special
1495 // error type, meaning that an error occurred when typechecking this expression),
1496 // this is a derived error. The error cascaded from another error (that was already
1497 // reported), so it's not useful to display it to the user.
1498 // The following methods implement this logic.
1499 // They check if either the actual or expected type is TyError, and don't print the error
1500 // in this case. The typechecker should only ever report type errors involving mismatched
1501 // types using one of these methods, and should not call span_err directly for such
1504 pub fn type_error_message<M>(&self,
1507 actual_ty: Ty<'tcx>)
1508 where M: FnOnce(String) -> String,
1510 self.type_error_struct(sp, mk_msg, actual_ty).emit();
1513 // FIXME: this results in errors without an error code. Deprecate?
1514 pub fn type_error_struct<M>(&self,
1517 actual_ty: Ty<'tcx>)
1518 -> DiagnosticBuilder<'tcx>
1519 where M: FnOnce(String) -> String,
1521 self.type_error_struct_with_diag(sp, |actual_ty| {
1522 self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1526 pub fn type_error_struct_with_diag<M>(&self,
1529 actual_ty: Ty<'tcx>)
1530 -> DiagnosticBuilder<'tcx>
1531 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1533 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1534 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1536 // Don't report an error if actual type is TyError.
1537 if actual_ty.references_error() {
1538 return self.tcx.sess.diagnostic().struct_dummy();
1541 mk_diag(self.ty_to_string(actual_ty))
1544 pub fn report_mismatched_types(&self,
1548 err: TypeError<'tcx>) {
1549 let trace = TypeTrace {
1551 values: Types(ExpectedFound {
1556 self.report_and_explain_type_error(trace, &err).emit();
1559 pub fn report_conflicting_default_types(&self,
1561 expected: type_variable::Default<'tcx>,
1562 actual: type_variable::Default<'tcx>) {
1563 let trace = TypeTrace {
1564 origin: TypeOrigin::Misc(span),
1565 values: Types(ExpectedFound {
1566 expected: expected.ty,
1571 self.report_and_explain_type_error(
1573 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1580 pub fn replace_late_bound_regions_with_fresh_var<T>(
1583 lbrct: LateBoundRegionConversionTime,
1584 value: &ty::Binder<T>)
1585 -> (T, FnvHashMap<ty::BoundRegion,ty::Region>)
1586 where T : TypeFoldable<'tcx>
1588 self.tcx.replace_late_bound_regions(
1590 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1593 /// Given a higher-ranked projection predicate like:
1595 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1597 /// and a target trait-ref like:
1599 /// <T as Fn<&'x u32>>
1601 /// find a substitution `S` for the higher-ranked regions (here,
1602 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1603 /// and then return the value (here, `&'a u32`) but with the
1604 /// substitution applied (hence, `&'x u32`).
1606 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1608 pub fn match_poly_projection_predicate(&self,
1610 match_a: ty::PolyProjectionPredicate<'tcx>,
1611 match_b: ty::TraitRef<'tcx>)
1612 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1614 let span = origin.span();
1615 let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1616 let trace = TypeTrace {
1618 values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1621 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1622 let combine = self.combine_fields(true, trace);
1623 let result = combine.higher_ranked_match(span, &match_pair, &match_b)?;
1624 Ok(InferOk { value: result, obligations: combine.obligations })
1627 /// See `verify_generic_bound` method in `region_inference`
1628 pub fn verify_generic_bound(&self,
1629 origin: SubregionOrigin<'tcx>,
1630 kind: GenericKind<'tcx>,
1632 bound: VerifyBound) {
1633 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1638 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1641 pub fn can_equate<T>(&self, a: &T, b: &T) -> UnitResult<'tcx>
1642 where T: Relate<'tcx> + fmt::Debug
1644 debug!("can_equate({:?}, {:?})", a, b);
1646 // Gin up a dummy trace, since this won't be committed
1647 // anyhow. We should make this typetrace stuff more
1648 // generic so we don't have to do anything quite this
1650 self.equate(true, TypeTrace::dummy(self.tcx), a, b)
1654 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1655 let ty = self.node_type(id);
1656 self.resolve_type_vars_or_error(&ty)
1659 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1660 let ty = self.adjust_expr_ty(expr, self.tables.borrow().adjustments.get(&expr.id));
1661 self.resolve_type_vars_or_error(&ty)
1664 pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1665 let ty = self.resolve_type_vars_if_possible(&ty);
1666 if let Some(ty) = self.tcx.lift_to_global(&ty) {
1667 // Even if the type may have no inference variables, during
1668 // type-checking closure types are in local tables only.
1669 let local_closures = match self.tables {
1670 InferTables::Local(_) => ty.has_closure_types(),
1671 InferTables::Global(_) => false
1673 if !local_closures {
1674 return ty.moves_by_default(self.tcx.global_tcx(), self.param_env(), span);
1678 // this can get called from typeck (by euv), and moves_by_default
1679 // rightly refuses to work with inference variables, but
1680 // moves_by_default has a cache, which we want to use in other
1682 !traits::type_known_to_meet_builtin_bound(self, ty, ty::BoundCopy, span)
1685 pub fn node_method_ty(&self, method_call: ty::MethodCall)
1686 -> Option<Ty<'tcx>> {
1691 .map(|method| method.ty)
1692 .map(|ty| self.resolve_type_vars_if_possible(&ty))
1695 pub fn node_method_id(&self, method_call: ty::MethodCall)
1701 .map(|method| method.def_id)
1704 pub fn adjustments(&self) -> Ref<NodeMap<adjustment::AutoAdjustment<'tcx>>> {
1705 fn project_adjustments<'a, 'tcx>(tables: &'a ty::Tables<'tcx>)
1706 -> &'a NodeMap<adjustment::AutoAdjustment<'tcx>> {
1710 Ref::map(self.tables.borrow(), project_adjustments)
1713 pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1714 self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1717 pub fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<CodeExtent> {
1718 self.tcx.region_maps.temporary_scope(rvalue_id)
1721 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
1722 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1725 pub fn param_env(&self) -> &ty::ParameterEnvironment<'gcx> {
1726 &self.parameter_environment
1729 pub fn closure_kind(&self,
1731 -> Option<ty::ClosureKind>
1733 if def_id.is_local() {
1734 self.tables.borrow().closure_kinds.get(&def_id).cloned()
1736 // During typeck, ALL closures are local. But afterwards,
1737 // during trans, we see closure ids from other traits.
1738 // That may require loading the closure data out of the
1740 Some(self.tcx.closure_kind(def_id))
1744 pub fn closure_type(&self,
1746 substs: ty::ClosureSubsts<'tcx>)
1747 -> ty::ClosureTy<'tcx>
1749 if let InferTables::Local(tables) = self.tables {
1750 if let Some(ty) = tables.borrow().closure_tys.get(&def_id) {
1751 return ty.subst(self.tcx, substs.func_substs);
1755 let closure_ty = self.tcx.closure_type(def_id, substs);
1757 let closure_ty = self.tcx.erase_regions(&closure_ty);
1759 if !closure_ty.has_projection_types() {
1763 self.normalize_projections_in(&closure_ty)
1770 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1771 pub fn span(&self) -> Span {
1775 pub fn types(origin: TypeOrigin,
1776 a_is_expected: bool,
1779 -> TypeTrace<'tcx> {
1782 values: Types(ExpectedFound::new(a_is_expected, a, b))
1786 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1788 origin: TypeOrigin::Misc(syntax_pos::DUMMY_SP),
1789 values: Types(ExpectedFound {
1790 expected: tcx.types.err,
1791 found: tcx.types.err,
1797 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1798 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1799 write!(f, "TypeTrace({:?})", self.origin)
1804 pub fn span(&self) -> Span {
1806 TypeOrigin::MethodCompatCheck(span) => span,
1807 TypeOrigin::ExprAssignable(span) => span,
1808 TypeOrigin::Misc(span) => span,
1809 TypeOrigin::RelateTraitRefs(span) => span,
1810 TypeOrigin::RelateSelfType(span) => span,
1811 TypeOrigin::RelateOutputImplTypes(span) => span,
1812 TypeOrigin::MatchExpressionArm(match_span, _, _) => match_span,
1813 TypeOrigin::IfExpression(span) => span,
1814 TypeOrigin::IfExpressionWithNoElse(span) => span,
1815 TypeOrigin::RangeExpression(span) => span,
1816 TypeOrigin::EquatePredicate(span) => span,
1817 TypeOrigin::MainFunctionType(span) => span,
1818 TypeOrigin::StartFunctionType(span) => span,
1819 TypeOrigin::IntrinsicType(span) => span,
1824 impl<'tcx> SubregionOrigin<'tcx> {
1825 pub fn span(&self) -> Span {
1827 Subtype(ref a) => a.span(),
1828 InfStackClosure(a) => a,
1829 InvokeClosure(a) => a,
1830 DerefPointer(a) => a,
1831 FreeVariable(a, _) => a,
1833 RelateObjectBound(a) => a,
1834 RelateParamBound(a, _) => a,
1835 RelateRegionParamBound(a) => a,
1836 RelateDefaultParamBound(a, _) => a,
1838 ReborrowUpvar(a, _) => a,
1839 DataBorrowed(_, a) => a,
1840 ReferenceOutlivesReferent(_, a) => a,
1841 ParameterInScope(_, a) => a,
1842 ExprTypeIsNotInScope(_, a) => a,
1843 BindingTypeIsNotValidAtDecl(a) => a,
1850 SafeDestructor(a) => a,
1855 impl RegionVariableOrigin {
1856 pub fn span(&self) -> Span {
1858 MiscVariable(a) => a,
1859 PatternRegion(a) => a,
1860 AddrOfRegion(a) => a,
1863 EarlyBoundRegion(a, _) => a,
1864 LateBoundRegion(a, _, _) => a,
1865 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1866 UpvarRegion(_, a) => a
1871 impl<'tcx> TypeFoldable<'tcx> for TypeOrigin {
1872 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _folder: &mut F) -> Self {
1876 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> bool {
1881 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1882 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1884 ValuePairs::Types(ref ef) => {
1885 ValuePairs::Types(ef.fold_with(folder))
1887 ValuePairs::TraitRefs(ref ef) => {
1888 ValuePairs::TraitRefs(ef.fold_with(folder))
1890 ValuePairs::PolyTraitRefs(ref ef) => {
1891 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1896 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1898 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1899 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1900 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1905 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1906 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1908 origin: self.origin.fold_with(folder),
1909 values: self.values.fold_with(folder)
1913 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1914 self.origin.visit_with(visitor) || self.values.visit_with(visitor)