1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See the Book for more information.
13 pub use self::LateBoundRegionConversionTime::*;
14 pub use self::RegionVariableOrigin::*;
15 pub use self::SubregionOrigin::*;
16 pub use self::ValuePairs::*;
17 pub use ty::IntVarValue;
18 pub use self::freshen::TypeFreshener;
19 pub use self::region_inference::{GenericKind, VerifyBound};
21 use hir::def_id::DefId;
23 use middle::free_region::FreeRegionMap;
24 use middle::mem_categorization as mc;
25 use middle::mem_categorization::McResult;
26 use middle::lang_items;
27 use mir::tcx::LvalueTy;
28 use ty::subst::{Kind, Subst, Substs};
29 use ty::{TyVid, IntVid, FloatVid};
30 use ty::{self, Ty, TyCtxt};
31 use ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
32 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
33 use ty::relate::{Relate, RelateResult, TypeRelation};
34 use traits::{self, ObligationCause, PredicateObligations, Reveal};
35 use rustc_data_structures::unify::{self, UnificationTable};
36 use std::cell::{Cell, RefCell, Ref, RefMut};
40 use errors::DiagnosticBuilder;
41 use syntax_pos::{self, Span, DUMMY_SP};
42 use util::nodemap::{FxHashMap, FxHashSet};
43 use arena::DroplessArena;
45 use self::combine::CombineFields;
46 use self::higher_ranked::HrMatchResult;
47 use self::region_inference::{RegionVarBindings, RegionSnapshot};
48 use self::type_variable::TypeVariableOrigin;
49 use self::unify_key::ToType;
53 pub mod error_reporting;
59 pub mod region_inference;
63 pub mod type_variable;
67 pub struct InferOk<'tcx, T> {
69 pub obligations: PredicateObligations<'tcx>,
71 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
73 pub type Bound<T> = Option<T>;
74 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
75 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
77 /// A version of &ty::TypeckTables which can be `Missing` (not needed),
78 /// `InProgress` (during typeck) or `Interned` (result of typeck).
79 /// Only the `InProgress` version supports `borrow_mut`.
80 #[derive(Copy, Clone)]
81 pub enum InferTables<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
82 Interned(&'a ty::TypeckTables<'gcx>),
83 InProgress(&'a RefCell<ty::TypeckTables<'tcx>>),
87 pub enum InferTablesRef<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
88 Interned(&'a ty::TypeckTables<'gcx>),
89 InProgress(Ref<'a, ty::TypeckTables<'tcx>>)
92 impl<'a, 'gcx, 'tcx> Deref for InferTablesRef<'a, 'gcx, 'tcx> {
93 type Target = ty::TypeckTables<'tcx>;
94 fn deref(&self) -> &Self::Target {
96 InferTablesRef::Interned(tables) => tables,
97 InferTablesRef::InProgress(ref tables) => tables
102 impl<'a, 'gcx, 'tcx> InferTables<'a, 'gcx, 'tcx> {
103 pub fn borrow(self) -> InferTablesRef<'a, 'gcx, 'tcx> {
105 InferTables::Interned(tables) => InferTablesRef::Interned(tables),
106 InferTables::InProgress(tables) => InferTablesRef::InProgress(tables.borrow()),
107 InferTables::Missing => {
108 bug!("InferTables: infcx.tables.borrow() with no tables")
113 pub fn expect_interned(self) -> &'a ty::TypeckTables<'gcx> {
115 InferTables::Interned(tables) => tables,
116 InferTables::InProgress(_) => {
117 bug!("InferTables: infcx.tables.expect_interned() during type-checking");
119 InferTables::Missing => {
120 bug!("InferTables: infcx.tables.expect_interned() with no tables")
125 pub fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> {
127 InferTables::Interned(_) => {
128 bug!("InferTables: infcx.tables.borrow_mut() outside of type-checking");
130 InferTables::InProgress(tables) => tables.borrow_mut(),
131 InferTables::Missing => {
132 bug!("InferTables: infcx.tables.borrow_mut() with no tables")
138 pub struct InferCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
139 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
141 pub tables: InferTables<'a, 'gcx, 'tcx>,
143 // Cache for projections. This cache is snapshotted along with the
146 // Public so that `traits::project` can use it.
147 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
149 // We instantiate UnificationTable with bounds<Ty> because the
150 // types that might instantiate a general type variable have an
151 // order, represented by its upper and lower bounds.
152 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
154 // Map from integral variable to the kind of integer it represents
155 int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
157 // Map from floating variable to the kind of float it represents
158 float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
160 // For region variables.
161 region_vars: RegionVarBindings<'a, 'gcx, 'tcx>,
163 pub parameter_environment: ty::ParameterEnvironment<'gcx>,
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 // Sadly, the behavior of projection varies a bit depending on the
177 // stage of compilation. The specifics are given in the
178 // documentation for `Reveal`.
179 projection_mode: Reveal,
181 // When an error occurs, we want to avoid reporting "derived"
182 // errors that are due to this original failure. Normally, we
183 // handle this with the `err_count_on_creation` count, which
184 // basically just tracks how many errors were reported when we
185 // started type-checking a fn and checks to see if any new errors
186 // have been reported since then. Not great, but it works.
188 // However, when errors originated in other passes -- notably
189 // resolve -- this heuristic breaks down. Therefore, we have this
190 // auxiliary flag that one can set whenever one creates a
191 // type-error that is due to an error in a prior pass.
193 // Don't read this flag directly, call `is_tainted_by_errors()`
194 // and `set_tainted_by_errors()`.
195 tainted_by_errors_flag: Cell<bool>,
197 // Track how many errors were reported when this infcx is created.
198 // If the number of errors increases, that's also a sign (line
199 // `tained_by_errors`) to avoid reporting certain kinds of errors.
200 err_count_on_creation: usize,
202 // This flag is used for debugging, and is set to true if there are
203 // any obligations set during the current snapshot. In that case, the
204 // snapshot can't be rolled back.
205 pub obligations_in_snapshot: Cell<bool>,
208 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
209 /// region that each late-bound region was replaced with.
210 pub type SkolemizationMap<'tcx> = FxHashMap<ty::BoundRegion, &'tcx ty::Region>;
212 /// See `error_reporting` module for more details
213 #[derive(Clone, Debug)]
214 pub enum ValuePairs<'tcx> {
215 Types(ExpectedFound<Ty<'tcx>>),
216 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
217 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
220 /// The trace designates the path through inference that we took to
221 /// encounter an error or subtyping constraint.
223 /// See `error_reporting` module for more details.
225 pub struct TypeTrace<'tcx> {
226 cause: ObligationCause<'tcx>,
227 values: ValuePairs<'tcx>,
230 /// The origin of a `r1 <= r2` constraint.
232 /// See `error_reporting` module for more details
233 #[derive(Clone, Debug)]
234 pub enum SubregionOrigin<'tcx> {
235 // Arose from a subtyping relation
236 Subtype(TypeTrace<'tcx>),
238 // Stack-allocated closures cannot outlive innermost loop
239 // or function so as to ensure we only require finite stack
240 InfStackClosure(Span),
242 // Invocation of closure must be within its lifetime
245 // Dereference of reference must be within its lifetime
248 // Closure bound must not outlive captured free variables
249 FreeVariable(Span, ast::NodeId),
251 // Index into slice must be within its lifetime
254 // When casting `&'a T` to an `&'b Trait` object,
255 // relating `'a` to `'b`
256 RelateObjectBound(Span),
258 // Some type parameter was instantiated with the given type,
259 // and that type must outlive some region.
260 RelateParamBound(Span, Ty<'tcx>),
262 // The given region parameter was instantiated with a region
263 // that must outlive some other region.
264 RelateRegionParamBound(Span),
266 // A bound placed on type parameters that states that must outlive
267 // the moment of their instantiation.
268 RelateDefaultParamBound(Span, Ty<'tcx>),
270 // Creating a pointer `b` to contents of another reference
273 // Creating a pointer `b` to contents of an upvar
274 ReborrowUpvar(Span, ty::UpvarId),
276 // Data with type `Ty<'tcx>` was borrowed
277 DataBorrowed(Ty<'tcx>, Span),
279 // (&'a &'b T) where a >= b
280 ReferenceOutlivesReferent(Ty<'tcx>, Span),
282 // Type or region parameters must be in scope.
283 ParameterInScope(ParameterOrigin, Span),
285 // The type T of an expression E must outlive the lifetime for E.
286 ExprTypeIsNotInScope(Ty<'tcx>, Span),
288 // A `ref b` whose region does not enclose the decl site
289 BindingTypeIsNotValidAtDecl(Span),
291 // Regions appearing in a method receiver must outlive method call
294 // Regions appearing in a function argument must outlive func call
297 // Region in return type of invoked fn must enclose call
300 // Operands must be in scope
303 // Region resulting from a `&` expr must enclose the `&` expr
306 // An auto-borrow that does not enclose the expr where it occurs
309 // Region constraint arriving from destructor safety
310 SafeDestructor(Span),
312 // Comparing the signature and requirements of an impl method against
313 // the containing trait.
314 CompareImplMethodObligation {
316 item_name: ast::Name,
317 impl_item_def_id: DefId,
318 trait_item_def_id: DefId,
320 // this is `Some(_)` if this error arises from the bug fix for
321 // #18937. This is a temporary measure.
322 lint_id: Option<ast::NodeId>,
326 /// Places that type/region parameters can appear.
327 #[derive(Clone, Copy, Debug)]
328 pub enum ParameterOrigin {
330 MethodCall, // foo.bar() <-- parameters on impl providing bar()
331 OverloadedOperator, // a + b when overloaded
332 OverloadedDeref, // *a when overloaded
335 /// Times when we replace late-bound regions with variables:
336 #[derive(Clone, Copy, Debug)]
337 pub enum LateBoundRegionConversionTime {
338 /// when a fn is called
341 /// when two higher-ranked types are compared
344 /// when projecting an associated type
345 AssocTypeProjection(ast::Name),
348 /// Reasons to create a region inference variable
350 /// See `error_reporting` module for more details
351 #[derive(Clone, Debug)]
352 pub enum RegionVariableOrigin {
353 // Region variables created for ill-categorized reasons,
354 // mostly indicates places in need of refactoring
357 // Regions created by a `&P` or `[...]` pattern
360 // Regions created by `&` operator
363 // Regions created as part of an autoref of a method receiver
366 // Regions created as part of an automatic coercion
369 // Region variables created as the values for early-bound regions
370 EarlyBoundRegion(Span, ast::Name, Option<ty::Issue32330>),
372 // Region variables created for bound regions
373 // in a function or method that is called
374 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
376 UpvarRegion(ty::UpvarId, Span),
378 BoundRegionInCoherence(ast::Name),
381 #[derive(Copy, Clone, Debug)]
382 pub enum FixupError {
383 UnresolvedIntTy(IntVid),
384 UnresolvedFloatTy(FloatVid),
388 impl fmt::Display for FixupError {
389 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
390 use self::FixupError::*;
393 UnresolvedIntTy(_) => {
394 write!(f, "cannot determine the type of this integer; \
395 add a suffix to specify the type explicitly")
397 UnresolvedFloatTy(_) => {
398 write!(f, "cannot determine the type of this number; \
399 add a suffix to specify the type explicitly")
401 UnresolvedTy(_) => write!(f, "unconstrained type")
406 pub trait InferEnv<'a, 'tcx> {
407 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
408 -> (Option<&'a ty::TypeckTables<'tcx>>,
409 Option<ty::TypeckTables<'tcx>>,
410 Option<ty::ParameterEnvironment<'tcx>>);
413 impl<'a, 'tcx> InferEnv<'a, 'tcx> for () {
414 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
415 -> (Option<&'a ty::TypeckTables<'tcx>>,
416 Option<ty::TypeckTables<'tcx>>,
417 Option<ty::ParameterEnvironment<'tcx>>) {
422 impl<'a, 'tcx> InferEnv<'a, 'tcx> for ty::ParameterEnvironment<'tcx> {
423 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
424 -> (Option<&'a ty::TypeckTables<'tcx>>,
425 Option<ty::TypeckTables<'tcx>>,
426 Option<ty::ParameterEnvironment<'tcx>>) {
427 (None, None, Some(self))
431 impl<'a, 'tcx> InferEnv<'a, 'tcx> for (&'a ty::TypeckTables<'tcx>, ty::ParameterEnvironment<'tcx>) {
432 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
433 -> (Option<&'a ty::TypeckTables<'tcx>>,
434 Option<ty::TypeckTables<'tcx>>,
435 Option<ty::ParameterEnvironment<'tcx>>) {
436 (Some(self.0), None, Some(self.1))
440 impl<'a, 'tcx> InferEnv<'a, 'tcx> for (ty::TypeckTables<'tcx>, ty::ParameterEnvironment<'tcx>) {
441 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
442 -> (Option<&'a ty::TypeckTables<'tcx>>,
443 Option<ty::TypeckTables<'tcx>>,
444 Option<ty::ParameterEnvironment<'tcx>>) {
445 (None, Some(self.0), Some(self.1))
449 impl<'a, 'tcx> InferEnv<'a, 'tcx> for hir::BodyId {
450 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
451 -> (Option<&'a ty::TypeckTables<'tcx>>,
452 Option<ty::TypeckTables<'tcx>>,
453 Option<ty::ParameterEnvironment<'tcx>>) {
454 let item_id = tcx.hir.body_owner(self);
455 (Some(tcx.item_tables(tcx.hir.local_def_id(item_id))),
457 Some(ty::ParameterEnvironment::for_item(tcx, item_id)))
461 /// Helper type of a temporary returned by tcx.infer_ctxt(...).
462 /// Necessary because we can't write the following bound:
463 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
464 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
465 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
466 arena: DroplessArena,
467 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
468 tables: Option<&'a ty::TypeckTables<'gcx>>,
469 param_env: Option<ty::ParameterEnvironment<'gcx>>,
470 projection_mode: Reveal,
473 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
474 pub fn infer_ctxt<E: InferEnv<'a, 'gcx>>(self,
476 projection_mode: Reveal)
477 -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
478 let (tables, fresh_tables, param_env) = env.to_parts(self);
481 arena: DroplessArena::new(),
482 fresh_tables: fresh_tables.map(RefCell::new),
484 param_env: param_env,
485 projection_mode: projection_mode,
489 /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
490 /// for MemCategorizationContext/ExprUseVisitor.
491 /// If any inference functionality is used, ICEs will occur.
492 pub fn borrowck_fake_infer_ctxt(self, body: hir::BodyId)
493 -> InferCtxt<'a, 'gcx, 'gcx> {
494 let (tables, _, param_env) = body.to_parts(self);
497 tables: InferTables::Interned(tables.unwrap()),
498 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
499 int_unification_table: RefCell::new(UnificationTable::new()),
500 float_unification_table: RefCell::new(UnificationTable::new()),
501 region_vars: RegionVarBindings::new(self),
502 parameter_environment: param_env.unwrap(),
503 selection_cache: traits::SelectionCache::new(),
504 evaluation_cache: traits::EvaluationCache::new(),
505 projection_cache: RefCell::new(traits::ProjectionCache::new()),
506 reported_trait_errors: RefCell::new(FxHashSet()),
507 projection_mode: Reveal::UserFacing,
508 tainted_by_errors_flag: Cell::new(false),
509 err_count_on_creation: self.sess.err_count(),
510 obligations_in_snapshot: Cell::new(false),
515 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
516 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
517 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
519 let InferCtxtBuilder {
527 let tables = tables.map(InferTables::Interned).unwrap_or_else(|| {
528 fresh_tables.as_ref().map_or(InferTables::Missing, InferTables::InProgress)
530 let param_env = param_env.take().unwrap_or_else(|| {
531 global_tcx.empty_parameter_environment()
533 global_tcx.enter_local(arena, |tcx| f(InferCtxt {
536 projection_cache: RefCell::new(traits::ProjectionCache::new()),
537 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
538 int_unification_table: RefCell::new(UnificationTable::new()),
539 float_unification_table: RefCell::new(UnificationTable::new()),
540 region_vars: RegionVarBindings::new(tcx),
541 parameter_environment: param_env,
542 selection_cache: traits::SelectionCache::new(),
543 evaluation_cache: traits::EvaluationCache::new(),
544 reported_trait_errors: RefCell::new(FxHashSet()),
545 projection_mode: projection_mode,
546 tainted_by_errors_flag: Cell::new(false),
547 err_count_on_creation: tcx.sess.err_count(),
548 obligations_in_snapshot: Cell::new(false),
553 impl<T> ExpectedFound<T> {
554 fn new(a_is_expected: bool, a: T, b: T) -> Self {
556 ExpectedFound {expected: a, found: b}
558 ExpectedFound {expected: b, found: a}
563 impl<'tcx, T> InferOk<'tcx, T> {
564 pub fn unit(self) -> InferOk<'tcx, ()> {
565 InferOk { value: (), obligations: self.obligations }
569 #[must_use = "once you start a snapshot, you should always consume it"]
570 pub struct CombinedSnapshot {
571 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
572 type_snapshot: type_variable::Snapshot,
573 int_snapshot: unify::Snapshot<ty::IntVid>,
574 float_snapshot: unify::Snapshot<ty::FloatVid>,
575 region_vars_snapshot: RegionSnapshot,
576 obligations_in_snapshot: bool,
579 /// Helper trait for shortening the lifetimes inside a
580 /// value for post-type-checking normalization.
581 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
582 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self;
585 macro_rules! items { ($($item:item)+) => ($($item)+) }
586 macro_rules! impl_trans_normalize {
587 ($lt_gcx:tt, $($ty:ty),+) => {
588 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
589 fn trans_normalize<'a, 'tcx>(&self,
590 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>)
592 infcx.normalize_projections_in(self)
598 impl_trans_normalize!('gcx,
603 ty::ClosureSubsts<'gcx>,
604 ty::PolyTraitRef<'gcx>,
605 ty::ExistentialTraitRef<'gcx>
608 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
609 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self {
611 LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx) },
612 LvalueTy::Downcast { adt_def, substs, variant_index } => {
615 substs: substs.trans_normalize(infcx),
616 variant_index: variant_index
623 // NOTE: Callable from trans only!
624 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
625 /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
626 /// each time we erase them in translation, we need to normalize
628 pub fn erase_late_bound_regions_and_normalize<T>(self, value: &ty::Binder<T>)
630 where T: TransNormalize<'tcx>
632 assert!(!value.needs_subst());
633 let value = self.erase_late_bound_regions(value);
634 self.normalize_associated_type(&value)
637 pub fn normalize_associated_type<T>(self, value: &T) -> T
638 where T: TransNormalize<'tcx>
640 debug!("normalize_associated_type(t={:?})", value);
642 let value = self.erase_regions(value);
644 if !value.has_projection_types() {
648 self.infer_ctxt((), Reveal::All).enter(|infcx| {
649 value.trans_normalize(&infcx)
653 pub fn normalize_associated_type_in_env<T>(
654 self, value: &T, env: &'a ty::ParameterEnvironment<'tcx>
656 where T: TransNormalize<'tcx>
658 debug!("normalize_associated_type_in_env(t={:?})", value);
660 let value = self.erase_regions(value);
662 if !value.has_projection_types() {
666 self.infer_ctxt(env.clone(), Reveal::All).enter(|infcx| {
667 value.trans_normalize(&infcx)
672 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
673 fn normalize_projections_in<T>(&self, value: &T) -> T::Lifted
674 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
676 let mut selcx = traits::SelectionContext::new(self);
677 let cause = traits::ObligationCause::dummy();
678 let traits::Normalized { value: result, obligations } =
679 traits::normalize(&mut selcx, cause, value);
681 debug!("normalize_projections_in: result={:?} obligations={:?}",
682 result, obligations);
684 let mut fulfill_cx = traits::FulfillmentContext::new();
686 for obligation in obligations {
687 fulfill_cx.register_predicate_obligation(self, obligation);
690 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
693 /// Finishes processes any obligations that remain in the
694 /// fulfillment context, and then returns the result with all type
695 /// variables removed and regions erased. Because this is intended
696 /// for use after type-check has completed, if any errors occur,
697 /// it will panic. It is used during normalization and other cases
698 /// where processing the obligations in `fulfill_cx` may cause
699 /// type inference variables that appear in `result` to be
700 /// unified, and hence we need to process those obligations to get
701 /// the complete picture of the type.
702 pub fn drain_fulfillment_cx_or_panic<T>(&self,
704 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
707 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
709 debug!("drain_fulfillment_cx_or_panic()");
711 // In principle, we only need to do this so long as `result`
712 // contains unbound type parameters. It could be a slight
713 // optimization to stop iterating early.
714 match fulfill_cx.select_all_or_error(self) {
717 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
722 let result = self.resolve_type_vars_if_possible(result);
723 let result = self.tcx.erase_regions(&result);
725 match self.tcx.lift_to_global(&result) {
726 Some(result) => result,
728 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
733 pub fn projection_mode(&self) -> Reveal {
737 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
738 t.fold_with(&mut self.freshener())
741 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
743 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
748 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
749 freshen::TypeFreshener::new(self)
752 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
753 use ty::error::UnconstrainedNumeric::Neither;
754 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
756 ty::TyInfer(ty::IntVar(vid)) => {
757 if self.int_unification_table.borrow_mut().has_value(vid) {
763 ty::TyInfer(ty::FloatVar(vid)) => {
764 if self.float_unification_table.borrow_mut().has_value(vid) {
774 /// Returns a type variable's default fallback if any exists. A default
775 /// must be attached to the variable when created, if it is created
776 /// without a default, this will return None.
778 /// This code does not apply to integral or floating point variables,
779 /// only to use declared defaults.
781 /// See `new_ty_var_with_default` to create a type variable with a default.
782 /// See `type_variable::Default` for details about what a default entails.
783 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
785 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
790 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
791 let mut variables = Vec::new();
793 let unbound_ty_vars = self.type_variables
795 .unsolved_variables()
797 .map(|t| self.tcx.mk_var(t));
799 let unbound_int_vars = self.int_unification_table
801 .unsolved_variables()
803 .map(|v| self.tcx.mk_int_var(v));
805 let unbound_float_vars = self.float_unification_table
807 .unsolved_variables()
809 .map(|v| self.tcx.mk_float_var(v));
811 variables.extend(unbound_ty_vars);
812 variables.extend(unbound_int_vars);
813 variables.extend(unbound_float_vars);
818 fn combine_fields(&'a self, trace: TypeTrace<'tcx>)
819 -> CombineFields<'a, 'gcx, 'tcx> {
824 obligations: PredicateObligations::new(),
828 pub fn equate<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
829 -> InferResult<'tcx, T>
830 where T: Relate<'tcx>
832 let mut fields = self.combine_fields(trace);
833 let result = fields.equate(a_is_expected).relate(a, b);
834 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
837 pub fn sub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
838 -> InferResult<'tcx, T>
839 where T: Relate<'tcx>
841 let mut fields = self.combine_fields(trace);
842 let result = fields.sub(a_is_expected).relate(a, b);
843 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
846 pub fn lub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
847 -> InferResult<'tcx, T>
848 where T: Relate<'tcx>
850 let mut fields = self.combine_fields(trace);
851 let result = fields.lub(a_is_expected).relate(a, b);
852 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
855 pub fn glb<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
856 -> InferResult<'tcx, T>
857 where T: Relate<'tcx>
859 let mut fields = self.combine_fields(trace);
860 let result = fields.glb(a_is_expected).relate(a, b);
861 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
864 // Clear the "obligations in snapshot" flag, invoke the closure,
865 // then restore the flag to its original value. This flag is a
866 // debugging measure designed to detect cases where we start a
867 // snapshot, create type variables, register obligations involving
868 // those type variables in the fulfillment cx, and then have to
869 // unroll the snapshot, leaving "dangling type variables" behind.
870 // In such cases, the flag will be set by the fulfillment cx, and
871 // an assertion will fail when rolling the snapshot back. Very
872 // useful, much better than grovelling through megabytes of
875 // HOWEVER, in some cases the flag is wrong. In particular, we
876 // sometimes create a "mini-fulfilment-cx" in which we enroll
877 // obligations. As long as this fulfillment cx is fully drained
878 // before we return, this is not a problem, as there won't be any
879 // escaping obligations in the main cx. In those cases, you can
880 // use this function.
881 pub fn save_and_restore_obligations_in_snapshot_flag<F, R>(&self, func: F) -> R
882 where F: FnOnce(&Self) -> R
884 let flag = self.obligations_in_snapshot.get();
885 self.obligations_in_snapshot.set(false);
886 let result = func(self);
887 self.obligations_in_snapshot.set(flag);
891 fn start_snapshot(&self) -> CombinedSnapshot {
892 debug!("start_snapshot()");
894 let obligations_in_snapshot = self.obligations_in_snapshot.get();
895 self.obligations_in_snapshot.set(false);
898 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
899 type_snapshot: self.type_variables.borrow_mut().snapshot(),
900 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
901 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
902 region_vars_snapshot: self.region_vars.start_snapshot(),
903 obligations_in_snapshot: obligations_in_snapshot,
907 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
908 debug!("rollback_to(cause={})", cause);
909 let CombinedSnapshot { projection_cache_snapshot,
913 region_vars_snapshot,
914 obligations_in_snapshot } = snapshot;
916 assert!(!self.obligations_in_snapshot.get());
917 self.obligations_in_snapshot.set(obligations_in_snapshot);
919 self.projection_cache
921 .rollback_to(projection_cache_snapshot);
924 .rollback_to(type_snapshot);
925 self.int_unification_table
927 .rollback_to(int_snapshot);
928 self.float_unification_table
930 .rollback_to(float_snapshot);
932 .rollback_to(region_vars_snapshot);
935 fn commit_from(&self, snapshot: CombinedSnapshot) {
936 debug!("commit_from()");
937 let CombinedSnapshot { projection_cache_snapshot,
941 region_vars_snapshot,
942 obligations_in_snapshot } = snapshot;
944 self.obligations_in_snapshot.set(obligations_in_snapshot);
946 self.projection_cache
948 .commit(projection_cache_snapshot);
951 .commit(type_snapshot);
952 self.int_unification_table
954 .commit(int_snapshot);
955 self.float_unification_table
957 .commit(float_snapshot);
959 .commit(region_vars_snapshot);
962 /// Execute `f` and commit the bindings
963 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
967 let snapshot = self.start_snapshot();
969 self.commit_from(snapshot);
973 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
974 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
975 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
977 debug!("commit_if_ok()");
978 let snapshot = self.start_snapshot();
979 let r = f(&snapshot);
980 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
982 Ok(_) => { self.commit_from(snapshot); }
983 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
988 // Execute `f` in a snapshot, and commit the bindings it creates
989 pub fn in_snapshot<T, F>(&self, f: F) -> T where
990 F: FnOnce(&CombinedSnapshot) -> T
992 debug!("in_snapshot()");
993 let snapshot = self.start_snapshot();
994 let r = f(&snapshot);
995 self.commit_from(snapshot);
999 /// Execute `f` then unroll any bindings it creates
1000 pub fn probe<R, F>(&self, f: F) -> R where
1001 F: FnOnce(&CombinedSnapshot) -> R,
1004 let snapshot = self.start_snapshot();
1005 let r = f(&snapshot);
1006 self.rollback_to("probe", snapshot);
1010 pub fn add_given(&self,
1011 sub: ty::FreeRegion,
1014 self.region_vars.add_given(sub, sup);
1017 pub fn sub_types(&self,
1018 a_is_expected: bool,
1019 cause: &ObligationCause<'tcx>,
1022 -> InferResult<'tcx, ()>
1024 debug!("sub_types({:?} <: {:?})", a, b);
1025 self.commit_if_ok(|_| {
1026 let trace = TypeTrace::types(cause, a_is_expected, a, b);
1027 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1031 pub fn can_sub_types(&self,
1037 let origin = &ObligationCause::dummy();
1038 let trace = TypeTrace::types(origin, true, a, b);
1039 self.sub(true, trace, &a, &b).map(|InferOk { obligations, .. }| {
1040 // FIXME(#32730) propagate obligations
1041 assert!(obligations.is_empty());
1046 pub fn eq_types(&self,
1047 a_is_expected: bool,
1048 cause: &ObligationCause<'tcx>,
1051 -> InferResult<'tcx, ()>
1053 self.commit_if_ok(|_| {
1054 let trace = TypeTrace::types(cause, a_is_expected, a, b);
1055 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1059 pub fn eq_trait_refs(&self,
1060 a_is_expected: bool,
1061 cause: &ObligationCause<'tcx>,
1062 a: ty::TraitRef<'tcx>,
1063 b: ty::TraitRef<'tcx>)
1064 -> InferResult<'tcx, ()>
1066 debug!("eq_trait_refs({:?} = {:?})", a, b);
1067 self.commit_if_ok(|_| {
1068 let trace = TypeTrace {
1069 cause: cause.clone(),
1070 values: TraitRefs(ExpectedFound::new(a_is_expected, a, b))
1072 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1076 pub fn eq_impl_headers(&self,
1077 a_is_expected: bool,
1078 cause: &ObligationCause<'tcx>,
1079 a: &ty::ImplHeader<'tcx>,
1080 b: &ty::ImplHeader<'tcx>)
1081 -> InferResult<'tcx, ()>
1083 debug!("eq_impl_header({:?} = {:?})", a, b);
1084 match (a.trait_ref, b.trait_ref) {
1085 (Some(a_ref), Some(b_ref)) => self.eq_trait_refs(a_is_expected, cause, a_ref, b_ref),
1086 (None, None) => self.eq_types(a_is_expected, cause, a.self_ty, b.self_ty),
1087 _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
1091 pub fn sub_poly_trait_refs(&self,
1092 a_is_expected: bool,
1093 cause: ObligationCause<'tcx>,
1094 a: ty::PolyTraitRef<'tcx>,
1095 b: ty::PolyTraitRef<'tcx>)
1096 -> InferResult<'tcx, ()>
1098 debug!("sub_poly_trait_refs({:?} <: {:?})", a, b);
1099 self.commit_if_ok(|_| {
1100 let trace = TypeTrace {
1102 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b))
1104 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1108 pub fn sub_regions(&self,
1109 origin: SubregionOrigin<'tcx>,
1110 a: &'tcx ty::Region,
1111 b: &'tcx ty::Region) {
1112 debug!("sub_regions({:?} <: {:?})", a, b);
1113 self.region_vars.make_subregion(origin, a, b);
1116 pub fn equality_predicate(&self,
1117 cause: &ObligationCause<'tcx>,
1118 predicate: &ty::PolyEquatePredicate<'tcx>)
1119 -> InferResult<'tcx, ()>
1121 self.commit_if_ok(|snapshot| {
1122 let (ty::EquatePredicate(a, b), skol_map) =
1123 self.skolemize_late_bound_regions(predicate, snapshot);
1124 let cause_span = cause.span;
1125 let eqty_ok = self.eq_types(false, cause, a, b)?;
1126 self.leak_check(false, cause_span, &skol_map, snapshot)?;
1127 self.pop_skolemized(skol_map, snapshot);
1132 pub fn region_outlives_predicate(&self,
1133 cause: &traits::ObligationCause<'tcx>,
1134 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1137 self.commit_if_ok(|snapshot| {
1138 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1139 self.skolemize_late_bound_regions(predicate, snapshot);
1141 SubregionOrigin::from_obligation_cause(cause,
1142 || RelateRegionParamBound(cause.span));
1143 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1144 self.leak_check(false, cause.span, &skol_map, snapshot)?;
1145 Ok(self.pop_skolemized(skol_map, snapshot))
1149 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1152 .new_var(diverging, origin, None)
1155 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1156 self.tcx.mk_var(self.next_ty_var_id(false, origin))
1159 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1160 self.tcx.mk_var(self.next_ty_var_id(true, origin))
1163 pub fn next_int_var_id(&self) -> IntVid {
1164 self.int_unification_table
1169 pub fn next_float_var_id(&self) -> FloatVid {
1170 self.float_unification_table
1175 pub fn next_region_var(&self, origin: RegionVariableOrigin)
1176 -> &'tcx ty::Region {
1177 self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
1180 /// Create a region inference variable for the given
1181 /// region parameter definition.
1182 pub fn region_var_for_def(&self,
1184 def: &ty::RegionParameterDef)
1185 -> &'tcx ty::Region {
1186 self.next_region_var(EarlyBoundRegion(span, def.name, def.issue_32330))
1189 /// Create a type inference variable for the given
1190 /// type parameter definition. The substitutions are
1191 /// for actual parameters that may be referred to by
1192 /// the default of this type parameter, if it exists.
1193 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1194 /// used in a path such as `Foo::<T, U>::new()` will
1195 /// use an inference variable for `C` with `[T, U]`
1196 /// as the substitutions for the default, `(T, U)`.
1197 pub fn type_var_for_def(&self,
1199 def: &ty::TypeParameterDef,
1200 substs: &[Kind<'tcx>])
1202 let default = if def.has_default {
1203 let default = self.tcx.item_type(def.def_id);
1204 Some(type_variable::Default {
1205 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1214 let ty_var_id = self.type_variables
1217 TypeVariableOrigin::TypeParameterDefinition(span, def.name),
1220 self.tcx.mk_var(ty_var_id)
1223 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1224 /// type/region parameter to a fresh inference variable.
1225 pub fn fresh_substs_for_item(&self,
1228 -> &'tcx Substs<'tcx> {
1229 Substs::for_item(self.tcx, def_id, |def, _| {
1230 self.region_var_for_def(span, def)
1232 self.type_var_for_def(span, def, substs)
1236 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> &'tcx ty::Region {
1237 self.region_vars.new_bound(debruijn)
1240 /// True if errors have been reported since this infcx was
1241 /// created. This is sometimes used as a heuristic to skip
1242 /// reporting errors that often occur as a result of earlier
1243 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1244 /// inference variables, regionck errors).
1245 pub fn is_tainted_by_errors(&self) -> bool {
1246 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1247 tainted_by_errors_flag={})",
1248 self.tcx.sess.err_count(),
1249 self.err_count_on_creation,
1250 self.tainted_by_errors_flag.get());
1252 if self.tcx.sess.err_count() > self.err_count_on_creation {
1253 return true; // errors reported since this infcx was made
1255 self.tainted_by_errors_flag.get()
1258 /// Set the "tainted by errors" flag to true. We call this when we
1259 /// observe an error from a prior pass.
1260 pub fn set_tainted_by_errors(&self) {
1261 debug!("set_tainted_by_errors()");
1262 self.tainted_by_errors_flag.set(true)
1265 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1266 match self.tables.borrow().node_types.get(&id) {
1269 None if self.is_tainted_by_errors() =>
1272 bug!("no type for node {}: {} in fcx",
1273 id, self.tcx.hir.node_to_string(id));
1278 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1279 match self.tables.borrow().node_types.get(&ex.id) {
1282 bug!("no type for expr in fcx");
1287 pub fn resolve_regions_and_report_errors(&self,
1288 free_regions: &FreeRegionMap,
1289 subject_node_id: ast::NodeId) {
1290 let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1291 if !self.is_tainted_by_errors() {
1292 // As a heuristic, just skip reporting region errors
1293 // altogether if other errors have been reported while
1294 // this infcx was in use. This is totally hokey but
1295 // otherwise we have a hard time separating legit region
1296 // errors from silly ones.
1297 self.report_region_errors(&errors); // see error_reporting module
1301 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1302 self.resolve_type_vars_if_possible(&t).to_string()
1305 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1306 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1307 format!("({})", tstrs.join(", "))
1310 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1311 self.resolve_type_vars_if_possible(t).to_string()
1314 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1316 ty::TyInfer(ty::TyVar(v)) => {
1317 // Not entirely obvious: if `typ` is a type variable,
1318 // it can be resolved to an int/float variable, which
1319 // can then be recursively resolved, hence the
1320 // recursion. Note though that we prevent type
1321 // variables from unifying to other type variables
1322 // directly (though they may be embedded
1323 // structurally), and we prevent cycles in any case,
1324 // so this recursion should always be of very limited
1326 self.type_variables.borrow_mut()
1328 .map(|t| self.shallow_resolve(t))
1332 ty::TyInfer(ty::IntVar(v)) => {
1333 self.int_unification_table
1336 .map(|v| v.to_type(self.tcx))
1340 ty::TyInfer(ty::FloatVar(v)) => {
1341 self.float_unification_table
1344 .map(|v| v.to_type(self.tcx))
1354 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1355 where T: TypeFoldable<'tcx>
1358 * Where possible, replaces type/int/float variables in
1359 * `value` with their final value. Note that region variables
1360 * are unaffected. If a type variable has not been unified, it
1361 * is left as is. This is an idempotent operation that does
1362 * not affect inference state in any way and so you can do it
1366 if !value.needs_infer() {
1367 return value.clone(); // avoid duplicated subst-folding
1369 let mut r = resolve::OpportunisticTypeResolver::new(self);
1370 value.fold_with(&mut r)
1373 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1374 where T: TypeFoldable<'tcx>
1376 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1377 value.fold_with(&mut r)
1380 /// Resolves all type variables in `t` and then, if any were left
1381 /// unresolved, substitutes an error type. This is used after the
1382 /// main checking when doing a second pass before writeback. The
1383 /// justification is that writeback will produce an error for
1384 /// these unconstrained type variables.
1385 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1386 let ty = self.resolve_type_vars_if_possible(t);
1387 if ty.references_error() || ty.is_ty_var() {
1388 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1395 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1397 * Attempts to resolve all type/region variables in
1398 * `value`. Region inference must have been run already (e.g.,
1399 * by calling `resolve_regions_and_report_errors`). If some
1400 * variable was never unified, an `Err` results.
1402 * This method is idempotent, but it not typically not invoked
1403 * except during the writeback phase.
1406 resolve::fully_resolve(self, value)
1409 // [Note-Type-error-reporting]
1410 // An invariant is that anytime the expected or actual type is TyError (the special
1411 // error type, meaning that an error occurred when typechecking this expression),
1412 // this is a derived error. The error cascaded from another error (that was already
1413 // reported), so it's not useful to display it to the user.
1414 // The following methods implement this logic.
1415 // They check if either the actual or expected type is TyError, and don't print the error
1416 // in this case. The typechecker should only ever report type errors involving mismatched
1417 // types using one of these methods, and should not call span_err directly for such
1420 pub fn type_error_message<M>(&self,
1423 actual_ty: Ty<'tcx>)
1424 where M: FnOnce(String) -> String,
1426 self.type_error_struct(sp, mk_msg, actual_ty).emit();
1429 // FIXME: this results in errors without an error code. Deprecate?
1430 pub fn type_error_struct<M>(&self,
1433 actual_ty: Ty<'tcx>)
1434 -> DiagnosticBuilder<'tcx>
1435 where M: FnOnce(String) -> String,
1437 self.type_error_struct_with_diag(sp, |actual_ty| {
1438 self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1442 pub fn type_error_struct_with_diag<M>(&self,
1445 actual_ty: Ty<'tcx>)
1446 -> DiagnosticBuilder<'tcx>
1447 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1449 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1450 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1452 // Don't report an error if actual type is TyError.
1453 if actual_ty.references_error() {
1454 return self.tcx.sess.diagnostic().struct_dummy();
1457 mk_diag(self.ty_to_string(actual_ty))
1460 pub fn report_mismatched_types(&self,
1461 cause: &ObligationCause<'tcx>,
1464 err: TypeError<'tcx>)
1465 -> DiagnosticBuilder<'tcx> {
1466 let trace = TypeTrace::types(cause, true, expected, actual);
1467 self.report_and_explain_type_error(trace, &err)
1470 pub fn report_conflicting_default_types(&self,
1472 body_id: ast::NodeId,
1473 expected: type_variable::Default<'tcx>,
1474 actual: type_variable::Default<'tcx>) {
1475 let trace = TypeTrace {
1476 cause: ObligationCause::misc(span, body_id),
1477 values: Types(ExpectedFound {
1478 expected: expected.ty,
1483 self.report_and_explain_type_error(
1485 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1492 pub fn replace_late_bound_regions_with_fresh_var<T>(
1495 lbrct: LateBoundRegionConversionTime,
1496 value: &ty::Binder<T>)
1497 -> (T, FxHashMap<ty::BoundRegion, &'tcx ty::Region>)
1498 where T : TypeFoldable<'tcx>
1500 self.tcx.replace_late_bound_regions(
1502 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1505 /// Given a higher-ranked projection predicate like:
1507 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1509 /// and a target trait-ref like:
1511 /// <T as Fn<&'x u32>>
1513 /// find a substitution `S` for the higher-ranked regions (here,
1514 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1515 /// and then return the value (here, `&'a u32`) but with the
1516 /// substitution applied (hence, `&'x u32`).
1518 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1520 pub fn match_poly_projection_predicate(&self,
1521 cause: ObligationCause<'tcx>,
1522 match_a: ty::PolyProjectionPredicate<'tcx>,
1523 match_b: ty::TraitRef<'tcx>)
1524 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1526 let span = cause.span;
1527 let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1528 let trace = TypeTrace {
1530 values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1533 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1534 let mut combine = self.combine_fields(trace);
1535 let result = combine.higher_ranked_match(span, &match_pair, &match_b, true)?;
1536 Ok(InferOk { value: result, obligations: combine.obligations })
1539 /// See `verify_generic_bound` method in `region_inference`
1540 pub fn verify_generic_bound(&self,
1541 origin: SubregionOrigin<'tcx>,
1542 kind: GenericKind<'tcx>,
1543 a: &'tcx ty::Region,
1544 bound: VerifyBound<'tcx>) {
1545 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1550 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1553 pub fn can_equate<T>(&self, a: &T, b: &T) -> UnitResult<'tcx>
1554 where T: Relate<'tcx> + fmt::Debug
1556 debug!("can_equate({:?}, {:?})", a, b);
1558 // Gin up a dummy trace, since this won't be committed
1559 // anyhow. We should make this typetrace stuff more
1560 // generic so we don't have to do anything quite this
1562 let trace = TypeTrace::dummy(self.tcx);
1563 self.equate(true, trace, a, b).map(|InferOk { obligations, .. }| {
1564 // FIXME(#32730) propagate obligations
1565 assert!(obligations.is_empty());
1570 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1571 let ty = self.node_type(id);
1572 self.resolve_type_vars_or_error(&ty)
1575 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1576 let ty = self.tables.borrow().expr_ty_adjusted(expr);
1577 self.resolve_type_vars_or_error(&ty)
1580 pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1581 let ty = self.resolve_type_vars_if_possible(&ty);
1582 if let Some(ty) = self.tcx.lift_to_global(&ty) {
1583 // Even if the type may have no inference variables, during
1584 // type-checking closure types are in local tables only.
1585 let local_closures = match self.tables {
1586 InferTables::InProgress(_) => ty.has_closure_types(),
1589 if !local_closures {
1590 return ty.moves_by_default(self.tcx.global_tcx(), self.param_env(), span);
1594 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1596 // this can get called from typeck (by euv), and moves_by_default
1597 // rightly refuses to work with inference variables, but
1598 // moves_by_default has a cache, which we want to use in other
1600 !traits::type_known_to_meet_bound(self, ty, copy_def_id, span)
1603 pub fn node_method_ty(&self, method_call: ty::MethodCall)
1604 -> Option<Ty<'tcx>> {
1609 .map(|method| method.ty)
1610 .map(|ty| self.resolve_type_vars_if_possible(&ty))
1613 pub fn node_method_id(&self, method_call: ty::MethodCall)
1619 .map(|method| method.def_id)
1622 pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1623 self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1626 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
1627 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1630 pub fn param_env(&self) -> &ty::ParameterEnvironment<'gcx> {
1631 &self.parameter_environment
1634 pub fn closure_kind(&self,
1636 -> Option<ty::ClosureKind>
1638 if let InferTables::InProgress(tables) = self.tables {
1639 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1640 return tables.borrow().closure_kinds.get(&id).cloned();
1644 // During typeck, ALL closures are local. But afterwards,
1645 // during trans, we see closure ids from other traits.
1646 // That may require loading the closure data out of the
1648 Some(self.tcx.closure_kind(def_id))
1651 pub fn closure_type(&self, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1652 if let InferTables::InProgress(tables) = self.tables {
1653 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1654 if let Some(&ty) = tables.borrow().closure_tys.get(&id) {
1660 self.tcx.closure_type(def_id)
1664 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1665 pub fn span(&self) -> Span {
1669 pub fn types(cause: &ObligationCause<'tcx>,
1670 a_is_expected: bool,
1673 -> TypeTrace<'tcx> {
1675 cause: cause.clone(),
1676 values: Types(ExpectedFound::new(a_is_expected, a, b))
1680 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1682 cause: ObligationCause::dummy(),
1683 values: Types(ExpectedFound {
1684 expected: tcx.types.err,
1685 found: tcx.types.err,
1691 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1692 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1693 write!(f, "TypeTrace({:?})", self.cause)
1697 impl<'tcx> SubregionOrigin<'tcx> {
1698 pub fn span(&self) -> Span {
1700 Subtype(ref a) => a.span(),
1701 InfStackClosure(a) => a,
1702 InvokeClosure(a) => a,
1703 DerefPointer(a) => a,
1704 FreeVariable(a, _) => a,
1706 RelateObjectBound(a) => a,
1707 RelateParamBound(a, _) => a,
1708 RelateRegionParamBound(a) => a,
1709 RelateDefaultParamBound(a, _) => a,
1711 ReborrowUpvar(a, _) => a,
1712 DataBorrowed(_, a) => a,
1713 ReferenceOutlivesReferent(_, a) => a,
1714 ParameterInScope(_, a) => a,
1715 ExprTypeIsNotInScope(_, a) => a,
1716 BindingTypeIsNotValidAtDecl(a) => a,
1723 SafeDestructor(a) => a,
1724 CompareImplMethodObligation { span, .. } => span,
1728 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>,
1731 where F: FnOnce() -> Self
1734 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
1735 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span),
1737 traits::ObligationCauseCode::CompareImplMethodObligation { item_name,
1741 SubregionOrigin::CompareImplMethodObligation {
1743 item_name: item_name,
1744 impl_item_def_id: impl_item_def_id,
1745 trait_item_def_id: trait_item_def_id,
1754 impl RegionVariableOrigin {
1755 pub fn span(&self) -> Span {
1757 MiscVariable(a) => a,
1758 PatternRegion(a) => a,
1759 AddrOfRegion(a) => a,
1762 EarlyBoundRegion(a, ..) => a,
1763 LateBoundRegion(a, ..) => a,
1764 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1765 UpvarRegion(_, a) => a
1770 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1771 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1773 ValuePairs::Types(ref ef) => {
1774 ValuePairs::Types(ef.fold_with(folder))
1776 ValuePairs::TraitRefs(ref ef) => {
1777 ValuePairs::TraitRefs(ef.fold_with(folder))
1779 ValuePairs::PolyTraitRefs(ref ef) => {
1780 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1785 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1787 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1788 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1789 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1794 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1795 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1797 cause: self.cause.fold_with(folder),
1798 values: self.values.fold_with(folder)
1802 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1803 self.cause.visit_with(visitor) || self.values.visit_with(visitor)