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
;
20 use hir
::def_id
::DefId
;
21 use middle
::free_region
::RegionRelations
;
23 use middle
::lang_items
;
24 use mir
::tcx
::PlaceTy
;
25 use ty
::subst
::{Kind, Subst, Substs}
;
26 use ty
::{TyVid, IntVid, FloatVid}
;
27 use ty
::{self, Ty, TyCtxt}
;
28 use ty
::error
::{ExpectedFound, TypeError, UnconstrainedNumeric}
;
29 use ty
::fold
::{TypeFoldable, TypeFolder, TypeVisitor}
;
30 use ty
::relate
::RelateResult
;
31 use traits
::{self, ObligationCause, PredicateObligations, Reveal}
;
32 use rustc_data_structures
::unify
::{self, UnificationTable}
;
33 use std
::cell
::{Cell, RefCell, Ref, RefMut}
;
34 use std
::collections
::BTreeMap
;
37 use errors
::DiagnosticBuilder
;
38 use syntax_pos
::{self, Span, DUMMY_SP}
;
39 use util
::nodemap
::FxHashMap
;
40 use arena
::DroplessArena
;
42 use self::combine
::CombineFields
;
43 use self::higher_ranked
::HrMatchResult
;
44 use self::region_constraints
::{RegionConstraintCollector, RegionSnapshot}
;
45 use self::region_constraints
::{GenericKind, VerifyBound, RegionConstraintData, VarOrigins}
;
46 use self::lexical_region_resolve
::LexicalRegionResolutions
;
47 use self::outlives
::env
::OutlivesEnvironment
;
48 use self::type_variable
::TypeVariableOrigin
;
49 use self::unify_key
::ToType
;
55 pub mod error_reporting
;
61 pub mod region_constraints
;
62 mod lexical_region_resolve
;
67 pub mod type_variable
;
71 pub struct InferOk
<'tcx
, T
> {
73 pub obligations
: PredicateObligations
<'tcx
>,
75 pub type InferResult
<'tcx
, T
> = Result
<InferOk
<'tcx
, T
>, TypeError
<'tcx
>>;
77 pub type Bound
<T
> = Option
<T
>;
78 pub type UnitResult
<'tcx
> = RelateResult
<'tcx
, ()>; // "unify result"
79 pub type FixupResult
<T
> = Result
<T
, FixupError
>; // "fixup result"
81 pub struct InferCtxt
<'a
, 'gcx
: 'a
+'tcx
, 'tcx
: 'a
> {
82 pub tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>,
84 /// During type-checking/inference of a body, `in_progress_tables`
85 /// contains a reference to the tables being built up, which are
86 /// used for reading closure kinds/signatures as they are inferred,
87 /// and for error reporting logic to read arbitrary node types.
88 pub in_progress_tables
: Option
<&'a RefCell
<ty
::TypeckTables
<'tcx
>>>,
90 // Cache for projections. This cache is snapshotted along with the
93 // Public so that `traits::project` can use it.
94 pub projection_cache
: RefCell
<traits
::ProjectionCache
<'tcx
>>,
96 // We instantiate UnificationTable with bounds<Ty> because the
97 // types that might instantiate a general type variable have an
98 // order, represented by its upper and lower bounds.
99 pub type_variables
: RefCell
<type_variable
::TypeVariableTable
<'tcx
>>,
101 // Map from integral variable to the kind of integer it represents
102 int_unification_table
: RefCell
<UnificationTable
<ty
::IntVid
>>,
104 // Map from floating variable to the kind of float it represents
105 float_unification_table
: RefCell
<UnificationTable
<ty
::FloatVid
>>,
107 // Tracks the set of region variables and the constraints between
108 // them. This is initially `Some(_)` but when
109 // `resolve_regions_and_report_errors` is invoked, this gets set
110 // to `None` -- further attempts to perform unification etc may
111 // fail if new region constraints would've been added.
112 region_constraints
: RefCell
<Option
<RegionConstraintCollector
<'tcx
>>>,
114 // Once region inference is done, the values for each variable.
115 lexical_region_resolutions
: RefCell
<Option
<LexicalRegionResolutions
<'tcx
>>>,
117 /// Caches the results of trait selection. This cache is used
118 /// for things that have to do with the parameters in scope.
119 pub selection_cache
: traits
::SelectionCache
<'tcx
>,
121 /// Caches the results of trait evaluation.
122 pub evaluation_cache
: traits
::EvaluationCache
<'tcx
>,
124 // the set of predicates on which errors have been reported, to
125 // avoid reporting the same error twice.
126 pub reported_trait_errors
: RefCell
<FxHashMap
<Span
, Vec
<ty
::Predicate
<'tcx
>>>>,
128 // When an error occurs, we want to avoid reporting "derived"
129 // errors that are due to this original failure. Normally, we
130 // handle this with the `err_count_on_creation` count, which
131 // basically just tracks how many errors were reported when we
132 // started type-checking a fn and checks to see if any new errors
133 // have been reported since then. Not great, but it works.
135 // However, when errors originated in other passes -- notably
136 // resolve -- this heuristic breaks down. Therefore, we have this
137 // auxiliary flag that one can set whenever one creates a
138 // type-error that is due to an error in a prior pass.
140 // Don't read this flag directly, call `is_tainted_by_errors()`
141 // and `set_tainted_by_errors()`.
142 tainted_by_errors_flag
: Cell
<bool
>,
144 // Track how many errors were reported when this infcx is created.
145 // If the number of errors increases, that's also a sign (line
146 // `tained_by_errors`) to avoid reporting certain kinds of errors.
147 err_count_on_creation
: usize,
149 // This flag is true while there is an active snapshot.
150 in_snapshot
: Cell
<bool
>,
152 // A set of constraints that regionck must validate. Each
153 // constraint has the form `T:'a`, meaning "some type `T` must
154 // outlive the lifetime 'a". These constraints derive from
155 // instantiated type parameters. So if you had a struct defined
158 // struct Foo<T:'static> { ... }
160 // then in some expression `let x = Foo { ... }` it will
161 // instantiate the type parameter `T` with a fresh type `$0`. At
162 // the same time, it will record a region obligation of
163 // `$0:'static`. This will get checked later by regionck. (We
164 // can't generally check these things right away because we have
165 // to wait until types are resolved.)
167 // These are stored in a map keyed to the id of the innermost
168 // enclosing fn body / static initializer expression. This is
169 // because the location where the obligation was incurred can be
170 // relevant with respect to which sublifetime assumptions are in
171 // place. The reason that we store under the fn-id, and not
172 // something more fine-grained, is so that it is easier for
173 // regionck to be sure that it has found *all* the region
174 // obligations (otherwise, it's easy to fail to walk to a
175 // particular node-id).
177 // Before running `resolve_regions_and_report_errors`, the creator
178 // of the inference context is expected to invoke
179 // `process_region_obligations` (defined in `self::region_obligations`)
180 // for each body-id in this map, which will process the
181 // obligations within. This is expected to be done 'late enough'
182 // that all type inference variables have been bound and so forth.
183 region_obligations
: RefCell
<Vec
<(ast
::NodeId
, RegionObligation
<'tcx
>)>>,
186 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
187 /// region that each late-bound region was replaced with.
188 pub type SkolemizationMap
<'tcx
> = BTreeMap
<ty
::BoundRegion
, ty
::Region
<'tcx
>>;
190 /// See `error_reporting` module for more details
191 #[derive(Clone, Debug)]
192 pub enum ValuePairs
<'tcx
> {
193 Types(ExpectedFound
<Ty
<'tcx
>>),
194 TraitRefs(ExpectedFound
<ty
::TraitRef
<'tcx
>>),
195 PolyTraitRefs(ExpectedFound
<ty
::PolyTraitRef
<'tcx
>>),
198 /// The trace designates the path through inference that we took to
199 /// encounter an error or subtyping constraint.
201 /// See `error_reporting` module for more details.
203 pub struct TypeTrace
<'tcx
> {
204 cause
: ObligationCause
<'tcx
>,
205 values
: ValuePairs
<'tcx
>,
208 /// The origin of a `r1 <= r2` constraint.
210 /// See `error_reporting` module for more details
211 #[derive(Clone, Debug)]
212 pub enum SubregionOrigin
<'tcx
> {
213 // Arose from a subtyping relation
214 Subtype(TypeTrace
<'tcx
>),
216 // Stack-allocated closures cannot outlive innermost loop
217 // or function so as to ensure we only require finite stack
218 InfStackClosure(Span
),
220 // Invocation of closure must be within its lifetime
223 // Dereference of reference must be within its lifetime
226 // Closure bound must not outlive captured free variables
227 FreeVariable(Span
, ast
::NodeId
),
229 // Index into slice must be within its lifetime
232 // When casting `&'a T` to an `&'b Trait` object,
233 // relating `'a` to `'b`
234 RelateObjectBound(Span
),
236 // Some type parameter was instantiated with the given type,
237 // and that type must outlive some region.
238 RelateParamBound(Span
, Ty
<'tcx
>),
240 // The given region parameter was instantiated with a region
241 // that must outlive some other region.
242 RelateRegionParamBound(Span
),
244 // A bound placed on type parameters that states that must outlive
245 // the moment of their instantiation.
246 RelateDefaultParamBound(Span
, Ty
<'tcx
>),
248 // Creating a pointer `b` to contents of another reference
251 // Creating a pointer `b` to contents of an upvar
252 ReborrowUpvar(Span
, ty
::UpvarId
),
254 // Data with type `Ty<'tcx>` was borrowed
255 DataBorrowed(Ty
<'tcx
>, Span
),
257 // (&'a &'b T) where a >= b
258 ReferenceOutlivesReferent(Ty
<'tcx
>, Span
),
260 // Type or region parameters must be in scope.
261 ParameterInScope(ParameterOrigin
, Span
),
263 // The type T of an expression E must outlive the lifetime for E.
264 ExprTypeIsNotInScope(Ty
<'tcx
>, Span
),
266 // A `ref b` whose region does not enclose the decl site
267 BindingTypeIsNotValidAtDecl(Span
),
269 // Regions appearing in a method receiver must outlive method call
272 // Regions appearing in a function argument must outlive func call
275 // Region in return type of invoked fn must enclose call
278 // Operands must be in scope
281 // Region resulting from a `&` expr must enclose the `&` expr
284 // An auto-borrow that does not enclose the expr where it occurs
287 // Region constraint arriving from destructor safety
288 SafeDestructor(Span
),
290 // Comparing the signature and requirements of an impl method against
291 // the containing trait.
292 CompareImplMethodObligation
{
294 item_name
: ast
::Name
,
295 impl_item_def_id
: DefId
,
296 trait_item_def_id
: DefId
,
300 /// Places that type/region parameters can appear.
301 #[derive(Clone, Copy, Debug)]
302 pub enum ParameterOrigin
{
304 MethodCall
, // foo.bar() <-- parameters on impl providing bar()
305 OverloadedOperator
, // a + b when overloaded
306 OverloadedDeref
, // *a when overloaded
309 /// Times when we replace late-bound regions with variables:
310 #[derive(Clone, Copy, Debug)]
311 pub enum LateBoundRegionConversionTime
{
312 /// when a fn is called
315 /// when two higher-ranked types are compared
318 /// when projecting an associated type
319 AssocTypeProjection(DefId
),
322 /// Reasons to create a region inference variable
324 /// See `error_reporting` module for more details
325 #[derive(Copy, Clone, Debug)]
326 pub enum RegionVariableOrigin
{
327 // Region variables created for ill-categorized reasons,
328 // mostly indicates places in need of refactoring
331 // Regions created by a `&P` or `[...]` pattern
334 // Regions created by `&` operator
337 // Regions created as part of an autoref of a method receiver
340 // Regions created as part of an automatic coercion
343 // Region variables created as the values for early-bound regions
344 EarlyBoundRegion(Span
, ast
::Name
),
346 // Region variables created for bound regions
347 // in a function or method that is called
348 LateBoundRegion(Span
, ty
::BoundRegion
, LateBoundRegionConversionTime
),
350 UpvarRegion(ty
::UpvarId
, Span
),
352 BoundRegionInCoherence(ast
::Name
),
354 // This origin is used for the inference variables that we create
355 // during NLL region processing.
356 NLL(NLLRegionVariableOrigin
),
359 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
360 pub enum NLLRegionVariableOrigin
{
361 // During NLL region processing, we create variables for free
362 // regions that we encounter in the function signature and
363 // elsewhere. This origin indices we've got one of those.
366 Inferred(::mir
::visit
::TyContext
),
369 #[derive(Copy, Clone, Debug)]
370 pub enum FixupError
{
371 UnresolvedIntTy(IntVid
),
372 UnresolvedFloatTy(FloatVid
),
376 /// See the `region_obligations` field for more information.
378 pub struct RegionObligation
<'tcx
> {
379 pub sub_region
: ty
::Region
<'tcx
>,
380 pub sup_type
: Ty
<'tcx
>,
381 pub cause
: ObligationCause
<'tcx
>,
384 impl fmt
::Display
for FixupError
{
385 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
386 use self::FixupError
::*;
389 UnresolvedIntTy(_
) => {
390 write
!(f
, "cannot determine the type of this integer; \
391 add a suffix to specify the type explicitly")
393 UnresolvedFloatTy(_
) => {
394 write
!(f
, "cannot determine the type of this number; \
395 add a suffix to specify the type explicitly")
397 UnresolvedTy(_
) => write
!(f
, "unconstrained type")
402 /// Helper type of a temporary returned by tcx.infer_ctxt().
403 /// Necessary because we can't write the following bound:
404 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
405 pub struct InferCtxtBuilder
<'a
, 'gcx
: 'a
+'tcx
, 'tcx
: 'a
> {
406 global_tcx
: TyCtxt
<'a
, 'gcx
, 'gcx
>,
407 arena
: DroplessArena
,
408 fresh_tables
: Option
<RefCell
<ty
::TypeckTables
<'tcx
>>>,
411 impl<'a
, 'gcx
, 'tcx
> TyCtxt
<'a
, 'gcx
, 'gcx
> {
412 pub fn infer_ctxt(self) -> InferCtxtBuilder
<'a
, 'gcx
, 'tcx
> {
415 arena
: DroplessArena
::new(),
422 impl<'a
, 'gcx
, 'tcx
> InferCtxtBuilder
<'a
, 'gcx
, 'tcx
> {
423 /// Used only by `rustc_typeck` during body type-checking/inference,
424 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
425 pub fn with_fresh_in_progress_tables(mut self, table_owner
: DefId
) -> Self {
426 self.fresh_tables
= Some(RefCell
::new(ty
::TypeckTables
::empty(Some(table_owner
))));
430 pub fn enter
<F
, R
>(&'tcx
mut self, f
: F
) -> R
431 where F
: for<'b
> FnOnce(InferCtxt
<'b
, 'gcx
, 'tcx
>) -> R
433 let InferCtxtBuilder
{
438 let in_progress_tables
= fresh_tables
.as_ref();
439 global_tcx
.enter_local(arena
, |tcx
| f(InferCtxt
{
442 projection_cache
: RefCell
::new(traits
::ProjectionCache
::new()),
443 type_variables
: RefCell
::new(type_variable
::TypeVariableTable
::new()),
444 int_unification_table
: RefCell
::new(UnificationTable
::new()),
445 float_unification_table
: RefCell
::new(UnificationTable
::new()),
446 region_constraints
: RefCell
::new(Some(RegionConstraintCollector
::new())),
447 lexical_region_resolutions
: RefCell
::new(None
),
448 selection_cache
: traits
::SelectionCache
::new(),
449 evaluation_cache
: traits
::EvaluationCache
::new(),
450 reported_trait_errors
: RefCell
::new(FxHashMap()),
451 tainted_by_errors_flag
: Cell
::new(false),
452 err_count_on_creation
: tcx
.sess
.err_count(),
453 in_snapshot
: Cell
::new(false),
454 region_obligations
: RefCell
::new(vec
![]),
459 impl<T
> ExpectedFound
<T
> {
460 pub fn new(a_is_expected
: bool
, a
: T
, b
: T
) -> Self {
462 ExpectedFound {expected: a, found: b}
464 ExpectedFound {expected: b, found: a}
469 impl<'tcx
, T
> InferOk
<'tcx
, T
> {
470 pub fn unit(self) -> InferOk
<'tcx
, ()> {
471 InferOk { value: (), obligations: self.obligations }
475 #[must_use = "once you start a snapshot, you should always consume it"]
476 pub struct CombinedSnapshot
<'a
, 'tcx
:'a
> {
477 projection_cache_snapshot
: traits
::ProjectionCacheSnapshot
,
478 type_snapshot
: type_variable
::Snapshot
,
479 int_snapshot
: unify
::Snapshot
<ty
::IntVid
>,
480 float_snapshot
: unify
::Snapshot
<ty
::FloatVid
>,
481 region_constraints_snapshot
: RegionSnapshot
,
482 region_obligations_snapshot
: usize,
483 was_in_snapshot
: bool
,
484 _in_progress_tables
: Option
<Ref
<'a
, ty
::TypeckTables
<'tcx
>>>,
487 /// Helper trait for shortening the lifetimes inside a
488 /// value for post-type-checking normalization.
489 pub trait TransNormalize
<'gcx
>: TypeFoldable
<'gcx
> {
490 fn trans_normalize
<'a
, 'tcx
>(&self,
491 infcx
: &InferCtxt
<'a
, 'gcx
, 'tcx
>,
492 param_env
: ty
::ParamEnv
<'tcx
>)
496 macro_rules
! items { ($($item:item)+) => ($($item)+) }
497 macro_rules
! impl_trans_normalize
{
498 ($lt_gcx
:tt
, $
($ty
:ty
),+) => {
499 items
!($
(impl<$lt_gcx
> TransNormalize
<$lt_gcx
> for $ty
{
500 fn trans_normalize
<'a
, 'tcx
>(&self,
501 infcx
: &InferCtxt
<'a
, $lt_gcx
, 'tcx
>,
502 param_env
: ty
::ParamEnv
<'tcx
>)
504 infcx
.normalize_projections_in(param_env
, self)
510 impl_trans_normalize
!('gcx
,
512 &'gcx ty
::Const
<'gcx
>,
516 ty
::ClosureSubsts
<'gcx
>,
517 ty
::PolyTraitRef
<'gcx
>,
518 ty
::ExistentialTraitRef
<'gcx
>
521 impl<'gcx
> TransNormalize
<'gcx
> for PlaceTy
<'gcx
> {
522 fn trans_normalize
<'a
, 'tcx
>(&self,
523 infcx
: &InferCtxt
<'a
, 'gcx
, 'tcx
>,
524 param_env
: ty
::ParamEnv
<'tcx
>)
527 PlaceTy
::Ty { ty }
=> PlaceTy
::Ty { ty: ty.trans_normalize(infcx, param_env) }
,
528 PlaceTy
::Downcast { adt_def, substs, variant_index }
=> {
531 substs
: substs
.trans_normalize(infcx
, param_env
),
539 // NOTE: Callable from trans only!
540 impl<'a
, 'tcx
> TyCtxt
<'a
, 'tcx
, 'tcx
> {
541 /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
542 /// each time we erase them in translation, we need to normalize
544 pub fn erase_late_bound_regions_and_normalize
<T
>(self, value
: &ty
::Binder
<T
>)
546 where T
: TransNormalize
<'tcx
>
548 assert
!(!value
.needs_subst());
549 let value
= self.erase_late_bound_regions(value
);
550 self.fully_normalize_associated_types_in(&value
)
553 /// Fully normalizes any associated types in `value`, using an
554 /// empty environment and `Reveal::All` mode (therefore, suitable
555 /// only for monomorphized code during trans, basically).
556 pub fn fully_normalize_associated_types_in
<T
>(self, value
: &T
) -> T
557 where T
: TransNormalize
<'tcx
>
559 debug
!("fully_normalize_associated_types_in(t={:?})", value
);
561 let param_env
= ty
::ParamEnv
::empty(Reveal
::All
);
562 let value
= self.erase_regions(value
);
564 if !value
.has_projections() {
568 self.infer_ctxt().enter(|infcx
| {
569 value
.trans_normalize(&infcx
, param_env
)
573 /// Does a best-effort to normalize any associated types in
574 /// `value`; this includes revealing specializable types, so this
575 /// should be not be used during type-checking, but only during
576 /// optimization and code generation.
577 pub fn normalize_associated_type_in_env
<T
>(
578 self, value
: &T
, env
: ty
::ParamEnv
<'tcx
>
580 where T
: TransNormalize
<'tcx
>
582 debug
!("normalize_associated_type_in_env(t={:?})", value
);
584 let value
= self.erase_regions(value
);
586 if !value
.has_projections() {
590 self.infer_ctxt().enter(|infcx
| {
591 value
.trans_normalize(&infcx
, env
.reveal_all())
596 impl<'a
, 'gcx
, 'tcx
> InferCtxt
<'a
, 'gcx
, 'tcx
> {
597 fn normalize_projections_in
<T
>(&self, param_env
: ty
::ParamEnv
<'tcx
>, value
: &T
) -> T
::Lifted
598 where T
: TypeFoldable
<'tcx
> + ty
::Lift
<'gcx
>
600 let mut selcx
= traits
::SelectionContext
::new(self);
601 let cause
= traits
::ObligationCause
::dummy();
602 let traits
::Normalized { value: result, obligations }
=
603 traits
::normalize(&mut selcx
, param_env
, cause
, value
);
605 debug
!("normalize_projections_in: result={:?} obligations={:?}",
606 result
, obligations
);
608 let mut fulfill_cx
= traits
::FulfillmentContext
::new();
610 for obligation
in obligations
{
611 fulfill_cx
.register_predicate_obligation(self, obligation
);
614 self.drain_fulfillment_cx_or_panic(DUMMY_SP
, &mut fulfill_cx
, &result
)
617 /// Finishes processes any obligations that remain in the
618 /// fulfillment context, and then returns the result with all type
619 /// variables removed and regions erased. Because this is intended
620 /// for use after type-check has completed, if any errors occur,
621 /// it will panic. It is used during normalization and other cases
622 /// where processing the obligations in `fulfill_cx` may cause
623 /// type inference variables that appear in `result` to be
624 /// unified, and hence we need to process those obligations to get
625 /// the complete picture of the type.
626 pub fn drain_fulfillment_cx_or_panic
<T
>(&self,
628 fulfill_cx
: &mut traits
::FulfillmentContext
<'tcx
>,
631 where T
: TypeFoldable
<'tcx
> + ty
::Lift
<'gcx
>
633 debug
!("drain_fulfillment_cx_or_panic()");
635 // In principle, we only need to do this so long as `result`
636 // contains unbound type parameters. It could be a slight
637 // optimization to stop iterating early.
638 match fulfill_cx
.select_all_or_error(self) {
641 span_bug
!(span
, "Encountered errors `{:?}` resolving bounds after type-checking",
646 let result
= self.resolve_type_vars_if_possible(result
);
647 let result
= self.tcx
.erase_regions(&result
);
649 match self.tcx
.lift_to_global(&result
) {
650 Some(result
) => result
,
652 span_bug
!(span
, "Uninferred types/regions in `{:?}`", result
);
657 pub fn is_in_snapshot(&self) -> bool
{
658 self.in_snapshot
.get()
661 pub fn freshen
<T
:TypeFoldable
<'tcx
>>(&self, t
: T
) -> T
{
662 t
.fold_with(&mut self.freshener())
665 pub fn type_var_diverges(&'a
self, ty
: Ty
) -> bool
{
667 ty
::TyInfer(ty
::TyVar(vid
)) => self.type_variables
.borrow().var_diverges(vid
),
672 pub fn freshener
<'b
>(&'b
self) -> TypeFreshener
<'b
, 'gcx
, 'tcx
> {
673 freshen
::TypeFreshener
::new(self)
676 pub fn type_is_unconstrained_numeric(&'a
self, ty
: Ty
) -> UnconstrainedNumeric
{
677 use ty
::error
::UnconstrainedNumeric
::Neither
;
678 use ty
::error
::UnconstrainedNumeric
::{UnconstrainedInt, UnconstrainedFloat}
;
680 ty
::TyInfer(ty
::IntVar(vid
)) => {
681 if self.int_unification_table
.borrow_mut().has_value(vid
) {
687 ty
::TyInfer(ty
::FloatVar(vid
)) => {
688 if self.float_unification_table
.borrow_mut().has_value(vid
) {
698 /// Returns a type variable's default fallback if any exists. A default
699 /// must be attached to the variable when created, if it is created
700 /// without a default, this will return None.
702 /// This code does not apply to integral or floating point variables,
703 /// only to use declared defaults.
705 /// See `new_ty_var_with_default` to create a type variable with a default.
706 /// See `type_variable::Default` for details about what a default entails.
707 pub fn default(&self, ty
: Ty
<'tcx
>) -> Option
<type_variable
::Default
<'tcx
>> {
709 ty
::TyInfer(ty
::TyVar(vid
)) => self.type_variables
.borrow().default(vid
),
714 pub fn unsolved_variables(&self) -> Vec
<Ty
<'tcx
>> {
715 let mut variables
= Vec
::new();
717 let unbound_ty_vars
= self.type_variables
719 .unsolved_variables()
721 .map(|t
| self.tcx
.mk_var(t
));
723 let unbound_int_vars
= self.int_unification_table
725 .unsolved_variables()
727 .map(|v
| self.tcx
.mk_int_var(v
));
729 let unbound_float_vars
= self.float_unification_table
731 .unsolved_variables()
733 .map(|v
| self.tcx
.mk_float_var(v
));
735 variables
.extend(unbound_ty_vars
);
736 variables
.extend(unbound_int_vars
);
737 variables
.extend(unbound_float_vars
);
742 fn combine_fields(&'a
self, trace
: TypeTrace
<'tcx
>, param_env
: ty
::ParamEnv
<'tcx
>)
743 -> CombineFields
<'a
, 'gcx
, 'tcx
> {
749 obligations
: PredicateObligations
::new(),
753 // Clear the "currently in a snapshot" flag, invoke the closure,
754 // then restore the flag to its original value. This flag is a
755 // debugging measure designed to detect cases where we start a
756 // snapshot, create type variables, and register obligations
757 // which may involve those type variables in the fulfillment cx,
758 // potentially leaving "dangling type variables" behind.
759 // In such cases, an assertion will fail when attempting to
760 // register obligations, within a snapshot. Very useful, much
761 // better than grovelling through megabytes of RUST_LOG output.
763 // HOWEVER, in some cases the flag is unhelpful. In particular, we
764 // sometimes create a "mini-fulfilment-cx" in which we enroll
765 // obligations. As long as this fulfillment cx is fully drained
766 // before we return, this is not a problem, as there won't be any
767 // escaping obligations in the main cx. In those cases, you can
768 // use this function.
769 pub fn save_and_restore_in_snapshot_flag
<F
, R
>(&self, func
: F
) -> R
770 where F
: FnOnce(&Self) -> R
772 let flag
= self.in_snapshot
.get();
773 self.in_snapshot
.set(false);
774 let result
= func(self);
775 self.in_snapshot
.set(flag
);
779 fn start_snapshot
<'b
>(&'b
self) -> CombinedSnapshot
<'b
, 'tcx
> {
780 debug
!("start_snapshot()");
782 let in_snapshot
= self.in_snapshot
.get();
783 self.in_snapshot
.set(true);
786 projection_cache_snapshot
: self.projection_cache
.borrow_mut().snapshot(),
787 type_snapshot
: self.type_variables
.borrow_mut().snapshot(),
788 int_snapshot
: self.int_unification_table
.borrow_mut().snapshot(),
789 float_snapshot
: self.float_unification_table
.borrow_mut().snapshot(),
790 region_constraints_snapshot
: self.borrow_region_constraints().start_snapshot(),
791 region_obligations_snapshot
: self.region_obligations
.borrow().len(),
792 was_in_snapshot
: in_snapshot
,
793 // Borrow tables "in progress" (i.e. during typeck)
794 // to ban writes from within a snapshot to them.
795 _in_progress_tables
: self.in_progress_tables
.map(|tables
| {
801 fn rollback_to(&self, cause
: &str, snapshot
: CombinedSnapshot
) {
802 debug
!("rollback_to(cause={})", cause
);
803 let CombinedSnapshot
{ projection_cache_snapshot
,
807 region_constraints_snapshot
,
808 region_obligations_snapshot
,
810 _in_progress_tables
} = snapshot
;
812 self.in_snapshot
.set(was_in_snapshot
);
814 self.projection_cache
816 .rollback_to(projection_cache_snapshot
);
819 .rollback_to(type_snapshot
);
820 self.int_unification_table
822 .rollback_to(int_snapshot
);
823 self.float_unification_table
825 .rollback_to(float_snapshot
);
826 self.region_obligations
828 .truncate(region_obligations_snapshot
);
829 self.borrow_region_constraints()
830 .rollback_to(region_constraints_snapshot
);
833 fn commit_from(&self, snapshot
: CombinedSnapshot
) {
834 debug
!("commit_from()");
835 let CombinedSnapshot
{ projection_cache_snapshot
,
839 region_constraints_snapshot
,
840 region_obligations_snapshot
: _
,
842 _in_progress_tables
} = snapshot
;
844 self.in_snapshot
.set(was_in_snapshot
);
846 self.projection_cache
848 .commit(projection_cache_snapshot
);
851 .commit(type_snapshot
);
852 self.int_unification_table
854 .commit(int_snapshot
);
855 self.float_unification_table
857 .commit(float_snapshot
);
858 self.borrow_region_constraints()
859 .commit(region_constraints_snapshot
);
862 /// Execute `f` and commit the bindings
863 pub fn commit_unconditionally
<R
, F
>(&self, f
: F
) -> R
where
867 let snapshot
= self.start_snapshot();
869 self.commit_from(snapshot
);
873 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
874 pub fn commit_if_ok
<T
, E
, F
>(&self, f
: F
) -> Result
<T
, E
> where
875 F
: FnOnce(&CombinedSnapshot
) -> Result
<T
, E
>
877 debug
!("commit_if_ok()");
878 let snapshot
= self.start_snapshot();
879 let r
= f(&snapshot
);
880 debug
!("commit_if_ok() -- r.is_ok() = {}", r
.is_ok());
882 Ok(_
) => { self.commit_from(snapshot); }
883 Err(_
) => { self.rollback_to("commit_if_ok -- error", snapshot); }
888 // Execute `f` in a snapshot, and commit the bindings it creates
889 pub fn in_snapshot
<T
, F
>(&self, f
: F
) -> T
where
890 F
: FnOnce(&CombinedSnapshot
) -> T
892 debug
!("in_snapshot()");
893 let snapshot
= self.start_snapshot();
894 let r
= f(&snapshot
);
895 self.commit_from(snapshot
);
899 /// Execute `f` then unroll any bindings it creates
900 pub fn probe
<R
, F
>(&self, f
: F
) -> R
where
901 F
: FnOnce(&CombinedSnapshot
) -> R
,
904 let snapshot
= self.start_snapshot();
905 let r
= f(&snapshot
);
906 self.rollback_to("probe", snapshot
);
910 pub fn add_given(&self,
911 sub
: ty
::Region
<'tcx
>,
914 self.borrow_region_constraints().add_given(sub
, sup
);
917 pub fn can_sub
<T
>(&self,
918 param_env
: ty
::ParamEnv
<'tcx
>,
922 where T
: at
::ToTrace
<'tcx
>
924 let origin
= &ObligationCause
::dummy();
926 self.at(origin
, param_env
).sub(a
, b
).map(|InferOk { obligations: _, .. }
| {
927 // Ignore obligations, since we are unrolling
928 // everything anyway.
933 pub fn can_eq
<T
>(&self,
934 param_env
: ty
::ParamEnv
<'tcx
>,
938 where T
: at
::ToTrace
<'tcx
>
940 let origin
= &ObligationCause
::dummy();
942 self.at(origin
, param_env
).eq(a
, b
).map(|InferOk { obligations: _, .. }
| {
943 // Ignore obligations, since we are unrolling
944 // everything anyway.
949 pub fn sub_regions(&self,
950 origin
: SubregionOrigin
<'tcx
>,
952 b
: ty
::Region
<'tcx
>) {
953 debug
!("sub_regions({:?} <: {:?})", a
, b
);
954 self.borrow_region_constraints().make_subregion(origin
, a
, b
);
957 pub fn equality_predicate(&self,
958 cause
: &ObligationCause
<'tcx
>,
959 param_env
: ty
::ParamEnv
<'tcx
>,
960 predicate
: &ty
::PolyEquatePredicate
<'tcx
>)
961 -> InferResult
<'tcx
, ()>
963 self.commit_if_ok(|snapshot
| {
964 let (ty
::EquatePredicate(a
, b
), skol_map
) =
965 self.skolemize_late_bound_regions(predicate
, snapshot
);
966 let cause_span
= cause
.span
;
967 let eqty_ok
= self.at(cause
, param_env
).eq(b
, a
)?
;
968 self.leak_check(false, cause_span
, &skol_map
, snapshot
)?
;
969 self.pop_skolemized(skol_map
, snapshot
);
974 pub fn subtype_predicate(&self,
975 cause
: &ObligationCause
<'tcx
>,
976 param_env
: ty
::ParamEnv
<'tcx
>,
977 predicate
: &ty
::PolySubtypePredicate
<'tcx
>)
978 -> Option
<InferResult
<'tcx
, ()>>
980 // Subtle: it's ok to skip the binder here and resolve because
981 // `shallow_resolve` just ignores anything that is not a type
982 // variable, and because type variable's can't (at present, at
983 // least) capture any of the things bound by this binder.
985 // Really, there is no *particular* reason to do this
986 // `shallow_resolve` here except as a
987 // micro-optimization. Naturally I could not
988 // resist. -nmatsakis
989 let two_unbound_type_vars
= {
990 let a
= self.shallow_resolve(predicate
.skip_binder().a
);
991 let b
= self.shallow_resolve(predicate
.skip_binder().b
);
992 a
.is_ty_var() && b
.is_ty_var()
995 if two_unbound_type_vars
{
996 // Two unbound type variables? Can't make progress.
1000 Some(self.commit_if_ok(|snapshot
| {
1001 let (ty
::SubtypePredicate { a_is_expected, a, b}
, skol_map
) =
1002 self.skolemize_late_bound_regions(predicate
, snapshot
);
1004 let cause_span
= cause
.span
;
1005 let ok
= self.at(cause
, param_env
).sub_exp(a_is_expected
, a
, b
)?
;
1006 self.leak_check(false, cause_span
, &skol_map
, snapshot
)?
;
1007 self.pop_skolemized(skol_map
, snapshot
);
1012 pub fn region_outlives_predicate(&self,
1013 cause
: &traits
::ObligationCause
<'tcx
>,
1014 predicate
: &ty
::PolyRegionOutlivesPredicate
<'tcx
>)
1017 self.commit_if_ok(|snapshot
| {
1018 let (ty
::OutlivesPredicate(r_a
, r_b
), skol_map
) =
1019 self.skolemize_late_bound_regions(predicate
, snapshot
);
1021 SubregionOrigin
::from_obligation_cause(cause
,
1022 || RelateRegionParamBound(cause
.span
));
1023 self.sub_regions(origin
, r_b
, r_a
); // `b : a` ==> `a <= b`
1024 self.leak_check(false, cause
.span
, &skol_map
, snapshot
)?
;
1025 Ok(self.pop_skolemized(skol_map
, snapshot
))
1029 pub fn next_ty_var_id(&self, diverging
: bool
, origin
: TypeVariableOrigin
) -> TyVid
{
1032 .new_var(diverging
, origin
, None
)
1035 pub fn next_ty_var(&self, origin
: TypeVariableOrigin
) -> Ty
<'tcx
> {
1036 self.tcx
.mk_var(self.next_ty_var_id(false, origin
))
1039 pub fn next_diverging_ty_var(&self, origin
: TypeVariableOrigin
) -> Ty
<'tcx
> {
1040 self.tcx
.mk_var(self.next_ty_var_id(true, origin
))
1043 pub fn next_int_var_id(&self) -> IntVid
{
1044 self.int_unification_table
1049 pub fn next_float_var_id(&self) -> FloatVid
{
1050 self.float_unification_table
1055 /// Create a fresh region variable with the next available index.
1059 /// - `origin`: information about why we created this variable, for use
1060 /// during diagnostics / error-reporting.
1061 pub fn next_region_var(&self, origin
: RegionVariableOrigin
)
1062 -> ty
::Region
<'tcx
> {
1063 self.tcx
.mk_region(ty
::ReVar(self.borrow_region_constraints().new_region_var(origin
)))
1066 /// Number of region variables created so far.
1067 pub fn num_region_vars(&self) -> usize {
1068 self.borrow_region_constraints().var_origins().len()
1071 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1072 pub fn next_nll_region_var(&self, origin
: NLLRegionVariableOrigin
)
1073 -> ty
::Region
<'tcx
> {
1074 self.next_region_var(RegionVariableOrigin
::NLL(origin
))
1077 /// Create a region inference variable for the given
1078 /// region parameter definition.
1079 pub fn region_var_for_def(&self,
1081 def
: &ty
::RegionParameterDef
)
1082 -> ty
::Region
<'tcx
> {
1083 self.next_region_var(EarlyBoundRegion(span
, def
.name
))
1086 /// Create a type inference variable for the given
1087 /// type parameter definition. The substitutions are
1088 /// for actual parameters that may be referred to by
1089 /// the default of this type parameter, if it exists.
1090 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1091 /// used in a path such as `Foo::<T, U>::new()` will
1092 /// use an inference variable for `C` with `[T, U]`
1093 /// as the substitutions for the default, `(T, U)`.
1094 pub fn type_var_for_def(&self,
1096 def
: &ty
::TypeParameterDef
,
1097 substs
: &[Kind
<'tcx
>])
1099 let default = if def
.has_default
{
1100 let default = self.tcx
.type_of(def
.def_id
);
1101 Some(type_variable
::Default
{
1102 ty
: default.subst_spanned(self.tcx
, substs
, Some(span
)),
1111 let ty_var_id
= self.type_variables
1114 TypeVariableOrigin
::TypeParameterDefinition(span
, def
.name
),
1117 self.tcx
.mk_var(ty_var_id
)
1120 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1121 /// type/region parameter to a fresh inference variable.
1122 pub fn fresh_substs_for_item(&self,
1125 -> &'tcx Substs
<'tcx
> {
1126 Substs
::for_item(self.tcx
, def_id
, |def
, _
| {
1127 self.region_var_for_def(span
, def
)
1129 self.type_var_for_def(span
, def
, substs
)
1133 /// True if errors have been reported since this infcx was
1134 /// created. This is sometimes used as a heuristic to skip
1135 /// reporting errors that often occur as a result of earlier
1136 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1137 /// inference variables, regionck errors).
1138 pub fn is_tainted_by_errors(&self) -> bool
{
1139 debug
!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1140 tainted_by_errors_flag={})",
1141 self.tcx
.sess
.err_count(),
1142 self.err_count_on_creation
,
1143 self.tainted_by_errors_flag
.get());
1145 if self.tcx
.sess
.err_count() > self.err_count_on_creation
{
1146 return true; // errors reported since this infcx was made
1148 self.tainted_by_errors_flag
.get()
1151 /// Set the "tainted by errors" flag to true. We call this when we
1152 /// observe an error from a prior pass.
1153 pub fn set_tainted_by_errors(&self) {
1154 debug
!("set_tainted_by_errors()");
1155 self.tainted_by_errors_flag
.set(true)
1158 /// Process the region constraints and report any errors that
1159 /// result. After this, no more unification operations should be
1160 /// done -- or the compiler will panic -- but it is legal to use
1161 /// `resolve_type_vars_if_possible` as well as `fully_resolve`.
1162 pub fn resolve_regions_and_report_errors(
1164 region_context
: DefId
,
1165 region_map
: ®ion
::ScopeTree
,
1166 outlives_env
: &OutlivesEnvironment
<'tcx
>,
1168 self.resolve_regions_and_report_errors_inner(
1176 /// Like `resolve_regions_and_report_errors`, but skips error
1177 /// reporting if NLL is enabled. This is used for fn bodies where
1178 /// the same error may later be reported by the NLL-based
1180 pub fn resolve_regions_and_report_errors_unless_nll(
1182 region_context
: DefId
,
1183 region_map
: ®ion
::ScopeTree
,
1184 outlives_env
: &OutlivesEnvironment
<'tcx
>,
1186 self.resolve_regions_and_report_errors_inner(
1194 fn resolve_regions_and_report_errors_inner(
1196 region_context
: DefId
,
1197 region_map
: ®ion
::ScopeTree
,
1198 outlives_env
: &OutlivesEnvironment
<'tcx
>,
1199 will_later_be_reported_by_nll
: bool
,
1201 assert
!(self.is_tainted_by_errors() || self.region_obligations
.borrow().is_empty(),
1202 "region_obligations not empty: {:#?}",
1203 self.region_obligations
.borrow());
1205 let region_rels
= &RegionRelations
::new(self.tcx
,
1208 outlives_env
.free_region_map());
1209 let (var_origins
, data
) = self.region_constraints
.borrow_mut()
1211 .expect("regions already resolved")
1212 .into_origins_and_data();
1213 let (lexical_region_resolutions
, errors
) =
1214 lexical_region_resolve
::resolve(region_rels
, var_origins
, data
);
1216 let old_value
= self.lexical_region_resolutions
.replace(Some(lexical_region_resolutions
));
1217 assert
!(old_value
.is_none());
1219 if !self.is_tainted_by_errors() {
1220 // As a heuristic, just skip reporting region errors
1221 // altogether if other errors have been reported while
1222 // this infcx was in use. This is totally hokey but
1223 // otherwise we have a hard time separating legit region
1224 // errors from silly ones.
1225 self.report_region_errors(region_map
, &errors
, will_later_be_reported_by_nll
);
1229 /// Obtains (and clears) the current set of region
1230 /// constraints. The inference context is still usable: further
1231 /// unifications will simply add new constraints.
1233 /// This method is not meant to be used with normal lexical region
1234 /// resolution. Rather, it is used in the NLL mode as a kind of
1235 /// interim hack: basically we run normal type-check and generate
1236 /// region constraints as normal, but then we take them and
1237 /// translate them into the form that the NLL solver
1238 /// understands. See the NLL module for mode details.
1239 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData
<'tcx
> {
1240 assert
!(self.region_obligations
.borrow().is_empty(),
1241 "region_obligations not empty: {:#?}",
1242 self.region_obligations
.borrow());
1244 self.borrow_region_constraints().take_and_reset_data()
1247 /// Takes ownership of the list of variable regions. This implies
1248 /// that all the region constriants have already been taken, and
1249 /// hence that `resolve_regions_and_report_errors` can never be
1250 /// called. This is used only during NLL processing to "hand off" ownership
1251 /// of the set of region vairables into the NLL region context.
1252 pub fn take_region_var_origins(&self) -> VarOrigins
{
1253 let (var_origins
, data
) = self.region_constraints
.borrow_mut()
1255 .expect("regions already resolved")
1256 .into_origins_and_data();
1257 assert
!(data
.is_empty());
1261 pub fn ty_to_string(&self, t
: Ty
<'tcx
>) -> String
{
1262 self.resolve_type_vars_if_possible(&t
).to_string()
1265 pub fn tys_to_string(&self, ts
: &[Ty
<'tcx
>]) -> String
{
1266 let tstrs
: Vec
<String
> = ts
.iter().map(|t
| self.ty_to_string(*t
)).collect();
1267 format
!("({})", tstrs
.join(", "))
1270 pub fn trait_ref_to_string(&self, t
: &ty
::TraitRef
<'tcx
>) -> String
{
1271 self.resolve_type_vars_if_possible(t
).to_string()
1274 pub fn shallow_resolve(&self, typ
: Ty
<'tcx
>) -> Ty
<'tcx
> {
1276 ty
::TyInfer(ty
::TyVar(v
)) => {
1277 // Not entirely obvious: if `typ` is a type variable,
1278 // it can be resolved to an int/float variable, which
1279 // can then be recursively resolved, hence the
1280 // recursion. Note though that we prevent type
1281 // variables from unifying to other type variables
1282 // directly (though they may be embedded
1283 // structurally), and we prevent cycles in any case,
1284 // so this recursion should always be of very limited
1286 self.type_variables
.borrow_mut()
1288 .map(|t
| self.shallow_resolve(t
))
1292 ty
::TyInfer(ty
::IntVar(v
)) => {
1293 self.int_unification_table
1296 .map(|v
| v
.to_type(self.tcx
))
1300 ty
::TyInfer(ty
::FloatVar(v
)) => {
1301 self.float_unification_table
1304 .map(|v
| v
.to_type(self.tcx
))
1314 pub fn resolve_type_vars_if_possible
<T
>(&self, value
: &T
) -> T
1315 where T
: TypeFoldable
<'tcx
>
1318 * Where possible, replaces type/int/float variables in
1319 * `value` with their final value. Note that region variables
1320 * are unaffected. If a type variable has not been unified, it
1321 * is left as is. This is an idempotent operation that does
1322 * not affect inference state in any way and so you can do it
1326 if !value
.needs_infer() {
1327 return value
.clone(); // avoid duplicated subst-folding
1329 let mut r
= resolve
::OpportunisticTypeResolver
::new(self);
1330 value
.fold_with(&mut r
)
1333 /// Returns true if `T` contains unresolved type variables. In the
1334 /// process of visiting `T`, this will resolve (where possible)
1335 /// type variables in `T`, but it never constructs the final,
1336 /// resolved type, so it's more efficient than
1337 /// `resolve_type_vars_if_possible()`.
1338 pub fn any_unresolved_type_vars
<T
>(&self, value
: &T
) -> bool
1339 where T
: TypeFoldable
<'tcx
>
1341 let mut r
= resolve
::UnresolvedTypeFinder
::new(self);
1342 value
.visit_with(&mut r
)
1345 pub fn resolve_type_and_region_vars_if_possible
<T
>(&self, value
: &T
) -> T
1346 where T
: TypeFoldable
<'tcx
>
1348 let mut r
= resolve
::OpportunisticTypeAndRegionResolver
::new(self);
1349 value
.fold_with(&mut r
)
1352 pub fn fully_resolve
<T
:TypeFoldable
<'tcx
>>(&self, value
: &T
) -> FixupResult
<T
> {
1354 * Attempts to resolve all type/region variables in
1355 * `value`. Region inference must have been run already (e.g.,
1356 * by calling `resolve_regions_and_report_errors`). If some
1357 * variable was never unified, an `Err` results.
1359 * This method is idempotent, but it not typically not invoked
1360 * except during the writeback phase.
1363 resolve
::fully_resolve(self, value
)
1366 // [Note-Type-error-reporting]
1367 // An invariant is that anytime the expected or actual type is TyError (the special
1368 // error type, meaning that an error occurred when typechecking this expression),
1369 // this is a derived error. The error cascaded from another error (that was already
1370 // reported), so it's not useful to display it to the user.
1371 // The following methods implement this logic.
1372 // They check if either the actual or expected type is TyError, and don't print the error
1373 // in this case. The typechecker should only ever report type errors involving mismatched
1374 // types using one of these methods, and should not call span_err directly for such
1377 pub fn type_error_struct_with_diag
<M
>(&self,
1380 actual_ty
: Ty
<'tcx
>)
1381 -> DiagnosticBuilder
<'tcx
>
1382 where M
: FnOnce(String
) -> DiagnosticBuilder
<'tcx
>,
1384 let actual_ty
= self.resolve_type_vars_if_possible(&actual_ty
);
1385 debug
!("type_error_struct_with_diag({:?}, {:?})", sp
, actual_ty
);
1387 // Don't report an error if actual type is TyError.
1388 if actual_ty
.references_error() {
1389 return self.tcx
.sess
.diagnostic().struct_dummy();
1392 mk_diag(self.ty_to_string(actual_ty
))
1395 pub fn report_mismatched_types(&self,
1396 cause
: &ObligationCause
<'tcx
>,
1399 err
: TypeError
<'tcx
>)
1400 -> DiagnosticBuilder
<'tcx
> {
1401 let trace
= TypeTrace
::types(cause
, true, expected
, actual
);
1402 self.report_and_explain_type_error(trace
, &err
)
1405 pub fn report_conflicting_default_types(&self,
1407 body_id
: ast
::NodeId
,
1408 expected
: type_variable
::Default
<'tcx
>,
1409 actual
: type_variable
::Default
<'tcx
>) {
1410 let trace
= TypeTrace
{
1411 cause
: ObligationCause
::misc(span
, body_id
),
1412 values
: Types(ExpectedFound
{
1413 expected
: expected
.ty
,
1418 self.report_and_explain_type_error(
1420 &TypeError
::TyParamDefaultMismatch(ExpectedFound
{
1427 pub fn replace_late_bound_regions_with_fresh_var
<T
>(
1430 lbrct
: LateBoundRegionConversionTime
,
1431 value
: &ty
::Binder
<T
>)
1432 -> (T
, BTreeMap
<ty
::BoundRegion
, ty
::Region
<'tcx
>>)
1433 where T
: TypeFoldable
<'tcx
>
1435 self.tcx
.replace_late_bound_regions(
1437 |br
| self.next_region_var(LateBoundRegion(span
, br
, lbrct
)))
1440 /// Given a higher-ranked projection predicate like:
1442 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1444 /// and a target trait-ref like:
1446 /// <T as Fn<&'x u32>>
1448 /// find a substitution `S` for the higher-ranked regions (here,
1449 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1450 /// and then return the value (here, `&'a u32`) but with the
1451 /// substitution applied (hence, `&'x u32`).
1453 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1455 pub fn match_poly_projection_predicate(&self,
1456 cause
: ObligationCause
<'tcx
>,
1457 param_env
: ty
::ParamEnv
<'tcx
>,
1458 match_a
: ty
::PolyProjectionPredicate
<'tcx
>,
1459 match_b
: ty
::TraitRef
<'tcx
>)
1460 -> InferResult
<'tcx
, HrMatchResult
<Ty
<'tcx
>>>
1462 let match_pair
= match_a
.map_bound(|p
| (p
.projection_ty
.trait_ref(self.tcx
), p
.ty
));
1463 let trace
= TypeTrace
{
1465 values
: TraitRefs(ExpectedFound
::new(true, match_pair
.skip_binder().0, match_b
))
1468 let mut combine
= self.combine_fields(trace
, param_env
);
1469 let result
= combine
.higher_ranked_match(&match_pair
, &match_b
, true)?
;
1470 Ok(InferOk { value: result, obligations: combine.obligations }
)
1473 /// See `verify_generic_bound` method in `region_constraints`
1474 pub fn verify_generic_bound(&self,
1475 origin
: SubregionOrigin
<'tcx
>,
1476 kind
: GenericKind
<'tcx
>,
1477 a
: ty
::Region
<'tcx
>,
1478 bound
: VerifyBound
<'tcx
>) {
1479 debug
!("verify_generic_bound({:?}, {:?} <: {:?})",
1484 self.borrow_region_constraints().verify_generic_bound(origin
, kind
, a
, bound
);
1487 pub fn type_moves_by_default(&self,
1488 param_env
: ty
::ParamEnv
<'tcx
>,
1492 let ty
= self.resolve_type_vars_if_possible(&ty
);
1493 // Even if the type may have no inference variables, during
1494 // type-checking closure types are in local tables only.
1495 if !self.in_progress_tables
.is_some() || !ty
.has_closure_types() {
1496 if let Some((param_env
, ty
)) = self.tcx
.lift_to_global(&(param_env
, ty
)) {
1497 return ty
.moves_by_default(self.tcx
.global_tcx(), param_env
, span
);
1501 let copy_def_id
= self.tcx
.require_lang_item(lang_items
::CopyTraitLangItem
);
1503 // this can get called from typeck (by euv), and moves_by_default
1504 // rightly refuses to work with inference variables, but
1505 // moves_by_default has a cache, which we want to use in other
1507 !traits
::type_known_to_meet_bound(self, param_env
, ty
, copy_def_id
, span
)
1510 /// Obtains the latest type of the given closure; this may be a
1511 /// closure in the current function, in which case its
1512 /// `ClosureKind` may not yet be known.
1513 pub fn closure_kind(&self,
1514 closure_def_id
: DefId
,
1515 closure_substs
: ty
::ClosureSubsts
<'tcx
>)
1516 -> Option
<ty
::ClosureKind
>
1518 let closure_kind_ty
= closure_substs
.closure_kind_ty(closure_def_id
, self.tcx
);
1519 let closure_kind_ty
= self.shallow_resolve(&closure_kind_ty
);
1520 closure_kind_ty
.to_opt_closure_kind()
1523 /// Obtain the signature of a closure. For closures, unlike
1524 /// `tcx.fn_sig(def_id)`, this method will work during the
1525 /// type-checking of the enclosing function and return the closure
1526 /// signature in its partially inferred state.
1530 substs
: ty
::ClosureSubsts
<'tcx
>
1531 ) -> ty
::PolyFnSig
<'tcx
> {
1532 let closure_sig_ty
= substs
.closure_sig_ty(def_id
, self.tcx
);
1533 let closure_sig_ty
= self.shallow_resolve(&closure_sig_ty
);
1534 closure_sig_ty
.fn_sig(self.tcx
)
1537 /// Normalizes associated types in `value`, potentially returning
1538 /// new obligations that must further be processed.
1539 pub fn partially_normalize_associated_types_in
<T
>(&self,
1541 body_id
: ast
::NodeId
,
1542 param_env
: ty
::ParamEnv
<'tcx
>,
1545 where T
: TypeFoldable
<'tcx
>
1547 debug
!("partially_normalize_associated_types_in(value={:?})", value
);
1548 let mut selcx
= traits
::SelectionContext
::new(self);
1549 let cause
= ObligationCause
::misc(span
, body_id
);
1550 let traits
::Normalized { value, obligations }
=
1551 traits
::normalize(&mut selcx
, param_env
, cause
, value
);
1552 debug
!("partially_normalize_associated_types_in: result={:?} predicates={:?}",
1555 InferOk { value, obligations }
1558 fn borrow_region_constraints(&self) -> RefMut
<'_
, RegionConstraintCollector
<'tcx
>> {
1560 self.region_constraints
.borrow_mut(),
1561 |c
| c
.as_mut().expect("region constraints already solved"))
1565 impl<'a
, 'gcx
, 'tcx
> TypeTrace
<'tcx
> {
1566 pub fn span(&self) -> Span
{
1570 pub fn types(cause
: &ObligationCause
<'tcx
>,
1571 a_is_expected
: bool
,
1574 -> TypeTrace
<'tcx
> {
1576 cause
: cause
.clone(),
1577 values
: Types(ExpectedFound
::new(a_is_expected
, a
, b
))
1581 pub fn dummy(tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>) -> TypeTrace
<'tcx
> {
1583 cause
: ObligationCause
::dummy(),
1584 values
: Types(ExpectedFound
{
1585 expected
: tcx
.types
.err
,
1586 found
: tcx
.types
.err
,
1592 impl<'tcx
> fmt
::Debug
for TypeTrace
<'tcx
> {
1593 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1594 write
!(f
, "TypeTrace({:?})", self.cause
)
1598 impl<'tcx
> SubregionOrigin
<'tcx
> {
1599 pub fn span(&self) -> Span
{
1601 Subtype(ref a
) => a
.span(),
1602 InfStackClosure(a
) => a
,
1603 InvokeClosure(a
) => a
,
1604 DerefPointer(a
) => a
,
1605 FreeVariable(a
, _
) => a
,
1607 RelateObjectBound(a
) => a
,
1608 RelateParamBound(a
, _
) => a
,
1609 RelateRegionParamBound(a
) => a
,
1610 RelateDefaultParamBound(a
, _
) => a
,
1612 ReborrowUpvar(a
, _
) => a
,
1613 DataBorrowed(_
, a
) => a
,
1614 ReferenceOutlivesReferent(_
, a
) => a
,
1615 ParameterInScope(_
, a
) => a
,
1616 ExprTypeIsNotInScope(_
, a
) => a
,
1617 BindingTypeIsNotValidAtDecl(a
) => a
,
1624 SafeDestructor(a
) => a
,
1625 CompareImplMethodObligation { span, .. }
=> span
,
1629 pub fn from_obligation_cause
<F
>(cause
: &traits
::ObligationCause
<'tcx
>,
1632 where F
: FnOnce() -> Self
1635 traits
::ObligationCauseCode
::ReferenceOutlivesReferent(ref_type
) =>
1636 SubregionOrigin
::ReferenceOutlivesReferent(ref_type
, cause
.span
),
1638 traits
::ObligationCauseCode
::CompareImplMethodObligation
{ item_name
,
1640 trait_item_def_id
, } =>
1641 SubregionOrigin
::CompareImplMethodObligation
{
1653 impl RegionVariableOrigin
{
1654 pub fn span(&self) -> Span
{
1656 MiscVariable(a
) => a
,
1657 PatternRegion(a
) => a
,
1658 AddrOfRegion(a
) => a
,
1661 EarlyBoundRegion(a
, ..) => a
,
1662 LateBoundRegion(a
, ..) => a
,
1663 BoundRegionInCoherence(_
) => syntax_pos
::DUMMY_SP
,
1664 UpvarRegion(_
, a
) => a
,
1665 NLL(..) => bug
!("NLL variable used with `span`"),
1670 impl<'tcx
> TypeFoldable
<'tcx
> for ValuePairs
<'tcx
> {
1671 fn super_fold_with
<'gcx
: 'tcx
, F
: TypeFolder
<'gcx
, 'tcx
>>(&self, folder
: &mut F
) -> Self {
1673 ValuePairs
::Types(ref ef
) => {
1674 ValuePairs
::Types(ef
.fold_with(folder
))
1676 ValuePairs
::TraitRefs(ref ef
) => {
1677 ValuePairs
::TraitRefs(ef
.fold_with(folder
))
1679 ValuePairs
::PolyTraitRefs(ref ef
) => {
1680 ValuePairs
::PolyTraitRefs(ef
.fold_with(folder
))
1685 fn super_visit_with
<V
: TypeVisitor
<'tcx
>>(&self, visitor
: &mut V
) -> bool
{
1687 ValuePairs
::Types(ref ef
) => ef
.visit_with(visitor
),
1688 ValuePairs
::TraitRefs(ref ef
) => ef
.visit_with(visitor
),
1689 ValuePairs
::PolyTraitRefs(ref ef
) => ef
.visit_with(visitor
),
1694 impl<'tcx
> TypeFoldable
<'tcx
> for TypeTrace
<'tcx
> {
1695 fn super_fold_with
<'gcx
: 'tcx
, F
: TypeFolder
<'gcx
, 'tcx
>>(&self, folder
: &mut F
) -> Self {
1697 cause
: self.cause
.fold_with(folder
),
1698 values
: self.values
.fold_with(folder
)
1702 fn super_visit_with
<V
: TypeVisitor
<'tcx
>>(&self, visitor
: &mut V
) -> bool
{
1703 self.cause
.visit_with(visitor
) || self.values
.visit_with(visitor
)
1707 impl<'tcx
> fmt
::Debug
for RegionObligation
<'tcx
> {
1708 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1709 write
!(f
, "RegionObligation(sub_region={:?}, sup_type={:?})",