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, RegionRelations};
24 use middle::region::RegionMaps;
25 use middle::mem_categorization as mc;
26 use middle::mem_categorization::McResult;
27 use middle::lang_items;
28 use mir::tcx::LvalueTy;
29 use ty::subst::{Kind, 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, ObligationCause, PredicateObligations, Reveal};
36 use rustc_data_structures::unify::{self, UnificationTable};
37 use std::cell::{Cell, RefCell, Ref, RefMut};
41 use errors::DiagnosticBuilder;
42 use syntax_pos::{self, Span, DUMMY_SP};
43 use util::nodemap::{FxHashMap, FxHashSet};
44 use arena::DroplessArena;
46 use self::combine::CombineFields;
47 use self::higher_ranked::HrMatchResult;
48 use self::region_inference::{RegionVarBindings, RegionSnapshot};
49 use self::type_variable::TypeVariableOrigin;
50 use self::unify_key::ToType;
54 pub mod error_reporting;
60 pub mod region_inference;
64 pub mod type_variable;
68 pub struct InferOk<'tcx, T> {
70 pub obligations: PredicateObligations<'tcx>,
72 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
74 pub type Bound<T> = Option<T>;
75 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
76 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
78 /// A version of &ty::TypeckTables which can be `Missing` (not needed),
79 /// `InProgress` (during typeck) or `Interned` (result of typeck).
80 /// Only the `InProgress` version supports `borrow_mut`.
81 #[derive(Copy, Clone)]
82 pub enum InferTables<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
83 Interned(&'a ty::TypeckTables<'gcx>),
84 InProgress(&'a RefCell<ty::TypeckTables<'tcx>>),
88 pub enum InferTablesRef<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
89 Interned(&'a ty::TypeckTables<'gcx>),
90 InProgress(Ref<'a, ty::TypeckTables<'tcx>>)
93 impl<'a, 'gcx, 'tcx> Deref for InferTablesRef<'a, 'gcx, 'tcx> {
94 type Target = ty::TypeckTables<'tcx>;
95 fn deref(&self) -> &Self::Target {
97 InferTablesRef::Interned(tables) => tables,
98 InferTablesRef::InProgress(ref tables) => tables
103 impl<'a, 'gcx, 'tcx> InferTables<'a, 'gcx, 'tcx> {
104 pub fn borrow(self) -> InferTablesRef<'a, 'gcx, 'tcx> {
106 InferTables::Interned(tables) => InferTablesRef::Interned(tables),
107 InferTables::InProgress(tables) => InferTablesRef::InProgress(tables.borrow()),
108 InferTables::Missing => {
109 bug!("InferTables: infcx.tables.borrow() with no tables")
114 pub fn expect_interned(self) -> &'a ty::TypeckTables<'gcx> {
116 InferTables::Interned(tables) => tables,
117 InferTables::InProgress(_) => {
118 bug!("InferTables: infcx.tables.expect_interned() during type-checking");
120 InferTables::Missing => {
121 bug!("InferTables: infcx.tables.expect_interned() with no tables")
126 pub fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> {
128 InferTables::Interned(_) => {
129 bug!("InferTables: infcx.tables.borrow_mut() outside of type-checking");
131 InferTables::InProgress(tables) => tables.borrow_mut(),
132 InferTables::Missing => {
133 bug!("InferTables: infcx.tables.borrow_mut() with no tables")
139 pub struct InferCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
140 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
142 pub tables: InferTables<'a, 'gcx, 'tcx>,
144 // Cache for projections. This cache is snapshotted along with the
147 // Public so that `traits::project` can use it.
148 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
150 // We instantiate UnificationTable with bounds<Ty> because the
151 // types that might instantiate a general type variable have an
152 // order, represented by its upper and lower bounds.
153 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
155 // Map from integral variable to the kind of integer it represents
156 int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
158 // Map from floating variable to the kind of float it represents
159 float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
161 // For region variables.
162 region_vars: RegionVarBindings<'a, 'gcx, 'tcx>,
164 /// Caches the results of trait selection. This cache is used
165 /// for things that have to do with the parameters in scope.
166 pub selection_cache: traits::SelectionCache<'tcx>,
168 /// Caches the results of trait evaluation.
169 pub evaluation_cache: traits::EvaluationCache<'tcx>,
171 // the set of predicates on which errors have been reported, to
172 // avoid reporting the same error twice.
173 pub reported_trait_errors: RefCell<FxHashSet<traits::TraitErrorKey<'tcx>>>,
175 // When an error occurs, we want to avoid reporting "derived"
176 // errors that are due to this original failure. Normally, we
177 // handle this with the `err_count_on_creation` count, which
178 // basically just tracks how many errors were reported when we
179 // started type-checking a fn and checks to see if any new errors
180 // have been reported since then. Not great, but it works.
182 // However, when errors originated in other passes -- notably
183 // resolve -- this heuristic breaks down. Therefore, we have this
184 // auxiliary flag that one can set whenever one creates a
185 // type-error that is due to an error in a prior pass.
187 // Don't read this flag directly, call `is_tainted_by_errors()`
188 // and `set_tainted_by_errors()`.
189 tainted_by_errors_flag: Cell<bool>,
191 // Track how many errors were reported when this infcx is created.
192 // If the number of errors increases, that's also a sign (line
193 // `tained_by_errors`) to avoid reporting certain kinds of errors.
194 err_count_on_creation: usize,
196 // This flag is true while there is an active snapshot.
197 in_snapshot: Cell<bool>,
200 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
201 /// region that each late-bound region was replaced with.
202 pub type SkolemizationMap<'tcx> = FxHashMap<ty::BoundRegion, ty::Region<'tcx>>;
204 /// See `error_reporting` module for more details
205 #[derive(Clone, Debug)]
206 pub enum ValuePairs<'tcx> {
207 Types(ExpectedFound<Ty<'tcx>>),
208 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
209 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
212 /// The trace designates the path through inference that we took to
213 /// encounter an error or subtyping constraint.
215 /// See `error_reporting` module for more details.
217 pub struct TypeTrace<'tcx> {
218 cause: ObligationCause<'tcx>,
219 values: ValuePairs<'tcx>,
222 /// The origin of a `r1 <= r2` constraint.
224 /// See `error_reporting` module for more details
225 #[derive(Clone, Debug)]
226 pub enum SubregionOrigin<'tcx> {
227 // Arose from a subtyping relation
228 Subtype(TypeTrace<'tcx>),
230 // Stack-allocated closures cannot outlive innermost loop
231 // or function so as to ensure we only require finite stack
232 InfStackClosure(Span),
234 // Invocation of closure must be within its lifetime
237 // Dereference of reference must be within its lifetime
240 // Closure bound must not outlive captured free variables
241 FreeVariable(Span, ast::NodeId),
243 // Index into slice must be within its lifetime
246 // When casting `&'a T` to an `&'b Trait` object,
247 // relating `'a` to `'b`
248 RelateObjectBound(Span),
250 // Some type parameter was instantiated with the given type,
251 // and that type must outlive some region.
252 RelateParamBound(Span, Ty<'tcx>),
254 // The given region parameter was instantiated with a region
255 // that must outlive some other region.
256 RelateRegionParamBound(Span),
258 // A bound placed on type parameters that states that must outlive
259 // the moment of their instantiation.
260 RelateDefaultParamBound(Span, Ty<'tcx>),
262 // Creating a pointer `b` to contents of another reference
265 // Creating a pointer `b` to contents of an upvar
266 ReborrowUpvar(Span, ty::UpvarId),
268 // Data with type `Ty<'tcx>` was borrowed
269 DataBorrowed(Ty<'tcx>, Span),
271 // (&'a &'b T) where a >= b
272 ReferenceOutlivesReferent(Ty<'tcx>, Span),
274 // Type or region parameters must be in scope.
275 ParameterInScope(ParameterOrigin, Span),
277 // The type T of an expression E must outlive the lifetime for E.
278 ExprTypeIsNotInScope(Ty<'tcx>, Span),
280 // A `ref b` whose region does not enclose the decl site
281 BindingTypeIsNotValidAtDecl(Span),
283 // Regions appearing in a method receiver must outlive method call
286 // Regions appearing in a function argument must outlive func call
289 // Region in return type of invoked fn must enclose call
292 // Operands must be in scope
295 // Region resulting from a `&` expr must enclose the `&` expr
298 // An auto-borrow that does not enclose the expr where it occurs
301 // Region constraint arriving from destructor safety
302 SafeDestructor(Span),
304 // Comparing the signature and requirements of an impl method against
305 // the containing trait.
306 CompareImplMethodObligation {
308 item_name: ast::Name,
309 impl_item_def_id: DefId,
310 trait_item_def_id: DefId,
312 // this is `Some(_)` if this error arises from the bug fix for
313 // #18937. This is a temporary measure.
314 lint_id: Option<ast::NodeId>,
318 /// Places that type/region parameters can appear.
319 #[derive(Clone, Copy, Debug)]
320 pub enum ParameterOrigin {
322 MethodCall, // foo.bar() <-- parameters on impl providing bar()
323 OverloadedOperator, // a + b when overloaded
324 OverloadedDeref, // *a when overloaded
327 /// Times when we replace late-bound regions with variables:
328 #[derive(Clone, Copy, Debug)]
329 pub enum LateBoundRegionConversionTime {
330 /// when a fn is called
333 /// when two higher-ranked types are compared
336 /// when projecting an associated type
337 AssocTypeProjection(ast::Name),
340 /// Reasons to create a region inference variable
342 /// See `error_reporting` module for more details
343 #[derive(Clone, Debug)]
344 pub enum RegionVariableOrigin {
345 // Region variables created for ill-categorized reasons,
346 // mostly indicates places in need of refactoring
349 // Regions created by a `&P` or `[...]` pattern
352 // Regions created by `&` operator
355 // Regions created as part of an autoref of a method receiver
358 // Regions created as part of an automatic coercion
361 // Region variables created as the values for early-bound regions
362 EarlyBoundRegion(Span, ast::Name, Option<ty::Issue32330>),
364 // Region variables created for bound regions
365 // in a function or method that is called
366 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
368 UpvarRegion(ty::UpvarId, Span),
370 BoundRegionInCoherence(ast::Name),
373 #[derive(Copy, Clone, Debug)]
374 pub enum FixupError {
375 UnresolvedIntTy(IntVid),
376 UnresolvedFloatTy(FloatVid),
380 impl fmt::Display for FixupError {
381 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
382 use self::FixupError::*;
385 UnresolvedIntTy(_) => {
386 write!(f, "cannot determine the type of this integer; \
387 add a suffix to specify the type explicitly")
389 UnresolvedFloatTy(_) => {
390 write!(f, "cannot determine the type of this number; \
391 add a suffix to specify the type explicitly")
393 UnresolvedTy(_) => write!(f, "unconstrained type")
398 pub trait InferEnv<'a, 'tcx> {
399 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
400 -> (Option<&'a ty::TypeckTables<'tcx>>,
401 Option<ty::TypeckTables<'tcx>>);
404 impl<'a, 'tcx> InferEnv<'a, 'tcx> for () {
405 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
406 -> (Option<&'a ty::TypeckTables<'tcx>>,
407 Option<ty::TypeckTables<'tcx>>) {
412 impl<'a, 'tcx> InferEnv<'a, 'tcx> for &'a ty::TypeckTables<'tcx> {
413 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
414 -> (Option<&'a ty::TypeckTables<'tcx>>,
415 Option<ty::TypeckTables<'tcx>>) {
420 impl<'a, 'tcx> InferEnv<'a, 'tcx> for ty::TypeckTables<'tcx> {
421 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
422 -> (Option<&'a ty::TypeckTables<'tcx>>,
423 Option<ty::TypeckTables<'tcx>>) {
428 impl<'a, 'tcx> InferEnv<'a, 'tcx> for hir::BodyId {
429 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
430 -> (Option<&'a ty::TypeckTables<'tcx>>,
431 Option<ty::TypeckTables<'tcx>>) {
432 let def_id = tcx.hir.body_owner_def_id(self);
433 (Some(tcx.typeck_tables_of(def_id)), None)
437 /// Helper type of a temporary returned by tcx.infer_ctxt(...).
438 /// Necessary because we can't write the following bound:
439 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
440 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
441 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
442 arena: DroplessArena,
443 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
444 tables: Option<&'a ty::TypeckTables<'gcx>>,
447 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
448 pub fn infer_ctxt<E: InferEnv<'a, 'gcx>>(self, env: E) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
449 let (tables, fresh_tables) = env.to_parts(self);
452 arena: DroplessArena::new(),
453 fresh_tables: fresh_tables.map(RefCell::new),
458 /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
459 /// for MemCategorizationContext/ExprUseVisitor.
460 /// If any inference functionality is used, ICEs will occur.
461 pub fn borrowck_fake_infer_ctxt(self, body: hir::BodyId)
462 -> InferCtxt<'a, 'gcx, 'gcx> {
463 let (tables, _) = body.to_parts(self);
466 tables: InferTables::Interned(tables.unwrap()),
467 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
468 int_unification_table: RefCell::new(UnificationTable::new()),
469 float_unification_table: RefCell::new(UnificationTable::new()),
470 region_vars: RegionVarBindings::new(self),
471 selection_cache: traits::SelectionCache::new(),
472 evaluation_cache: traits::EvaluationCache::new(),
473 projection_cache: RefCell::new(traits::ProjectionCache::new()),
474 reported_trait_errors: RefCell::new(FxHashSet()),
475 tainted_by_errors_flag: Cell::new(false),
476 err_count_on_creation: self.sess.err_count(),
477 in_snapshot: Cell::new(false),
482 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
483 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
484 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
486 let InferCtxtBuilder {
492 let tables = tables.map(InferTables::Interned).unwrap_or_else(|| {
493 fresh_tables.as_ref().map_or(InferTables::Missing, InferTables::InProgress)
495 global_tcx.enter_local(arena, |tcx| f(InferCtxt {
498 projection_cache: RefCell::new(traits::ProjectionCache::new()),
499 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
500 int_unification_table: RefCell::new(UnificationTable::new()),
501 float_unification_table: RefCell::new(UnificationTable::new()),
502 region_vars: RegionVarBindings::new(tcx),
503 selection_cache: traits::SelectionCache::new(),
504 evaluation_cache: traits::EvaluationCache::new(),
505 reported_trait_errors: RefCell::new(FxHashSet()),
506 tainted_by_errors_flag: Cell::new(false),
507 err_count_on_creation: tcx.sess.err_count(),
508 in_snapshot: Cell::new(false),
513 impl<T> ExpectedFound<T> {
514 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
516 ExpectedFound {expected: a, found: b}
518 ExpectedFound {expected: b, found: a}
523 impl<'tcx, T> InferOk<'tcx, T> {
524 pub fn unit(self) -> InferOk<'tcx, ()> {
525 InferOk { value: (), obligations: self.obligations }
529 #[must_use = "once you start a snapshot, you should always consume it"]
530 pub struct CombinedSnapshot<'a, 'tcx:'a> {
531 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
532 type_snapshot: type_variable::Snapshot,
533 int_snapshot: unify::Snapshot<ty::IntVid>,
534 float_snapshot: unify::Snapshot<ty::FloatVid>,
535 region_vars_snapshot: RegionSnapshot,
536 was_in_snapshot: bool,
537 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
540 /// Helper trait for shortening the lifetimes inside a
541 /// value for post-type-checking normalization.
542 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
543 fn trans_normalize<'a, 'tcx>(&self,
544 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
545 param_env: ty::ParamEnv<'tcx>)
549 macro_rules! items { ($($item:item)+) => ($($item)+) }
550 macro_rules! impl_trans_normalize {
551 ($lt_gcx:tt, $($ty:ty),+) => {
552 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
553 fn trans_normalize<'a, 'tcx>(&self,
554 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>,
555 param_env: ty::ParamEnv<'tcx>)
557 infcx.normalize_projections_in(param_env, self)
563 impl_trans_normalize!('gcx,
568 ty::ClosureSubsts<'gcx>,
569 ty::PolyTraitRef<'gcx>,
570 ty::ExistentialTraitRef<'gcx>
573 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
574 fn trans_normalize<'a, 'tcx>(&self,
575 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
576 param_env: ty::ParamEnv<'tcx>)
579 LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx, param_env) },
580 LvalueTy::Downcast { adt_def, substs, variant_index } => {
583 substs: substs.trans_normalize(infcx, param_env),
584 variant_index: variant_index
591 // NOTE: Callable from trans only!
592 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
593 /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
594 /// each time we erase them in translation, we need to normalize
596 pub fn erase_late_bound_regions_and_normalize<T>(self, value: &ty::Binder<T>)
598 where T: TransNormalize<'tcx>
600 assert!(!value.needs_subst());
601 let value = self.erase_late_bound_regions(value);
602 self.normalize_associated_type(&value)
605 /// Fully normalizes any associated types in `value`, using an
606 /// empty environment and `Reveal::All` mode (therefore, suitable
607 /// only for monomorphized code during trans, basically).
608 pub fn normalize_associated_type<T>(self, value: &T) -> T
609 where T: TransNormalize<'tcx>
611 debug!("normalize_associated_type(t={:?})", value);
613 let param_env = ty::ParamEnv::empty(Reveal::All);
614 let value = self.erase_regions(value);
616 if !value.has_projection_types() {
620 self.infer_ctxt(()).enter(|infcx| {
621 value.trans_normalize(&infcx, param_env)
625 /// Does a best-effort to normalize any associated types in
626 /// `value`; this includes revealing specializable types, so this
627 /// should be not be used during type-checking, but only during
628 /// optimization and code generation.
629 pub fn normalize_associated_type_in_env<T>(
630 self, value: &T, env: ty::ParamEnv<'tcx>
632 where T: TransNormalize<'tcx>
634 debug!("normalize_associated_type_in_env(t={:?})", value);
636 let value = self.erase_regions(value);
638 if !value.has_projection_types() {
642 self.infer_ctxt(()).enter(|infcx| {
643 value.trans_normalize(&infcx, env.reveal_all())
648 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
649 fn normalize_projections_in<T>(&self, param_env: ty::ParamEnv<'tcx>, value: &T) -> T::Lifted
650 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
652 let mut selcx = traits::SelectionContext::new(self);
653 let cause = traits::ObligationCause::dummy();
654 let traits::Normalized { value: result, obligations } =
655 traits::normalize(&mut selcx, param_env, cause, value);
657 debug!("normalize_projections_in: result={:?} obligations={:?}",
658 result, obligations);
660 let mut fulfill_cx = traits::FulfillmentContext::new();
662 for obligation in obligations {
663 fulfill_cx.register_predicate_obligation(self, obligation);
666 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
669 /// Finishes processes any obligations that remain in the
670 /// fulfillment context, and then returns the result with all type
671 /// variables removed and regions erased. Because this is intended
672 /// for use after type-check has completed, if any errors occur,
673 /// it will panic. It is used during normalization and other cases
674 /// where processing the obligations in `fulfill_cx` may cause
675 /// type inference variables that appear in `result` to be
676 /// unified, and hence we need to process those obligations to get
677 /// the complete picture of the type.
678 pub fn drain_fulfillment_cx_or_panic<T>(&self,
680 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
683 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
685 debug!("drain_fulfillment_cx_or_panic()");
687 // In principle, we only need to do this so long as `result`
688 // contains unbound type parameters. It could be a slight
689 // optimization to stop iterating early.
690 match fulfill_cx.select_all_or_error(self) {
693 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
698 let result = self.resolve_type_vars_if_possible(result);
699 let result = self.tcx.erase_regions(&result);
701 match self.tcx.lift_to_global(&result) {
702 Some(result) => result,
704 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
709 pub fn is_in_snapshot(&self) -> bool {
710 self.in_snapshot.get()
713 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
714 t.fold_with(&mut self.freshener())
717 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
719 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
724 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
725 freshen::TypeFreshener::new(self)
728 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
729 use ty::error::UnconstrainedNumeric::Neither;
730 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
732 ty::TyInfer(ty::IntVar(vid)) => {
733 if self.int_unification_table.borrow_mut().has_value(vid) {
739 ty::TyInfer(ty::FloatVar(vid)) => {
740 if self.float_unification_table.borrow_mut().has_value(vid) {
750 /// Returns a type variable's default fallback if any exists. A default
751 /// must be attached to the variable when created, if it is created
752 /// without a default, this will return None.
754 /// This code does not apply to integral or floating point variables,
755 /// only to use declared defaults.
757 /// See `new_ty_var_with_default` to create a type variable with a default.
758 /// See `type_variable::Default` for details about what a default entails.
759 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
761 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
766 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
767 let mut variables = Vec::new();
769 let unbound_ty_vars = self.type_variables
771 .unsolved_variables()
773 .map(|t| self.tcx.mk_var(t));
775 let unbound_int_vars = self.int_unification_table
777 .unsolved_variables()
779 .map(|v| self.tcx.mk_int_var(v));
781 let unbound_float_vars = self.float_unification_table
783 .unsolved_variables()
785 .map(|v| self.tcx.mk_float_var(v));
787 variables.extend(unbound_ty_vars);
788 variables.extend(unbound_int_vars);
789 variables.extend(unbound_float_vars);
794 fn combine_fields(&'a self, trace: TypeTrace<'tcx>, param_env: ty::ParamEnv<'tcx>)
795 -> CombineFields<'a, 'gcx, 'tcx> {
801 obligations: PredicateObligations::new(),
805 pub fn equate<T>(&'a self,
807 trace: TypeTrace<'tcx>,
808 param_env: ty::ParamEnv<'tcx>,
811 -> InferResult<'tcx, T>
812 where T: Relate<'tcx>
814 let mut fields = self.combine_fields(trace, param_env);
815 let result = fields.equate(a_is_expected).relate(a, b);
816 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
819 pub fn sub<T>(&'a self,
821 trace: TypeTrace<'tcx>,
822 param_env: ty::ParamEnv<'tcx>,
825 -> InferResult<'tcx, T>
826 where T: Relate<'tcx>
828 let mut fields = self.combine_fields(trace, param_env);
829 let result = fields.sub(a_is_expected).relate(a, b);
830 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
833 pub fn lub<T>(&'a self,
835 trace: TypeTrace<'tcx>,
836 param_env: ty::ParamEnv<'tcx>,
839 -> InferResult<'tcx, T>
840 where T: Relate<'tcx>
842 let mut fields = self.combine_fields(trace, param_env);
843 let result = fields.lub(a_is_expected).relate(a, b);
844 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
847 pub fn glb<T>(&'a self,
849 trace: TypeTrace<'tcx>,
850 param_env: ty::ParamEnv<'tcx>,
853 -> InferResult<'tcx, T>
854 where T: Relate<'tcx>
856 let mut fields = self.combine_fields(trace, param_env);
857 let result = fields.glb(a_is_expected).relate(a, b);
858 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
861 // Clear the "currently in a snapshot" flag, invoke the closure,
862 // then restore the flag to its original value. This flag is a
863 // debugging measure designed to detect cases where we start a
864 // snapshot, create type variables, and register obligations
865 // which may involve those type variables in the fulfillment cx,
866 // potentially leaving "dangling type variables" behind.
867 // In such cases, an assertion will fail when attempting to
868 // register obligations, within a snapshot. Very useful, much
869 // better than grovelling through megabytes of RUST_LOG output.
871 // HOWEVER, in some cases the flag is unhelpful. In particular, we
872 // sometimes create a "mini-fulfilment-cx" in which we enroll
873 // obligations. As long as this fulfillment cx is fully drained
874 // before we return, this is not a problem, as there won't be any
875 // escaping obligations in the main cx. In those cases, you can
876 // use this function.
877 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
878 where F: FnOnce(&Self) -> R
880 let flag = self.in_snapshot.get();
881 self.in_snapshot.set(false);
882 let result = func(self);
883 self.in_snapshot.set(flag);
887 fn start_snapshot<'b>(&'b self) -> CombinedSnapshot<'b, 'tcx> {
888 debug!("start_snapshot()");
890 let in_snapshot = self.in_snapshot.get();
891 self.in_snapshot.set(true);
894 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
895 type_snapshot: self.type_variables.borrow_mut().snapshot(),
896 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
897 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
898 region_vars_snapshot: self.region_vars.start_snapshot(),
899 was_in_snapshot: in_snapshot,
900 // Borrow tables "in progress" (i.e. during typeck)
901 // to ban writes from within a snapshot to them.
902 _in_progress_tables: match self.tables {
903 InferTables::InProgress(ref tables) => tables.try_borrow().ok(),
909 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
910 debug!("rollback_to(cause={})", cause);
911 let CombinedSnapshot { projection_cache_snapshot,
915 region_vars_snapshot,
917 _in_progress_tables } = snapshot;
919 self.in_snapshot.set(was_in_snapshot);
921 self.projection_cache
923 .rollback_to(projection_cache_snapshot);
926 .rollback_to(type_snapshot);
927 self.int_unification_table
929 .rollback_to(int_snapshot);
930 self.float_unification_table
932 .rollback_to(float_snapshot);
934 .rollback_to(region_vars_snapshot);
937 fn commit_from(&self, snapshot: CombinedSnapshot) {
938 debug!("commit_from()");
939 let CombinedSnapshot { projection_cache_snapshot,
943 region_vars_snapshot,
945 _in_progress_tables } = snapshot;
947 self.in_snapshot.set(was_in_snapshot);
949 self.projection_cache
951 .commit(projection_cache_snapshot);
954 .commit(type_snapshot);
955 self.int_unification_table
957 .commit(int_snapshot);
958 self.float_unification_table
960 .commit(float_snapshot);
962 .commit(region_vars_snapshot);
965 /// Execute `f` and commit the bindings
966 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
970 let snapshot = self.start_snapshot();
972 self.commit_from(snapshot);
976 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
977 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
978 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
980 debug!("commit_if_ok()");
981 let snapshot = self.start_snapshot();
982 let r = f(&snapshot);
983 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
985 Ok(_) => { self.commit_from(snapshot); }
986 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
991 // Execute `f` in a snapshot, and commit the bindings it creates
992 pub fn in_snapshot<T, F>(&self, f: F) -> T where
993 F: FnOnce(&CombinedSnapshot) -> T
995 debug!("in_snapshot()");
996 let snapshot = self.start_snapshot();
997 let r = f(&snapshot);
998 self.commit_from(snapshot);
1002 /// Execute `f` then unroll any bindings it creates
1003 pub fn probe<R, F>(&self, f: F) -> R where
1004 F: FnOnce(&CombinedSnapshot) -> R,
1007 let snapshot = self.start_snapshot();
1008 let r = f(&snapshot);
1009 self.rollback_to("probe", snapshot);
1013 pub fn add_given(&self,
1014 sub: ty::Region<'tcx>,
1017 self.region_vars.add_given(sub, sup);
1020 pub fn sub_types(&self,
1021 a_is_expected: bool,
1022 cause: &ObligationCause<'tcx>,
1023 param_env: ty::ParamEnv<'tcx>,
1026 -> InferResult<'tcx, ()>
1028 debug!("sub_types({:?} <: {:?})", a, b);
1029 self.commit_if_ok(|_| {
1030 let trace = TypeTrace::types(cause, a_is_expected, a, b);
1031 self.sub(a_is_expected, trace, param_env, &a, &b).map(|ok| ok.unit())
1035 pub fn can_sub_types(&self,
1036 param_env: ty::ParamEnv<'tcx>,
1042 let origin = &ObligationCause::dummy();
1043 let trace = TypeTrace::types(origin, true, a, b);
1044 self.sub(true, trace, param_env, &a, &b).map(|InferOk { obligations: _, .. }| {
1045 // Ignore obligations, since we are unrolling
1046 // everything anyway.
1051 pub fn eq_types(&self,
1052 a_is_expected: bool,
1053 cause: &ObligationCause<'tcx>,
1054 param_env: ty::ParamEnv<'tcx>,
1057 -> InferResult<'tcx, ()>
1059 self.commit_if_ok(|_| {
1060 let trace = TypeTrace::types(cause, a_is_expected, a, b);
1061 self.equate(a_is_expected, trace, param_env, &a, &b).map(|ok| ok.unit())
1065 pub fn eq_trait_refs(&self,
1066 a_is_expected: bool,
1067 cause: &ObligationCause<'tcx>,
1068 param_env: ty::ParamEnv<'tcx>,
1069 a: ty::TraitRef<'tcx>,
1070 b: ty::TraitRef<'tcx>)
1071 -> InferResult<'tcx, ()>
1073 debug!("eq_trait_refs({:?} = {:?})", a, b);
1074 self.commit_if_ok(|_| {
1075 let trace = TypeTrace {
1076 cause: cause.clone(),
1077 values: TraitRefs(ExpectedFound::new(a_is_expected, a, b))
1079 self.equate(a_is_expected, trace, param_env, &a, &b).map(|ok| ok.unit())
1083 pub fn eq_impl_headers(&self,
1084 a_is_expected: bool,
1085 cause: &ObligationCause<'tcx>,
1086 param_env: ty::ParamEnv<'tcx>,
1087 a: &ty::ImplHeader<'tcx>,
1088 b: &ty::ImplHeader<'tcx>)
1089 -> InferResult<'tcx, ()>
1091 debug!("eq_impl_header({:?} = {:?})", a, b);
1092 match (a.trait_ref, b.trait_ref) {
1093 (Some(a_ref), Some(b_ref)) =>
1094 self.eq_trait_refs(a_is_expected, cause, param_env, a_ref, b_ref),
1096 self.eq_types(a_is_expected, cause, param_env, a.self_ty, b.self_ty),
1097 _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
1101 pub fn sub_poly_trait_refs(&self,
1102 a_is_expected: bool,
1103 cause: ObligationCause<'tcx>,
1104 param_env: ty::ParamEnv<'tcx>,
1105 a: ty::PolyTraitRef<'tcx>,
1106 b: ty::PolyTraitRef<'tcx>)
1107 -> InferResult<'tcx, ()>
1109 debug!("sub_poly_trait_refs({:?} <: {:?})", a, b);
1110 self.commit_if_ok(|_| {
1111 let trace = TypeTrace {
1113 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b))
1115 self.sub(a_is_expected, trace, param_env, &a, &b).map(|ok| ok.unit())
1119 pub fn sub_regions(&self,
1120 origin: SubregionOrigin<'tcx>,
1121 a: ty::Region<'tcx>,
1122 b: ty::Region<'tcx>) {
1123 debug!("sub_regions({:?} <: {:?})", a, b);
1124 self.region_vars.make_subregion(origin, a, b);
1127 pub fn equality_predicate(&self,
1128 cause: &ObligationCause<'tcx>,
1129 param_env: ty::ParamEnv<'tcx>,
1130 predicate: &ty::PolyEquatePredicate<'tcx>)
1131 -> InferResult<'tcx, ()>
1133 self.commit_if_ok(|snapshot| {
1134 let (ty::EquatePredicate(a, b), skol_map) =
1135 self.skolemize_late_bound_regions(predicate, snapshot);
1136 let cause_span = cause.span;
1137 let eqty_ok = self.eq_types(false, cause, param_env, a, b)?;
1138 self.leak_check(false, cause_span, &skol_map, snapshot)?;
1139 self.pop_skolemized(skol_map, snapshot);
1144 pub fn subtype_predicate(&self,
1145 cause: &ObligationCause<'tcx>,
1146 param_env: ty::ParamEnv<'tcx>,
1147 predicate: &ty::PolySubtypePredicate<'tcx>)
1148 -> Option<InferResult<'tcx, ()>>
1150 // Subtle: it's ok to skip the binder here and resolve because
1151 // `shallow_resolve` just ignores anything that is not a type
1152 // variable, and because type variable's can't (at present, at
1153 // least) capture any of the things bound by this binder.
1155 // Really, there is no *particular* reason to do this
1156 // `shallow_resolve` here except as a
1157 // micro-optimization. Naturally I could not
1158 // resist. -nmatsakis
1159 let two_unbound_type_vars = {
1160 let a = self.shallow_resolve(predicate.skip_binder().a);
1161 let b = self.shallow_resolve(predicate.skip_binder().b);
1162 a.is_ty_var() && b.is_ty_var()
1165 if two_unbound_type_vars {
1166 // Two unbound type variables? Can't make progress.
1170 Some(self.commit_if_ok(|snapshot| {
1171 let (ty::SubtypePredicate { a_is_expected, a, b}, skol_map) =
1172 self.skolemize_late_bound_regions(predicate, snapshot);
1174 let cause_span = cause.span;
1175 let ok = self.sub_types(a_is_expected, cause, param_env, a, b)?;
1176 self.leak_check(false, cause_span, &skol_map, snapshot)?;
1177 self.pop_skolemized(skol_map, snapshot);
1182 pub fn region_outlives_predicate(&self,
1183 cause: &traits::ObligationCause<'tcx>,
1184 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1187 self.commit_if_ok(|snapshot| {
1188 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1189 self.skolemize_late_bound_regions(predicate, snapshot);
1191 SubregionOrigin::from_obligation_cause(cause,
1192 || RelateRegionParamBound(cause.span));
1193 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1194 self.leak_check(false, cause.span, &skol_map, snapshot)?;
1195 Ok(self.pop_skolemized(skol_map, snapshot))
1199 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1202 .new_var(diverging, origin, None)
1205 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1206 self.tcx.mk_var(self.next_ty_var_id(false, origin))
1209 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1210 self.tcx.mk_var(self.next_ty_var_id(true, origin))
1213 pub fn next_int_var_id(&self) -> IntVid {
1214 self.int_unification_table
1219 pub fn next_float_var_id(&self) -> FloatVid {
1220 self.float_unification_table
1225 pub fn next_region_var(&self, origin: RegionVariableOrigin)
1226 -> ty::Region<'tcx> {
1227 self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
1230 /// Create a region inference variable for the given
1231 /// region parameter definition.
1232 pub fn region_var_for_def(&self,
1234 def: &ty::RegionParameterDef)
1235 -> ty::Region<'tcx> {
1236 self.next_region_var(EarlyBoundRegion(span, def.name, def.issue_32330))
1239 /// Create a type inference variable for the given
1240 /// type parameter definition. The substitutions are
1241 /// for actual parameters that may be referred to by
1242 /// the default of this type parameter, if it exists.
1243 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1244 /// used in a path such as `Foo::<T, U>::new()` will
1245 /// use an inference variable for `C` with `[T, U]`
1246 /// as the substitutions for the default, `(T, U)`.
1247 pub fn type_var_for_def(&self,
1249 def: &ty::TypeParameterDef,
1250 substs: &[Kind<'tcx>])
1252 let default = if def.has_default {
1253 let default = self.tcx.type_of(def.def_id);
1254 Some(type_variable::Default {
1255 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1264 let ty_var_id = self.type_variables
1267 TypeVariableOrigin::TypeParameterDefinition(span, def.name),
1270 self.tcx.mk_var(ty_var_id)
1273 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1274 /// type/region parameter to a fresh inference variable.
1275 pub fn fresh_substs_for_item(&self,
1278 -> &'tcx Substs<'tcx> {
1279 Substs::for_item(self.tcx, def_id, |def, _| {
1280 self.region_var_for_def(span, def)
1282 self.type_var_for_def(span, def, substs)
1286 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region<'tcx> {
1287 self.region_vars.new_bound(debruijn)
1290 /// True if errors have been reported since this infcx was
1291 /// created. This is sometimes used as a heuristic to skip
1292 /// reporting errors that often occur as a result of earlier
1293 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1294 /// inference variables, regionck errors).
1295 pub fn is_tainted_by_errors(&self) -> bool {
1296 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1297 tainted_by_errors_flag={})",
1298 self.tcx.sess.err_count(),
1299 self.err_count_on_creation,
1300 self.tainted_by_errors_flag.get());
1302 if self.tcx.sess.err_count() > self.err_count_on_creation {
1303 return true; // errors reported since this infcx was made
1305 self.tainted_by_errors_flag.get()
1308 /// Set the "tainted by errors" flag to true. We call this when we
1309 /// observe an error from a prior pass.
1310 pub fn set_tainted_by_errors(&self) {
1311 debug!("set_tainted_by_errors()");
1312 self.tainted_by_errors_flag.set(true)
1315 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1316 match self.tables.borrow().node_types.get(&id) {
1319 None if self.is_tainted_by_errors() =>
1322 bug!("no type for node {}: {} in fcx",
1323 id, self.tcx.hir.node_to_string(id));
1328 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1329 match self.tables.borrow().node_types.get(&ex.id) {
1332 bug!("no type for expr in fcx");
1337 pub fn resolve_regions_and_report_errors(&self,
1338 region_context: DefId,
1339 region_map: &RegionMaps,
1340 free_regions: &FreeRegionMap<'tcx>) {
1341 let region_rels = RegionRelations::new(self.tcx,
1345 let errors = self.region_vars.resolve_regions(®ion_rels);
1346 if !self.is_tainted_by_errors() {
1347 // As a heuristic, just skip reporting region errors
1348 // altogether if other errors have been reported while
1349 // this infcx was in use. This is totally hokey but
1350 // otherwise we have a hard time separating legit region
1351 // errors from silly ones.
1352 self.report_region_errors(&errors); // see error_reporting module
1356 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1357 self.resolve_type_vars_if_possible(&t).to_string()
1360 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1361 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1362 format!("({})", tstrs.join(", "))
1365 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1366 self.resolve_type_vars_if_possible(t).to_string()
1369 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1371 ty::TyInfer(ty::TyVar(v)) => {
1372 // Not entirely obvious: if `typ` is a type variable,
1373 // it can be resolved to an int/float variable, which
1374 // can then be recursively resolved, hence the
1375 // recursion. Note though that we prevent type
1376 // variables from unifying to other type variables
1377 // directly (though they may be embedded
1378 // structurally), and we prevent cycles in any case,
1379 // so this recursion should always be of very limited
1381 self.type_variables.borrow_mut()
1383 .map(|t| self.shallow_resolve(t))
1387 ty::TyInfer(ty::IntVar(v)) => {
1388 self.int_unification_table
1391 .map(|v| v.to_type(self.tcx))
1395 ty::TyInfer(ty::FloatVar(v)) => {
1396 self.float_unification_table
1399 .map(|v| v.to_type(self.tcx))
1409 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1410 where T: TypeFoldable<'tcx>
1413 * Where possible, replaces type/int/float variables in
1414 * `value` with their final value. Note that region variables
1415 * are unaffected. If a type variable has not been unified, it
1416 * is left as is. This is an idempotent operation that does
1417 * not affect inference state in any way and so you can do it
1421 if !value.needs_infer() {
1422 return value.clone(); // avoid duplicated subst-folding
1424 let mut r = resolve::OpportunisticTypeResolver::new(self);
1425 value.fold_with(&mut r)
1428 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1429 where T: TypeFoldable<'tcx>
1431 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1432 value.fold_with(&mut r)
1435 /// Resolves all type variables in `t` and then, if any were left
1436 /// unresolved, substitutes an error type. This is used after the
1437 /// main checking when doing a second pass before writeback. The
1438 /// justification is that writeback will produce an error for
1439 /// these unconstrained type variables.
1440 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1441 let ty = self.resolve_type_vars_if_possible(t);
1442 if ty.references_error() || ty.is_ty_var() {
1443 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1450 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1452 * Attempts to resolve all type/region variables in
1453 * `value`. Region inference must have been run already (e.g.,
1454 * by calling `resolve_regions_and_report_errors`). If some
1455 * variable was never unified, an `Err` results.
1457 * This method is idempotent, but it not typically not invoked
1458 * except during the writeback phase.
1461 resolve::fully_resolve(self, value)
1464 // [Note-Type-error-reporting]
1465 // An invariant is that anytime the expected or actual type is TyError (the special
1466 // error type, meaning that an error occurred when typechecking this expression),
1467 // this is a derived error. The error cascaded from another error (that was already
1468 // reported), so it's not useful to display it to the user.
1469 // The following methods implement this logic.
1470 // They check if either the actual or expected type is TyError, and don't print the error
1471 // in this case. The typechecker should only ever report type errors involving mismatched
1472 // types using one of these methods, and should not call span_err directly for such
1475 pub fn type_error_message<M>(&self,
1478 actual_ty: Ty<'tcx>)
1479 where M: FnOnce(String) -> String,
1481 self.type_error_struct(sp, mk_msg, actual_ty).emit();
1484 // FIXME: this results in errors without an error code. Deprecate?
1485 pub fn type_error_struct<M>(&self,
1488 actual_ty: Ty<'tcx>)
1489 -> DiagnosticBuilder<'tcx>
1490 where M: FnOnce(String) -> String,
1492 self.type_error_struct_with_diag(sp, |actual_ty| {
1493 self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1497 pub fn type_error_struct_with_diag<M>(&self,
1500 actual_ty: Ty<'tcx>)
1501 -> DiagnosticBuilder<'tcx>
1502 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1504 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1505 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1507 // Don't report an error if actual type is TyError.
1508 if actual_ty.references_error() {
1509 return self.tcx.sess.diagnostic().struct_dummy();
1512 mk_diag(self.ty_to_string(actual_ty))
1515 pub fn report_mismatched_types(&self,
1516 cause: &ObligationCause<'tcx>,
1519 err: TypeError<'tcx>)
1520 -> DiagnosticBuilder<'tcx> {
1521 let trace = TypeTrace::types(cause, true, expected, actual);
1522 self.report_and_explain_type_error(trace, &err)
1525 pub fn report_conflicting_default_types(&self,
1527 body_id: ast::NodeId,
1528 expected: type_variable::Default<'tcx>,
1529 actual: type_variable::Default<'tcx>) {
1530 let trace = TypeTrace {
1531 cause: ObligationCause::misc(span, body_id),
1532 values: Types(ExpectedFound {
1533 expected: expected.ty,
1538 self.report_and_explain_type_error(
1540 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1547 pub fn replace_late_bound_regions_with_fresh_var<T>(
1550 lbrct: LateBoundRegionConversionTime,
1551 value: &ty::Binder<T>)
1552 -> (T, FxHashMap<ty::BoundRegion, ty::Region<'tcx>>)
1553 where T : TypeFoldable<'tcx>
1555 self.tcx.replace_late_bound_regions(
1557 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1560 /// Given a higher-ranked projection predicate like:
1562 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1564 /// and a target trait-ref like:
1566 /// <T as Fn<&'x u32>>
1568 /// find a substitution `S` for the higher-ranked regions (here,
1569 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1570 /// and then return the value (here, `&'a u32`) but with the
1571 /// substitution applied (hence, `&'x u32`).
1573 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1575 pub fn match_poly_projection_predicate(&self,
1576 cause: ObligationCause<'tcx>,
1577 param_env: ty::ParamEnv<'tcx>,
1578 match_a: ty::PolyProjectionPredicate<'tcx>,
1579 match_b: ty::TraitRef<'tcx>)
1580 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1582 let span = cause.span;
1583 let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1584 let trace = TypeTrace {
1586 values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1589 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1590 let mut combine = self.combine_fields(trace, param_env);
1591 let result = combine.higher_ranked_match(span, &match_pair, &match_b, true)?;
1592 Ok(InferOk { value: result, obligations: combine.obligations })
1595 /// See `verify_generic_bound` method in `region_inference`
1596 pub fn verify_generic_bound(&self,
1597 origin: SubregionOrigin<'tcx>,
1598 kind: GenericKind<'tcx>,
1599 a: ty::Region<'tcx>,
1600 bound: VerifyBound<'tcx>) {
1601 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1606 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1609 pub fn can_equate<T>(&self, param_env: ty::ParamEnv<'tcx>, a: &T, b: &T) -> UnitResult<'tcx>
1610 where T: Relate<'tcx> + fmt::Debug
1612 debug!("can_equate({:?}, {:?})", a, b);
1614 // Gin up a dummy trace, since this won't be committed
1615 // anyhow. We should make this typetrace stuff more
1616 // generic so we don't have to do anything quite this
1618 let trace = TypeTrace::dummy(self.tcx);
1619 self.equate(true, trace, param_env, a, b).map(|InferOk { obligations: _, .. }| {
1620 // We can intentionally ignore obligations here, since
1621 // this is part of a simple test for general
1622 // "equatability". However, it's not entirely clear
1623 // that we *ought* to be, perhaps a better thing would
1624 // be to use a mini-fulfillment context or something
1630 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1631 let ty = self.node_type(id);
1632 self.resolve_type_vars_or_error(&ty)
1635 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1636 let ty = self.tables.borrow().expr_ty_adjusted(expr);
1637 self.resolve_type_vars_or_error(&ty)
1640 pub fn type_moves_by_default(&self,
1641 param_env: ty::ParamEnv<'tcx>,
1645 let ty = self.resolve_type_vars_if_possible(&ty);
1646 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1647 // Even if the type may have no inference variables, during
1648 // type-checking closure types are in local tables only.
1649 let local_closures = match self.tables {
1650 InferTables::InProgress(_) => ty.has_closure_types(),
1653 if !local_closures {
1654 return ty.moves_by_default(self.tcx.global_tcx(), param_env, span);
1658 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1660 // this can get called from typeck (by euv), and moves_by_default
1661 // rightly refuses to work with inference variables, but
1662 // moves_by_default has a cache, which we want to use in other
1664 !traits::type_known_to_meet_bound(self, param_env, ty, copy_def_id, span)
1667 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
1668 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1671 pub fn closure_kind(&self,
1673 -> Option<ty::ClosureKind>
1675 if let InferTables::InProgress(tables) = self.tables {
1676 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1677 return tables.borrow()
1681 .map(|(kind, _)| kind);
1685 // During typeck, ALL closures are local. But afterwards,
1686 // during trans, we see closure ids from other traits.
1687 // That may require loading the closure data out of the
1689 Some(self.tcx.closure_kind(def_id))
1692 pub fn closure_type(&self, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1693 if let InferTables::InProgress(tables) = self.tables {
1694 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1695 if let Some(&ty) = tables.borrow().closure_tys.get(&id) {
1701 self.tcx.closure_type(def_id)
1705 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1706 pub fn span(&self) -> Span {
1710 pub fn types(cause: &ObligationCause<'tcx>,
1711 a_is_expected: bool,
1714 -> TypeTrace<'tcx> {
1716 cause: cause.clone(),
1717 values: Types(ExpectedFound::new(a_is_expected, a, b))
1721 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1723 cause: ObligationCause::dummy(),
1724 values: Types(ExpectedFound {
1725 expected: tcx.types.err,
1726 found: tcx.types.err,
1732 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1733 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1734 write!(f, "TypeTrace({:?})", self.cause)
1738 impl<'tcx> SubregionOrigin<'tcx> {
1739 pub fn span(&self) -> Span {
1741 Subtype(ref a) => a.span(),
1742 InfStackClosure(a) => a,
1743 InvokeClosure(a) => a,
1744 DerefPointer(a) => a,
1745 FreeVariable(a, _) => a,
1747 RelateObjectBound(a) => a,
1748 RelateParamBound(a, _) => a,
1749 RelateRegionParamBound(a) => a,
1750 RelateDefaultParamBound(a, _) => a,
1752 ReborrowUpvar(a, _) => a,
1753 DataBorrowed(_, a) => a,
1754 ReferenceOutlivesReferent(_, a) => a,
1755 ParameterInScope(_, a) => a,
1756 ExprTypeIsNotInScope(_, a) => a,
1757 BindingTypeIsNotValidAtDecl(a) => a,
1764 SafeDestructor(a) => a,
1765 CompareImplMethodObligation { span, .. } => span,
1769 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>,
1772 where F: FnOnce() -> Self
1775 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
1776 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span),
1778 traits::ObligationCauseCode::CompareImplMethodObligation { item_name,
1782 SubregionOrigin::CompareImplMethodObligation {
1784 item_name: item_name,
1785 impl_item_def_id: impl_item_def_id,
1786 trait_item_def_id: trait_item_def_id,
1795 impl RegionVariableOrigin {
1796 pub fn span(&self) -> Span {
1798 MiscVariable(a) => a,
1799 PatternRegion(a) => a,
1800 AddrOfRegion(a) => a,
1803 EarlyBoundRegion(a, ..) => a,
1804 LateBoundRegion(a, ..) => a,
1805 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1806 UpvarRegion(_, a) => a
1811 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1812 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1814 ValuePairs::Types(ref ef) => {
1815 ValuePairs::Types(ef.fold_with(folder))
1817 ValuePairs::TraitRefs(ref ef) => {
1818 ValuePairs::TraitRefs(ef.fold_with(folder))
1820 ValuePairs::PolyTraitRefs(ref ef) => {
1821 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1826 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1828 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1829 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1830 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1835 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1836 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1838 cause: self.cause.fold_with(folder),
1839 values: self.values.fold_with(folder)
1843 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1844 self.cause.visit_with(visitor) || self.values.visit_with(visitor)