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::RelateResult;
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;
55 pub mod error_reporting;
61 pub mod region_inference;
65 pub mod type_variable;
69 pub struct InferOk<'tcx, T> {
71 pub obligations: PredicateObligations<'tcx>,
73 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
75 pub type Bound<T> = Option<T>;
76 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
77 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
79 /// A version of &ty::TypeckTables which can be `Missing` (not needed),
80 /// `InProgress` (during typeck) or `Interned` (result of typeck).
81 /// Only the `InProgress` version supports `borrow_mut`.
82 #[derive(Copy, Clone)]
83 pub enum InferTables<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
84 Interned(&'a ty::TypeckTables<'gcx>),
85 InProgress(&'a RefCell<ty::TypeckTables<'tcx>>),
89 pub enum InferTablesRef<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
90 Interned(&'a ty::TypeckTables<'gcx>),
91 InProgress(Ref<'a, ty::TypeckTables<'tcx>>)
94 impl<'a, 'gcx, 'tcx> Deref for InferTablesRef<'a, 'gcx, 'tcx> {
95 type Target = ty::TypeckTables<'tcx>;
96 fn deref(&self) -> &Self::Target {
98 InferTablesRef::Interned(tables) => tables,
99 InferTablesRef::InProgress(ref tables) => tables
104 impl<'a, 'gcx, 'tcx> InferTables<'a, 'gcx, 'tcx> {
105 pub fn borrow(self) -> InferTablesRef<'a, 'gcx, 'tcx> {
107 InferTables::Interned(tables) => InferTablesRef::Interned(tables),
108 InferTables::InProgress(tables) => InferTablesRef::InProgress(tables.borrow()),
109 InferTables::Missing => {
110 bug!("InferTables: infcx.tables.borrow() with no tables")
115 pub fn expect_interned(self) -> &'a ty::TypeckTables<'gcx> {
117 InferTables::Interned(tables) => tables,
118 InferTables::InProgress(_) => {
119 bug!("InferTables: infcx.tables.expect_interned() during type-checking");
121 InferTables::Missing => {
122 bug!("InferTables: infcx.tables.expect_interned() with no tables")
127 pub fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> {
129 InferTables::Interned(_) => {
130 bug!("InferTables: infcx.tables.borrow_mut() outside of type-checking");
132 InferTables::InProgress(tables) => tables.borrow_mut(),
133 InferTables::Missing => {
134 bug!("InferTables: infcx.tables.borrow_mut() with no tables")
140 pub struct InferCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
141 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
143 pub tables: InferTables<'a, 'gcx, 'tcx>,
145 // Cache for projections. This cache is snapshotted along with the
148 // Public so that `traits::project` can use it.
149 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
151 // We instantiate UnificationTable with bounds<Ty> because the
152 // types that might instantiate a general type variable have an
153 // order, represented by its upper and lower bounds.
154 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
156 // Map from integral variable to the kind of integer it represents
157 int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
159 // Map from floating variable to the kind of float it represents
160 float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
162 // For region variables.
163 region_vars: RegionVarBindings<'a, 'gcx, 'tcx>,
165 /// Caches the results of trait selection. This cache is used
166 /// for things that have to do with the parameters in scope.
167 pub selection_cache: traits::SelectionCache<'tcx>,
169 /// Caches the results of trait evaluation.
170 pub evaluation_cache: traits::EvaluationCache<'tcx>,
172 // the set of predicates on which errors have been reported, to
173 // avoid reporting the same error twice.
174 pub reported_trait_errors: RefCell<FxHashSet<traits::TraitErrorKey<'tcx>>>,
176 // When an error occurs, we want to avoid reporting "derived"
177 // errors that are due to this original failure. Normally, we
178 // handle this with the `err_count_on_creation` count, which
179 // basically just tracks how many errors were reported when we
180 // started type-checking a fn and checks to see if any new errors
181 // have been reported since then. Not great, but it works.
183 // However, when errors originated in other passes -- notably
184 // resolve -- this heuristic breaks down. Therefore, we have this
185 // auxiliary flag that one can set whenever one creates a
186 // type-error that is due to an error in a prior pass.
188 // Don't read this flag directly, call `is_tainted_by_errors()`
189 // and `set_tainted_by_errors()`.
190 tainted_by_errors_flag: Cell<bool>,
192 // Track how many errors were reported when this infcx is created.
193 // If the number of errors increases, that's also a sign (line
194 // `tained_by_errors`) to avoid reporting certain kinds of errors.
195 err_count_on_creation: usize,
197 // This flag is true while there is an active snapshot.
198 in_snapshot: Cell<bool>,
201 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
202 /// region that each late-bound region was replaced with.
203 pub type SkolemizationMap<'tcx> = FxHashMap<ty::BoundRegion, ty::Region<'tcx>>;
205 /// See `error_reporting` module for more details
206 #[derive(Clone, Debug)]
207 pub enum ValuePairs<'tcx> {
208 Types(ExpectedFound<Ty<'tcx>>),
209 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
210 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
213 /// The trace designates the path through inference that we took to
214 /// encounter an error or subtyping constraint.
216 /// See `error_reporting` module for more details.
218 pub struct TypeTrace<'tcx> {
219 cause: ObligationCause<'tcx>,
220 values: ValuePairs<'tcx>,
223 /// The origin of a `r1 <= r2` constraint.
225 /// See `error_reporting` module for more details
226 #[derive(Clone, Debug)]
227 pub enum SubregionOrigin<'tcx> {
228 // Arose from a subtyping relation
229 Subtype(TypeTrace<'tcx>),
231 // Stack-allocated closures cannot outlive innermost loop
232 // or function so as to ensure we only require finite stack
233 InfStackClosure(Span),
235 // Invocation of closure must be within its lifetime
238 // Dereference of reference must be within its lifetime
241 // Closure bound must not outlive captured free variables
242 FreeVariable(Span, ast::NodeId),
244 // Index into slice must be within its lifetime
247 // When casting `&'a T` to an `&'b Trait` object,
248 // relating `'a` to `'b`
249 RelateObjectBound(Span),
251 // Some type parameter was instantiated with the given type,
252 // and that type must outlive some region.
253 RelateParamBound(Span, Ty<'tcx>),
255 // The given region parameter was instantiated with a region
256 // that must outlive some other region.
257 RelateRegionParamBound(Span),
259 // A bound placed on type parameters that states that must outlive
260 // the moment of their instantiation.
261 RelateDefaultParamBound(Span, Ty<'tcx>),
263 // Creating a pointer `b` to contents of another reference
266 // Creating a pointer `b` to contents of an upvar
267 ReborrowUpvar(Span, ty::UpvarId),
269 // Data with type `Ty<'tcx>` was borrowed
270 DataBorrowed(Ty<'tcx>, Span),
272 // (&'a &'b T) where a >= b
273 ReferenceOutlivesReferent(Ty<'tcx>, Span),
275 // Type or region parameters must be in scope.
276 ParameterInScope(ParameterOrigin, Span),
278 // The type T of an expression E must outlive the lifetime for E.
279 ExprTypeIsNotInScope(Ty<'tcx>, Span),
281 // A `ref b` whose region does not enclose the decl site
282 BindingTypeIsNotValidAtDecl(Span),
284 // Regions appearing in a method receiver must outlive method call
287 // Regions appearing in a function argument must outlive func call
290 // Region in return type of invoked fn must enclose call
293 // Operands must be in scope
296 // Region resulting from a `&` expr must enclose the `&` expr
299 // An auto-borrow that does not enclose the expr where it occurs
302 // Region constraint arriving from destructor safety
303 SafeDestructor(Span),
305 // Comparing the signature and requirements of an impl method against
306 // the containing trait.
307 CompareImplMethodObligation {
309 item_name: ast::Name,
310 impl_item_def_id: DefId,
311 trait_item_def_id: DefId,
313 // this is `Some(_)` if this error arises from the bug fix for
314 // #18937. This is a temporary measure.
315 lint_id: Option<ast::NodeId>,
319 /// Places that type/region parameters can appear.
320 #[derive(Clone, Copy, Debug)]
321 pub enum ParameterOrigin {
323 MethodCall, // foo.bar() <-- parameters on impl providing bar()
324 OverloadedOperator, // a + b when overloaded
325 OverloadedDeref, // *a when overloaded
328 /// Times when we replace late-bound regions with variables:
329 #[derive(Clone, Copy, Debug)]
330 pub enum LateBoundRegionConversionTime {
331 /// when a fn is called
334 /// when two higher-ranked types are compared
337 /// when projecting an associated type
338 AssocTypeProjection(ast::Name),
341 /// Reasons to create a region inference variable
343 /// See `error_reporting` module for more details
344 #[derive(Clone, Debug)]
345 pub enum RegionVariableOrigin {
346 // Region variables created for ill-categorized reasons,
347 // mostly indicates places in need of refactoring
350 // Regions created by a `&P` or `[...]` pattern
353 // Regions created by `&` operator
356 // Regions created as part of an autoref of a method receiver
359 // Regions created as part of an automatic coercion
362 // Region variables created as the values for early-bound regions
363 EarlyBoundRegion(Span, ast::Name, Option<ty::Issue32330>),
365 // Region variables created for bound regions
366 // in a function or method that is called
367 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
369 UpvarRegion(ty::UpvarId, Span),
371 BoundRegionInCoherence(ast::Name),
374 #[derive(Copy, Clone, Debug)]
375 pub enum FixupError {
376 UnresolvedIntTy(IntVid),
377 UnresolvedFloatTy(FloatVid),
381 impl fmt::Display for FixupError {
382 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
383 use self::FixupError::*;
386 UnresolvedIntTy(_) => {
387 write!(f, "cannot determine the type of this integer; \
388 add a suffix to specify the type explicitly")
390 UnresolvedFloatTy(_) => {
391 write!(f, "cannot determine the type of this number; \
392 add a suffix to specify the type explicitly")
394 UnresolvedTy(_) => write!(f, "unconstrained type")
399 pub trait InferEnv<'a, 'tcx> {
400 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
401 -> (Option<&'a ty::TypeckTables<'tcx>>,
402 Option<ty::TypeckTables<'tcx>>);
405 impl<'a, 'tcx> InferEnv<'a, 'tcx> for () {
406 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
407 -> (Option<&'a ty::TypeckTables<'tcx>>,
408 Option<ty::TypeckTables<'tcx>>) {
413 impl<'a, 'tcx> InferEnv<'a, 'tcx> for &'a ty::TypeckTables<'tcx> {
414 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
415 -> (Option<&'a ty::TypeckTables<'tcx>>,
416 Option<ty::TypeckTables<'tcx>>) {
421 impl<'a, 'tcx> InferEnv<'a, 'tcx> for ty::TypeckTables<'tcx> {
422 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
423 -> (Option<&'a ty::TypeckTables<'tcx>>,
424 Option<ty::TypeckTables<'tcx>>) {
429 impl<'a, 'tcx> InferEnv<'a, 'tcx> for hir::BodyId {
430 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
431 -> (Option<&'a ty::TypeckTables<'tcx>>,
432 Option<ty::TypeckTables<'tcx>>) {
433 let def_id = tcx.hir.body_owner_def_id(self);
434 (Some(tcx.typeck_tables_of(def_id)), None)
438 /// Helper type of a temporary returned by tcx.infer_ctxt(...).
439 /// Necessary because we can't write the following bound:
440 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
441 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
442 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
443 arena: DroplessArena,
444 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
445 tables: Option<&'a ty::TypeckTables<'gcx>>,
448 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
449 pub fn infer_ctxt<E: InferEnv<'a, 'gcx>>(self, env: E) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
450 let (tables, fresh_tables) = env.to_parts(self);
453 arena: DroplessArena::new(),
454 fresh_tables: fresh_tables.map(RefCell::new),
459 /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
460 /// for MemCategorizationContext/ExprUseVisitor.
461 /// If any inference functionality is used, ICEs will occur.
462 pub fn borrowck_fake_infer_ctxt(self, body: hir::BodyId)
463 -> InferCtxt<'a, 'gcx, 'gcx> {
464 let (tables, _) = body.to_parts(self);
467 tables: InferTables::Interned(tables.unwrap()),
468 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
469 int_unification_table: RefCell::new(UnificationTable::new()),
470 float_unification_table: RefCell::new(UnificationTable::new()),
471 region_vars: RegionVarBindings::new(self),
472 selection_cache: traits::SelectionCache::new(),
473 evaluation_cache: traits::EvaluationCache::new(),
474 projection_cache: RefCell::new(traits::ProjectionCache::new()),
475 reported_trait_errors: RefCell::new(FxHashSet()),
476 tainted_by_errors_flag: Cell::new(false),
477 err_count_on_creation: self.sess.err_count(),
478 in_snapshot: Cell::new(false),
483 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
484 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
485 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
487 let InferCtxtBuilder {
493 let tables = tables.map(InferTables::Interned).unwrap_or_else(|| {
494 fresh_tables.as_ref().map_or(InferTables::Missing, InferTables::InProgress)
496 global_tcx.enter_local(arena, |tcx| f(InferCtxt {
499 projection_cache: RefCell::new(traits::ProjectionCache::new()),
500 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
501 int_unification_table: RefCell::new(UnificationTable::new()),
502 float_unification_table: RefCell::new(UnificationTable::new()),
503 region_vars: RegionVarBindings::new(tcx),
504 selection_cache: traits::SelectionCache::new(),
505 evaluation_cache: traits::EvaluationCache::new(),
506 reported_trait_errors: RefCell::new(FxHashSet()),
507 tainted_by_errors_flag: Cell::new(false),
508 err_count_on_creation: tcx.sess.err_count(),
509 in_snapshot: Cell::new(false),
514 impl<T> ExpectedFound<T> {
515 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
517 ExpectedFound {expected: a, found: b}
519 ExpectedFound {expected: b, found: a}
524 impl<'tcx, T> InferOk<'tcx, T> {
525 pub fn unit(self) -> InferOk<'tcx, ()> {
526 InferOk { value: (), obligations: self.obligations }
530 #[must_use = "once you start a snapshot, you should always consume it"]
531 pub struct CombinedSnapshot<'a, 'tcx:'a> {
532 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
533 type_snapshot: type_variable::Snapshot,
534 int_snapshot: unify::Snapshot<ty::IntVid>,
535 float_snapshot: unify::Snapshot<ty::FloatVid>,
536 region_vars_snapshot: RegionSnapshot,
537 was_in_snapshot: bool,
538 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
541 /// Helper trait for shortening the lifetimes inside a
542 /// value for post-type-checking normalization.
543 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
544 fn trans_normalize<'a, 'tcx>(&self,
545 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
546 param_env: ty::ParamEnv<'tcx>)
550 macro_rules! items { ($($item:item)+) => ($($item)+) }
551 macro_rules! impl_trans_normalize {
552 ($lt_gcx:tt, $($ty:ty),+) => {
553 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
554 fn trans_normalize<'a, 'tcx>(&self,
555 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>,
556 param_env: ty::ParamEnv<'tcx>)
558 infcx.normalize_projections_in(param_env, self)
564 impl_trans_normalize!('gcx,
569 ty::ClosureSubsts<'gcx>,
570 ty::PolyTraitRef<'gcx>,
571 ty::ExistentialTraitRef<'gcx>
574 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
575 fn trans_normalize<'a, 'tcx>(&self,
576 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
577 param_env: ty::ParamEnv<'tcx>)
580 LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx, param_env) },
581 LvalueTy::Downcast { adt_def, substs, variant_index } => {
584 substs: substs.trans_normalize(infcx, param_env),
585 variant_index: variant_index
592 // NOTE: Callable from trans only!
593 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
594 /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
595 /// each time we erase them in translation, we need to normalize
597 pub fn erase_late_bound_regions_and_normalize<T>(self, value: &ty::Binder<T>)
599 where T: TransNormalize<'tcx>
601 assert!(!value.needs_subst());
602 let value = self.erase_late_bound_regions(value);
603 self.normalize_associated_type(&value)
606 /// Fully normalizes any associated types in `value`, using an
607 /// empty environment and `Reveal::All` mode (therefore, suitable
608 /// only for monomorphized code during trans, basically).
609 pub fn normalize_associated_type<T>(self, value: &T) -> T
610 where T: TransNormalize<'tcx>
612 debug!("normalize_associated_type(t={:?})", value);
614 let param_env = ty::ParamEnv::empty(Reveal::All);
615 let value = self.erase_regions(value);
617 if !value.has_projection_types() {
621 self.infer_ctxt(()).enter(|infcx| {
622 value.trans_normalize(&infcx, param_env)
626 /// Does a best-effort to normalize any associated types in
627 /// `value`; this includes revealing specializable types, so this
628 /// should be not be used during type-checking, but only during
629 /// optimization and code generation.
630 pub fn normalize_associated_type_in_env<T>(
631 self, value: &T, env: ty::ParamEnv<'tcx>
633 where T: TransNormalize<'tcx>
635 debug!("normalize_associated_type_in_env(t={:?})", value);
637 let value = self.erase_regions(value);
639 if !value.has_projection_types() {
643 self.infer_ctxt(()).enter(|infcx| {
644 value.trans_normalize(&infcx, env.reveal_all())
649 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
650 fn normalize_projections_in<T>(&self, param_env: ty::ParamEnv<'tcx>, value: &T) -> T::Lifted
651 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
653 let mut selcx = traits::SelectionContext::new(self);
654 let cause = traits::ObligationCause::dummy();
655 let traits::Normalized { value: result, obligations } =
656 traits::normalize(&mut selcx, param_env, cause, value);
658 debug!("normalize_projections_in: result={:?} obligations={:?}",
659 result, obligations);
661 let mut fulfill_cx = traits::FulfillmentContext::new();
663 for obligation in obligations {
664 fulfill_cx.register_predicate_obligation(self, obligation);
667 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
670 /// Finishes processes any obligations that remain in the
671 /// fulfillment context, and then returns the result with all type
672 /// variables removed and regions erased. Because this is intended
673 /// for use after type-check has completed, if any errors occur,
674 /// it will panic. It is used during normalization and other cases
675 /// where processing the obligations in `fulfill_cx` may cause
676 /// type inference variables that appear in `result` to be
677 /// unified, and hence we need to process those obligations to get
678 /// the complete picture of the type.
679 pub fn drain_fulfillment_cx_or_panic<T>(&self,
681 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
684 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
686 debug!("drain_fulfillment_cx_or_panic()");
688 // In principle, we only need to do this so long as `result`
689 // contains unbound type parameters. It could be a slight
690 // optimization to stop iterating early.
691 match fulfill_cx.select_all_or_error(self) {
694 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
699 let result = self.resolve_type_vars_if_possible(result);
700 let result = self.tcx.erase_regions(&result);
702 match self.tcx.lift_to_global(&result) {
703 Some(result) => result,
705 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
710 pub fn is_in_snapshot(&self) -> bool {
711 self.in_snapshot.get()
714 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
715 t.fold_with(&mut self.freshener())
718 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
720 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
725 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
726 freshen::TypeFreshener::new(self)
729 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
730 use ty::error::UnconstrainedNumeric::Neither;
731 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
733 ty::TyInfer(ty::IntVar(vid)) => {
734 if self.int_unification_table.borrow_mut().has_value(vid) {
740 ty::TyInfer(ty::FloatVar(vid)) => {
741 if self.float_unification_table.borrow_mut().has_value(vid) {
751 /// Returns a type variable's default fallback if any exists. A default
752 /// must be attached to the variable when created, if it is created
753 /// without a default, this will return None.
755 /// This code does not apply to integral or floating point variables,
756 /// only to use declared defaults.
758 /// See `new_ty_var_with_default` to create a type variable with a default.
759 /// See `type_variable::Default` for details about what a default entails.
760 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
762 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
767 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
768 let mut variables = Vec::new();
770 let unbound_ty_vars = self.type_variables
772 .unsolved_variables()
774 .map(|t| self.tcx.mk_var(t));
776 let unbound_int_vars = self.int_unification_table
778 .unsolved_variables()
780 .map(|v| self.tcx.mk_int_var(v));
782 let unbound_float_vars = self.float_unification_table
784 .unsolved_variables()
786 .map(|v| self.tcx.mk_float_var(v));
788 variables.extend(unbound_ty_vars);
789 variables.extend(unbound_int_vars);
790 variables.extend(unbound_float_vars);
795 fn combine_fields(&'a self, trace: TypeTrace<'tcx>, param_env: ty::ParamEnv<'tcx>)
796 -> CombineFields<'a, 'gcx, 'tcx> {
802 obligations: PredicateObligations::new(),
806 // Clear the "currently in a snapshot" flag, invoke the closure,
807 // then restore the flag to its original value. This flag is a
808 // debugging measure designed to detect cases where we start a
809 // snapshot, create type variables, and register obligations
810 // which may involve those type variables in the fulfillment cx,
811 // potentially leaving "dangling type variables" behind.
812 // In such cases, an assertion will fail when attempting to
813 // register obligations, within a snapshot. Very useful, much
814 // better than grovelling through megabytes of RUST_LOG output.
816 // HOWEVER, in some cases the flag is unhelpful. In particular, we
817 // sometimes create a "mini-fulfilment-cx" in which we enroll
818 // obligations. As long as this fulfillment cx is fully drained
819 // before we return, this is not a problem, as there won't be any
820 // escaping obligations in the main cx. In those cases, you can
821 // use this function.
822 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
823 where F: FnOnce(&Self) -> R
825 let flag = self.in_snapshot.get();
826 self.in_snapshot.set(false);
827 let result = func(self);
828 self.in_snapshot.set(flag);
832 fn start_snapshot<'b>(&'b self) -> CombinedSnapshot<'b, 'tcx> {
833 debug!("start_snapshot()");
835 let in_snapshot = self.in_snapshot.get();
836 self.in_snapshot.set(true);
839 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
840 type_snapshot: self.type_variables.borrow_mut().snapshot(),
841 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
842 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
843 region_vars_snapshot: self.region_vars.start_snapshot(),
844 was_in_snapshot: in_snapshot,
845 // Borrow tables "in progress" (i.e. during typeck)
846 // to ban writes from within a snapshot to them.
847 _in_progress_tables: match self.tables {
848 InferTables::InProgress(ref tables) => tables.try_borrow().ok(),
854 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
855 debug!("rollback_to(cause={})", cause);
856 let CombinedSnapshot { projection_cache_snapshot,
860 region_vars_snapshot,
862 _in_progress_tables } = snapshot;
864 self.in_snapshot.set(was_in_snapshot);
866 self.projection_cache
868 .rollback_to(projection_cache_snapshot);
871 .rollback_to(type_snapshot);
872 self.int_unification_table
874 .rollback_to(int_snapshot);
875 self.float_unification_table
877 .rollback_to(float_snapshot);
879 .rollback_to(region_vars_snapshot);
882 fn commit_from(&self, snapshot: CombinedSnapshot) {
883 debug!("commit_from()");
884 let CombinedSnapshot { projection_cache_snapshot,
888 region_vars_snapshot,
890 _in_progress_tables } = snapshot;
892 self.in_snapshot.set(was_in_snapshot);
894 self.projection_cache
896 .commit(projection_cache_snapshot);
899 .commit(type_snapshot);
900 self.int_unification_table
902 .commit(int_snapshot);
903 self.float_unification_table
905 .commit(float_snapshot);
907 .commit(region_vars_snapshot);
910 /// Execute `f` and commit the bindings
911 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
915 let snapshot = self.start_snapshot();
917 self.commit_from(snapshot);
921 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
922 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
923 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
925 debug!("commit_if_ok()");
926 let snapshot = self.start_snapshot();
927 let r = f(&snapshot);
928 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
930 Ok(_) => { self.commit_from(snapshot); }
931 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
936 // Execute `f` in a snapshot, and commit the bindings it creates
937 pub fn in_snapshot<T, F>(&self, f: F) -> T where
938 F: FnOnce(&CombinedSnapshot) -> T
940 debug!("in_snapshot()");
941 let snapshot = self.start_snapshot();
942 let r = f(&snapshot);
943 self.commit_from(snapshot);
947 /// Execute `f` then unroll any bindings it creates
948 pub fn probe<R, F>(&self, f: F) -> R where
949 F: FnOnce(&CombinedSnapshot) -> R,
952 let snapshot = self.start_snapshot();
953 let r = f(&snapshot);
954 self.rollback_to("probe", snapshot);
958 pub fn add_given(&self,
959 sub: ty::Region<'tcx>,
962 self.region_vars.add_given(sub, sup);
965 pub fn can_sub<T>(&self,
966 param_env: ty::ParamEnv<'tcx>,
970 where T: at::ToTrace<'tcx>
972 let origin = &ObligationCause::dummy();
974 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
975 // Ignore obligations, since we are unrolling
976 // everything anyway.
981 pub fn can_eq<T>(&self,
982 param_env: ty::ParamEnv<'tcx>,
986 where T: at::ToTrace<'tcx>
988 let origin = &ObligationCause::dummy();
990 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
991 // Ignore obligations, since we are unrolling
992 // everything anyway.
997 pub fn sub_regions(&self,
998 origin: SubregionOrigin<'tcx>,
1000 b: ty::Region<'tcx>) {
1001 debug!("sub_regions({:?} <: {:?})", a, b);
1002 self.region_vars.make_subregion(origin, a, b);
1005 pub fn equality_predicate(&self,
1006 cause: &ObligationCause<'tcx>,
1007 param_env: ty::ParamEnv<'tcx>,
1008 predicate: &ty::PolyEquatePredicate<'tcx>)
1009 -> InferResult<'tcx, ()>
1011 self.commit_if_ok(|snapshot| {
1012 let (ty::EquatePredicate(a, b), skol_map) =
1013 self.skolemize_late_bound_regions(predicate, snapshot);
1014 let cause_span = cause.span;
1015 let eqty_ok = self.at(cause, param_env).eq(b, a)?;
1016 self.leak_check(false, cause_span, &skol_map, snapshot)?;
1017 self.pop_skolemized(skol_map, snapshot);
1022 pub fn subtype_predicate(&self,
1023 cause: &ObligationCause<'tcx>,
1024 param_env: ty::ParamEnv<'tcx>,
1025 predicate: &ty::PolySubtypePredicate<'tcx>)
1026 -> Option<InferResult<'tcx, ()>>
1028 // Subtle: it's ok to skip the binder here and resolve because
1029 // `shallow_resolve` just ignores anything that is not a type
1030 // variable, and because type variable's can't (at present, at
1031 // least) capture any of the things bound by this binder.
1033 // Really, there is no *particular* reason to do this
1034 // `shallow_resolve` here except as a
1035 // micro-optimization. Naturally I could not
1036 // resist. -nmatsakis
1037 let two_unbound_type_vars = {
1038 let a = self.shallow_resolve(predicate.skip_binder().a);
1039 let b = self.shallow_resolve(predicate.skip_binder().b);
1040 a.is_ty_var() && b.is_ty_var()
1043 if two_unbound_type_vars {
1044 // Two unbound type variables? Can't make progress.
1048 Some(self.commit_if_ok(|snapshot| {
1049 let (ty::SubtypePredicate { a_is_expected, a, b}, skol_map) =
1050 self.skolemize_late_bound_regions(predicate, snapshot);
1052 let cause_span = cause.span;
1053 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1054 self.leak_check(false, cause_span, &skol_map, snapshot)?;
1055 self.pop_skolemized(skol_map, snapshot);
1060 pub fn region_outlives_predicate(&self,
1061 cause: &traits::ObligationCause<'tcx>,
1062 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1065 self.commit_if_ok(|snapshot| {
1066 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1067 self.skolemize_late_bound_regions(predicate, snapshot);
1069 SubregionOrigin::from_obligation_cause(cause,
1070 || RelateRegionParamBound(cause.span));
1071 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1072 self.leak_check(false, cause.span, &skol_map, snapshot)?;
1073 Ok(self.pop_skolemized(skol_map, snapshot))
1077 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1080 .new_var(diverging, origin, None)
1083 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1084 self.tcx.mk_var(self.next_ty_var_id(false, origin))
1087 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1088 self.tcx.mk_var(self.next_ty_var_id(true, origin))
1091 pub fn next_int_var_id(&self) -> IntVid {
1092 self.int_unification_table
1097 pub fn next_float_var_id(&self) -> FloatVid {
1098 self.float_unification_table
1103 pub fn next_region_var(&self, origin: RegionVariableOrigin)
1104 -> ty::Region<'tcx> {
1105 self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
1108 /// Create a region inference variable for the given
1109 /// region parameter definition.
1110 pub fn region_var_for_def(&self,
1112 def: &ty::RegionParameterDef)
1113 -> ty::Region<'tcx> {
1114 self.next_region_var(EarlyBoundRegion(span, def.name, def.issue_32330))
1117 /// Create a type inference variable for the given
1118 /// type parameter definition. The substitutions are
1119 /// for actual parameters that may be referred to by
1120 /// the default of this type parameter, if it exists.
1121 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1122 /// used in a path such as `Foo::<T, U>::new()` will
1123 /// use an inference variable for `C` with `[T, U]`
1124 /// as the substitutions for the default, `(T, U)`.
1125 pub fn type_var_for_def(&self,
1127 def: &ty::TypeParameterDef,
1128 substs: &[Kind<'tcx>])
1130 let default = if def.has_default {
1131 let default = self.tcx.type_of(def.def_id);
1132 Some(type_variable::Default {
1133 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1142 let ty_var_id = self.type_variables
1145 TypeVariableOrigin::TypeParameterDefinition(span, def.name),
1148 self.tcx.mk_var(ty_var_id)
1151 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1152 /// type/region parameter to a fresh inference variable.
1153 pub fn fresh_substs_for_item(&self,
1156 -> &'tcx Substs<'tcx> {
1157 Substs::for_item(self.tcx, def_id, |def, _| {
1158 self.region_var_for_def(span, def)
1160 self.type_var_for_def(span, def, substs)
1164 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region<'tcx> {
1165 self.region_vars.new_bound(debruijn)
1168 /// True if errors have been reported since this infcx was
1169 /// created. This is sometimes used as a heuristic to skip
1170 /// reporting errors that often occur as a result of earlier
1171 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1172 /// inference variables, regionck errors).
1173 pub fn is_tainted_by_errors(&self) -> bool {
1174 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1175 tainted_by_errors_flag={})",
1176 self.tcx.sess.err_count(),
1177 self.err_count_on_creation,
1178 self.tainted_by_errors_flag.get());
1180 if self.tcx.sess.err_count() > self.err_count_on_creation {
1181 return true; // errors reported since this infcx was made
1183 self.tainted_by_errors_flag.get()
1186 /// Set the "tainted by errors" flag to true. We call this when we
1187 /// observe an error from a prior pass.
1188 pub fn set_tainted_by_errors(&self) {
1189 debug!("set_tainted_by_errors()");
1190 self.tainted_by_errors_flag.set(true)
1193 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1194 match self.tables.borrow().node_types.get(&id) {
1197 None if self.is_tainted_by_errors() =>
1200 bug!("no type for node {}: {} in fcx",
1201 id, self.tcx.hir.node_to_string(id));
1206 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1207 match self.tables.borrow().node_types.get(&ex.id) {
1210 bug!("no type for expr in fcx");
1215 pub fn resolve_regions_and_report_errors(&self,
1216 region_context: DefId,
1217 region_map: &RegionMaps,
1218 free_regions: &FreeRegionMap<'tcx>) {
1219 let region_rels = RegionRelations::new(self.tcx,
1223 let errors = self.region_vars.resolve_regions(®ion_rels);
1224 if !self.is_tainted_by_errors() {
1225 // As a heuristic, just skip reporting region errors
1226 // altogether if other errors have been reported while
1227 // this infcx was in use. This is totally hokey but
1228 // otherwise we have a hard time separating legit region
1229 // errors from silly ones.
1230 self.report_region_errors(&errors); // see error_reporting module
1234 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1235 self.resolve_type_vars_if_possible(&t).to_string()
1238 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1239 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1240 format!("({})", tstrs.join(", "))
1243 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1244 self.resolve_type_vars_if_possible(t).to_string()
1247 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1249 ty::TyInfer(ty::TyVar(v)) => {
1250 // Not entirely obvious: if `typ` is a type variable,
1251 // it can be resolved to an int/float variable, which
1252 // can then be recursively resolved, hence the
1253 // recursion. Note though that we prevent type
1254 // variables from unifying to other type variables
1255 // directly (though they may be embedded
1256 // structurally), and we prevent cycles in any case,
1257 // so this recursion should always be of very limited
1259 self.type_variables.borrow_mut()
1261 .map(|t| self.shallow_resolve(t))
1265 ty::TyInfer(ty::IntVar(v)) => {
1266 self.int_unification_table
1269 .map(|v| v.to_type(self.tcx))
1273 ty::TyInfer(ty::FloatVar(v)) => {
1274 self.float_unification_table
1277 .map(|v| v.to_type(self.tcx))
1287 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1288 where T: TypeFoldable<'tcx>
1291 * Where possible, replaces type/int/float variables in
1292 * `value` with their final value. Note that region variables
1293 * are unaffected. If a type variable has not been unified, it
1294 * is left as is. This is an idempotent operation that does
1295 * not affect inference state in any way and so you can do it
1299 if !value.needs_infer() {
1300 return value.clone(); // avoid duplicated subst-folding
1302 let mut r = resolve::OpportunisticTypeResolver::new(self);
1303 value.fold_with(&mut r)
1306 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1307 where T: TypeFoldable<'tcx>
1309 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1310 value.fold_with(&mut r)
1313 /// Resolves all type variables in `t` and then, if any were left
1314 /// unresolved, substitutes an error type. This is used after the
1315 /// main checking when doing a second pass before writeback. The
1316 /// justification is that writeback will produce an error for
1317 /// these unconstrained type variables.
1318 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1319 let ty = self.resolve_type_vars_if_possible(t);
1320 if ty.references_error() || ty.is_ty_var() {
1321 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1328 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1330 * Attempts to resolve all type/region variables in
1331 * `value`. Region inference must have been run already (e.g.,
1332 * by calling `resolve_regions_and_report_errors`). If some
1333 * variable was never unified, an `Err` results.
1335 * This method is idempotent, but it not typically not invoked
1336 * except during the writeback phase.
1339 resolve::fully_resolve(self, value)
1342 // [Note-Type-error-reporting]
1343 // An invariant is that anytime the expected or actual type is TyError (the special
1344 // error type, meaning that an error occurred when typechecking this expression),
1345 // this is a derived error. The error cascaded from another error (that was already
1346 // reported), so it's not useful to display it to the user.
1347 // The following methods implement this logic.
1348 // They check if either the actual or expected type is TyError, and don't print the error
1349 // in this case. The typechecker should only ever report type errors involving mismatched
1350 // types using one of these methods, and should not call span_err directly for such
1353 pub fn type_error_message<M>(&self,
1356 actual_ty: Ty<'tcx>)
1357 where M: FnOnce(String) -> String,
1359 self.type_error_struct(sp, mk_msg, actual_ty).emit();
1362 // FIXME: this results in errors without an error code. Deprecate?
1363 pub fn type_error_struct<M>(&self,
1366 actual_ty: Ty<'tcx>)
1367 -> DiagnosticBuilder<'tcx>
1368 where M: FnOnce(String) -> String,
1370 self.type_error_struct_with_diag(sp, |actual_ty| {
1371 self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1375 pub fn type_error_struct_with_diag<M>(&self,
1378 actual_ty: Ty<'tcx>)
1379 -> DiagnosticBuilder<'tcx>
1380 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1382 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1383 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1385 // Don't report an error if actual type is TyError.
1386 if actual_ty.references_error() {
1387 return self.tcx.sess.diagnostic().struct_dummy();
1390 mk_diag(self.ty_to_string(actual_ty))
1393 pub fn report_mismatched_types(&self,
1394 cause: &ObligationCause<'tcx>,
1397 err: TypeError<'tcx>)
1398 -> DiagnosticBuilder<'tcx> {
1399 let trace = TypeTrace::types(cause, true, expected, actual);
1400 self.report_and_explain_type_error(trace, &err)
1403 pub fn report_conflicting_default_types(&self,
1405 body_id: ast::NodeId,
1406 expected: type_variable::Default<'tcx>,
1407 actual: type_variable::Default<'tcx>) {
1408 let trace = TypeTrace {
1409 cause: ObligationCause::misc(span, body_id),
1410 values: Types(ExpectedFound {
1411 expected: expected.ty,
1416 self.report_and_explain_type_error(
1418 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1425 pub fn replace_late_bound_regions_with_fresh_var<T>(
1428 lbrct: LateBoundRegionConversionTime,
1429 value: &ty::Binder<T>)
1430 -> (T, FxHashMap<ty::BoundRegion, ty::Region<'tcx>>)
1431 where T : TypeFoldable<'tcx>
1433 self.tcx.replace_late_bound_regions(
1435 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1438 /// Given a higher-ranked projection predicate like:
1440 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1442 /// and a target trait-ref like:
1444 /// <T as Fn<&'x u32>>
1446 /// find a substitution `S` for the higher-ranked regions (here,
1447 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1448 /// and then return the value (here, `&'a u32`) but with the
1449 /// substitution applied (hence, `&'x u32`).
1451 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1453 pub fn match_poly_projection_predicate(&self,
1454 cause: ObligationCause<'tcx>,
1455 param_env: ty::ParamEnv<'tcx>,
1456 match_a: ty::PolyProjectionPredicate<'tcx>,
1457 match_b: ty::TraitRef<'tcx>)
1458 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1460 let span = cause.span;
1461 let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1462 let trace = TypeTrace {
1464 values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1467 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1468 let mut combine = self.combine_fields(trace, param_env);
1469 let result = combine.higher_ranked_match(span, &match_pair, &match_b, true)?;
1470 Ok(InferOk { value: result, obligations: combine.obligations })
1473 /// See `verify_generic_bound` method in `region_inference`
1474 pub fn verify_generic_bound(&self,
1475 origin: SubregionOrigin<'tcx>,
1476 kind: GenericKind<'tcx>,
1477 a: ty::Region<'tcx>,
1478 bound: VerifyBound<'tcx>) {
1479 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1484 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1487 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1488 let ty = self.node_type(id);
1489 self.resolve_type_vars_or_error(&ty)
1492 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1493 let ty = self.tables.borrow().expr_ty_adjusted(expr);
1494 self.resolve_type_vars_or_error(&ty)
1497 pub fn type_moves_by_default(&self,
1498 param_env: ty::ParamEnv<'tcx>,
1502 let ty = self.resolve_type_vars_if_possible(&ty);
1503 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1504 // Even if the type may have no inference variables, during
1505 // type-checking closure types are in local tables only.
1506 let local_closures = match self.tables {
1507 InferTables::InProgress(_) => ty.has_closure_types(),
1510 if !local_closures {
1511 return ty.moves_by_default(self.tcx.global_tcx(), param_env, span);
1515 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1517 // this can get called from typeck (by euv), and moves_by_default
1518 // rightly refuses to work with inference variables, but
1519 // moves_by_default has a cache, which we want to use in other
1521 !traits::type_known_to_meet_bound(self, param_env, ty, copy_def_id, span)
1524 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
1525 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1528 pub fn closure_kind(&self,
1530 -> Option<ty::ClosureKind>
1532 if let InferTables::InProgress(tables) = self.tables {
1533 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1534 return tables.borrow()
1538 .map(|(kind, _)| kind);
1542 // During typeck, ALL closures are local. But afterwards,
1543 // during trans, we see closure ids from other traits.
1544 // That may require loading the closure data out of the
1546 Some(self.tcx.closure_kind(def_id))
1549 pub fn closure_type(&self, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1550 if let InferTables::InProgress(tables) = self.tables {
1551 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1552 if let Some(&ty) = tables.borrow().closure_tys.get(&id) {
1558 self.tcx.closure_type(def_id)
1562 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1563 pub fn span(&self) -> Span {
1567 pub fn types(cause: &ObligationCause<'tcx>,
1568 a_is_expected: bool,
1571 -> TypeTrace<'tcx> {
1573 cause: cause.clone(),
1574 values: Types(ExpectedFound::new(a_is_expected, a, b))
1578 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1580 cause: ObligationCause::dummy(),
1581 values: Types(ExpectedFound {
1582 expected: tcx.types.err,
1583 found: tcx.types.err,
1589 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1590 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1591 write!(f, "TypeTrace({:?})", self.cause)
1595 impl<'tcx> SubregionOrigin<'tcx> {
1596 pub fn span(&self) -> Span {
1598 Subtype(ref a) => a.span(),
1599 InfStackClosure(a) => a,
1600 InvokeClosure(a) => a,
1601 DerefPointer(a) => a,
1602 FreeVariable(a, _) => a,
1604 RelateObjectBound(a) => a,
1605 RelateParamBound(a, _) => a,
1606 RelateRegionParamBound(a) => a,
1607 RelateDefaultParamBound(a, _) => a,
1609 ReborrowUpvar(a, _) => a,
1610 DataBorrowed(_, a) => a,
1611 ReferenceOutlivesReferent(_, a) => a,
1612 ParameterInScope(_, a) => a,
1613 ExprTypeIsNotInScope(_, a) => a,
1614 BindingTypeIsNotValidAtDecl(a) => a,
1621 SafeDestructor(a) => a,
1622 CompareImplMethodObligation { span, .. } => span,
1626 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>,
1629 where F: FnOnce() -> Self
1632 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
1633 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span),
1635 traits::ObligationCauseCode::CompareImplMethodObligation { item_name,
1639 SubregionOrigin::CompareImplMethodObligation {
1641 item_name: item_name,
1642 impl_item_def_id: impl_item_def_id,
1643 trait_item_def_id: trait_item_def_id,
1652 impl RegionVariableOrigin {
1653 pub fn span(&self) -> Span {
1655 MiscVariable(a) => a,
1656 PatternRegion(a) => a,
1657 AddrOfRegion(a) => a,
1660 EarlyBoundRegion(a, ..) => a,
1661 LateBoundRegion(a, ..) => a,
1662 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1663 UpvarRegion(_, a) => a
1668 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1669 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1671 ValuePairs::Types(ref ef) => {
1672 ValuePairs::Types(ef.fold_with(folder))
1674 ValuePairs::TraitRefs(ref ef) => {
1675 ValuePairs::TraitRefs(ef.fold_with(folder))
1677 ValuePairs::PolyTraitRefs(ref ef) => {
1678 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1683 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1685 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1686 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1687 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1692 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1693 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1695 cause: self.cause.fold_with(folder),
1696 values: self.values.fold_with(folder)
1700 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1701 self.cause.visit_with(visitor) || self.values.visit_with(visitor)