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 true while there is an active snapshot.
203 in_snapshot: Cell<bool>,
206 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
207 /// region that each late-bound region was replaced with.
208 pub type SkolemizationMap<'tcx> = FxHashMap<ty::BoundRegion, ty::Region<'tcx>>;
210 /// See `error_reporting` module for more details
211 #[derive(Clone, Debug)]
212 pub enum ValuePairs<'tcx> {
213 Types(ExpectedFound<Ty<'tcx>>),
214 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
215 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
218 /// The trace designates the path through inference that we took to
219 /// encounter an error or subtyping constraint.
221 /// See `error_reporting` module for more details.
223 pub struct TypeTrace<'tcx> {
224 cause: ObligationCause<'tcx>,
225 values: ValuePairs<'tcx>,
228 /// The origin of a `r1 <= r2` constraint.
230 /// See `error_reporting` module for more details
231 #[derive(Clone, Debug)]
232 pub enum SubregionOrigin<'tcx> {
233 // Arose from a subtyping relation
234 Subtype(TypeTrace<'tcx>),
236 // Stack-allocated closures cannot outlive innermost loop
237 // or function so as to ensure we only require finite stack
238 InfStackClosure(Span),
240 // Invocation of closure must be within its lifetime
243 // Dereference of reference must be within its lifetime
246 // Closure bound must not outlive captured free variables
247 FreeVariable(Span, ast::NodeId),
249 // Index into slice must be within its lifetime
252 // When casting `&'a T` to an `&'b Trait` object,
253 // relating `'a` to `'b`
254 RelateObjectBound(Span),
256 // Some type parameter was instantiated with the given type,
257 // and that type must outlive some region.
258 RelateParamBound(Span, Ty<'tcx>),
260 // The given region parameter was instantiated with a region
261 // that must outlive some other region.
262 RelateRegionParamBound(Span),
264 // A bound placed on type parameters that states that must outlive
265 // the moment of their instantiation.
266 RelateDefaultParamBound(Span, Ty<'tcx>),
268 // Creating a pointer `b` to contents of another reference
271 // Creating a pointer `b` to contents of an upvar
272 ReborrowUpvar(Span, ty::UpvarId),
274 // Data with type `Ty<'tcx>` was borrowed
275 DataBorrowed(Ty<'tcx>, Span),
277 // (&'a &'b T) where a >= b
278 ReferenceOutlivesReferent(Ty<'tcx>, Span),
280 // Type or region parameters must be in scope.
281 ParameterInScope(ParameterOrigin, Span),
283 // The type T of an expression E must outlive the lifetime for E.
284 ExprTypeIsNotInScope(Ty<'tcx>, Span),
286 // A `ref b` whose region does not enclose the decl site
287 BindingTypeIsNotValidAtDecl(Span),
289 // Regions appearing in a method receiver must outlive method call
292 // Regions appearing in a function argument must outlive func call
295 // Region in return type of invoked fn must enclose call
298 // Operands must be in scope
301 // Region resulting from a `&` expr must enclose the `&` expr
304 // An auto-borrow that does not enclose the expr where it occurs
307 // Region constraint arriving from destructor safety
308 SafeDestructor(Span),
310 // Comparing the signature and requirements of an impl method against
311 // the containing trait.
312 CompareImplMethodObligation {
314 item_name: ast::Name,
315 impl_item_def_id: DefId,
316 trait_item_def_id: DefId,
318 // this is `Some(_)` if this error arises from the bug fix for
319 // #18937. This is a temporary measure.
320 lint_id: Option<ast::NodeId>,
324 /// Places that type/region parameters can appear.
325 #[derive(Clone, Copy, Debug)]
326 pub enum ParameterOrigin {
328 MethodCall, // foo.bar() <-- parameters on impl providing bar()
329 OverloadedOperator, // a + b when overloaded
330 OverloadedDeref, // *a when overloaded
333 /// Times when we replace late-bound regions with variables:
334 #[derive(Clone, Copy, Debug)]
335 pub enum LateBoundRegionConversionTime {
336 /// when a fn is called
339 /// when two higher-ranked types are compared
342 /// when projecting an associated type
343 AssocTypeProjection(ast::Name),
346 /// Reasons to create a region inference variable
348 /// See `error_reporting` module for more details
349 #[derive(Clone, Debug)]
350 pub enum RegionVariableOrigin {
351 // Region variables created for ill-categorized reasons,
352 // mostly indicates places in need of refactoring
355 // Regions created by a `&P` or `[...]` pattern
358 // Regions created by `&` operator
361 // Regions created as part of an autoref of a method receiver
364 // Regions created as part of an automatic coercion
367 // Region variables created as the values for early-bound regions
368 EarlyBoundRegion(Span, ast::Name, Option<ty::Issue32330>),
370 // Region variables created for bound regions
371 // in a function or method that is called
372 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
374 UpvarRegion(ty::UpvarId, Span),
376 BoundRegionInCoherence(ast::Name),
379 #[derive(Copy, Clone, Debug)]
380 pub enum FixupError {
381 UnresolvedIntTy(IntVid),
382 UnresolvedFloatTy(FloatVid),
386 impl fmt::Display for FixupError {
387 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
388 use self::FixupError::*;
391 UnresolvedIntTy(_) => {
392 write!(f, "cannot determine the type of this integer; \
393 add a suffix to specify the type explicitly")
395 UnresolvedFloatTy(_) => {
396 write!(f, "cannot determine the type of this number; \
397 add a suffix to specify the type explicitly")
399 UnresolvedTy(_) => write!(f, "unconstrained type")
404 pub trait InferEnv<'a, 'tcx> {
405 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
406 -> (Option<&'a ty::TypeckTables<'tcx>>,
407 Option<ty::TypeckTables<'tcx>>,
408 Option<ty::ParameterEnvironment<'tcx>>);
411 impl<'a, 'tcx> InferEnv<'a, 'tcx> for () {
412 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
413 -> (Option<&'a ty::TypeckTables<'tcx>>,
414 Option<ty::TypeckTables<'tcx>>,
415 Option<ty::ParameterEnvironment<'tcx>>) {
420 impl<'a, 'tcx> InferEnv<'a, 'tcx> for ty::ParameterEnvironment<'tcx> {
421 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
422 -> (Option<&'a ty::TypeckTables<'tcx>>,
423 Option<ty::TypeckTables<'tcx>>,
424 Option<ty::ParameterEnvironment<'tcx>>) {
425 (None, None, Some(self))
429 impl<'a, 'tcx> InferEnv<'a, 'tcx> for (&'a ty::TypeckTables<'tcx>, ty::ParameterEnvironment<'tcx>) {
430 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
431 -> (Option<&'a ty::TypeckTables<'tcx>>,
432 Option<ty::TypeckTables<'tcx>>,
433 Option<ty::ParameterEnvironment<'tcx>>) {
434 (Some(self.0), None, Some(self.1))
438 impl<'a, 'tcx> InferEnv<'a, 'tcx> for (ty::TypeckTables<'tcx>, ty::ParameterEnvironment<'tcx>) {
439 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
440 -> (Option<&'a ty::TypeckTables<'tcx>>,
441 Option<ty::TypeckTables<'tcx>>,
442 Option<ty::ParameterEnvironment<'tcx>>) {
443 (None, Some(self.0), Some(self.1))
447 impl<'a, 'tcx> InferEnv<'a, 'tcx> for hir::BodyId {
448 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
449 -> (Option<&'a ty::TypeckTables<'tcx>>,
450 Option<ty::TypeckTables<'tcx>>,
451 Option<ty::ParameterEnvironment<'tcx>>) {
452 let item_id = tcx.hir.body_owner(self);
453 (Some(tcx.typeck_tables_of(tcx.hir.local_def_id(item_id))),
455 Some(ty::ParameterEnvironment::for_item(tcx, item_id)))
459 /// Helper type of a temporary returned by tcx.infer_ctxt(...).
460 /// Necessary because we can't write the following bound:
461 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
462 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
463 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
464 arena: DroplessArena,
465 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
466 tables: Option<&'a ty::TypeckTables<'gcx>>,
467 param_env: Option<ty::ParameterEnvironment<'gcx>>,
468 projection_mode: Reveal,
471 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
472 pub fn infer_ctxt<E: InferEnv<'a, 'gcx>>(self,
474 projection_mode: Reveal)
475 -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
476 let (tables, fresh_tables, param_env) = env.to_parts(self);
479 arena: DroplessArena::new(),
480 fresh_tables: fresh_tables.map(RefCell::new),
482 param_env: param_env,
483 projection_mode: projection_mode,
487 /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
488 /// for MemCategorizationContext/ExprUseVisitor.
489 /// If any inference functionality is used, ICEs will occur.
490 pub fn borrowck_fake_infer_ctxt(self, body: hir::BodyId)
491 -> InferCtxt<'a, 'gcx, 'gcx> {
492 let (tables, _, param_env) = body.to_parts(self);
495 tables: InferTables::Interned(tables.unwrap()),
496 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
497 int_unification_table: RefCell::new(UnificationTable::new()),
498 float_unification_table: RefCell::new(UnificationTable::new()),
499 region_vars: RegionVarBindings::new(self),
500 parameter_environment: param_env.unwrap(),
501 selection_cache: traits::SelectionCache::new(),
502 evaluation_cache: traits::EvaluationCache::new(),
503 projection_cache: RefCell::new(traits::ProjectionCache::new()),
504 reported_trait_errors: RefCell::new(FxHashSet()),
505 projection_mode: Reveal::UserFacing,
506 tainted_by_errors_flag: Cell::new(false),
507 err_count_on_creation: self.sess.err_count(),
508 in_snapshot: Cell::new(false),
513 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
514 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
515 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
517 let InferCtxtBuilder {
525 let tables = tables.map(InferTables::Interned).unwrap_or_else(|| {
526 fresh_tables.as_ref().map_or(InferTables::Missing, InferTables::InProgress)
528 let param_env = param_env.take().unwrap_or_else(|| {
529 global_tcx.empty_parameter_environment()
531 global_tcx.enter_local(arena, |tcx| f(InferCtxt {
534 projection_cache: RefCell::new(traits::ProjectionCache::new()),
535 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
536 int_unification_table: RefCell::new(UnificationTable::new()),
537 float_unification_table: RefCell::new(UnificationTable::new()),
538 region_vars: RegionVarBindings::new(tcx),
539 parameter_environment: param_env,
540 selection_cache: traits::SelectionCache::new(),
541 evaluation_cache: traits::EvaluationCache::new(),
542 reported_trait_errors: RefCell::new(FxHashSet()),
543 projection_mode: projection_mode,
544 tainted_by_errors_flag: Cell::new(false),
545 err_count_on_creation: tcx.sess.err_count(),
546 in_snapshot: Cell::new(false),
551 impl<T> ExpectedFound<T> {
552 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
554 ExpectedFound {expected: a, found: b}
556 ExpectedFound {expected: b, found: a}
561 impl<'tcx, T> InferOk<'tcx, T> {
562 pub fn unit(self) -> InferOk<'tcx, ()> {
563 InferOk { value: (), obligations: self.obligations }
567 #[must_use = "once you start a snapshot, you should always consume it"]
568 pub struct CombinedSnapshot {
569 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
570 type_snapshot: type_variable::Snapshot,
571 int_snapshot: unify::Snapshot<ty::IntVid>,
572 float_snapshot: unify::Snapshot<ty::FloatVid>,
573 region_vars_snapshot: RegionSnapshot,
574 was_in_snapshot: bool,
577 /// Helper trait for shortening the lifetimes inside a
578 /// value for post-type-checking normalization.
579 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
580 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self;
583 macro_rules! items { ($($item:item)+) => ($($item)+) }
584 macro_rules! impl_trans_normalize {
585 ($lt_gcx:tt, $($ty:ty),+) => {
586 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
587 fn trans_normalize<'a, 'tcx>(&self,
588 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>)
590 infcx.normalize_projections_in(self)
596 impl_trans_normalize!('gcx,
601 ty::ClosureSubsts<'gcx>,
602 ty::PolyTraitRef<'gcx>,
603 ty::ExistentialTraitRef<'gcx>
606 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
607 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self {
609 LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx) },
610 LvalueTy::Downcast { adt_def, substs, variant_index } => {
613 substs: substs.trans_normalize(infcx),
614 variant_index: variant_index
621 // NOTE: Callable from trans only!
622 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
623 /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
624 /// each time we erase them in translation, we need to normalize
626 pub fn erase_late_bound_regions_and_normalize<T>(self, value: &ty::Binder<T>)
628 where T: TransNormalize<'tcx>
630 assert!(!value.needs_subst());
631 let value = self.erase_late_bound_regions(value);
632 self.normalize_associated_type(&value)
635 pub fn normalize_associated_type<T>(self, value: &T) -> T
636 where T: TransNormalize<'tcx>
638 debug!("normalize_associated_type(t={:?})", value);
640 let value = self.erase_regions(value);
642 if !value.has_projection_types() {
646 self.infer_ctxt((), Reveal::All).enter(|infcx| {
647 value.trans_normalize(&infcx)
651 pub fn normalize_associated_type_in_env<T>(
652 self, value: &T, env: &'a ty::ParameterEnvironment<'tcx>
654 where T: TransNormalize<'tcx>
656 debug!("normalize_associated_type_in_env(t={:?})", value);
658 let value = self.erase_regions(value);
660 if !value.has_projection_types() {
664 self.infer_ctxt(env.clone(), Reveal::All).enter(|infcx| {
665 value.trans_normalize(&infcx)
670 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
671 fn normalize_projections_in<T>(&self, value: &T) -> T::Lifted
672 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
674 let mut selcx = traits::SelectionContext::new(self);
675 let cause = traits::ObligationCause::dummy();
676 let traits::Normalized { value: result, obligations } =
677 traits::normalize(&mut selcx, cause, value);
679 debug!("normalize_projections_in: result={:?} obligations={:?}",
680 result, obligations);
682 let mut fulfill_cx = traits::FulfillmentContext::new();
684 for obligation in obligations {
685 fulfill_cx.register_predicate_obligation(self, obligation);
688 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
691 /// Finishes processes any obligations that remain in the
692 /// fulfillment context, and then returns the result with all type
693 /// variables removed and regions erased. Because this is intended
694 /// for use after type-check has completed, if any errors occur,
695 /// it will panic. It is used during normalization and other cases
696 /// where processing the obligations in `fulfill_cx` may cause
697 /// type inference variables that appear in `result` to be
698 /// unified, and hence we need to process those obligations to get
699 /// the complete picture of the type.
700 pub fn drain_fulfillment_cx_or_panic<T>(&self,
702 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
705 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
707 debug!("drain_fulfillment_cx_or_panic()");
709 // In principle, we only need to do this so long as `result`
710 // contains unbound type parameters. It could be a slight
711 // optimization to stop iterating early.
712 match fulfill_cx.select_all_or_error(self) {
715 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
720 let result = self.resolve_type_vars_if_possible(result);
721 let result = self.tcx.erase_regions(&result);
723 match self.tcx.lift_to_global(&result) {
724 Some(result) => result,
726 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
731 pub fn projection_mode(&self) -> Reveal {
735 pub fn is_in_snapshot(&self) -> bool {
736 self.in_snapshot.get()
739 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
740 t.fold_with(&mut self.freshener())
743 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
745 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
750 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
751 freshen::TypeFreshener::new(self)
754 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
755 use ty::error::UnconstrainedNumeric::Neither;
756 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
758 ty::TyInfer(ty::IntVar(vid)) => {
759 if self.int_unification_table.borrow_mut().has_value(vid) {
765 ty::TyInfer(ty::FloatVar(vid)) => {
766 if self.float_unification_table.borrow_mut().has_value(vid) {
776 /// Returns a type variable's default fallback if any exists. A default
777 /// must be attached to the variable when created, if it is created
778 /// without a default, this will return None.
780 /// This code does not apply to integral or floating point variables,
781 /// only to use declared defaults.
783 /// See `new_ty_var_with_default` to create a type variable with a default.
784 /// See `type_variable::Default` for details about what a default entails.
785 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
787 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
792 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
793 let mut variables = Vec::new();
795 let unbound_ty_vars = self.type_variables
797 .unsolved_variables()
799 .map(|t| self.tcx.mk_var(t));
801 let unbound_int_vars = self.int_unification_table
803 .unsolved_variables()
805 .map(|v| self.tcx.mk_int_var(v));
807 let unbound_float_vars = self.float_unification_table
809 .unsolved_variables()
811 .map(|v| self.tcx.mk_float_var(v));
813 variables.extend(unbound_ty_vars);
814 variables.extend(unbound_int_vars);
815 variables.extend(unbound_float_vars);
820 fn combine_fields(&'a self, trace: TypeTrace<'tcx>)
821 -> CombineFields<'a, 'gcx, 'tcx> {
826 obligations: PredicateObligations::new(),
830 pub fn equate<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
831 -> InferResult<'tcx, T>
832 where T: Relate<'tcx>
834 let mut fields = self.combine_fields(trace);
835 let result = fields.equate(a_is_expected).relate(a, b);
836 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
839 pub fn sub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
840 -> InferResult<'tcx, T>
841 where T: Relate<'tcx>
843 let mut fields = self.combine_fields(trace);
844 let result = fields.sub(a_is_expected).relate(a, b);
845 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
848 pub fn lub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
849 -> InferResult<'tcx, T>
850 where T: Relate<'tcx>
852 let mut fields = self.combine_fields(trace);
853 let result = fields.lub(a_is_expected).relate(a, b);
854 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
857 pub fn glb<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
858 -> InferResult<'tcx, T>
859 where T: Relate<'tcx>
861 let mut fields = self.combine_fields(trace);
862 let result = fields.glb(a_is_expected).relate(a, b);
863 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
866 // Clear the "currently in a snapshot" flag, invoke the closure,
867 // then restore the flag to its original value. This flag is a
868 // debugging measure designed to detect cases where we start a
869 // snapshot, create type variables, and register obligations
870 // which may involve those type variables in the fulfillment cx,
871 // potentially leaving "dangling type variables" behind.
872 // In such cases, an assertion will fail when attempting to
873 // register obligations, within a snapshot. Very useful, much
874 // better than grovelling through megabytes of RUST_LOG output.
876 // HOWEVER, in some cases the flag is unhelpful. In particular, we
877 // sometimes create a "mini-fulfilment-cx" in which we enroll
878 // obligations. As long as this fulfillment cx is fully drained
879 // before we return, this is not a problem, as there won't be any
880 // escaping obligations in the main cx. In those cases, you can
881 // use this function.
882 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
883 where F: FnOnce(&Self) -> R
885 let flag = self.in_snapshot.get();
886 self.in_snapshot.set(false);
887 let result = func(self);
888 self.in_snapshot.set(flag);
892 fn start_snapshot(&self) -> CombinedSnapshot {
893 debug!("start_snapshot()");
895 let in_snapshot = self.in_snapshot.get();
896 self.in_snapshot.set(true);
899 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
900 type_snapshot: self.type_variables.borrow_mut().snapshot(),
901 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
902 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
903 region_vars_snapshot: self.region_vars.start_snapshot(),
904 was_in_snapshot: in_snapshot,
908 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
909 debug!("rollback_to(cause={})", cause);
910 let CombinedSnapshot { projection_cache_snapshot,
914 region_vars_snapshot,
915 was_in_snapshot } = snapshot;
917 self.in_snapshot.set(was_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 was_in_snapshot } = snapshot;
944 self.in_snapshot.set(was_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<'tcx>,
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 // Ignore obligations, since we are unrolling
1041 // everything anyway.
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: ty::Region<'tcx>,
1111 b: ty::Region<'tcx>) {
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 subtype_predicate(&self,
1133 cause: &ObligationCause<'tcx>,
1134 predicate: &ty::PolySubtypePredicate<'tcx>)
1135 -> Option<InferResult<'tcx, ()>>
1137 // Subtle: it's ok to skip the binder here and resolve because
1138 // `shallow_resolve` just ignores anything that is not a type
1139 // variable, and because type variable's can't (at present, at
1140 // least) capture any of the things bound by this binder.
1142 // Really, there is no *particular* reason to do this
1143 // `shallow_resolve` here except as a
1144 // micro-optimization. Naturally I could not
1145 // resist. -nmatsakis
1146 let two_unbound_type_vars = {
1147 let a = self.shallow_resolve(predicate.skip_binder().a);
1148 let b = self.shallow_resolve(predicate.skip_binder().b);
1149 a.is_ty_var() && b.is_ty_var()
1152 if two_unbound_type_vars {
1153 // Two unbound type variables? Can't make progress.
1157 Some(self.commit_if_ok(|snapshot| {
1158 let (ty::SubtypePredicate { a_is_expected, a, b}, skol_map) =
1159 self.skolemize_late_bound_regions(predicate, snapshot);
1161 let cause_span = cause.span;
1162 let ok = self.sub_types(a_is_expected, cause, a, b)?;
1163 self.leak_check(false, cause_span, &skol_map, snapshot)?;
1164 self.pop_skolemized(skol_map, snapshot);
1169 pub fn region_outlives_predicate(&self,
1170 cause: &traits::ObligationCause<'tcx>,
1171 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1174 self.commit_if_ok(|snapshot| {
1175 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1176 self.skolemize_late_bound_regions(predicate, snapshot);
1178 SubregionOrigin::from_obligation_cause(cause,
1179 || RelateRegionParamBound(cause.span));
1180 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1181 self.leak_check(false, cause.span, &skol_map, snapshot)?;
1182 Ok(self.pop_skolemized(skol_map, snapshot))
1186 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1189 .new_var(diverging, origin, None)
1192 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1193 self.tcx.mk_var(self.next_ty_var_id(false, origin))
1196 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1197 self.tcx.mk_var(self.next_ty_var_id(true, origin))
1200 pub fn next_int_var_id(&self) -> IntVid {
1201 self.int_unification_table
1206 pub fn next_float_var_id(&self) -> FloatVid {
1207 self.float_unification_table
1212 pub fn next_region_var(&self, origin: RegionVariableOrigin)
1213 -> ty::Region<'tcx> {
1214 self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
1217 /// Create a region inference variable for the given
1218 /// region parameter definition.
1219 pub fn region_var_for_def(&self,
1221 def: &ty::RegionParameterDef)
1222 -> ty::Region<'tcx> {
1223 self.next_region_var(EarlyBoundRegion(span, def.name, def.issue_32330))
1226 /// Create a type inference variable for the given
1227 /// type parameter definition. The substitutions are
1228 /// for actual parameters that may be referred to by
1229 /// the default of this type parameter, if it exists.
1230 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1231 /// used in a path such as `Foo::<T, U>::new()` will
1232 /// use an inference variable for `C` with `[T, U]`
1233 /// as the substitutions for the default, `(T, U)`.
1234 pub fn type_var_for_def(&self,
1236 def: &ty::TypeParameterDef,
1237 substs: &[Kind<'tcx>])
1239 let default = if def.has_default {
1240 let default = self.tcx.type_of(def.def_id);
1241 Some(type_variable::Default {
1242 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1251 let ty_var_id = self.type_variables
1254 TypeVariableOrigin::TypeParameterDefinition(span, def.name),
1257 self.tcx.mk_var(ty_var_id)
1260 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1261 /// type/region parameter to a fresh inference variable.
1262 pub fn fresh_substs_for_item(&self,
1265 -> &'tcx Substs<'tcx> {
1266 Substs::for_item(self.tcx, def_id, |def, _| {
1267 self.region_var_for_def(span, def)
1269 self.type_var_for_def(span, def, substs)
1273 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region<'tcx> {
1274 self.region_vars.new_bound(debruijn)
1277 /// True if errors have been reported since this infcx was
1278 /// created. This is sometimes used as a heuristic to skip
1279 /// reporting errors that often occur as a result of earlier
1280 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1281 /// inference variables, regionck errors).
1282 pub fn is_tainted_by_errors(&self) -> bool {
1283 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1284 tainted_by_errors_flag={})",
1285 self.tcx.sess.err_count(),
1286 self.err_count_on_creation,
1287 self.tainted_by_errors_flag.get());
1289 if self.tcx.sess.err_count() > self.err_count_on_creation {
1290 return true; // errors reported since this infcx was made
1292 self.tainted_by_errors_flag.get()
1295 /// Set the "tainted by errors" flag to true. We call this when we
1296 /// observe an error from a prior pass.
1297 pub fn set_tainted_by_errors(&self) {
1298 debug!("set_tainted_by_errors()");
1299 self.tainted_by_errors_flag.set(true)
1302 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1303 match self.tables.borrow().node_types.get(&id) {
1306 None if self.is_tainted_by_errors() =>
1309 bug!("no type for node {}: {} in fcx",
1310 id, self.tcx.hir.node_to_string(id));
1315 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1316 match self.tables.borrow().node_types.get(&ex.id) {
1319 bug!("no type for expr in fcx");
1324 pub fn resolve_regions_and_report_errors(&self,
1325 free_regions: &FreeRegionMap<'tcx>,
1326 subject_node_id: ast::NodeId) {
1327 let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1328 if !self.is_tainted_by_errors() {
1329 // As a heuristic, just skip reporting region errors
1330 // altogether if other errors have been reported while
1331 // this infcx was in use. This is totally hokey but
1332 // otherwise we have a hard time separating legit region
1333 // errors from silly ones.
1334 self.report_region_errors(&errors); // see error_reporting module
1338 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1339 self.resolve_type_vars_if_possible(&t).to_string()
1342 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1343 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1344 format!("({})", tstrs.join(", "))
1347 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1348 self.resolve_type_vars_if_possible(t).to_string()
1351 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1353 ty::TyInfer(ty::TyVar(v)) => {
1354 // Not entirely obvious: if `typ` is a type variable,
1355 // it can be resolved to an int/float variable, which
1356 // can then be recursively resolved, hence the
1357 // recursion. Note though that we prevent type
1358 // variables from unifying to other type variables
1359 // directly (though they may be embedded
1360 // structurally), and we prevent cycles in any case,
1361 // so this recursion should always be of very limited
1363 self.type_variables.borrow_mut()
1365 .map(|t| self.shallow_resolve(t))
1369 ty::TyInfer(ty::IntVar(v)) => {
1370 self.int_unification_table
1373 .map(|v| v.to_type(self.tcx))
1377 ty::TyInfer(ty::FloatVar(v)) => {
1378 self.float_unification_table
1381 .map(|v| v.to_type(self.tcx))
1391 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1392 where T: TypeFoldable<'tcx>
1395 * Where possible, replaces type/int/float variables in
1396 * `value` with their final value. Note that region variables
1397 * are unaffected. If a type variable has not been unified, it
1398 * is left as is. This is an idempotent operation that does
1399 * not affect inference state in any way and so you can do it
1403 if !value.needs_infer() {
1404 return value.clone(); // avoid duplicated subst-folding
1406 let mut r = resolve::OpportunisticTypeResolver::new(self);
1407 value.fold_with(&mut r)
1410 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1411 where T: TypeFoldable<'tcx>
1413 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1414 value.fold_with(&mut r)
1417 /// Resolves all type variables in `t` and then, if any were left
1418 /// unresolved, substitutes an error type. This is used after the
1419 /// main checking when doing a second pass before writeback. The
1420 /// justification is that writeback will produce an error for
1421 /// these unconstrained type variables.
1422 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1423 let ty = self.resolve_type_vars_if_possible(t);
1424 if ty.references_error() || ty.is_ty_var() {
1425 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1432 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1434 * Attempts to resolve all type/region variables in
1435 * `value`. Region inference must have been run already (e.g.,
1436 * by calling `resolve_regions_and_report_errors`). If some
1437 * variable was never unified, an `Err` results.
1439 * This method is idempotent, but it not typically not invoked
1440 * except during the writeback phase.
1443 resolve::fully_resolve(self, value)
1446 // [Note-Type-error-reporting]
1447 // An invariant is that anytime the expected or actual type is TyError (the special
1448 // error type, meaning that an error occurred when typechecking this expression),
1449 // this is a derived error. The error cascaded from another error (that was already
1450 // reported), so it's not useful to display it to the user.
1451 // The following methods implement this logic.
1452 // They check if either the actual or expected type is TyError, and don't print the error
1453 // in this case. The typechecker should only ever report type errors involving mismatched
1454 // types using one of these methods, and should not call span_err directly for such
1457 pub fn type_error_message<M>(&self,
1460 actual_ty: Ty<'tcx>)
1461 where M: FnOnce(String) -> String,
1463 self.type_error_struct(sp, mk_msg, actual_ty).emit();
1466 // FIXME: this results in errors without an error code. Deprecate?
1467 pub fn type_error_struct<M>(&self,
1470 actual_ty: Ty<'tcx>)
1471 -> DiagnosticBuilder<'tcx>
1472 where M: FnOnce(String) -> String,
1474 self.type_error_struct_with_diag(sp, |actual_ty| {
1475 self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1479 pub fn type_error_struct_with_diag<M>(&self,
1482 actual_ty: Ty<'tcx>)
1483 -> DiagnosticBuilder<'tcx>
1484 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1486 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1487 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1489 // Don't report an error if actual type is TyError.
1490 if actual_ty.references_error() {
1491 return self.tcx.sess.diagnostic().struct_dummy();
1494 mk_diag(self.ty_to_string(actual_ty))
1497 pub fn report_mismatched_types(&self,
1498 cause: &ObligationCause<'tcx>,
1501 err: TypeError<'tcx>)
1502 -> DiagnosticBuilder<'tcx> {
1503 let trace = TypeTrace::types(cause, true, expected, actual);
1504 self.report_and_explain_type_error(trace, &err)
1507 pub fn report_conflicting_default_types(&self,
1509 body_id: ast::NodeId,
1510 expected: type_variable::Default<'tcx>,
1511 actual: type_variable::Default<'tcx>) {
1512 let trace = TypeTrace {
1513 cause: ObligationCause::misc(span, body_id),
1514 values: Types(ExpectedFound {
1515 expected: expected.ty,
1520 self.report_and_explain_type_error(
1522 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1529 pub fn replace_late_bound_regions_with_fresh_var<T>(
1532 lbrct: LateBoundRegionConversionTime,
1533 value: &ty::Binder<T>)
1534 -> (T, FxHashMap<ty::BoundRegion, ty::Region<'tcx>>)
1535 where T : TypeFoldable<'tcx>
1537 self.tcx.replace_late_bound_regions(
1539 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1542 /// Given a higher-ranked projection predicate like:
1544 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1546 /// and a target trait-ref like:
1548 /// <T as Fn<&'x u32>>
1550 /// find a substitution `S` for the higher-ranked regions (here,
1551 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1552 /// and then return the value (here, `&'a u32`) but with the
1553 /// substitution applied (hence, `&'x u32`).
1555 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1557 pub fn match_poly_projection_predicate(&self,
1558 cause: ObligationCause<'tcx>,
1559 match_a: ty::PolyProjectionPredicate<'tcx>,
1560 match_b: ty::TraitRef<'tcx>)
1561 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1563 let span = cause.span;
1564 let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1565 let trace = TypeTrace {
1567 values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1570 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1571 let mut combine = self.combine_fields(trace);
1572 let result = combine.higher_ranked_match(span, &match_pair, &match_b, true)?;
1573 Ok(InferOk { value: result, obligations: combine.obligations })
1576 /// See `verify_generic_bound` method in `region_inference`
1577 pub fn verify_generic_bound(&self,
1578 origin: SubregionOrigin<'tcx>,
1579 kind: GenericKind<'tcx>,
1580 a: ty::Region<'tcx>,
1581 bound: VerifyBound<'tcx>) {
1582 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1587 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1590 pub fn can_equate<T>(&self, a: &T, b: &T) -> UnitResult<'tcx>
1591 where T: Relate<'tcx> + fmt::Debug
1593 debug!("can_equate({:?}, {:?})", a, b);
1595 // Gin up a dummy trace, since this won't be committed
1596 // anyhow. We should make this typetrace stuff more
1597 // generic so we don't have to do anything quite this
1599 let trace = TypeTrace::dummy(self.tcx);
1600 self.equate(true, trace, a, b).map(|InferOk { obligations: _, .. }| {
1601 // We can intentionally ignore obligations here, since
1602 // this is part of a simple test for general
1603 // "equatability". However, it's not entirely clear
1604 // that we *ought* to be, perhaps a better thing would
1605 // be to use a mini-fulfillment context or something
1611 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1612 let ty = self.node_type(id);
1613 self.resolve_type_vars_or_error(&ty)
1616 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1617 let ty = self.tables.borrow().expr_ty_adjusted(expr);
1618 self.resolve_type_vars_or_error(&ty)
1621 pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1622 let ty = self.resolve_type_vars_if_possible(&ty);
1623 if let Some(ty) = self.tcx.lift_to_global(&ty) {
1624 // Even if the type may have no inference variables, during
1625 // type-checking closure types are in local tables only.
1626 let local_closures = match self.tables {
1627 InferTables::InProgress(_) => ty.has_closure_types(),
1630 if !local_closures {
1631 return ty.moves_by_default(self.tcx.global_tcx(), self.param_env(), span);
1635 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1637 // this can get called from typeck (by euv), and moves_by_default
1638 // rightly refuses to work with inference variables, but
1639 // moves_by_default has a cache, which we want to use in other
1641 !traits::type_known_to_meet_bound(self, ty, copy_def_id, span)
1644 pub fn node_method_ty(&self, method_call: ty::MethodCall)
1645 -> Option<Ty<'tcx>> {
1650 .map(|method| method.ty)
1651 .map(|ty| self.resolve_type_vars_if_possible(&ty))
1654 pub fn node_method_id(&self, method_call: ty::MethodCall)
1660 .map(|method| method.def_id)
1663 pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1664 self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1667 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
1668 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1671 pub fn param_env(&self) -> &ty::ParameterEnvironment<'gcx> {
1672 &self.parameter_environment
1675 pub fn closure_kind(&self,
1677 -> Option<ty::ClosureKind>
1679 if let InferTables::InProgress(tables) = self.tables {
1680 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1681 return tables.borrow().closure_kinds.get(&id).cloned();
1685 // During typeck, ALL closures are local. But afterwards,
1686 // during trans, we see closure ids from other traits.
1687 // That may require loading the closure data out of the
1689 Some(self.tcx.closure_kind(def_id))
1692 pub fn closure_type(&self, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1693 if let InferTables::InProgress(tables) = self.tables {
1694 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1695 if let Some(&ty) = tables.borrow().closure_tys.get(&id) {
1701 self.tcx.closure_type(def_id)
1705 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1706 pub fn span(&self) -> Span {
1710 pub fn types(cause: &ObligationCause<'tcx>,
1711 a_is_expected: bool,
1714 -> TypeTrace<'tcx> {
1716 cause: cause.clone(),
1717 values: Types(ExpectedFound::new(a_is_expected, a, b))
1721 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1723 cause: ObligationCause::dummy(),
1724 values: Types(ExpectedFound {
1725 expected: tcx.types.err,
1726 found: tcx.types.err,
1732 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1733 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1734 write!(f, "TypeTrace({:?})", self.cause)
1738 impl<'tcx> SubregionOrigin<'tcx> {
1739 pub fn span(&self) -> Span {
1741 Subtype(ref a) => a.span(),
1742 InfStackClosure(a) => a,
1743 InvokeClosure(a) => a,
1744 DerefPointer(a) => a,
1745 FreeVariable(a, _) => a,
1747 RelateObjectBound(a) => a,
1748 RelateParamBound(a, _) => a,
1749 RelateRegionParamBound(a) => a,
1750 RelateDefaultParamBound(a, _) => a,
1752 ReborrowUpvar(a, _) => a,
1753 DataBorrowed(_, a) => a,
1754 ReferenceOutlivesReferent(_, a) => a,
1755 ParameterInScope(_, a) => a,
1756 ExprTypeIsNotInScope(_, a) => a,
1757 BindingTypeIsNotValidAtDecl(a) => a,
1764 SafeDestructor(a) => a,
1765 CompareImplMethodObligation { span, .. } => span,
1769 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>,
1772 where F: FnOnce() -> Self
1775 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
1776 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span),
1778 traits::ObligationCauseCode::CompareImplMethodObligation { item_name,
1782 SubregionOrigin::CompareImplMethodObligation {
1784 item_name: item_name,
1785 impl_item_def_id: impl_item_def_id,
1786 trait_item_def_id: trait_item_def_id,
1795 impl RegionVariableOrigin {
1796 pub fn span(&self) -> Span {
1798 MiscVariable(a) => a,
1799 PatternRegion(a) => a,
1800 AddrOfRegion(a) => a,
1803 EarlyBoundRegion(a, ..) => a,
1804 LateBoundRegion(a, ..) => a,
1805 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1806 UpvarRegion(_, a) => a
1811 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1812 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1814 ValuePairs::Types(ref ef) => {
1815 ValuePairs::Types(ef.fold_with(folder))
1817 ValuePairs::TraitRefs(ref ef) => {
1818 ValuePairs::TraitRefs(ef.fold_with(folder))
1820 ValuePairs::PolyTraitRefs(ref ef) => {
1821 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1826 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1828 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1829 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1830 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1835 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1836 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1838 cause: self.cause.fold_with(folder),
1839 values: self.values.fold_with(folder)
1843 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1844 self.cause.visit_with(visitor) || self.values.visit_with(visitor)