1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See the Book for more information.
13 pub use self::LateBoundRegionConversionTime::*;
14 pub use self::RegionVariableOrigin::*;
15 pub use self::SubregionOrigin::*;
16 pub use self::ValuePairs::*;
17 pub use ty::IntVarValue;
18 pub use self::freshen::TypeFreshener;
19 pub use self::region_inference::{GenericKind, VerifyBound};
21 use hir::def_id::DefId;
23 use middle::free_region::{FreeRegionMap, RegionRelations};
24 use middle::region::RegionMaps;
25 use middle::mem_categorization as mc;
26 use middle::mem_categorization::McResult;
27 use middle::lang_items;
28 use mir::tcx::LvalueTy;
29 use ty::subst::{Kind, Subst, Substs};
30 use ty::{TyVid, IntVid, FloatVid};
31 use ty::{self, Ty, TyCtxt};
32 use ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
33 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
34 use ty::relate::{Relate, RelateResult, TypeRelation};
35 use traits::{self, ObligationCause, PredicateObligations, Reveal};
36 use rustc_data_structures::unify::{self, UnificationTable};
37 use std::cell::{Cell, RefCell, Ref, RefMut};
41 use errors::DiagnosticBuilder;
42 use syntax_pos::{self, Span, DUMMY_SP};
43 use util::nodemap::{FxHashMap, FxHashSet};
44 use arena::DroplessArena;
46 use self::combine::CombineFields;
47 use self::higher_ranked::HrMatchResult;
48 use self::region_inference::{RegionVarBindings, RegionSnapshot};
49 use self::type_variable::TypeVariableOrigin;
50 use self::unify_key::ToType;
54 pub mod error_reporting;
60 pub mod region_inference;
64 pub mod type_variable;
68 pub struct InferOk<'tcx, T> {
70 pub obligations: PredicateObligations<'tcx>,
72 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
74 pub type Bound<T> = Option<T>;
75 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
76 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
78 /// A version of &ty::TypeckTables which can be `Missing` (not needed),
79 /// `InProgress` (during typeck) or `Interned` (result of typeck).
80 /// Only the `InProgress` version supports `borrow_mut`.
81 #[derive(Copy, Clone)]
82 pub enum InferTables<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
83 Interned(&'a ty::TypeckTables<'gcx>),
84 InProgress(&'a RefCell<ty::TypeckTables<'tcx>>),
88 pub enum InferTablesRef<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
89 Interned(&'a ty::TypeckTables<'gcx>),
90 InProgress(Ref<'a, ty::TypeckTables<'tcx>>)
93 impl<'a, 'gcx, 'tcx> Deref for InferTablesRef<'a, 'gcx, 'tcx> {
94 type Target = ty::TypeckTables<'tcx>;
95 fn deref(&self) -> &Self::Target {
97 InferTablesRef::Interned(tables) => tables,
98 InferTablesRef::InProgress(ref tables) => tables
103 impl<'a, 'gcx, 'tcx> InferTables<'a, 'gcx, 'tcx> {
104 pub fn borrow(self) -> InferTablesRef<'a, 'gcx, 'tcx> {
106 InferTables::Interned(tables) => InferTablesRef::Interned(tables),
107 InferTables::InProgress(tables) => InferTablesRef::InProgress(tables.borrow()),
108 InferTables::Missing => {
109 bug!("InferTables: infcx.tables.borrow() with no tables")
114 pub fn expect_interned(self) -> &'a ty::TypeckTables<'gcx> {
116 InferTables::Interned(tables) => tables,
117 InferTables::InProgress(_) => {
118 bug!("InferTables: infcx.tables.expect_interned() during type-checking");
120 InferTables::Missing => {
121 bug!("InferTables: infcx.tables.expect_interned() with no tables")
126 pub fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> {
128 InferTables::Interned(_) => {
129 bug!("InferTables: infcx.tables.borrow_mut() outside of type-checking");
131 InferTables::InProgress(tables) => tables.borrow_mut(),
132 InferTables::Missing => {
133 bug!("InferTables: infcx.tables.borrow_mut() with no tables")
139 pub struct InferCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
140 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
142 pub tables: InferTables<'a, 'gcx, 'tcx>,
144 // Cache for projections. This cache is snapshotted along with the
147 // Public so that `traits::project` can use it.
148 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
150 // We instantiate UnificationTable with bounds<Ty> because the
151 // types that might instantiate a general type variable have an
152 // order, represented by its upper and lower bounds.
153 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
155 // Map from integral variable to the kind of integer it represents
156 int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
158 // Map from floating variable to the kind of float it represents
159 float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
161 // For region variables.
162 region_vars: RegionVarBindings<'a, 'gcx, 'tcx>,
164 pub param_env: ty::ParamEnv<'gcx>,
166 /// Caches the results of trait selection. This cache is used
167 /// for things that have to do with the parameters in scope.
168 pub selection_cache: traits::SelectionCache<'tcx>,
170 /// Caches the results of trait evaluation.
171 pub evaluation_cache: traits::EvaluationCache<'tcx>,
173 // the set of predicates on which errors have been reported, to
174 // avoid reporting the same error twice.
175 pub reported_trait_errors: RefCell<FxHashSet<traits::TraitErrorKey<'tcx>>>,
177 // Sadly, the behavior of projection varies a bit depending on the
178 // stage of compilation. The specifics are given in the
179 // documentation for `Reveal`.
180 projection_mode: Reveal,
182 // When an error occurs, we want to avoid reporting "derived"
183 // errors that are due to this original failure. Normally, we
184 // handle this with the `err_count_on_creation` count, which
185 // basically just tracks how many errors were reported when we
186 // started type-checking a fn and checks to see if any new errors
187 // have been reported since then. Not great, but it works.
189 // However, when errors originated in other passes -- notably
190 // resolve -- this heuristic breaks down. Therefore, we have this
191 // auxiliary flag that one can set whenever one creates a
192 // type-error that is due to an error in a prior pass.
194 // Don't read this flag directly, call `is_tainted_by_errors()`
195 // and `set_tainted_by_errors()`.
196 tainted_by_errors_flag: Cell<bool>,
198 // Track how many errors were reported when this infcx is created.
199 // If the number of errors increases, that's also a sign (line
200 // `tained_by_errors`) to avoid reporting certain kinds of errors.
201 err_count_on_creation: usize,
203 // This flag is true while there is an active snapshot.
204 in_snapshot: Cell<bool>,
207 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
208 /// region that each late-bound region was replaced with.
209 pub type SkolemizationMap<'tcx> = FxHashMap<ty::BoundRegion, ty::Region<'tcx>>;
211 /// See `error_reporting` module for more details
212 #[derive(Clone, Debug)]
213 pub enum ValuePairs<'tcx> {
214 Types(ExpectedFound<Ty<'tcx>>),
215 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
216 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
219 /// The trace designates the path through inference that we took to
220 /// encounter an error or subtyping constraint.
222 /// See `error_reporting` module for more details.
224 pub struct TypeTrace<'tcx> {
225 cause: ObligationCause<'tcx>,
226 values: ValuePairs<'tcx>,
229 /// The origin of a `r1 <= r2` constraint.
231 /// See `error_reporting` module for more details
232 #[derive(Clone, Debug)]
233 pub enum SubregionOrigin<'tcx> {
234 // Arose from a subtyping relation
235 Subtype(TypeTrace<'tcx>),
237 // Stack-allocated closures cannot outlive innermost loop
238 // or function so as to ensure we only require finite stack
239 InfStackClosure(Span),
241 // Invocation of closure must be within its lifetime
244 // Dereference of reference must be within its lifetime
247 // Closure bound must not outlive captured free variables
248 FreeVariable(Span, ast::NodeId),
250 // Index into slice must be within its lifetime
253 // When casting `&'a T` to an `&'b Trait` object,
254 // relating `'a` to `'b`
255 RelateObjectBound(Span),
257 // Some type parameter was instantiated with the given type,
258 // and that type must outlive some region.
259 RelateParamBound(Span, Ty<'tcx>),
261 // The given region parameter was instantiated with a region
262 // that must outlive some other region.
263 RelateRegionParamBound(Span),
265 // A bound placed on type parameters that states that must outlive
266 // the moment of their instantiation.
267 RelateDefaultParamBound(Span, Ty<'tcx>),
269 // Creating a pointer `b` to contents of another reference
272 // Creating a pointer `b` to contents of an upvar
273 ReborrowUpvar(Span, ty::UpvarId),
275 // Data with type `Ty<'tcx>` was borrowed
276 DataBorrowed(Ty<'tcx>, Span),
278 // (&'a &'b T) where a >= b
279 ReferenceOutlivesReferent(Ty<'tcx>, Span),
281 // Type or region parameters must be in scope.
282 ParameterInScope(ParameterOrigin, Span),
284 // The type T of an expression E must outlive the lifetime for E.
285 ExprTypeIsNotInScope(Ty<'tcx>, Span),
287 // A `ref b` whose region does not enclose the decl site
288 BindingTypeIsNotValidAtDecl(Span),
290 // Regions appearing in a method receiver must outlive method call
293 // Regions appearing in a function argument must outlive func call
296 // Region in return type of invoked fn must enclose call
299 // Operands must be in scope
302 // Region resulting from a `&` expr must enclose the `&` expr
305 // An auto-borrow that does not enclose the expr where it occurs
308 // Region constraint arriving from destructor safety
309 SafeDestructor(Span),
311 // Comparing the signature and requirements of an impl method against
312 // the containing trait.
313 CompareImplMethodObligation {
315 item_name: ast::Name,
316 impl_item_def_id: DefId,
317 trait_item_def_id: DefId,
319 // this is `Some(_)` if this error arises from the bug fix for
320 // #18937. This is a temporary measure.
321 lint_id: Option<ast::NodeId>,
325 /// Places that type/region parameters can appear.
326 #[derive(Clone, Copy, Debug)]
327 pub enum ParameterOrigin {
329 MethodCall, // foo.bar() <-- parameters on impl providing bar()
330 OverloadedOperator, // a + b when overloaded
331 OverloadedDeref, // *a when overloaded
334 /// Times when we replace late-bound regions with variables:
335 #[derive(Clone, Copy, Debug)]
336 pub enum LateBoundRegionConversionTime {
337 /// when a fn is called
340 /// when two higher-ranked types are compared
343 /// when projecting an associated type
344 AssocTypeProjection(ast::Name),
347 /// Reasons to create a region inference variable
349 /// See `error_reporting` module for more details
350 #[derive(Clone, Debug)]
351 pub enum RegionVariableOrigin {
352 // Region variables created for ill-categorized reasons,
353 // mostly indicates places in need of refactoring
356 // Regions created by a `&P` or `[...]` pattern
359 // Regions created by `&` operator
362 // Regions created as part of an autoref of a method receiver
365 // Regions created as part of an automatic coercion
368 // Region variables created as the values for early-bound regions
369 EarlyBoundRegion(Span, ast::Name, Option<ty::Issue32330>),
371 // Region variables created for bound regions
372 // in a function or method that is called
373 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
375 UpvarRegion(ty::UpvarId, Span),
377 BoundRegionInCoherence(ast::Name),
380 #[derive(Copy, Clone, Debug)]
381 pub enum FixupError {
382 UnresolvedIntTy(IntVid),
383 UnresolvedFloatTy(FloatVid),
387 impl fmt::Display for FixupError {
388 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
389 use self::FixupError::*;
392 UnresolvedIntTy(_) => {
393 write!(f, "cannot determine the type of this integer; \
394 add a suffix to specify the type explicitly")
396 UnresolvedFloatTy(_) => {
397 write!(f, "cannot determine the type of this number; \
398 add a suffix to specify the type explicitly")
400 UnresolvedTy(_) => write!(f, "unconstrained type")
405 pub trait InferEnv<'a, 'tcx> {
406 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
407 -> (Option<&'a ty::TypeckTables<'tcx>>,
408 Option<ty::TypeckTables<'tcx>>,
409 Option<ty::ParamEnv<'tcx>>);
412 impl<'a, 'tcx> InferEnv<'a, 'tcx> for () {
413 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
414 -> (Option<&'a ty::TypeckTables<'tcx>>,
415 Option<ty::TypeckTables<'tcx>>,
416 Option<ty::ParamEnv<'tcx>>) {
421 impl<'a, 'tcx> InferEnv<'a, 'tcx> for ty::ParamEnv<'tcx> {
422 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
423 -> (Option<&'a ty::TypeckTables<'tcx>>,
424 Option<ty::TypeckTables<'tcx>>,
425 Option<ty::ParamEnv<'tcx>>) {
426 (None, None, Some(self))
430 impl<'a, 'tcx> InferEnv<'a, 'tcx> for (&'a ty::TypeckTables<'tcx>, ty::ParamEnv<'tcx>) {
431 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
432 -> (Option<&'a ty::TypeckTables<'tcx>>,
433 Option<ty::TypeckTables<'tcx>>,
434 Option<ty::ParamEnv<'tcx>>) {
435 (Some(self.0), None, Some(self.1))
439 impl<'a, 'tcx> InferEnv<'a, 'tcx> for (ty::TypeckTables<'tcx>, ty::ParamEnv<'tcx>) {
440 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
441 -> (Option<&'a ty::TypeckTables<'tcx>>,
442 Option<ty::TypeckTables<'tcx>>,
443 Option<ty::ParamEnv<'tcx>>) {
444 (None, Some(self.0), Some(self.1))
448 impl<'a, 'tcx> InferEnv<'a, 'tcx> for hir::BodyId {
449 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
450 -> (Option<&'a ty::TypeckTables<'tcx>>,
451 Option<ty::TypeckTables<'tcx>>,
452 Option<ty::ParamEnv<'tcx>>) {
453 let def_id = tcx.hir.body_owner_def_id(self);
454 (Some(tcx.typeck_tables_of(def_id)),
456 Some(tcx.param_env(def_id)))
460 /// Helper type of a temporary returned by tcx.infer_ctxt(...).
461 /// Necessary because we can't write the following bound:
462 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
463 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
464 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
465 arena: DroplessArena,
466 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
467 tables: Option<&'a ty::TypeckTables<'gcx>>,
468 param_env: Option<ty::ParamEnv<'gcx>>,
469 projection_mode: Reveal,
472 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
473 pub fn infer_ctxt<E: InferEnv<'a, 'gcx>>(self,
475 projection_mode: Reveal)
476 -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
477 let (tables, fresh_tables, param_env) = env.to_parts(self);
480 arena: DroplessArena::new(),
481 fresh_tables: fresh_tables.map(RefCell::new),
483 param_env: param_env,
484 projection_mode: projection_mode,
488 /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
489 /// for MemCategorizationContext/ExprUseVisitor.
490 /// If any inference functionality is used, ICEs will occur.
491 pub fn borrowck_fake_infer_ctxt(self, body: hir::BodyId)
492 -> InferCtxt<'a, 'gcx, 'gcx> {
493 let (tables, _, param_env) = body.to_parts(self);
496 tables: InferTables::Interned(tables.unwrap()),
497 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
498 int_unification_table: RefCell::new(UnificationTable::new()),
499 float_unification_table: RefCell::new(UnificationTable::new()),
500 region_vars: RegionVarBindings::new(self),
501 param_env: param_env.unwrap(),
502 selection_cache: traits::SelectionCache::new(),
503 evaluation_cache: traits::EvaluationCache::new(),
504 projection_cache: RefCell::new(traits::ProjectionCache::new()),
505 reported_trait_errors: RefCell::new(FxHashSet()),
506 projection_mode: Reveal::UserFacing,
507 tainted_by_errors_flag: Cell::new(false),
508 err_count_on_creation: self.sess.err_count(),
509 in_snapshot: Cell::new(false),
514 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
515 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
516 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
518 let InferCtxtBuilder {
526 let tables = tables.map(InferTables::Interned).unwrap_or_else(|| {
527 fresh_tables.as_ref().map_or(InferTables::Missing, InferTables::InProgress)
529 let param_env = param_env.take().unwrap_or_else(|| ty::ParamEnv::empty());
530 global_tcx.enter_local(arena, |tcx| f(InferCtxt {
533 projection_cache: RefCell::new(traits::ProjectionCache::new()),
534 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
535 int_unification_table: RefCell::new(UnificationTable::new()),
536 float_unification_table: RefCell::new(UnificationTable::new()),
537 region_vars: RegionVarBindings::new(tcx),
538 param_env: param_env,
539 selection_cache: traits::SelectionCache::new(),
540 evaluation_cache: traits::EvaluationCache::new(),
541 reported_trait_errors: RefCell::new(FxHashSet()),
542 projection_mode: projection_mode,
543 tainted_by_errors_flag: Cell::new(false),
544 err_count_on_creation: tcx.sess.err_count(),
545 in_snapshot: Cell::new(false),
550 impl<T> ExpectedFound<T> {
551 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
553 ExpectedFound {expected: a, found: b}
555 ExpectedFound {expected: b, found: a}
560 impl<'tcx, T> InferOk<'tcx, T> {
561 pub fn unit(self) -> InferOk<'tcx, ()> {
562 InferOk { value: (), obligations: self.obligations }
566 #[must_use = "once you start a snapshot, you should always consume it"]
567 pub struct CombinedSnapshot {
568 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
569 type_snapshot: type_variable::Snapshot,
570 int_snapshot: unify::Snapshot<ty::IntVid>,
571 float_snapshot: unify::Snapshot<ty::FloatVid>,
572 region_vars_snapshot: RegionSnapshot,
573 was_in_snapshot: bool,
576 /// Helper trait for shortening the lifetimes inside a
577 /// value for post-type-checking normalization.
578 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
579 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self;
582 macro_rules! items { ($($item:item)+) => ($($item)+) }
583 macro_rules! impl_trans_normalize {
584 ($lt_gcx:tt, $($ty:ty),+) => {
585 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
586 fn trans_normalize<'a, 'tcx>(&self,
587 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>)
589 infcx.normalize_projections_in(self)
595 impl_trans_normalize!('gcx,
600 ty::ClosureSubsts<'gcx>,
601 ty::PolyTraitRef<'gcx>,
602 ty::ExistentialTraitRef<'gcx>
605 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
606 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self {
608 LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx) },
609 LvalueTy::Downcast { adt_def, substs, variant_index } => {
612 substs: substs.trans_normalize(infcx),
613 variant_index: variant_index
620 // NOTE: Callable from trans only!
621 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
622 /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
623 /// each time we erase them in translation, we need to normalize
625 pub fn erase_late_bound_regions_and_normalize<T>(self, value: &ty::Binder<T>)
627 where T: TransNormalize<'tcx>
629 assert!(!value.needs_subst());
630 let value = self.erase_late_bound_regions(value);
631 self.normalize_associated_type(&value)
634 pub fn normalize_associated_type<T>(self, value: &T) -> T
635 where T: TransNormalize<'tcx>
637 debug!("normalize_associated_type(t={:?})", value);
639 let value = self.erase_regions(value);
641 if !value.has_projection_types() {
645 self.infer_ctxt((), Reveal::All).enter(|infcx| {
646 value.trans_normalize(&infcx)
650 pub fn normalize_associated_type_in_env<T>(
651 self, value: &T, env: ty::ParamEnv<'tcx>
653 where T: TransNormalize<'tcx>
655 debug!("normalize_associated_type_in_env(t={:?})", value);
657 let value = self.erase_regions(value);
659 if !value.has_projection_types() {
663 self.infer_ctxt(env, Reveal::All).enter(|infcx| {
664 value.trans_normalize(&infcx)
669 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
670 fn normalize_projections_in<T>(&self, value: &T) -> T::Lifted
671 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
673 let mut selcx = traits::SelectionContext::new(self);
674 let cause = traits::ObligationCause::dummy();
675 let traits::Normalized { value: result, obligations } =
676 traits::normalize(&mut selcx, cause, value);
678 debug!("normalize_projections_in: result={:?} obligations={:?}",
679 result, obligations);
681 let mut fulfill_cx = traits::FulfillmentContext::new();
683 for obligation in obligations {
684 fulfill_cx.register_predicate_obligation(self, obligation);
687 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
690 /// Finishes processes any obligations that remain in the
691 /// fulfillment context, and then returns the result with all type
692 /// variables removed and regions erased. Because this is intended
693 /// for use after type-check has completed, if any errors occur,
694 /// it will panic. It is used during normalization and other cases
695 /// where processing the obligations in `fulfill_cx` may cause
696 /// type inference variables that appear in `result` to be
697 /// unified, and hence we need to process those obligations to get
698 /// the complete picture of the type.
699 pub fn drain_fulfillment_cx_or_panic<T>(&self,
701 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
704 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
706 debug!("drain_fulfillment_cx_or_panic()");
708 // In principle, we only need to do this so long as `result`
709 // contains unbound type parameters. It could be a slight
710 // optimization to stop iterating early.
711 match fulfill_cx.select_all_or_error(self) {
714 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
719 let result = self.resolve_type_vars_if_possible(result);
720 let result = self.tcx.erase_regions(&result);
722 match self.tcx.lift_to_global(&result) {
723 Some(result) => result,
725 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
730 pub fn projection_mode(&self) -> Reveal {
734 pub fn is_in_snapshot(&self) -> bool {
735 self.in_snapshot.get()
738 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
739 t.fold_with(&mut self.freshener())
742 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
744 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
749 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
750 freshen::TypeFreshener::new(self)
753 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
754 use ty::error::UnconstrainedNumeric::Neither;
755 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
757 ty::TyInfer(ty::IntVar(vid)) => {
758 if self.int_unification_table.borrow_mut().has_value(vid) {
764 ty::TyInfer(ty::FloatVar(vid)) => {
765 if self.float_unification_table.borrow_mut().has_value(vid) {
775 /// Returns a type variable's default fallback if any exists. A default
776 /// must be attached to the variable when created, if it is created
777 /// without a default, this will return None.
779 /// This code does not apply to integral or floating point variables,
780 /// only to use declared defaults.
782 /// See `new_ty_var_with_default` to create a type variable with a default.
783 /// See `type_variable::Default` for details about what a default entails.
784 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
786 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
791 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
792 let mut variables = Vec::new();
794 let unbound_ty_vars = self.type_variables
796 .unsolved_variables()
798 .map(|t| self.tcx.mk_var(t));
800 let unbound_int_vars = self.int_unification_table
802 .unsolved_variables()
804 .map(|v| self.tcx.mk_int_var(v));
806 let unbound_float_vars = self.float_unification_table
808 .unsolved_variables()
810 .map(|v| self.tcx.mk_float_var(v));
812 variables.extend(unbound_ty_vars);
813 variables.extend(unbound_int_vars);
814 variables.extend(unbound_float_vars);
819 fn combine_fields(&'a self, trace: TypeTrace<'tcx>)
820 -> CombineFields<'a, 'gcx, 'tcx> {
825 obligations: PredicateObligations::new(),
829 pub fn equate<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
830 -> InferResult<'tcx, T>
831 where T: Relate<'tcx>
833 let mut fields = self.combine_fields(trace);
834 let result = fields.equate(a_is_expected).relate(a, b);
835 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
838 pub fn sub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
839 -> InferResult<'tcx, T>
840 where T: Relate<'tcx>
842 let mut fields = self.combine_fields(trace);
843 let result = fields.sub(a_is_expected).relate(a, b);
844 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
847 pub fn lub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
848 -> InferResult<'tcx, T>
849 where T: Relate<'tcx>
851 let mut fields = self.combine_fields(trace);
852 let result = fields.lub(a_is_expected).relate(a, b);
853 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
856 pub fn glb<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
857 -> InferResult<'tcx, T>
858 where T: Relate<'tcx>
860 let mut fields = self.combine_fields(trace);
861 let result = fields.glb(a_is_expected).relate(a, b);
862 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
865 // Clear the "currently in a snapshot" flag, invoke the closure,
866 // then restore the flag to its original value. This flag is a
867 // debugging measure designed to detect cases where we start a
868 // snapshot, create type variables, and register obligations
869 // which may involve those type variables in the fulfillment cx,
870 // potentially leaving "dangling type variables" behind.
871 // In such cases, an assertion will fail when attempting to
872 // register obligations, within a snapshot. Very useful, much
873 // better than grovelling through megabytes of RUST_LOG output.
875 // HOWEVER, in some cases the flag is unhelpful. 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_in_snapshot_flag<F, R>(&self, func: F) -> R
882 where F: FnOnce(&Self) -> R
884 let flag = self.in_snapshot.get();
885 self.in_snapshot.set(false);
886 let result = func(self);
887 self.in_snapshot.set(flag);
891 fn start_snapshot(&self) -> CombinedSnapshot {
892 debug!("start_snapshot()");
894 let in_snapshot = self.in_snapshot.get();
895 self.in_snapshot.set(true);
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 was_in_snapshot: 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 was_in_snapshot } = snapshot;
916 self.in_snapshot.set(was_in_snapshot);
918 self.projection_cache
920 .rollback_to(projection_cache_snapshot);
923 .rollback_to(type_snapshot);
924 self.int_unification_table
926 .rollback_to(int_snapshot);
927 self.float_unification_table
929 .rollback_to(float_snapshot);
931 .rollback_to(region_vars_snapshot);
934 fn commit_from(&self, snapshot: CombinedSnapshot) {
935 debug!("commit_from()");
936 let CombinedSnapshot { projection_cache_snapshot,
940 region_vars_snapshot,
941 was_in_snapshot } = snapshot;
943 self.in_snapshot.set(was_in_snapshot);
945 self.projection_cache
947 .commit(projection_cache_snapshot);
950 .commit(type_snapshot);
951 self.int_unification_table
953 .commit(int_snapshot);
954 self.float_unification_table
956 .commit(float_snapshot);
958 .commit(region_vars_snapshot);
961 /// Execute `f` and commit the bindings
962 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
966 let snapshot = self.start_snapshot();
968 self.commit_from(snapshot);
972 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
973 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
974 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
976 debug!("commit_if_ok()");
977 let snapshot = self.start_snapshot();
978 let r = f(&snapshot);
979 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
981 Ok(_) => { self.commit_from(snapshot); }
982 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
987 // Execute `f` in a snapshot, and commit the bindings it creates
988 pub fn in_snapshot<T, F>(&self, f: F) -> T where
989 F: FnOnce(&CombinedSnapshot) -> T
991 debug!("in_snapshot()");
992 let snapshot = self.start_snapshot();
993 let r = f(&snapshot);
994 self.commit_from(snapshot);
998 /// Execute `f` then unroll any bindings it creates
999 pub fn probe<R, F>(&self, f: F) -> R where
1000 F: FnOnce(&CombinedSnapshot) -> R,
1003 let snapshot = self.start_snapshot();
1004 let r = f(&snapshot);
1005 self.rollback_to("probe", snapshot);
1009 pub fn add_given(&self,
1010 sub: ty::Region<'tcx>,
1013 self.region_vars.add_given(sub, sup);
1016 pub fn sub_types(&self,
1017 a_is_expected: bool,
1018 cause: &ObligationCause<'tcx>,
1021 -> InferResult<'tcx, ()>
1023 debug!("sub_types({:?} <: {:?})", a, b);
1024 self.commit_if_ok(|_| {
1025 let trace = TypeTrace::types(cause, a_is_expected, a, b);
1026 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1030 pub fn can_sub_types(&self,
1036 let origin = &ObligationCause::dummy();
1037 let trace = TypeTrace::types(origin, true, a, b);
1038 self.sub(true, trace, &a, &b).map(|InferOk { obligations: _, .. }| {
1039 // Ignore obligations, since we are unrolling
1040 // everything anyway.
1045 pub fn eq_types(&self,
1046 a_is_expected: bool,
1047 cause: &ObligationCause<'tcx>,
1050 -> InferResult<'tcx, ()>
1052 self.commit_if_ok(|_| {
1053 let trace = TypeTrace::types(cause, a_is_expected, a, b);
1054 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1058 pub fn eq_trait_refs(&self,
1059 a_is_expected: bool,
1060 cause: &ObligationCause<'tcx>,
1061 a: ty::TraitRef<'tcx>,
1062 b: ty::TraitRef<'tcx>)
1063 -> InferResult<'tcx, ()>
1065 debug!("eq_trait_refs({:?} = {:?})", a, b);
1066 self.commit_if_ok(|_| {
1067 let trace = TypeTrace {
1068 cause: cause.clone(),
1069 values: TraitRefs(ExpectedFound::new(a_is_expected, a, b))
1071 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1075 pub fn eq_impl_headers(&self,
1076 a_is_expected: bool,
1077 cause: &ObligationCause<'tcx>,
1078 a: &ty::ImplHeader<'tcx>,
1079 b: &ty::ImplHeader<'tcx>)
1080 -> InferResult<'tcx, ()>
1082 debug!("eq_impl_header({:?} = {:?})", a, b);
1083 match (a.trait_ref, b.trait_ref) {
1084 (Some(a_ref), Some(b_ref)) => self.eq_trait_refs(a_is_expected, cause, a_ref, b_ref),
1085 (None, None) => self.eq_types(a_is_expected, cause, a.self_ty, b.self_ty),
1086 _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
1090 pub fn sub_poly_trait_refs(&self,
1091 a_is_expected: bool,
1092 cause: ObligationCause<'tcx>,
1093 a: ty::PolyTraitRef<'tcx>,
1094 b: ty::PolyTraitRef<'tcx>)
1095 -> InferResult<'tcx, ()>
1097 debug!("sub_poly_trait_refs({:?} <: {:?})", a, b);
1098 self.commit_if_ok(|_| {
1099 let trace = TypeTrace {
1101 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b))
1103 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1107 pub fn sub_regions(&self,
1108 origin: SubregionOrigin<'tcx>,
1109 a: ty::Region<'tcx>,
1110 b: ty::Region<'tcx>) {
1111 debug!("sub_regions({:?} <: {:?})", a, b);
1112 self.region_vars.make_subregion(origin, a, b);
1115 pub fn equality_predicate(&self,
1116 cause: &ObligationCause<'tcx>,
1117 predicate: &ty::PolyEquatePredicate<'tcx>)
1118 -> InferResult<'tcx, ()>
1120 self.commit_if_ok(|snapshot| {
1121 let (ty::EquatePredicate(a, b), skol_map) =
1122 self.skolemize_late_bound_regions(predicate, snapshot);
1123 let cause_span = cause.span;
1124 let eqty_ok = self.eq_types(false, cause, a, b)?;
1125 self.leak_check(false, cause_span, &skol_map, snapshot)?;
1126 self.pop_skolemized(skol_map, snapshot);
1131 pub fn subtype_predicate(&self,
1132 cause: &ObligationCause<'tcx>,
1133 predicate: &ty::PolySubtypePredicate<'tcx>)
1134 -> Option<InferResult<'tcx, ()>>
1136 // Subtle: it's ok to skip the binder here and resolve because
1137 // `shallow_resolve` just ignores anything that is not a type
1138 // variable, and because type variable's can't (at present, at
1139 // least) capture any of the things bound by this binder.
1141 // Really, there is no *particular* reason to do this
1142 // `shallow_resolve` here except as a
1143 // micro-optimization. Naturally I could not
1144 // resist. -nmatsakis
1145 let two_unbound_type_vars = {
1146 let a = self.shallow_resolve(predicate.skip_binder().a);
1147 let b = self.shallow_resolve(predicate.skip_binder().b);
1148 a.is_ty_var() && b.is_ty_var()
1151 if two_unbound_type_vars {
1152 // Two unbound type variables? Can't make progress.
1156 Some(self.commit_if_ok(|snapshot| {
1157 let (ty::SubtypePredicate { a_is_expected, a, b}, skol_map) =
1158 self.skolemize_late_bound_regions(predicate, snapshot);
1160 let cause_span = cause.span;
1161 let ok = self.sub_types(a_is_expected, cause, a, b)?;
1162 self.leak_check(false, cause_span, &skol_map, snapshot)?;
1163 self.pop_skolemized(skol_map, snapshot);
1168 pub fn region_outlives_predicate(&self,
1169 cause: &traits::ObligationCause<'tcx>,
1170 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1173 self.commit_if_ok(|snapshot| {
1174 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1175 self.skolemize_late_bound_regions(predicate, snapshot);
1177 SubregionOrigin::from_obligation_cause(cause,
1178 || RelateRegionParamBound(cause.span));
1179 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1180 self.leak_check(false, cause.span, &skol_map, snapshot)?;
1181 Ok(self.pop_skolemized(skol_map, snapshot))
1185 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1188 .new_var(diverging, origin, None)
1191 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1192 self.tcx.mk_var(self.next_ty_var_id(false, origin))
1195 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1196 self.tcx.mk_var(self.next_ty_var_id(true, origin))
1199 pub fn next_int_var_id(&self) -> IntVid {
1200 self.int_unification_table
1205 pub fn next_float_var_id(&self) -> FloatVid {
1206 self.float_unification_table
1211 pub fn next_region_var(&self, origin: RegionVariableOrigin)
1212 -> ty::Region<'tcx> {
1213 self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
1216 /// Create a region inference variable for the given
1217 /// region parameter definition.
1218 pub fn region_var_for_def(&self,
1220 def: &ty::RegionParameterDef)
1221 -> ty::Region<'tcx> {
1222 self.next_region_var(EarlyBoundRegion(span, def.name, def.issue_32330))
1225 /// Create a type inference variable for the given
1226 /// type parameter definition. The substitutions are
1227 /// for actual parameters that may be referred to by
1228 /// the default of this type parameter, if it exists.
1229 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1230 /// used in a path such as `Foo::<T, U>::new()` will
1231 /// use an inference variable for `C` with `[T, U]`
1232 /// as the substitutions for the default, `(T, U)`.
1233 pub fn type_var_for_def(&self,
1235 def: &ty::TypeParameterDef,
1236 substs: &[Kind<'tcx>])
1238 let default = if def.has_default {
1239 let default = self.tcx.type_of(def.def_id);
1240 Some(type_variable::Default {
1241 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1250 let ty_var_id = self.type_variables
1253 TypeVariableOrigin::TypeParameterDefinition(span, def.name),
1256 self.tcx.mk_var(ty_var_id)
1259 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1260 /// type/region parameter to a fresh inference variable.
1261 pub fn fresh_substs_for_item(&self,
1264 -> &'tcx Substs<'tcx> {
1265 Substs::for_item(self.tcx, def_id, |def, _| {
1266 self.region_var_for_def(span, def)
1268 self.type_var_for_def(span, def, substs)
1272 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region<'tcx> {
1273 self.region_vars.new_bound(debruijn)
1276 /// True if errors have been reported since this infcx was
1277 /// created. This is sometimes used as a heuristic to skip
1278 /// reporting errors that often occur as a result of earlier
1279 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1280 /// inference variables, regionck errors).
1281 pub fn is_tainted_by_errors(&self) -> bool {
1282 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1283 tainted_by_errors_flag={})",
1284 self.tcx.sess.err_count(),
1285 self.err_count_on_creation,
1286 self.tainted_by_errors_flag.get());
1288 if self.tcx.sess.err_count() > self.err_count_on_creation {
1289 return true; // errors reported since this infcx was made
1291 self.tainted_by_errors_flag.get()
1294 /// Set the "tainted by errors" flag to true. We call this when we
1295 /// observe an error from a prior pass.
1296 pub fn set_tainted_by_errors(&self) {
1297 debug!("set_tainted_by_errors()");
1298 self.tainted_by_errors_flag.set(true)
1301 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1302 match self.tables.borrow().node_types.get(&id) {
1305 None if self.is_tainted_by_errors() =>
1308 bug!("no type for node {}: {} in fcx",
1309 id, self.tcx.hir.node_to_string(id));
1314 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1315 match self.tables.borrow().node_types.get(&ex.id) {
1318 bug!("no type for expr in fcx");
1323 pub fn resolve_regions_and_report_errors(&self,
1324 region_context: DefId,
1325 region_map: &RegionMaps,
1326 free_regions: &FreeRegionMap<'tcx>) {
1327 let region_rels = RegionRelations::new(self.tcx,
1331 let errors = self.region_vars.resolve_regions(®ion_rels);
1332 if !self.is_tainted_by_errors() {
1333 // As a heuristic, just skip reporting region errors
1334 // altogether if other errors have been reported while
1335 // this infcx was in use. This is totally hokey but
1336 // otherwise we have a hard time separating legit region
1337 // errors from silly ones.
1338 self.report_region_errors(&errors); // see error_reporting module
1342 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1343 self.resolve_type_vars_if_possible(&t).to_string()
1346 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1347 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1348 format!("({})", tstrs.join(", "))
1351 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1352 self.resolve_type_vars_if_possible(t).to_string()
1355 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1357 ty::TyInfer(ty::TyVar(v)) => {
1358 // Not entirely obvious: if `typ` is a type variable,
1359 // it can be resolved to an int/float variable, which
1360 // can then be recursively resolved, hence the
1361 // recursion. Note though that we prevent type
1362 // variables from unifying to other type variables
1363 // directly (though they may be embedded
1364 // structurally), and we prevent cycles in any case,
1365 // so this recursion should always be of very limited
1367 self.type_variables.borrow_mut()
1369 .map(|t| self.shallow_resolve(t))
1373 ty::TyInfer(ty::IntVar(v)) => {
1374 self.int_unification_table
1377 .map(|v| v.to_type(self.tcx))
1381 ty::TyInfer(ty::FloatVar(v)) => {
1382 self.float_unification_table
1385 .map(|v| v.to_type(self.tcx))
1395 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1396 where T: TypeFoldable<'tcx>
1399 * Where possible, replaces type/int/float variables in
1400 * `value` with their final value. Note that region variables
1401 * are unaffected. If a type variable has not been unified, it
1402 * is left as is. This is an idempotent operation that does
1403 * not affect inference state in any way and so you can do it
1407 if !value.needs_infer() {
1408 return value.clone(); // avoid duplicated subst-folding
1410 let mut r = resolve::OpportunisticTypeResolver::new(self);
1411 value.fold_with(&mut r)
1414 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1415 where T: TypeFoldable<'tcx>
1417 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1418 value.fold_with(&mut r)
1421 /// Resolves all type variables in `t` and then, if any were left
1422 /// unresolved, substitutes an error type. This is used after the
1423 /// main checking when doing a second pass before writeback. The
1424 /// justification is that writeback will produce an error for
1425 /// these unconstrained type variables.
1426 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1427 let ty = self.resolve_type_vars_if_possible(t);
1428 if ty.references_error() || ty.is_ty_var() {
1429 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1436 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1438 * Attempts to resolve all type/region variables in
1439 * `value`. Region inference must have been run already (e.g.,
1440 * by calling `resolve_regions_and_report_errors`). If some
1441 * variable was never unified, an `Err` results.
1443 * This method is idempotent, but it not typically not invoked
1444 * except during the writeback phase.
1447 resolve::fully_resolve(self, value)
1450 // [Note-Type-error-reporting]
1451 // An invariant is that anytime the expected or actual type is TyError (the special
1452 // error type, meaning that an error occurred when typechecking this expression),
1453 // this is a derived error. The error cascaded from another error (that was already
1454 // reported), so it's not useful to display it to the user.
1455 // The following methods implement this logic.
1456 // They check if either the actual or expected type is TyError, and don't print the error
1457 // in this case. The typechecker should only ever report type errors involving mismatched
1458 // types using one of these methods, and should not call span_err directly for such
1461 pub fn type_error_message<M>(&self,
1464 actual_ty: Ty<'tcx>)
1465 where M: FnOnce(String) -> String,
1467 self.type_error_struct(sp, mk_msg, actual_ty).emit();
1470 // FIXME: this results in errors without an error code. Deprecate?
1471 pub fn type_error_struct<M>(&self,
1474 actual_ty: Ty<'tcx>)
1475 -> DiagnosticBuilder<'tcx>
1476 where M: FnOnce(String) -> String,
1478 self.type_error_struct_with_diag(sp, |actual_ty| {
1479 self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1483 pub fn type_error_struct_with_diag<M>(&self,
1486 actual_ty: Ty<'tcx>)
1487 -> DiagnosticBuilder<'tcx>
1488 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1490 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1491 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1493 // Don't report an error if actual type is TyError.
1494 if actual_ty.references_error() {
1495 return self.tcx.sess.diagnostic().struct_dummy();
1498 mk_diag(self.ty_to_string(actual_ty))
1501 pub fn report_mismatched_types(&self,
1502 cause: &ObligationCause<'tcx>,
1505 err: TypeError<'tcx>)
1506 -> DiagnosticBuilder<'tcx> {
1507 let trace = TypeTrace::types(cause, true, expected, actual);
1508 self.report_and_explain_type_error(trace, &err)
1511 pub fn report_conflicting_default_types(&self,
1513 body_id: ast::NodeId,
1514 expected: type_variable::Default<'tcx>,
1515 actual: type_variable::Default<'tcx>) {
1516 let trace = TypeTrace {
1517 cause: ObligationCause::misc(span, body_id),
1518 values: Types(ExpectedFound {
1519 expected: expected.ty,
1524 self.report_and_explain_type_error(
1526 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1533 pub fn replace_late_bound_regions_with_fresh_var<T>(
1536 lbrct: LateBoundRegionConversionTime,
1537 value: &ty::Binder<T>)
1538 -> (T, FxHashMap<ty::BoundRegion, ty::Region<'tcx>>)
1539 where T : TypeFoldable<'tcx>
1541 self.tcx.replace_late_bound_regions(
1543 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1546 /// Given a higher-ranked projection predicate like:
1548 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1550 /// and a target trait-ref like:
1552 /// <T as Fn<&'x u32>>
1554 /// find a substitution `S` for the higher-ranked regions (here,
1555 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1556 /// and then return the value (here, `&'a u32`) but with the
1557 /// substitution applied (hence, `&'x u32`).
1559 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1561 pub fn match_poly_projection_predicate(&self,
1562 cause: ObligationCause<'tcx>,
1563 match_a: ty::PolyProjectionPredicate<'tcx>,
1564 match_b: ty::TraitRef<'tcx>)
1565 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1567 let span = cause.span;
1568 let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1569 let trace = TypeTrace {
1571 values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1574 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1575 let mut combine = self.combine_fields(trace);
1576 let result = combine.higher_ranked_match(span, &match_pair, &match_b, true)?;
1577 Ok(InferOk { value: result, obligations: combine.obligations })
1580 /// See `verify_generic_bound` method in `region_inference`
1581 pub fn verify_generic_bound(&self,
1582 origin: SubregionOrigin<'tcx>,
1583 kind: GenericKind<'tcx>,
1584 a: ty::Region<'tcx>,
1585 bound: VerifyBound<'tcx>) {
1586 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1591 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1594 pub fn can_equate<T>(&self, a: &T, b: &T) -> UnitResult<'tcx>
1595 where T: Relate<'tcx> + fmt::Debug
1597 debug!("can_equate({:?}, {:?})", a, b);
1599 // Gin up a dummy trace, since this won't be committed
1600 // anyhow. We should make this typetrace stuff more
1601 // generic so we don't have to do anything quite this
1603 let trace = TypeTrace::dummy(self.tcx);
1604 self.equate(true, trace, a, b).map(|InferOk { obligations: _, .. }| {
1605 // We can intentionally ignore obligations here, since
1606 // this is part of a simple test for general
1607 // "equatability". However, it's not entirely clear
1608 // that we *ought* to be, perhaps a better thing would
1609 // be to use a mini-fulfillment context or something
1615 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1616 let ty = self.node_type(id);
1617 self.resolve_type_vars_or_error(&ty)
1620 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1621 let ty = self.tables.borrow().expr_ty_adjusted(expr);
1622 self.resolve_type_vars_or_error(&ty)
1625 pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1626 let ty = self.resolve_type_vars_if_possible(&ty);
1627 if let Some(ty) = self.tcx.lift_to_global(&ty) {
1628 // Even if the type may have no inference variables, during
1629 // type-checking closure types are in local tables only.
1630 let local_closures = match self.tables {
1631 InferTables::InProgress(_) => ty.has_closure_types(),
1634 if !local_closures {
1635 return ty.moves_by_default(self.tcx.global_tcx(), self.param_env(), span);
1639 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1641 // this can get called from typeck (by euv), and moves_by_default
1642 // rightly refuses to work with inference variables, but
1643 // moves_by_default has a cache, which we want to use in other
1645 !traits::type_known_to_meet_bound(self, ty, copy_def_id, span)
1648 pub fn node_method_ty(&self, method_call: ty::MethodCall)
1649 -> Option<Ty<'tcx>> {
1654 .map(|method| method.ty)
1655 .map(|ty| self.resolve_type_vars_if_possible(&ty))
1658 pub fn node_method_id(&self, method_call: ty::MethodCall)
1664 .map(|method| method.def_id)
1667 pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1668 self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1671 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
1672 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1675 pub fn param_env(&self) -> ty::ParamEnv<'gcx> {
1679 pub fn closure_kind(&self,
1681 -> Option<ty::ClosureKind>
1683 if let InferTables::InProgress(tables) = self.tables {
1684 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1685 return tables.borrow()
1689 .map(|(kind, _)| kind);
1693 // During typeck, ALL closures are local. But afterwards,
1694 // during trans, we see closure ids from other traits.
1695 // That may require loading the closure data out of the
1697 Some(self.tcx.closure_kind(def_id))
1700 pub fn closure_type(&self, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1701 if let InferTables::InProgress(tables) = self.tables {
1702 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1703 if let Some(&ty) = tables.borrow().closure_tys.get(&id) {
1709 self.tcx.closure_type(def_id)
1713 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1714 pub fn span(&self) -> Span {
1718 pub fn types(cause: &ObligationCause<'tcx>,
1719 a_is_expected: bool,
1722 -> TypeTrace<'tcx> {
1724 cause: cause.clone(),
1725 values: Types(ExpectedFound::new(a_is_expected, a, b))
1729 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1731 cause: ObligationCause::dummy(),
1732 values: Types(ExpectedFound {
1733 expected: tcx.types.err,
1734 found: tcx.types.err,
1740 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1741 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1742 write!(f, "TypeTrace({:?})", self.cause)
1746 impl<'tcx> SubregionOrigin<'tcx> {
1747 pub fn span(&self) -> Span {
1749 Subtype(ref a) => a.span(),
1750 InfStackClosure(a) => a,
1751 InvokeClosure(a) => a,
1752 DerefPointer(a) => a,
1753 FreeVariable(a, _) => a,
1755 RelateObjectBound(a) => a,
1756 RelateParamBound(a, _) => a,
1757 RelateRegionParamBound(a) => a,
1758 RelateDefaultParamBound(a, _) => a,
1760 ReborrowUpvar(a, _) => a,
1761 DataBorrowed(_, a) => a,
1762 ReferenceOutlivesReferent(_, a) => a,
1763 ParameterInScope(_, a) => a,
1764 ExprTypeIsNotInScope(_, a) => a,
1765 BindingTypeIsNotValidAtDecl(a) => a,
1772 SafeDestructor(a) => a,
1773 CompareImplMethodObligation { span, .. } => span,
1777 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>,
1780 where F: FnOnce() -> Self
1783 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
1784 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span),
1786 traits::ObligationCauseCode::CompareImplMethodObligation { item_name,
1790 SubregionOrigin::CompareImplMethodObligation {
1792 item_name: item_name,
1793 impl_item_def_id: impl_item_def_id,
1794 trait_item_def_id: trait_item_def_id,
1803 impl RegionVariableOrigin {
1804 pub fn span(&self) -> Span {
1806 MiscVariable(a) => a,
1807 PatternRegion(a) => a,
1808 AddrOfRegion(a) => a,
1811 EarlyBoundRegion(a, ..) => a,
1812 LateBoundRegion(a, ..) => a,
1813 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1814 UpvarRegion(_, a) => a
1819 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1820 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1822 ValuePairs::Types(ref ef) => {
1823 ValuePairs::Types(ef.fold_with(folder))
1825 ValuePairs::TraitRefs(ref ef) => {
1826 ValuePairs::TraitRefs(ef.fold_with(folder))
1828 ValuePairs::PolyTraitRefs(ref ef) => {
1829 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1834 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1836 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1837 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1838 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1843 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1844 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1846 cause: self.cause.fold_with(folder),
1847 values: self.values.fold_with(folder)
1851 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1852 self.cause.visit_with(visitor) || self.values.visit_with(visitor)