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 // When an error occurs, we want to avoid reporting "derived"
178 // errors that are due to this original failure. Normally, we
179 // handle this with the `err_count_on_creation` count, which
180 // basically just tracks how many errors were reported when we
181 // started type-checking a fn and checks to see if any new errors
182 // have been reported since then. Not great, but it works.
184 // However, when errors originated in other passes -- notably
185 // resolve -- this heuristic breaks down. Therefore, we have this
186 // auxiliary flag that one can set whenever one creates a
187 // type-error that is due to an error in a prior pass.
189 // Don't read this flag directly, call `is_tainted_by_errors()`
190 // and `set_tainted_by_errors()`.
191 tainted_by_errors_flag: Cell<bool>,
193 // Track how many errors were reported when this infcx is created.
194 // If the number of errors increases, that's also a sign (line
195 // `tained_by_errors`) to avoid reporting certain kinds of errors.
196 err_count_on_creation: usize,
198 // This flag is true while there is an active snapshot.
199 in_snapshot: Cell<bool>,
202 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
203 /// region that each late-bound region was replaced with.
204 pub type SkolemizationMap<'tcx> = FxHashMap<ty::BoundRegion, ty::Region<'tcx>>;
206 /// See `error_reporting` module for more details
207 #[derive(Clone, Debug)]
208 pub enum ValuePairs<'tcx> {
209 Types(ExpectedFound<Ty<'tcx>>),
210 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
211 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
214 /// The trace designates the path through inference that we took to
215 /// encounter an error or subtyping constraint.
217 /// See `error_reporting` module for more details.
219 pub struct TypeTrace<'tcx> {
220 cause: ObligationCause<'tcx>,
221 values: ValuePairs<'tcx>,
224 /// The origin of a `r1 <= r2` constraint.
226 /// See `error_reporting` module for more details
227 #[derive(Clone, Debug)]
228 pub enum SubregionOrigin<'tcx> {
229 // Arose from a subtyping relation
230 Subtype(TypeTrace<'tcx>),
232 // Stack-allocated closures cannot outlive innermost loop
233 // or function so as to ensure we only require finite stack
234 InfStackClosure(Span),
236 // Invocation of closure must be within its lifetime
239 // Dereference of reference must be within its lifetime
242 // Closure bound must not outlive captured free variables
243 FreeVariable(Span, ast::NodeId),
245 // Index into slice must be within its lifetime
248 // When casting `&'a T` to an `&'b Trait` object,
249 // relating `'a` to `'b`
250 RelateObjectBound(Span),
252 // Some type parameter was instantiated with the given type,
253 // and that type must outlive some region.
254 RelateParamBound(Span, Ty<'tcx>),
256 // The given region parameter was instantiated with a region
257 // that must outlive some other region.
258 RelateRegionParamBound(Span),
260 // A bound placed on type parameters that states that must outlive
261 // the moment of their instantiation.
262 RelateDefaultParamBound(Span, Ty<'tcx>),
264 // Creating a pointer `b` to contents of another reference
267 // Creating a pointer `b` to contents of an upvar
268 ReborrowUpvar(Span, ty::UpvarId),
270 // Data with type `Ty<'tcx>` was borrowed
271 DataBorrowed(Ty<'tcx>, Span),
273 // (&'a &'b T) where a >= b
274 ReferenceOutlivesReferent(Ty<'tcx>, Span),
276 // Type or region parameters must be in scope.
277 ParameterInScope(ParameterOrigin, Span),
279 // The type T of an expression E must outlive the lifetime for E.
280 ExprTypeIsNotInScope(Ty<'tcx>, Span),
282 // A `ref b` whose region does not enclose the decl site
283 BindingTypeIsNotValidAtDecl(Span),
285 // Regions appearing in a method receiver must outlive method call
288 // Regions appearing in a function argument must outlive func call
291 // Region in return type of invoked fn must enclose call
294 // Operands must be in scope
297 // Region resulting from a `&` expr must enclose the `&` expr
300 // An auto-borrow that does not enclose the expr where it occurs
303 // Region constraint arriving from destructor safety
304 SafeDestructor(Span),
306 // Comparing the signature and requirements of an impl method against
307 // the containing trait.
308 CompareImplMethodObligation {
310 item_name: ast::Name,
311 impl_item_def_id: DefId,
312 trait_item_def_id: DefId,
314 // this is `Some(_)` if this error arises from the bug fix for
315 // #18937. This is a temporary measure.
316 lint_id: Option<ast::NodeId>,
320 /// Places that type/region parameters can appear.
321 #[derive(Clone, Copy, Debug)]
322 pub enum ParameterOrigin {
324 MethodCall, // foo.bar() <-- parameters on impl providing bar()
325 OverloadedOperator, // a + b when overloaded
326 OverloadedDeref, // *a when overloaded
329 /// Times when we replace late-bound regions with variables:
330 #[derive(Clone, Copy, Debug)]
331 pub enum LateBoundRegionConversionTime {
332 /// when a fn is called
335 /// when two higher-ranked types are compared
338 /// when projecting an associated type
339 AssocTypeProjection(ast::Name),
342 /// Reasons to create a region inference variable
344 /// See `error_reporting` module for more details
345 #[derive(Clone, Debug)]
346 pub enum RegionVariableOrigin {
347 // Region variables created for ill-categorized reasons,
348 // mostly indicates places in need of refactoring
351 // Regions created by a `&P` or `[...]` pattern
354 // Regions created by `&` operator
357 // Regions created as part of an autoref of a method receiver
360 // Regions created as part of an automatic coercion
363 // Region variables created as the values for early-bound regions
364 EarlyBoundRegion(Span, ast::Name, Option<ty::Issue32330>),
366 // Region variables created for bound regions
367 // in a function or method that is called
368 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
370 UpvarRegion(ty::UpvarId, Span),
372 BoundRegionInCoherence(ast::Name),
375 #[derive(Copy, Clone, Debug)]
376 pub enum FixupError {
377 UnresolvedIntTy(IntVid),
378 UnresolvedFloatTy(FloatVid),
382 impl fmt::Display for FixupError {
383 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
384 use self::FixupError::*;
387 UnresolvedIntTy(_) => {
388 write!(f, "cannot determine the type of this integer; \
389 add a suffix to specify the type explicitly")
391 UnresolvedFloatTy(_) => {
392 write!(f, "cannot determine the type of this number; \
393 add a suffix to specify the type explicitly")
395 UnresolvedTy(_) => write!(f, "unconstrained type")
400 pub trait InferEnv<'a, 'tcx> {
401 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
402 -> (Option<&'a ty::TypeckTables<'tcx>>,
403 Option<ty::TypeckTables<'tcx>>,
407 impl<'a, 'tcx> InferEnv<'a, 'tcx> for Reveal {
408 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
409 -> (Option<&'a ty::TypeckTables<'tcx>>,
410 Option<ty::TypeckTables<'tcx>>,
411 ty::ParamEnv<'tcx>) {
412 (None, None, ty::ParamEnv::empty(self))
416 impl<'a, 'tcx> InferEnv<'a, 'tcx> for ty::ParamEnv<'tcx> {
417 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
418 -> (Option<&'a ty::TypeckTables<'tcx>>,
419 Option<ty::TypeckTables<'tcx>>,
420 ty::ParamEnv<'tcx>) {
425 impl<'a, 'tcx> InferEnv<'a, 'tcx> for (&'a ty::TypeckTables<'tcx>, ty::ParamEnv<'tcx>) {
426 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
427 -> (Option<&'a ty::TypeckTables<'tcx>>,
428 Option<ty::TypeckTables<'tcx>>,
429 ty::ParamEnv<'tcx>) {
430 (Some(self.0), None, self.1)
434 impl<'a, 'tcx> InferEnv<'a, 'tcx> for (ty::TypeckTables<'tcx>, ty::ParamEnv<'tcx>) {
435 fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
436 -> (Option<&'a ty::TypeckTables<'tcx>>,
437 Option<ty::TypeckTables<'tcx>>,
438 ty::ParamEnv<'tcx>) {
439 (None, Some(self.0), self.1)
443 impl<'a, 'tcx> InferEnv<'a, 'tcx> for hir::BodyId {
444 fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
445 -> (Option<&'a ty::TypeckTables<'tcx>>,
446 Option<ty::TypeckTables<'tcx>>,
447 ty::ParamEnv<'tcx>) {
448 let def_id = tcx.hir.body_owner_def_id(self);
449 (Some(tcx.typeck_tables_of(def_id)),
451 tcx.param_env(def_id))
455 /// Helper type of a temporary returned by tcx.infer_ctxt(...).
456 /// Necessary because we can't write the following bound:
457 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
458 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
459 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
460 arena: DroplessArena,
461 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
462 tables: Option<&'a ty::TypeckTables<'gcx>>,
463 param_env: ty::ParamEnv<'gcx>,
466 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
467 pub fn infer_ctxt<E: InferEnv<'a, 'gcx>>(self, env: E) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
468 let (tables, fresh_tables, param_env) = env.to_parts(self);
471 arena: DroplessArena::new(),
472 fresh_tables: fresh_tables.map(RefCell::new),
474 param_env: param_env,
478 /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
479 /// for MemCategorizationContext/ExprUseVisitor.
480 /// If any inference functionality is used, ICEs will occur.
481 pub fn borrowck_fake_infer_ctxt(self, body: hir::BodyId)
482 -> InferCtxt<'a, 'gcx, 'gcx> {
483 let (tables, _, param_env) = body.to_parts(self);
486 tables: InferTables::Interned(tables.unwrap()),
487 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
488 int_unification_table: RefCell::new(UnificationTable::new()),
489 float_unification_table: RefCell::new(UnificationTable::new()),
490 region_vars: RegionVarBindings::new(self),
491 param_env: param_env,
492 selection_cache: traits::SelectionCache::new(),
493 evaluation_cache: traits::EvaluationCache::new(),
494 projection_cache: RefCell::new(traits::ProjectionCache::new()),
495 reported_trait_errors: RefCell::new(FxHashSet()),
496 tainted_by_errors_flag: Cell::new(false),
497 err_count_on_creation: self.sess.err_count(),
498 in_snapshot: Cell::new(false),
503 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
504 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
505 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
507 let InferCtxtBuilder {
514 let tables = tables.map(InferTables::Interned).unwrap_or_else(|| {
515 fresh_tables.as_ref().map_or(InferTables::Missing, InferTables::InProgress)
517 global_tcx.enter_local(arena, |tcx| f(InferCtxt {
520 projection_cache: RefCell::new(traits::ProjectionCache::new()),
521 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
522 int_unification_table: RefCell::new(UnificationTable::new()),
523 float_unification_table: RefCell::new(UnificationTable::new()),
524 region_vars: RegionVarBindings::new(tcx),
525 param_env: param_env,
526 selection_cache: traits::SelectionCache::new(),
527 evaluation_cache: traits::EvaluationCache::new(),
528 reported_trait_errors: RefCell::new(FxHashSet()),
529 tainted_by_errors_flag: Cell::new(false),
530 err_count_on_creation: tcx.sess.err_count(),
531 in_snapshot: Cell::new(false),
536 impl<T> ExpectedFound<T> {
537 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
539 ExpectedFound {expected: a, found: b}
541 ExpectedFound {expected: b, found: a}
546 impl<'tcx, T> InferOk<'tcx, T> {
547 pub fn unit(self) -> InferOk<'tcx, ()> {
548 InferOk { value: (), obligations: self.obligations }
552 #[must_use = "once you start a snapshot, you should always consume it"]
553 pub struct CombinedSnapshot<'a, 'tcx:'a> {
554 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
555 type_snapshot: type_variable::Snapshot,
556 int_snapshot: unify::Snapshot<ty::IntVid>,
557 float_snapshot: unify::Snapshot<ty::FloatVid>,
558 region_vars_snapshot: RegionSnapshot,
559 was_in_snapshot: bool,
560 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
563 /// Helper trait for shortening the lifetimes inside a
564 /// value for post-type-checking normalization.
565 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
566 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self;
569 macro_rules! items { ($($item:item)+) => ($($item)+) }
570 macro_rules! impl_trans_normalize {
571 ($lt_gcx:tt, $($ty:ty),+) => {
572 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
573 fn trans_normalize<'a, 'tcx>(&self,
574 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>)
576 infcx.normalize_projections_in(self)
582 impl_trans_normalize!('gcx,
587 ty::ClosureSubsts<'gcx>,
588 ty::PolyTraitRef<'gcx>,
589 ty::ExistentialTraitRef<'gcx>
592 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
593 fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self {
595 LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx) },
596 LvalueTy::Downcast { adt_def, substs, variant_index } => {
599 substs: substs.trans_normalize(infcx),
600 variant_index: variant_index
607 // NOTE: Callable from trans only!
608 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
609 /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
610 /// each time we erase them in translation, we need to normalize
612 pub fn erase_late_bound_regions_and_normalize<T>(self, value: &ty::Binder<T>)
614 where T: TransNormalize<'tcx>
616 assert!(!value.needs_subst());
617 let value = self.erase_late_bound_regions(value);
618 self.normalize_associated_type(&value)
621 pub fn normalize_associated_type<T>(self, value: &T) -> T
622 where T: TransNormalize<'tcx>
624 debug!("normalize_associated_type(t={:?})", value);
626 let value = self.erase_regions(value);
628 if !value.has_projection_types() {
632 self.infer_ctxt(Reveal::All).enter(|infcx| {
633 value.trans_normalize(&infcx)
637 /// Does a best-effort to normalize any associated types in
638 /// `value`; this includes revealing specializable types, so this
639 /// should be not be used during type-checking, but only during
640 /// optimization and code generation.
641 pub fn normalize_associated_type_in_env<T>(
642 self, value: &T, env: ty::ParamEnv<'tcx>
644 where T: TransNormalize<'tcx>
646 debug!("normalize_associated_type_in_env(t={:?})", value);
648 let value = self.erase_regions(value);
650 if !value.has_projection_types() {
654 self.infer_ctxt(env.reveal_all()).enter(|infcx| {
655 value.trans_normalize(&infcx)
660 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
661 fn normalize_projections_in<T>(&self, value: &T) -> T::Lifted
662 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
664 let mut selcx = traits::SelectionContext::new(self);
665 let cause = traits::ObligationCause::dummy();
666 let traits::Normalized { value: result, obligations } =
667 traits::normalize(&mut selcx, cause, value);
669 debug!("normalize_projections_in: result={:?} obligations={:?}",
670 result, obligations);
672 let mut fulfill_cx = traits::FulfillmentContext::new();
674 for obligation in obligations {
675 fulfill_cx.register_predicate_obligation(self, obligation);
678 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
681 /// Finishes processes any obligations that remain in the
682 /// fulfillment context, and then returns the result with all type
683 /// variables removed and regions erased. Because this is intended
684 /// for use after type-check has completed, if any errors occur,
685 /// it will panic. It is used during normalization and other cases
686 /// where processing the obligations in `fulfill_cx` may cause
687 /// type inference variables that appear in `result` to be
688 /// unified, and hence we need to process those obligations to get
689 /// the complete picture of the type.
690 pub fn drain_fulfillment_cx_or_panic<T>(&self,
692 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
695 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
697 debug!("drain_fulfillment_cx_or_panic()");
699 // In principle, we only need to do this so long as `result`
700 // contains unbound type parameters. It could be a slight
701 // optimization to stop iterating early.
702 match fulfill_cx.select_all_or_error(self) {
705 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
710 let result = self.resolve_type_vars_if_possible(result);
711 let result = self.tcx.erase_regions(&result);
713 match self.tcx.lift_to_global(&result) {
714 Some(result) => result,
716 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
721 pub fn is_in_snapshot(&self) -> bool {
722 self.in_snapshot.get()
725 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
726 t.fold_with(&mut self.freshener())
729 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
731 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
736 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
737 freshen::TypeFreshener::new(self)
740 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
741 use ty::error::UnconstrainedNumeric::Neither;
742 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
744 ty::TyInfer(ty::IntVar(vid)) => {
745 if self.int_unification_table.borrow_mut().has_value(vid) {
751 ty::TyInfer(ty::FloatVar(vid)) => {
752 if self.float_unification_table.borrow_mut().has_value(vid) {
762 /// Returns a type variable's default fallback if any exists. A default
763 /// must be attached to the variable when created, if it is created
764 /// without a default, this will return None.
766 /// This code does not apply to integral or floating point variables,
767 /// only to use declared defaults.
769 /// See `new_ty_var_with_default` to create a type variable with a default.
770 /// See `type_variable::Default` for details about what a default entails.
771 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
773 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
778 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
779 let mut variables = Vec::new();
781 let unbound_ty_vars = self.type_variables
783 .unsolved_variables()
785 .map(|t| self.tcx.mk_var(t));
787 let unbound_int_vars = self.int_unification_table
789 .unsolved_variables()
791 .map(|v| self.tcx.mk_int_var(v));
793 let unbound_float_vars = self.float_unification_table
795 .unsolved_variables()
797 .map(|v| self.tcx.mk_float_var(v));
799 variables.extend(unbound_ty_vars);
800 variables.extend(unbound_int_vars);
801 variables.extend(unbound_float_vars);
806 fn combine_fields(&'a self, trace: TypeTrace<'tcx>)
807 -> CombineFields<'a, 'gcx, 'tcx> {
812 obligations: PredicateObligations::new(),
816 pub fn equate<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
817 -> InferResult<'tcx, T>
818 where T: Relate<'tcx>
820 let mut fields = self.combine_fields(trace);
821 let result = fields.equate(a_is_expected).relate(a, b);
822 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
825 pub fn sub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
826 -> InferResult<'tcx, T>
827 where T: Relate<'tcx>
829 let mut fields = self.combine_fields(trace);
830 let result = fields.sub(a_is_expected).relate(a, b);
831 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
834 pub fn lub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
835 -> InferResult<'tcx, T>
836 where T: Relate<'tcx>
838 let mut fields = self.combine_fields(trace);
839 let result = fields.lub(a_is_expected).relate(a, b);
840 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
843 pub fn glb<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
844 -> InferResult<'tcx, T>
845 where T: Relate<'tcx>
847 let mut fields = self.combine_fields(trace);
848 let result = fields.glb(a_is_expected).relate(a, b);
849 result.map(move |t| InferOk { value: t, obligations: fields.obligations })
852 // Clear the "currently in a snapshot" flag, invoke the closure,
853 // then restore the flag to its original value. This flag is a
854 // debugging measure designed to detect cases where we start a
855 // snapshot, create type variables, and register obligations
856 // which may involve those type variables in the fulfillment cx,
857 // potentially leaving "dangling type variables" behind.
858 // In such cases, an assertion will fail when attempting to
859 // register obligations, within a snapshot. Very useful, much
860 // better than grovelling through megabytes of RUST_LOG output.
862 // HOWEVER, in some cases the flag is unhelpful. In particular, we
863 // sometimes create a "mini-fulfilment-cx" in which we enroll
864 // obligations. As long as this fulfillment cx is fully drained
865 // before we return, this is not a problem, as there won't be any
866 // escaping obligations in the main cx. In those cases, you can
867 // use this function.
868 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
869 where F: FnOnce(&Self) -> R
871 let flag = self.in_snapshot.get();
872 self.in_snapshot.set(false);
873 let result = func(self);
874 self.in_snapshot.set(flag);
878 fn start_snapshot<'b>(&'b self) -> CombinedSnapshot<'b, 'tcx> {
879 debug!("start_snapshot()");
881 let in_snapshot = self.in_snapshot.get();
882 self.in_snapshot.set(true);
885 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
886 type_snapshot: self.type_variables.borrow_mut().snapshot(),
887 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
888 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
889 region_vars_snapshot: self.region_vars.start_snapshot(),
890 was_in_snapshot: in_snapshot,
891 // Borrow tables "in progress" (i.e. during typeck)
892 // to ban writes from within a snapshot to them.
893 _in_progress_tables: match self.tables {
894 InferTables::InProgress(ref tables) => tables.try_borrow().ok(),
900 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
901 debug!("rollback_to(cause={})", cause);
902 let CombinedSnapshot { projection_cache_snapshot,
906 region_vars_snapshot,
908 _in_progress_tables } = snapshot;
910 self.in_snapshot.set(was_in_snapshot);
912 self.projection_cache
914 .rollback_to(projection_cache_snapshot);
917 .rollback_to(type_snapshot);
918 self.int_unification_table
920 .rollback_to(int_snapshot);
921 self.float_unification_table
923 .rollback_to(float_snapshot);
925 .rollback_to(region_vars_snapshot);
928 fn commit_from(&self, snapshot: CombinedSnapshot) {
929 debug!("commit_from()");
930 let CombinedSnapshot { projection_cache_snapshot,
934 region_vars_snapshot,
936 _in_progress_tables } = snapshot;
938 self.in_snapshot.set(was_in_snapshot);
940 self.projection_cache
942 .commit(projection_cache_snapshot);
945 .commit(type_snapshot);
946 self.int_unification_table
948 .commit(int_snapshot);
949 self.float_unification_table
951 .commit(float_snapshot);
953 .commit(region_vars_snapshot);
956 /// Execute `f` and commit the bindings
957 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
961 let snapshot = self.start_snapshot();
963 self.commit_from(snapshot);
967 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
968 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
969 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
971 debug!("commit_if_ok()");
972 let snapshot = self.start_snapshot();
973 let r = f(&snapshot);
974 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
976 Ok(_) => { self.commit_from(snapshot); }
977 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
982 // Execute `f` in a snapshot, and commit the bindings it creates
983 pub fn in_snapshot<T, F>(&self, f: F) -> T where
984 F: FnOnce(&CombinedSnapshot) -> T
986 debug!("in_snapshot()");
987 let snapshot = self.start_snapshot();
988 let r = f(&snapshot);
989 self.commit_from(snapshot);
993 /// Execute `f` then unroll any bindings it creates
994 pub fn probe<R, F>(&self, f: F) -> R where
995 F: FnOnce(&CombinedSnapshot) -> R,
998 let snapshot = self.start_snapshot();
999 let r = f(&snapshot);
1000 self.rollback_to("probe", snapshot);
1004 pub fn add_given(&self,
1005 sub: ty::Region<'tcx>,
1008 self.region_vars.add_given(sub, sup);
1011 pub fn sub_types(&self,
1012 a_is_expected: bool,
1013 cause: &ObligationCause<'tcx>,
1016 -> InferResult<'tcx, ()>
1018 debug!("sub_types({:?} <: {:?})", a, b);
1019 self.commit_if_ok(|_| {
1020 let trace = TypeTrace::types(cause, a_is_expected, a, b);
1021 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1025 pub fn can_sub_types(&self,
1031 let origin = &ObligationCause::dummy();
1032 let trace = TypeTrace::types(origin, true, a, b);
1033 self.sub(true, trace, &a, &b).map(|InferOk { obligations: _, .. }| {
1034 // Ignore obligations, since we are unrolling
1035 // everything anyway.
1040 pub fn eq_types(&self,
1041 a_is_expected: bool,
1042 cause: &ObligationCause<'tcx>,
1045 -> InferResult<'tcx, ()>
1047 self.commit_if_ok(|_| {
1048 let trace = TypeTrace::types(cause, a_is_expected, a, b);
1049 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1053 pub fn eq_trait_refs(&self,
1054 a_is_expected: bool,
1055 cause: &ObligationCause<'tcx>,
1056 a: ty::TraitRef<'tcx>,
1057 b: ty::TraitRef<'tcx>)
1058 -> InferResult<'tcx, ()>
1060 debug!("eq_trait_refs({:?} = {:?})", a, b);
1061 self.commit_if_ok(|_| {
1062 let trace = TypeTrace {
1063 cause: cause.clone(),
1064 values: TraitRefs(ExpectedFound::new(a_is_expected, a, b))
1066 self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1070 pub fn eq_impl_headers(&self,
1071 a_is_expected: bool,
1072 cause: &ObligationCause<'tcx>,
1073 a: &ty::ImplHeader<'tcx>,
1074 b: &ty::ImplHeader<'tcx>)
1075 -> InferResult<'tcx, ()>
1077 debug!("eq_impl_header({:?} = {:?})", a, b);
1078 match (a.trait_ref, b.trait_ref) {
1079 (Some(a_ref), Some(b_ref)) => self.eq_trait_refs(a_is_expected, cause, a_ref, b_ref),
1080 (None, None) => self.eq_types(a_is_expected, cause, a.self_ty, b.self_ty),
1081 _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
1085 pub fn sub_poly_trait_refs(&self,
1086 a_is_expected: bool,
1087 cause: ObligationCause<'tcx>,
1088 a: ty::PolyTraitRef<'tcx>,
1089 b: ty::PolyTraitRef<'tcx>)
1090 -> InferResult<'tcx, ()>
1092 debug!("sub_poly_trait_refs({:?} <: {:?})", a, b);
1093 self.commit_if_ok(|_| {
1094 let trace = TypeTrace {
1096 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b))
1098 self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1102 pub fn sub_regions(&self,
1103 origin: SubregionOrigin<'tcx>,
1104 a: ty::Region<'tcx>,
1105 b: ty::Region<'tcx>) {
1106 debug!("sub_regions({:?} <: {:?})", a, b);
1107 self.region_vars.make_subregion(origin, a, b);
1110 pub fn equality_predicate(&self,
1111 cause: &ObligationCause<'tcx>,
1112 predicate: &ty::PolyEquatePredicate<'tcx>)
1113 -> InferResult<'tcx, ()>
1115 self.commit_if_ok(|snapshot| {
1116 let (ty::EquatePredicate(a, b), skol_map) =
1117 self.skolemize_late_bound_regions(predicate, snapshot);
1118 let cause_span = cause.span;
1119 let eqty_ok = self.eq_types(false, cause, a, b)?;
1120 self.leak_check(false, cause_span, &skol_map, snapshot)?;
1121 self.pop_skolemized(skol_map, snapshot);
1126 pub fn subtype_predicate(&self,
1127 cause: &ObligationCause<'tcx>,
1128 predicate: &ty::PolySubtypePredicate<'tcx>)
1129 -> Option<InferResult<'tcx, ()>>
1131 // Subtle: it's ok to skip the binder here and resolve because
1132 // `shallow_resolve` just ignores anything that is not a type
1133 // variable, and because type variable's can't (at present, at
1134 // least) capture any of the things bound by this binder.
1136 // Really, there is no *particular* reason to do this
1137 // `shallow_resolve` here except as a
1138 // micro-optimization. Naturally I could not
1139 // resist. -nmatsakis
1140 let two_unbound_type_vars = {
1141 let a = self.shallow_resolve(predicate.skip_binder().a);
1142 let b = self.shallow_resolve(predicate.skip_binder().b);
1143 a.is_ty_var() && b.is_ty_var()
1146 if two_unbound_type_vars {
1147 // Two unbound type variables? Can't make progress.
1151 Some(self.commit_if_ok(|snapshot| {
1152 let (ty::SubtypePredicate { a_is_expected, a, b}, skol_map) =
1153 self.skolemize_late_bound_regions(predicate, snapshot);
1155 let cause_span = cause.span;
1156 let ok = self.sub_types(a_is_expected, cause, a, b)?;
1157 self.leak_check(false, cause_span, &skol_map, snapshot)?;
1158 self.pop_skolemized(skol_map, snapshot);
1163 pub fn region_outlives_predicate(&self,
1164 cause: &traits::ObligationCause<'tcx>,
1165 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1168 self.commit_if_ok(|snapshot| {
1169 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1170 self.skolemize_late_bound_regions(predicate, snapshot);
1172 SubregionOrigin::from_obligation_cause(cause,
1173 || RelateRegionParamBound(cause.span));
1174 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1175 self.leak_check(false, cause.span, &skol_map, snapshot)?;
1176 Ok(self.pop_skolemized(skol_map, snapshot))
1180 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1183 .new_var(diverging, origin, None)
1186 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1187 self.tcx.mk_var(self.next_ty_var_id(false, origin))
1190 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1191 self.tcx.mk_var(self.next_ty_var_id(true, origin))
1194 pub fn next_int_var_id(&self) -> IntVid {
1195 self.int_unification_table
1200 pub fn next_float_var_id(&self) -> FloatVid {
1201 self.float_unification_table
1206 pub fn next_region_var(&self, origin: RegionVariableOrigin)
1207 -> ty::Region<'tcx> {
1208 self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
1211 /// Create a region inference variable for the given
1212 /// region parameter definition.
1213 pub fn region_var_for_def(&self,
1215 def: &ty::RegionParameterDef)
1216 -> ty::Region<'tcx> {
1217 self.next_region_var(EarlyBoundRegion(span, def.name, def.issue_32330))
1220 /// Create a type inference variable for the given
1221 /// type parameter definition. The substitutions are
1222 /// for actual parameters that may be referred to by
1223 /// the default of this type parameter, if it exists.
1224 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1225 /// used in a path such as `Foo::<T, U>::new()` will
1226 /// use an inference variable for `C` with `[T, U]`
1227 /// as the substitutions for the default, `(T, U)`.
1228 pub fn type_var_for_def(&self,
1230 def: &ty::TypeParameterDef,
1231 substs: &[Kind<'tcx>])
1233 let default = if def.has_default {
1234 let default = self.tcx.type_of(def.def_id);
1235 Some(type_variable::Default {
1236 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1245 let ty_var_id = self.type_variables
1248 TypeVariableOrigin::TypeParameterDefinition(span, def.name),
1251 self.tcx.mk_var(ty_var_id)
1254 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1255 /// type/region parameter to a fresh inference variable.
1256 pub fn fresh_substs_for_item(&self,
1259 -> &'tcx Substs<'tcx> {
1260 Substs::for_item(self.tcx, def_id, |def, _| {
1261 self.region_var_for_def(span, def)
1263 self.type_var_for_def(span, def, substs)
1267 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region<'tcx> {
1268 self.region_vars.new_bound(debruijn)
1271 /// True if errors have been reported since this infcx was
1272 /// created. This is sometimes used as a heuristic to skip
1273 /// reporting errors that often occur as a result of earlier
1274 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1275 /// inference variables, regionck errors).
1276 pub fn is_tainted_by_errors(&self) -> bool {
1277 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1278 tainted_by_errors_flag={})",
1279 self.tcx.sess.err_count(),
1280 self.err_count_on_creation,
1281 self.tainted_by_errors_flag.get());
1283 if self.tcx.sess.err_count() > self.err_count_on_creation {
1284 return true; // errors reported since this infcx was made
1286 self.tainted_by_errors_flag.get()
1289 /// Set the "tainted by errors" flag to true. We call this when we
1290 /// observe an error from a prior pass.
1291 pub fn set_tainted_by_errors(&self) {
1292 debug!("set_tainted_by_errors()");
1293 self.tainted_by_errors_flag.set(true)
1296 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1297 match self.tables.borrow().node_types.get(&id) {
1300 None if self.is_tainted_by_errors() =>
1303 bug!("no type for node {}: {} in fcx",
1304 id, self.tcx.hir.node_to_string(id));
1309 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1310 match self.tables.borrow().node_types.get(&ex.id) {
1313 bug!("no type for expr in fcx");
1318 pub fn resolve_regions_and_report_errors(&self,
1319 region_context: DefId,
1320 region_map: &RegionMaps,
1321 free_regions: &FreeRegionMap<'tcx>) {
1322 let region_rels = RegionRelations::new(self.tcx,
1326 let errors = self.region_vars.resolve_regions(®ion_rels);
1327 if !self.is_tainted_by_errors() {
1328 // As a heuristic, just skip reporting region errors
1329 // altogether if other errors have been reported while
1330 // this infcx was in use. This is totally hokey but
1331 // otherwise we have a hard time separating legit region
1332 // errors from silly ones.
1333 self.report_region_errors(&errors); // see error_reporting module
1337 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1338 self.resolve_type_vars_if_possible(&t).to_string()
1341 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1342 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1343 format!("({})", tstrs.join(", "))
1346 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1347 self.resolve_type_vars_if_possible(t).to_string()
1350 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1352 ty::TyInfer(ty::TyVar(v)) => {
1353 // Not entirely obvious: if `typ` is a type variable,
1354 // it can be resolved to an int/float variable, which
1355 // can then be recursively resolved, hence the
1356 // recursion. Note though that we prevent type
1357 // variables from unifying to other type variables
1358 // directly (though they may be embedded
1359 // structurally), and we prevent cycles in any case,
1360 // so this recursion should always be of very limited
1362 self.type_variables.borrow_mut()
1364 .map(|t| self.shallow_resolve(t))
1368 ty::TyInfer(ty::IntVar(v)) => {
1369 self.int_unification_table
1372 .map(|v| v.to_type(self.tcx))
1376 ty::TyInfer(ty::FloatVar(v)) => {
1377 self.float_unification_table
1380 .map(|v| v.to_type(self.tcx))
1390 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1391 where T: TypeFoldable<'tcx>
1394 * Where possible, replaces type/int/float variables in
1395 * `value` with their final value. Note that region variables
1396 * are unaffected. If a type variable has not been unified, it
1397 * is left as is. This is an idempotent operation that does
1398 * not affect inference state in any way and so you can do it
1402 if !value.needs_infer() {
1403 return value.clone(); // avoid duplicated subst-folding
1405 let mut r = resolve::OpportunisticTypeResolver::new(self);
1406 value.fold_with(&mut r)
1409 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1410 where T: TypeFoldable<'tcx>
1412 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1413 value.fold_with(&mut r)
1416 /// Resolves all type variables in `t` and then, if any were left
1417 /// unresolved, substitutes an error type. This is used after the
1418 /// main checking when doing a second pass before writeback. The
1419 /// justification is that writeback will produce an error for
1420 /// these unconstrained type variables.
1421 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1422 let ty = self.resolve_type_vars_if_possible(t);
1423 if ty.references_error() || ty.is_ty_var() {
1424 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1431 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1433 * Attempts to resolve all type/region variables in
1434 * `value`. Region inference must have been run already (e.g.,
1435 * by calling `resolve_regions_and_report_errors`). If some
1436 * variable was never unified, an `Err` results.
1438 * This method is idempotent, but it not typically not invoked
1439 * except during the writeback phase.
1442 resolve::fully_resolve(self, value)
1445 // [Note-Type-error-reporting]
1446 // An invariant is that anytime the expected or actual type is TyError (the special
1447 // error type, meaning that an error occurred when typechecking this expression),
1448 // this is a derived error. The error cascaded from another error (that was already
1449 // reported), so it's not useful to display it to the user.
1450 // The following methods implement this logic.
1451 // They check if either the actual or expected type is TyError, and don't print the error
1452 // in this case. The typechecker should only ever report type errors involving mismatched
1453 // types using one of these methods, and should not call span_err directly for such
1456 pub fn type_error_message<M>(&self,
1459 actual_ty: Ty<'tcx>)
1460 where M: FnOnce(String) -> String,
1462 self.type_error_struct(sp, mk_msg, actual_ty).emit();
1465 // FIXME: this results in errors without an error code. Deprecate?
1466 pub fn type_error_struct<M>(&self,
1469 actual_ty: Ty<'tcx>)
1470 -> DiagnosticBuilder<'tcx>
1471 where M: FnOnce(String) -> String,
1473 self.type_error_struct_with_diag(sp, |actual_ty| {
1474 self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1478 pub fn type_error_struct_with_diag<M>(&self,
1481 actual_ty: Ty<'tcx>)
1482 -> DiagnosticBuilder<'tcx>
1483 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1485 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1486 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1488 // Don't report an error if actual type is TyError.
1489 if actual_ty.references_error() {
1490 return self.tcx.sess.diagnostic().struct_dummy();
1493 mk_diag(self.ty_to_string(actual_ty))
1496 pub fn report_mismatched_types(&self,
1497 cause: &ObligationCause<'tcx>,
1500 err: TypeError<'tcx>)
1501 -> DiagnosticBuilder<'tcx> {
1502 let trace = TypeTrace::types(cause, true, expected, actual);
1503 self.report_and_explain_type_error(trace, &err)
1506 pub fn report_conflicting_default_types(&self,
1508 body_id: ast::NodeId,
1509 expected: type_variable::Default<'tcx>,
1510 actual: type_variable::Default<'tcx>) {
1511 let trace = TypeTrace {
1512 cause: ObligationCause::misc(span, body_id),
1513 values: Types(ExpectedFound {
1514 expected: expected.ty,
1519 self.report_and_explain_type_error(
1521 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1528 pub fn replace_late_bound_regions_with_fresh_var<T>(
1531 lbrct: LateBoundRegionConversionTime,
1532 value: &ty::Binder<T>)
1533 -> (T, FxHashMap<ty::BoundRegion, ty::Region<'tcx>>)
1534 where T : TypeFoldable<'tcx>
1536 self.tcx.replace_late_bound_regions(
1538 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1541 /// Given a higher-ranked projection predicate like:
1543 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1545 /// and a target trait-ref like:
1547 /// <T as Fn<&'x u32>>
1549 /// find a substitution `S` for the higher-ranked regions (here,
1550 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1551 /// and then return the value (here, `&'a u32`) but with the
1552 /// substitution applied (hence, `&'x u32`).
1554 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1556 pub fn match_poly_projection_predicate(&self,
1557 cause: ObligationCause<'tcx>,
1558 match_a: ty::PolyProjectionPredicate<'tcx>,
1559 match_b: ty::TraitRef<'tcx>)
1560 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1562 let span = cause.span;
1563 let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1564 let trace = TypeTrace {
1566 values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1569 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1570 let mut combine = self.combine_fields(trace);
1571 let result = combine.higher_ranked_match(span, &match_pair, &match_b, true)?;
1572 Ok(InferOk { value: result, obligations: combine.obligations })
1575 /// See `verify_generic_bound` method in `region_inference`
1576 pub fn verify_generic_bound(&self,
1577 origin: SubregionOrigin<'tcx>,
1578 kind: GenericKind<'tcx>,
1579 a: ty::Region<'tcx>,
1580 bound: VerifyBound<'tcx>) {
1581 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1586 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1589 pub fn can_equate<T>(&self, a: &T, b: &T) -> UnitResult<'tcx>
1590 where T: Relate<'tcx> + fmt::Debug
1592 debug!("can_equate({:?}, {:?})", a, b);
1594 // Gin up a dummy trace, since this won't be committed
1595 // anyhow. We should make this typetrace stuff more
1596 // generic so we don't have to do anything quite this
1598 let trace = TypeTrace::dummy(self.tcx);
1599 self.equate(true, trace, a, b).map(|InferOk { obligations: _, .. }| {
1600 // We can intentionally ignore obligations here, since
1601 // this is part of a simple test for general
1602 // "equatability". However, it's not entirely clear
1603 // that we *ought* to be, perhaps a better thing would
1604 // be to use a mini-fulfillment context or something
1610 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1611 let ty = self.node_type(id);
1612 self.resolve_type_vars_or_error(&ty)
1615 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1616 let ty = self.tables.borrow().expr_ty_adjusted(expr);
1617 self.resolve_type_vars_or_error(&ty)
1620 pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1621 let ty = self.resolve_type_vars_if_possible(&ty);
1622 if let Some(ty) = self.tcx.lift_to_global(&ty) {
1623 // Even if the type may have no inference variables, during
1624 // type-checking closure types are in local tables only.
1625 let local_closures = match self.tables {
1626 InferTables::InProgress(_) => ty.has_closure_types(),
1629 if !local_closures {
1630 return ty.moves_by_default(self.tcx.global_tcx(), self.param_env(), span);
1634 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1636 // this can get called from typeck (by euv), and moves_by_default
1637 // rightly refuses to work with inference variables, but
1638 // moves_by_default has a cache, which we want to use in other
1640 !traits::type_known_to_meet_bound(self, ty, copy_def_id, span)
1643 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
1644 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1647 pub fn param_env(&self) -> ty::ParamEnv<'gcx> {
1651 pub fn closure_kind(&self,
1653 -> Option<ty::ClosureKind>
1655 if let InferTables::InProgress(tables) = self.tables {
1656 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1657 return tables.borrow()
1661 .map(|(kind, _)| kind);
1665 // During typeck, ALL closures are local. But afterwards,
1666 // during trans, we see closure ids from other traits.
1667 // That may require loading the closure data out of the
1669 Some(self.tcx.closure_kind(def_id))
1672 pub fn closure_type(&self, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1673 if let InferTables::InProgress(tables) = self.tables {
1674 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1675 if let Some(&ty) = tables.borrow().closure_tys.get(&id) {
1681 self.tcx.closure_type(def_id)
1685 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1686 pub fn span(&self) -> Span {
1690 pub fn types(cause: &ObligationCause<'tcx>,
1691 a_is_expected: bool,
1694 -> TypeTrace<'tcx> {
1696 cause: cause.clone(),
1697 values: Types(ExpectedFound::new(a_is_expected, a, b))
1701 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1703 cause: ObligationCause::dummy(),
1704 values: Types(ExpectedFound {
1705 expected: tcx.types.err,
1706 found: tcx.types.err,
1712 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1713 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1714 write!(f, "TypeTrace({:?})", self.cause)
1718 impl<'tcx> SubregionOrigin<'tcx> {
1719 pub fn span(&self) -> Span {
1721 Subtype(ref a) => a.span(),
1722 InfStackClosure(a) => a,
1723 InvokeClosure(a) => a,
1724 DerefPointer(a) => a,
1725 FreeVariable(a, _) => a,
1727 RelateObjectBound(a) => a,
1728 RelateParamBound(a, _) => a,
1729 RelateRegionParamBound(a) => a,
1730 RelateDefaultParamBound(a, _) => a,
1732 ReborrowUpvar(a, _) => a,
1733 DataBorrowed(_, a) => a,
1734 ReferenceOutlivesReferent(_, a) => a,
1735 ParameterInScope(_, a) => a,
1736 ExprTypeIsNotInScope(_, a) => a,
1737 BindingTypeIsNotValidAtDecl(a) => a,
1744 SafeDestructor(a) => a,
1745 CompareImplMethodObligation { span, .. } => span,
1749 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>,
1752 where F: FnOnce() -> Self
1755 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
1756 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span),
1758 traits::ObligationCauseCode::CompareImplMethodObligation { item_name,
1762 SubregionOrigin::CompareImplMethodObligation {
1764 item_name: item_name,
1765 impl_item_def_id: impl_item_def_id,
1766 trait_item_def_id: trait_item_def_id,
1775 impl RegionVariableOrigin {
1776 pub fn span(&self) -> Span {
1778 MiscVariable(a) => a,
1779 PatternRegion(a) => a,
1780 AddrOfRegion(a) => a,
1783 EarlyBoundRegion(a, ..) => a,
1784 LateBoundRegion(a, ..) => a,
1785 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1786 UpvarRegion(_, a) => a
1791 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1792 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1794 ValuePairs::Types(ref ef) => {
1795 ValuePairs::Types(ef.fold_with(folder))
1797 ValuePairs::TraitRefs(ref ef) => {
1798 ValuePairs::TraitRefs(ef.fold_with(folder))
1800 ValuePairs::PolyTraitRefs(ref ef) => {
1801 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1806 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1808 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1809 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1810 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1815 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1816 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1818 cause: self.cause.fold_with(folder),
1819 values: self.values.fold_with(folder)
1823 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1824 self.cause.visit_with(visitor) || self.values.visit_with(visitor)