1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See the Book for more information.
13 pub use self::LateBoundRegionConversionTime
::*;
14 pub use self::RegionVariableOrigin
::*;
15 pub use self::SubregionOrigin
::*;
16 pub use self::ValuePairs
::*;
17 pub use ty
::IntVarValue
;
18 pub use self::freshen
::TypeFreshener
;
19 pub use self::region_inference
::{GenericKind, VerifyBound}
;
21 use hir
::def_id
::DefId
;
23 use middle
::free_region
::FreeRegionMap
;
24 use middle
::mem_categorization
as mc
;
25 use middle
::mem_categorization
::McResult
;
26 use middle
::region
::CodeExtent
;
28 use ty
::subst
::Substs
;
31 use ty
::{TyVid, IntVid, FloatVid}
;
32 use ty
::{self, Ty, TyCtxt}
;
33 use ty
::error
::{ExpectedFound, TypeError, UnconstrainedNumeric}
;
34 use ty
::fold
::{TypeFolder, TypeFoldable}
;
35 use ty
::relate
::{Relate, RelateResult, TypeRelation}
;
36 use traits
::{self, PredicateObligations, ProjectionMode}
;
37 use rustc_data_structures
::unify
::{self, UnificationTable}
;
38 use std
::cell
::{RefCell, Ref}
;
42 use syntax
::codemap
::{Span, DUMMY_SP}
;
43 use syntax
::errors
::DiagnosticBuilder
;
44 use util
::nodemap
::{FnvHashMap, FnvHashSet, NodeMap}
;
46 use self::combine
::CombineFields
;
47 use self::region_inference
::{RegionVarBindings, RegionSnapshot}
;
48 use self::error_reporting
::ErrorReporting
;
49 use self::unify_key
::ToType
;
54 pub mod error_reporting
;
59 pub mod region_inference
;
63 pub mod type_variable
;
66 pub struct InferOk
<'tcx
, T
> {
68 pub obligations
: PredicateObligations
<'tcx
>,
70 pub type InferResult
<'tcx
, T
> = Result
<InferOk
<'tcx
, T
>, TypeError
<'tcx
>>;
72 pub type Bound
<T
> = Option
<T
>;
73 pub type UnitResult
<'tcx
> = RelateResult
<'tcx
, ()>; // "unify result"
74 pub type FixupResult
<T
> = Result
<T
, FixupError
>; // "fixup result"
76 pub struct InferCtxt
<'a
, 'tcx
: 'a
> {
77 pub tcx
: &'a TyCtxt
<'tcx
>,
79 pub tables
: &'a RefCell
<ty
::Tables
<'tcx
>>,
81 // We instantiate UnificationTable with bounds<Ty> because the
82 // types that might instantiate a general type variable have an
83 // order, represented by its upper and lower bounds.
84 type_variables
: RefCell
<type_variable
::TypeVariableTable
<'tcx
>>,
86 // Map from integral variable to the kind of integer it represents
87 int_unification_table
: RefCell
<UnificationTable
<ty
::IntVid
>>,
89 // Map from floating variable to the kind of float it represents
90 float_unification_table
: RefCell
<UnificationTable
<ty
::FloatVid
>>,
92 // For region variables.
93 region_vars
: RegionVarBindings
<'a
, 'tcx
>,
95 pub parameter_environment
: ty
::ParameterEnvironment
<'a
, 'tcx
>,
97 // the set of predicates on which errors have been reported, to
98 // avoid reporting the same error twice.
99 pub reported_trait_errors
: RefCell
<FnvHashSet
<traits
::TraitErrorKey
<'tcx
>>>,
101 // This is a temporary field used for toggling on normalization in the inference context,
102 // as we move towards the approach described here:
103 // https://internals.rust-lang.org/t/flattening-the-contexts-for-fun-and-profit/2293
104 // At a point sometime in the future normalization will be done by the typing context
108 // Sadly, the behavior of projection varies a bit depending on the
109 // stage of compilation. The specifics are given in the
110 // documentation for `ProjectionMode`.
111 projection_mode
: ProjectionMode
,
113 err_count_on_creation
: usize,
116 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
117 /// region that each late-bound region was replaced with.
118 pub type SkolemizationMap
= FnvHashMap
<ty
::BoundRegion
,ty
::Region
>;
120 /// Why did we require that the two types be related?
122 /// See `error_reporting.rs` for more details
123 #[derive(Clone, Copy, Debug)]
124 pub enum TypeOrigin
{
125 // Not yet categorized in a better way
128 // Checking that method of impl is compatible with trait
129 MethodCompatCheck(Span
),
131 // Checking that this expression can be assigned where it needs to be
132 // FIXME(eddyb) #11161 is the original Expr required?
133 ExprAssignable(Span
),
135 // Relating trait refs when resolving vtables
136 RelateTraitRefs(Span
),
138 // Relating self types when resolving vtables
139 RelateSelfType(Span
),
141 // Relating trait type parameters to those found in impl etc
142 RelateOutputImplTypes(Span
),
144 // Computing common supertype in the arms of a match expression
145 MatchExpressionArm(Span
, Span
, hir
::MatchSource
),
147 // Computing common supertype in an if expression
150 // Computing common supertype of an if expression with no else counter-part
151 IfExpressionWithNoElse(Span
),
153 // Computing common supertype in a range expression
154 RangeExpression(Span
),
157 EquatePredicate(Span
),
161 fn as_str(&self) -> &'
static str {
163 &TypeOrigin
::Misc(_
) |
164 &TypeOrigin
::RelateSelfType(_
) |
165 &TypeOrigin
::RelateOutputImplTypes(_
) |
166 &TypeOrigin
::ExprAssignable(_
) => "mismatched types",
167 &TypeOrigin
::RelateTraitRefs(_
) => "mismatched traits",
168 &TypeOrigin
::MethodCompatCheck(_
) => "method not compatible with trait",
169 &TypeOrigin
::MatchExpressionArm(_
, _
, source
) => match source
{
170 hir
::MatchSource
::IfLetDesugar{..}
=> "`if let` arms have incompatible types",
171 _
=> "match arms have incompatible types",
173 &TypeOrigin
::IfExpression(_
) => "if and else have incompatible types",
174 &TypeOrigin
::IfExpressionWithNoElse(_
) => "if may be missing an else clause",
175 &TypeOrigin
::RangeExpression(_
) => "start and end of range have incompatible types",
176 &TypeOrigin
::EquatePredicate(_
) => "equality predicate not satisfied",
181 impl fmt
::Display
for TypeOrigin
{
182 fn fmt(&self, f
: &mut fmt
::Formatter
) -> Result
<(),fmt
::Error
> {
183 fmt
::Display
::fmt(self.as_str(), f
)
187 /// See `error_reporting.rs` for more details
188 #[derive(Clone, Debug)]
189 pub enum ValuePairs
<'tcx
> {
190 Types(ExpectedFound
<Ty
<'tcx
>>),
191 TraitRefs(ExpectedFound
<ty
::TraitRef
<'tcx
>>),
192 PolyTraitRefs(ExpectedFound
<ty
::PolyTraitRef
<'tcx
>>),
195 /// The trace designates the path through inference that we took to
196 /// encounter an error or subtyping constraint.
198 /// See `error_reporting.rs` for more details.
200 pub struct TypeTrace
<'tcx
> {
202 values
: ValuePairs
<'tcx
>,
205 /// The origin of a `r1 <= r2` constraint.
207 /// See `error_reporting.rs` for more details
208 #[derive(Clone, Debug)]
209 pub enum SubregionOrigin
<'tcx
> {
210 // Arose from a subtyping relation
211 Subtype(TypeTrace
<'tcx
>),
213 // Stack-allocated closures cannot outlive innermost loop
214 // or function so as to ensure we only require finite stack
215 InfStackClosure(Span
),
217 // Invocation of closure must be within its lifetime
220 // Dereference of reference must be within its lifetime
223 // Closure bound must not outlive captured free variables
224 FreeVariable(Span
, ast
::NodeId
),
226 // Index into slice must be within its lifetime
229 // When casting `&'a T` to an `&'b Trait` object,
230 // relating `'a` to `'b`
231 RelateObjectBound(Span
),
233 // Some type parameter was instantiated with the given type,
234 // and that type must outlive some region.
235 RelateParamBound(Span
, Ty
<'tcx
>),
237 // The given region parameter was instantiated with a region
238 // that must outlive some other region.
239 RelateRegionParamBound(Span
),
241 // A bound placed on type parameters that states that must outlive
242 // the moment of their instantiation.
243 RelateDefaultParamBound(Span
, Ty
<'tcx
>),
245 // Creating a pointer `b` to contents of another reference
248 // Creating a pointer `b` to contents of an upvar
249 ReborrowUpvar(Span
, ty
::UpvarId
),
251 // Data with type `Ty<'tcx>` was borrowed
252 DataBorrowed(Ty
<'tcx
>, Span
),
254 // (&'a &'b T) where a >= b
255 ReferenceOutlivesReferent(Ty
<'tcx
>, Span
),
257 // Type or region parameters must be in scope.
258 ParameterInScope(ParameterOrigin
, Span
),
260 // The type T of an expression E must outlive the lifetime for E.
261 ExprTypeIsNotInScope(Ty
<'tcx
>, Span
),
263 // A `ref b` whose region does not enclose the decl site
264 BindingTypeIsNotValidAtDecl(Span
),
266 // Regions appearing in a method receiver must outlive method call
269 // Regions appearing in a function argument must outlive func call
272 // Region in return type of invoked fn must enclose call
275 // Operands must be in scope
278 // Region resulting from a `&` expr must enclose the `&` expr
281 // An auto-borrow that does not enclose the expr where it occurs
284 // Region constraint arriving from destructor safety
285 SafeDestructor(Span
),
288 /// Places that type/region parameters can appear.
289 #[derive(Clone, Copy, Debug)]
290 pub enum ParameterOrigin
{
292 MethodCall
, // foo.bar() <-- parameters on impl providing bar()
293 OverloadedOperator
, // a + b when overloaded
294 OverloadedDeref
, // *a when overloaded
297 /// Times when we replace late-bound regions with variables:
298 #[derive(Clone, Copy, Debug)]
299 pub enum LateBoundRegionConversionTime
{
300 /// when a fn is called
303 /// when two higher-ranked types are compared
306 /// when projecting an associated type
307 AssocTypeProjection(ast
::Name
),
310 /// Reasons to create a region inference variable
312 /// See `error_reporting.rs` for more details
313 #[derive(Clone, Debug)]
314 pub enum RegionVariableOrigin
{
315 // Region variables created for ill-categorized reasons,
316 // mostly indicates places in need of refactoring
319 // Regions created by a `&P` or `[...]` pattern
322 // Regions created by `&` operator
325 // Regions created as part of an autoref of a method receiver
328 // Regions created as part of an automatic coercion
331 // Region variables created as the values for early-bound regions
332 EarlyBoundRegion(Span
, ast
::Name
),
334 // Region variables created for bound regions
335 // in a function or method that is called
336 LateBoundRegion(Span
, ty
::BoundRegion
, LateBoundRegionConversionTime
),
338 UpvarRegion(ty
::UpvarId
, Span
),
340 BoundRegionInCoherence(ast
::Name
),
343 #[derive(Copy, Clone, Debug)]
344 pub enum FixupError
{
345 UnresolvedIntTy(IntVid
),
346 UnresolvedFloatTy(FloatVid
),
350 pub fn fixup_err_to_string(f
: FixupError
) -> String
{
351 use self::FixupError
::*;
354 UnresolvedIntTy(_
) => {
355 "cannot determine the type of this integer; add a suffix to \
356 specify the type explicitly".to_string()
358 UnresolvedFloatTy(_
) => {
359 "cannot determine the type of this number; add a suffix to specify \
360 the type explicitly".to_string()
362 UnresolvedTy(_
) => "unconstrained type".to_string(),
366 pub fn new_infer_ctxt
<'a
, 'tcx
>(tcx
: &'a TyCtxt
<'tcx
>,
367 tables
: &'a RefCell
<ty
::Tables
<'tcx
>>,
368 param_env
: Option
<ty
::ParameterEnvironment
<'a
, 'tcx
>>,
369 projection_mode
: ProjectionMode
)
370 -> InferCtxt
<'a
, 'tcx
> {
374 type_variables
: RefCell
::new(type_variable
::TypeVariableTable
::new()),
375 int_unification_table
: RefCell
::new(UnificationTable
::new()),
376 float_unification_table
: RefCell
::new(UnificationTable
::new()),
377 region_vars
: RegionVarBindings
::new(tcx
),
378 parameter_environment
: param_env
.unwrap_or(tcx
.empty_parameter_environment()),
379 reported_trait_errors
: RefCell
::new(FnvHashSet()),
381 projection_mode
: projection_mode
,
382 err_count_on_creation
: tcx
.sess
.err_count()
386 pub fn normalizing_infer_ctxt
<'a
, 'tcx
>(tcx
: &'a TyCtxt
<'tcx
>,
387 tables
: &'a RefCell
<ty
::Tables
<'tcx
>>,
388 projection_mode
: ProjectionMode
)
389 -> InferCtxt
<'a
, 'tcx
> {
390 let mut infcx
= new_infer_ctxt(tcx
, tables
, None
, projection_mode
);
391 infcx
.normalize
= true;
395 pub fn mk_subty
<'a
, 'tcx
>(cx
: &InferCtxt
<'a
, 'tcx
>,
400 -> InferResult
<'tcx
, ()>
402 debug
!("mk_subty({:?} <: {:?})", a
, b
);
403 cx
.sub_types(a_is_expected
, origin
, a
, b
)
406 pub fn can_mk_subty
<'a
, 'tcx
>(cx
: &InferCtxt
<'a
, 'tcx
>, a
: Ty
<'tcx
>, b
: Ty
<'tcx
>)
409 debug
!("can_mk_subty({:?} <: {:?})", a
, b
);
411 let trace
= TypeTrace
{
412 origin
: TypeOrigin
::Misc(codemap
::DUMMY_SP
),
413 values
: Types(expected_found(true, a
, b
))
415 cx
.sub(true, trace
, &a
, &b
).map(|_
| ())
419 pub fn can_mk_eqty
<'a
, 'tcx
>(cx
: &InferCtxt
<'a
, 'tcx
>, a
: Ty
<'tcx
>, b
: Ty
<'tcx
>)
422 cx
.can_equate(&a
, &b
)
425 pub fn mk_subr
<'a
, 'tcx
>(cx
: &InferCtxt
<'a
, 'tcx
>,
426 origin
: SubregionOrigin
<'tcx
>,
429 debug
!("mk_subr({:?} <: {:?})", a
, b
);
430 let snapshot
= cx
.region_vars
.start_snapshot();
431 cx
.region_vars
.make_subregion(origin
, a
, b
);
432 cx
.region_vars
.commit(snapshot
);
435 pub fn mk_eqty
<'a
, 'tcx
>(cx
: &InferCtxt
<'a
, 'tcx
>,
440 -> InferResult
<'tcx
, ()>
442 debug
!("mk_eqty({:?} <: {:?})", a
, b
);
443 cx
.eq_types(a_is_expected
, origin
, a
, b
)
446 pub fn mk_eq_trait_refs
<'a
, 'tcx
>(cx
: &InferCtxt
<'a
, 'tcx
>,
449 a
: ty
::TraitRef
<'tcx
>,
450 b
: ty
::TraitRef
<'tcx
>)
451 -> InferResult
<'tcx
, ()>
453 debug
!("mk_eq_trait_refs({:?} = {:?})", a
, b
);
454 cx
.eq_trait_refs(a_is_expected
, origin
, a
, b
)
457 pub fn mk_sub_poly_trait_refs
<'a
, 'tcx
>(cx
: &InferCtxt
<'a
, 'tcx
>,
460 a
: ty
::PolyTraitRef
<'tcx
>,
461 b
: ty
::PolyTraitRef
<'tcx
>)
462 -> InferResult
<'tcx
, ()>
464 debug
!("mk_sub_poly_trait_refs({:?} <: {:?})", a
, b
);
465 cx
.sub_poly_trait_refs(a_is_expected
, origin
, a
, b
)
468 pub fn mk_eq_impl_headers
<'a
, 'tcx
>(cx
: &InferCtxt
<'a
, 'tcx
>,
471 a
: &ty
::ImplHeader
<'tcx
>,
472 b
: &ty
::ImplHeader
<'tcx
>)
473 -> InferResult
<'tcx
, ()>
475 debug
!("mk_eq_impl_header({:?} = {:?})", a
, b
);
476 match (a
.trait_ref
, b
.trait_ref
) {
477 (Some(a_ref
), Some(b_ref
)) => mk_eq_trait_refs(cx
, a_is_expected
, origin
, a_ref
, b_ref
),
478 (None
, None
) => mk_eqty(cx
, a_is_expected
, origin
, a
.self_ty
, b
.self_ty
),
479 _
=> bug
!("mk_eq_impl_headers given mismatched impl kinds"),
483 fn expected_found
<T
>(a_is_expected
: bool
,
489 ExpectedFound {expected: a, found: b}
491 ExpectedFound {expected: b, found: a}
495 #[must_use = "once you start a snapshot, you should always consume it"]
496 pub struct CombinedSnapshot
{
497 type_snapshot
: type_variable
::Snapshot
,
498 int_snapshot
: unify
::Snapshot
<ty
::IntVid
>,
499 float_snapshot
: unify
::Snapshot
<ty
::FloatVid
>,
500 region_vars_snapshot
: RegionSnapshot
,
503 // NOTE: Callable from trans only!
504 pub fn normalize_associated_type
<'tcx
,T
>(tcx
: &TyCtxt
<'tcx
>, value
: &T
) -> T
505 where T
: TypeFoldable
<'tcx
>
507 debug
!("normalize_associated_type(t={:?})", value
);
509 let value
= tcx
.erase_regions(value
);
511 if !value
.has_projection_types() {
515 let infcx
= new_infer_ctxt(tcx
, &tcx
.tables
, None
, ProjectionMode
::Any
);
516 let mut selcx
= traits
::SelectionContext
::new(&infcx
);
517 let cause
= traits
::ObligationCause
::dummy();
518 let traits
::Normalized { value: result, obligations }
=
519 traits
::normalize(&mut selcx
, cause
, &value
);
521 debug
!("normalize_associated_type: result={:?} obligations={:?}",
525 let mut fulfill_cx
= traits
::FulfillmentContext
::new();
527 for obligation
in obligations
{
528 fulfill_cx
.register_predicate_obligation(&infcx
, obligation
);
531 drain_fulfillment_cx_or_panic(DUMMY_SP
, &infcx
, &mut fulfill_cx
, &result
)
534 pub fn drain_fulfillment_cx_or_panic
<'a
,'tcx
,T
>(span
: Span
,
535 infcx
: &InferCtxt
<'a
,'tcx
>,
536 fulfill_cx
: &mut traits
::FulfillmentContext
<'tcx
>,
539 where T
: TypeFoldable
<'tcx
>
541 match drain_fulfillment_cx(infcx
, fulfill_cx
, result
) {
546 "Encountered errors `{:?}` fulfilling during trans",
552 /// Finishes processes any obligations that remain in the fulfillment
553 /// context, and then "freshens" and returns `result`. This is
554 /// primarily used during normalization and other cases where
555 /// processing the obligations in `fulfill_cx` may cause type
556 /// inference variables that appear in `result` to be unified, and
557 /// hence we need to process those obligations to get the complete
558 /// picture of the type.
559 pub fn drain_fulfillment_cx
<'a
,'tcx
,T
>(infcx
: &InferCtxt
<'a
,'tcx
>,
560 fulfill_cx
: &mut traits
::FulfillmentContext
<'tcx
>,
562 -> Result
<T
,Vec
<traits
::FulfillmentError
<'tcx
>>>
563 where T
: TypeFoldable
<'tcx
>
565 debug
!("drain_fulfillment_cx(result={:?})",
568 // In principle, we only need to do this so long as `result`
569 // contains unbound type parameters. It could be a slight
570 // optimization to stop iterating early.
571 match fulfill_cx
.select_all_or_error(infcx
) {
578 let result
= infcx
.resolve_type_vars_if_possible(result
);
579 Ok(infcx
.tcx
.erase_regions(&result
))
582 impl<'tcx
, T
> InferOk
<'tcx
, T
> {
583 fn unit(self) -> InferOk
<'tcx
, ()> {
584 InferOk { value: (), obligations: self.obligations }
588 impl<'a
, 'tcx
> InferCtxt
<'a
, 'tcx
> {
589 pub fn projection_mode(&self) -> ProjectionMode
{
593 pub fn freshen
<T
:TypeFoldable
<'tcx
>>(&self, t
: T
) -> T
{
594 t
.fold_with(&mut self.freshener())
597 pub fn type_var_diverges(&'a
self, ty
: Ty
) -> bool
{
599 ty
::TyInfer(ty
::TyVar(vid
)) => self.type_variables
.borrow().var_diverges(vid
),
604 pub fn freshener
<'b
>(&'b
self) -> TypeFreshener
<'b
, 'tcx
> {
605 freshen
::TypeFreshener
::new(self)
608 pub fn type_is_unconstrained_numeric(&'a
self, ty
: Ty
) -> UnconstrainedNumeric
{
609 use ty
::error
::UnconstrainedNumeric
::Neither
;
610 use ty
::error
::UnconstrainedNumeric
::{UnconstrainedInt, UnconstrainedFloat}
;
612 ty
::TyInfer(ty
::IntVar(vid
)) => {
613 if self.int_unification_table
.borrow_mut().has_value(vid
) {
619 ty
::TyInfer(ty
::FloatVar(vid
)) => {
620 if self.float_unification_table
.borrow_mut().has_value(vid
) {
630 /// Returns a type variable's default fallback if any exists. A default
631 /// must be attached to the variable when created, if it is created
632 /// without a default, this will return None.
634 /// This code does not apply to integral or floating point variables,
635 /// only to use declared defaults.
637 /// See `new_ty_var_with_default` to create a type variable with a default.
638 /// See `type_variable::Default` for details about what a default entails.
639 pub fn default(&self, ty
: Ty
<'tcx
>) -> Option
<type_variable
::Default
<'tcx
>> {
641 ty
::TyInfer(ty
::TyVar(vid
)) => self.type_variables
.borrow().default(vid
),
646 pub fn unsolved_variables(&self) -> Vec
<ty
::Ty
<'tcx
>> {
647 let mut variables
= Vec
::new();
649 let unbound_ty_vars
= self.type_variables
651 .unsolved_variables()
653 .map(|t
| self.tcx
.mk_var(t
));
655 let unbound_int_vars
= self.int_unification_table
657 .unsolved_variables()
659 .map(|v
| self.tcx
.mk_int_var(v
));
661 let unbound_float_vars
= self.float_unification_table
663 .unsolved_variables()
665 .map(|v
| self.tcx
.mk_float_var(v
));
667 variables
.extend(unbound_ty_vars
);
668 variables
.extend(unbound_int_vars
);
669 variables
.extend(unbound_float_vars
);
674 fn combine_fields(&'a
self, a_is_expected
: bool
, trace
: TypeTrace
<'tcx
>)
675 -> CombineFields
<'a
, 'tcx
>
679 a_is_expected
: a_is_expected
,
682 obligations
: PredicateObligations
::new(),
686 pub fn equate
<T
>(&'a
self, a_is_expected
: bool
, trace
: TypeTrace
<'tcx
>, a
: &T
, b
: &T
)
687 -> InferResult
<'tcx
, T
>
688 where T
: Relate
<'a
, 'tcx
>
690 let mut equate
= self.combine_fields(a_is_expected
, trace
).equate();
691 let result
= equate
.relate(a
, b
);
692 result
.map(|t
| InferOk { value: t, obligations: equate.obligations() }
)
695 pub fn sub
<T
>(&'a
self, a_is_expected
: bool
, trace
: TypeTrace
<'tcx
>, a
: &T
, b
: &T
)
696 -> InferResult
<'tcx
, T
>
697 where T
: Relate
<'a
, 'tcx
>
699 let mut sub
= self.combine_fields(a_is_expected
, trace
).sub();
700 let result
= sub
.relate(a
, b
);
701 result
.map(|t
| InferOk { value: t, obligations: sub.obligations() }
)
704 pub fn lub
<T
>(&'a
self, a_is_expected
: bool
, trace
: TypeTrace
<'tcx
>, a
: &T
, b
: &T
)
705 -> InferResult
<'tcx
, T
>
706 where T
: Relate
<'a
, 'tcx
>
708 let mut lub
= self.combine_fields(a_is_expected
, trace
).lub();
709 let result
= lub
.relate(a
, b
);
710 result
.map(|t
| InferOk { value: t, obligations: lub.obligations() }
)
713 pub fn glb
<T
>(&'a
self, a_is_expected
: bool
, trace
: TypeTrace
<'tcx
>, a
: &T
, b
: &T
)
714 -> InferResult
<'tcx
, T
>
715 where T
: Relate
<'a
, 'tcx
>
717 let mut glb
= self.combine_fields(a_is_expected
, trace
).glb();
718 let result
= glb
.relate(a
, b
);
719 result
.map(|t
| InferOk { value: t, obligations: glb.obligations() }
)
722 fn start_snapshot(&self) -> CombinedSnapshot
{
724 type_snapshot
: self.type_variables
.borrow_mut().snapshot(),
725 int_snapshot
: self.int_unification_table
.borrow_mut().snapshot(),
726 float_snapshot
: self.float_unification_table
.borrow_mut().snapshot(),
727 region_vars_snapshot
: self.region_vars
.start_snapshot(),
731 fn rollback_to(&self, cause
: &str, snapshot
: CombinedSnapshot
) {
732 debug
!("rollback_to(cause={})", cause
);
733 let CombinedSnapshot
{ type_snapshot
,
736 region_vars_snapshot
} = snapshot
;
740 .rollback_to(type_snapshot
);
741 self.int_unification_table
743 .rollback_to(int_snapshot
);
744 self.float_unification_table
746 .rollback_to(float_snapshot
);
748 .rollback_to(region_vars_snapshot
);
751 fn commit_from(&self, snapshot
: CombinedSnapshot
) {
752 debug
!("commit_from!");
753 let CombinedSnapshot
{ type_snapshot
,
756 region_vars_snapshot
} = snapshot
;
760 .commit(type_snapshot
);
761 self.int_unification_table
763 .commit(int_snapshot
);
764 self.float_unification_table
766 .commit(float_snapshot
);
768 .commit(region_vars_snapshot
);
771 /// Execute `f` and commit the bindings
772 pub fn commit_unconditionally
<R
, F
>(&self, f
: F
) -> R
where
776 let snapshot
= self.start_snapshot();
778 self.commit_from(snapshot
);
782 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
783 pub fn commit_if_ok
<T
, E
, F
>(&self, f
: F
) -> Result
<T
, E
> where
784 F
: FnOnce(&CombinedSnapshot
) -> Result
<T
, E
>
786 debug
!("commit_if_ok()");
787 let snapshot
= self.start_snapshot();
788 let r
= f(&snapshot
);
789 debug
!("commit_if_ok() -- r.is_ok() = {}", r
.is_ok());
791 Ok(_
) => { self.commit_from(snapshot); }
792 Err(_
) => { self.rollback_to("commit_if_ok -- error", snapshot); }
797 /// Execute `f` and commit only the region bindings if successful.
798 /// The function f must be very careful not to leak any non-region
799 /// variables that get created.
800 pub fn commit_regions_if_ok
<T
, E
, F
>(&self, f
: F
) -> Result
<T
, E
> where
801 F
: FnOnce() -> Result
<T
, E
>
803 debug
!("commit_regions_if_ok()");
804 let CombinedSnapshot
{ type_snapshot
,
807 region_vars_snapshot
} = self.start_snapshot();
809 let r
= self.commit_if_ok(|_
| f());
811 debug
!("commit_regions_if_ok: rolling back everything but regions");
813 // Roll back any non-region bindings - they should be resolved
814 // inside `f`, with, e.g. `resolve_type_vars_if_possible`.
817 .rollback_to(type_snapshot
);
818 self.int_unification_table
820 .rollback_to(int_snapshot
);
821 self.float_unification_table
823 .rollback_to(float_snapshot
);
825 // Commit region vars that may escape through resolved types.
827 .commit(region_vars_snapshot
);
832 /// Execute `f` then unroll any bindings it creates
833 pub fn probe
<R
, F
>(&self, f
: F
) -> R
where
834 F
: FnOnce(&CombinedSnapshot
) -> R
,
837 let snapshot
= self.start_snapshot();
838 let r
= f(&snapshot
);
839 self.rollback_to("probe", snapshot
);
843 pub fn add_given(&self,
847 self.region_vars
.add_given(sub
, sup
);
850 pub fn sub_types(&self,
855 -> InferResult
<'tcx
, ()>
857 debug
!("sub_types({:?} <: {:?})", a
, b
);
858 self.commit_if_ok(|_
| {
859 let trace
= TypeTrace
::types(origin
, a_is_expected
, a
, b
);
860 self.sub(a_is_expected
, trace
, &a
, &b
).map(|ok
| ok
.unit())
864 pub fn eq_types(&self,
869 -> InferResult
<'tcx
, ()>
871 self.commit_if_ok(|_
| {
872 let trace
= TypeTrace
::types(origin
, a_is_expected
, a
, b
);
873 self.equate(a_is_expected
, trace
, &a
, &b
).map(|ok
| ok
.unit())
877 pub fn eq_trait_refs(&self,
880 a
: ty
::TraitRef
<'tcx
>,
881 b
: ty
::TraitRef
<'tcx
>)
882 -> InferResult
<'tcx
, ()>
884 debug
!("eq_trait_refs({:?} <: {:?})",
887 self.commit_if_ok(|_
| {
888 let trace
= TypeTrace
{
890 values
: TraitRefs(expected_found(a_is_expected
, a
.clone(), b
.clone()))
892 self.equate(a_is_expected
, trace
, &a
, &b
).map(|ok
| ok
.unit())
896 pub fn sub_poly_trait_refs(&self,
899 a
: ty
::PolyTraitRef
<'tcx
>,
900 b
: ty
::PolyTraitRef
<'tcx
>)
901 -> InferResult
<'tcx
, ()>
903 debug
!("sub_poly_trait_refs({:?} <: {:?})",
906 self.commit_if_ok(|_
| {
907 let trace
= TypeTrace
{
909 values
: PolyTraitRefs(expected_found(a_is_expected
, a
.clone(), b
.clone()))
911 self.sub(a_is_expected
, trace
, &a
, &b
).map(|ok
| ok
.unit())
915 pub fn skolemize_late_bound_regions
<T
>(&self,
916 value
: &ty
::Binder
<T
>,
917 snapshot
: &CombinedSnapshot
)
918 -> (T
, SkolemizationMap
)
919 where T
: TypeFoldable
<'tcx
>
921 /*! See `higher_ranked::skolemize_late_bound_regions` */
923 higher_ranked
::skolemize_late_bound_regions(self, value
, snapshot
)
926 pub fn leak_check(&self,
927 skol_map
: &SkolemizationMap
,
928 snapshot
: &CombinedSnapshot
)
931 /*! See `higher_ranked::leak_check` */
933 match higher_ranked
::leak_check(self, skol_map
, snapshot
) {
935 Err((br
, r
)) => Err(TypeError
::RegionsInsufficientlyPolymorphic(br
, r
))
939 pub fn plug_leaks
<T
>(&self,
940 skol_map
: SkolemizationMap
,
941 snapshot
: &CombinedSnapshot
,
944 where T
: TypeFoldable
<'tcx
>
946 /*! See `higher_ranked::plug_leaks` */
948 higher_ranked
::plug_leaks(self, skol_map
, snapshot
, value
)
951 pub fn equality_predicate(&self,
953 predicate
: &ty
::PolyEquatePredicate
<'tcx
>)
954 -> InferResult
<'tcx
, ()>
956 self.commit_if_ok(|snapshot
| {
957 let (ty
::EquatePredicate(a
, b
), skol_map
) =
958 self.skolemize_late_bound_regions(predicate
, snapshot
);
959 let origin
= TypeOrigin
::EquatePredicate(span
);
960 let eqty_ok
= mk_eqty(self, false, origin
, a
, b
)?
;
961 self.leak_check(&skol_map
, snapshot
).map(|_
| eqty_ok
.unit())
965 pub fn region_outlives_predicate(&self,
967 predicate
: &ty
::PolyRegionOutlivesPredicate
)
970 self.commit_if_ok(|snapshot
| {
971 let (ty
::OutlivesPredicate(r_a
, r_b
), skol_map
) =
972 self.skolemize_late_bound_regions(predicate
, snapshot
);
973 let origin
= RelateRegionParamBound(span
);
974 let () = mk_subr(self, origin
, r_b
, r_a
); // `b : a` ==> `a <= b`
975 self.leak_check(&skol_map
, snapshot
)
979 pub fn next_ty_var_id(&self, diverging
: bool
) -> TyVid
{
982 .new_var(diverging
, None
)
985 pub fn next_ty_var(&self) -> Ty
<'tcx
> {
986 self.tcx
.mk_var(self.next_ty_var_id(false))
989 pub fn next_ty_var_with_default(&self,
990 default: Option
<type_variable
::Default
<'tcx
>>) -> Ty
<'tcx
> {
991 let ty_var_id
= self.type_variables
993 .new_var(false, default);
995 self.tcx
.mk_var(ty_var_id
)
998 pub fn next_diverging_ty_var(&self) -> Ty
<'tcx
> {
999 self.tcx
.mk_var(self.next_ty_var_id(true))
1002 pub fn next_ty_vars(&self, n
: usize) -> Vec
<Ty
<'tcx
>> {
1003 (0..n
).map(|_i
| self.next_ty_var()).collect()
1006 pub fn next_int_var_id(&self) -> IntVid
{
1007 self.int_unification_table
1012 pub fn next_float_var_id(&self) -> FloatVid
{
1013 self.float_unification_table
1018 pub fn next_region_var(&self, origin
: RegionVariableOrigin
) -> ty
::Region
{
1019 ty
::ReVar(self.region_vars
.new_region_var(origin
))
1022 pub fn region_vars_for_defs(&self,
1024 defs
: &[ty
::RegionParameterDef
])
1025 -> Vec
<ty
::Region
> {
1027 .map(|d
| self.next_region_var(EarlyBoundRegion(span
, d
.name
)))
1031 // We have to take `&mut Substs` in order to provide the correct substitutions for defaults
1032 // along the way, for this reason we don't return them.
1033 pub fn type_vars_for_defs(&self,
1035 space
: subst
::ParamSpace
,
1036 substs
: &mut Substs
<'tcx
>,
1037 defs
: &[ty
::TypeParameterDef
<'tcx
>]) {
1039 for def
in defs
.iter() {
1040 let default = def
.default.map(|default| {
1041 type_variable
::Default
{
1042 ty
: default.subst_spanned(self.tcx
, substs
, Some(span
)),
1044 def_id
: def
.default_def_id
1048 let ty_var
= self.next_ty_var_with_default(default);
1049 substs
.types
.push(space
, ty_var
);
1053 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1054 /// type/region parameter to a fresh inference variable.
1055 pub fn fresh_substs_for_generics(&self,
1057 generics
: &ty
::Generics
<'tcx
>)
1058 -> subst
::Substs
<'tcx
>
1060 let type_params
= subst
::VecPerParamSpace
::empty();
1063 generics
.regions
.map(
1064 |d
| self.next_region_var(EarlyBoundRegion(span
, d
.name
)));
1066 let mut substs
= subst
::Substs
::new(type_params
, region_params
);
1068 for space
in subst
::ParamSpace
::all().iter() {
1069 self.type_vars_for_defs(
1073 generics
.types
.get_slice(*space
));
1079 /// Given a set of generics defined on a trait, returns a substitution mapping each output
1080 /// type/region parameter to a fresh inference variable, and mapping the self type to
1082 pub fn fresh_substs_for_trait(&self,
1084 generics
: &ty
::Generics
<'tcx
>,
1086 -> subst
::Substs
<'tcx
>
1089 assert
!(generics
.types
.len(subst
::SelfSpace
) == 1);
1090 assert
!(generics
.types
.len(subst
::FnSpace
) == 0);
1091 assert
!(generics
.regions
.len(subst
::SelfSpace
) == 0);
1092 assert
!(generics
.regions
.len(subst
::FnSpace
) == 0);
1094 let type_params
= Vec
::new();
1096 let region_param_defs
= generics
.regions
.get_slice(subst
::TypeSpace
);
1097 let regions
= self.region_vars_for_defs(span
, region_param_defs
);
1099 let mut substs
= subst
::Substs
::new_trait(type_params
, regions
, self_ty
);
1101 let type_parameter_defs
= generics
.types
.get_slice(subst
::TypeSpace
);
1102 self.type_vars_for_defs(span
, subst
::TypeSpace
, &mut substs
, type_parameter_defs
);
1107 pub fn fresh_bound_region(&self, debruijn
: ty
::DebruijnIndex
) -> ty
::Region
{
1108 self.region_vars
.new_bound(debruijn
)
1111 /// Apply `adjustment` to the type of `expr`
1112 pub fn adjust_expr_ty(&self,
1114 adjustment
: Option
<&adjustment
::AutoAdjustment
<'tcx
>>)
1117 let raw_ty
= self.expr_ty(expr
);
1118 let raw_ty
= self.shallow_resolve(raw_ty
);
1119 let resolve_ty
= |ty
: Ty
<'tcx
>| self.resolve_type_vars_if_possible(&ty
);
1120 raw_ty
.adjust(self.tcx
,
1124 |method_call
| self.tables
1128 .map(|method
| resolve_ty(method
.ty
)))
1131 pub fn errors_since_creation(&self) -> bool
{
1132 self.tcx
.sess
.err_count() - self.err_count_on_creation
!= 0
1135 pub fn node_type(&self, id
: ast
::NodeId
) -> Ty
<'tcx
> {
1136 match self.tables
.borrow().node_types
.get(&id
) {
1139 None
if self.errors_since_creation() =>
1142 bug
!("no type for node {}: {} in fcx",
1143 id
, self.tcx
.map
.node_to_string(id
));
1148 pub fn expr_ty(&self, ex
: &hir
::Expr
) -> Ty
<'tcx
> {
1149 match self.tables
.borrow().node_types
.get(&ex
.id
) {
1152 bug
!("no type for expr in fcx");
1157 pub fn resolve_regions_and_report_errors(&self,
1158 free_regions
: &FreeRegionMap
,
1159 subject_node_id
: ast
::NodeId
) {
1160 let errors
= self.region_vars
.resolve_regions(free_regions
, subject_node_id
);
1161 if !self.errors_since_creation() {
1162 // As a heuristic, just skip reporting region errors
1163 // altogether if other errors have been reported while
1164 // this infcx was in use. This is totally hokey but
1165 // otherwise we have a hard time separating legit region
1166 // errors from silly ones.
1167 self.report_region_errors(&errors
); // see error_reporting.rs
1171 pub fn ty_to_string(&self, t
: Ty
<'tcx
>) -> String
{
1172 self.resolve_type_vars_if_possible(&t
).to_string()
1175 pub fn tys_to_string(&self, ts
: &[Ty
<'tcx
>]) -> String
{
1176 let tstrs
: Vec
<String
> = ts
.iter().map(|t
| self.ty_to_string(*t
)).collect();
1177 format
!("({})", tstrs
.join(", "))
1180 pub fn trait_ref_to_string(&self, t
: &ty
::TraitRef
<'tcx
>) -> String
{
1181 self.resolve_type_vars_if_possible(t
).to_string()
1184 pub fn shallow_resolve(&self, typ
: Ty
<'tcx
>) -> Ty
<'tcx
> {
1186 ty
::TyInfer(ty
::TyVar(v
)) => {
1187 // Not entirely obvious: if `typ` is a type variable,
1188 // it can be resolved to an int/float variable, which
1189 // can then be recursively resolved, hence the
1190 // recursion. Note though that we prevent type
1191 // variables from unifying to other type variables
1192 // directly (though they may be embedded
1193 // structurally), and we prevent cycles in any case,
1194 // so this recursion should always be of very limited
1196 self.type_variables
.borrow_mut()
1198 .map(|t
| self.shallow_resolve(t
))
1202 ty
::TyInfer(ty
::IntVar(v
)) => {
1203 self.int_unification_table
1206 .map(|v
| v
.to_type(self.tcx
))
1210 ty
::TyInfer(ty
::FloatVar(v
)) => {
1211 self.float_unification_table
1214 .map(|v
| v
.to_type(self.tcx
))
1224 pub fn resolve_type_vars_if_possible
<T
>(&self, value
: &T
) -> T
1225 where T
: TypeFoldable
<'tcx
>
1228 * Where possible, replaces type/int/float variables in
1229 * `value` with their final value. Note that region variables
1230 * are unaffected. If a type variable has not been unified, it
1231 * is left as is. This is an idempotent operation that does
1232 * not affect inference state in any way and so you can do it
1236 if !value
.needs_infer() {
1237 return value
.clone(); // avoid duplicated subst-folding
1239 let mut r
= resolve
::OpportunisticTypeResolver
::new(self);
1240 value
.fold_with(&mut r
)
1243 pub fn resolve_type_and_region_vars_if_possible
<T
>(&self, value
: &T
) -> T
1244 where T
: TypeFoldable
<'tcx
>
1246 let mut r
= resolve
::OpportunisticTypeAndRegionResolver
::new(self);
1247 value
.fold_with(&mut r
)
1250 /// Resolves all type variables in `t` and then, if any were left
1251 /// unresolved, substitutes an error type. This is used after the
1252 /// main checking when doing a second pass before writeback. The
1253 /// justification is that writeback will produce an error for
1254 /// these unconstrained type variables.
1255 fn resolve_type_vars_or_error(&self, t
: &Ty
<'tcx
>) -> mc
::McResult
<Ty
<'tcx
>> {
1256 let ty
= self.resolve_type_vars_if_possible(t
);
1257 if ty
.references_error() || ty
.is_ty_var() {
1258 debug
!("resolve_type_vars_or_error: error from {:?}", ty
);
1265 pub fn fully_resolve
<T
:TypeFoldable
<'tcx
>>(&self, value
: &T
) -> FixupResult
<T
> {
1267 * Attempts to resolve all type/region variables in
1268 * `value`. Region inference must have been run already (e.g.,
1269 * by calling `resolve_regions_and_report_errors`). If some
1270 * variable was never unified, an `Err` results.
1272 * This method is idempotent, but it not typically not invoked
1273 * except during the writeback phase.
1276 resolve
::fully_resolve(self, value
)
1279 // [Note-Type-error-reporting]
1280 // An invariant is that anytime the expected or actual type is TyError (the special
1281 // error type, meaning that an error occurred when typechecking this expression),
1282 // this is a derived error. The error cascaded from another error (that was already
1283 // reported), so it's not useful to display it to the user.
1284 // The following four methods -- type_error_message_str, type_error_message_str_with_expected,
1285 // type_error_message, and report_mismatched_types -- implement this logic.
1286 // They check if either the actual or expected type is TyError, and don't print the error
1287 // in this case. The typechecker should only ever report type errors involving mismatched
1288 // types using one of these four methods, and should not call span_err directly for such
1290 pub fn type_error_message_str
<M
>(&self,
1294 err
: Option
<&TypeError
<'tcx
>>)
1295 where M
: FnOnce(Option
<String
>, String
) -> String
,
1297 self.type_error_message_str_with_expected(sp
, mk_msg
, None
, actual_ty
, err
)
1300 pub fn type_error_struct_str
<M
>(&self,
1304 err
: Option
<&TypeError
<'tcx
>>)
1305 -> DiagnosticBuilder
<'tcx
>
1306 where M
: FnOnce(Option
<String
>, String
) -> String
,
1308 self.type_error_struct_str_with_expected(sp
, mk_msg
, None
, actual_ty
, err
)
1311 pub fn type_error_message_str_with_expected
<M
>(&self,
1314 expected_ty
: Option
<Ty
<'tcx
>>,
1316 err
: Option
<&TypeError
<'tcx
>>)
1317 where M
: FnOnce(Option
<String
>, String
) -> String
,
1319 self.type_error_struct_str_with_expected(sp
, mk_msg
, expected_ty
, actual_ty
, err
)
1323 pub fn type_error_struct_str_with_expected
<M
>(&self,
1326 expected_ty
: Option
<Ty
<'tcx
>>,
1328 err
: Option
<&TypeError
<'tcx
>>)
1329 -> DiagnosticBuilder
<'tcx
>
1330 where M
: FnOnce(Option
<String
>, String
) -> String
,
1332 debug
!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty
, actual_ty
);
1334 let resolved_expected
= expected_ty
.map(|e_ty
| self.resolve_type_vars_if_possible(&e_ty
));
1336 if !resolved_expected
.references_error() {
1337 let error_str
= err
.map_or("".to_string(), |t_err
| {
1338 format
!(" ({})", t_err
)
1341 let mut db
= self.tcx
.sess
.struct_span_err(sp
, &format
!("{}{}",
1342 mk_msg(resolved_expected
.map(|t
| self.ty_to_string(t
)), actual_ty
),
1345 if let Some(err
) = err
{
1346 self.tcx
.note_and_explain_type_err(&mut db
, err
, sp
);
1350 self.tcx
.sess
.diagnostic().struct_dummy()
1354 pub fn type_error_message
<M
>(&self,
1357 actual_ty
: Ty
<'tcx
>,
1358 err
: Option
<&TypeError
<'tcx
>>)
1359 where M
: FnOnce(String
) -> String
,
1361 self.type_error_struct(sp
, mk_msg
, actual_ty
, err
).emit();
1364 pub fn type_error_struct
<M
>(&self,
1367 actual_ty
: Ty
<'tcx
>,
1368 err
: Option
<&TypeError
<'tcx
>>)
1369 -> DiagnosticBuilder
<'tcx
>
1370 where M
: FnOnce(String
) -> String
,
1372 let actual_ty
= self.resolve_type_vars_if_possible(&actual_ty
);
1374 // Don't report an error if actual type is TyError.
1375 if actual_ty
.references_error() {
1376 return self.tcx
.sess
.diagnostic().struct_dummy();
1379 self.type_error_struct_str(sp
,
1380 move |_e
, a
| { mk_msg(a) }
,
1381 self.ty_to_string(actual_ty
), err
)
1384 pub fn report_mismatched_types(&self,
1388 err
: TypeError
<'tcx
>) {
1389 let trace
= TypeTrace
{
1391 values
: Types(ExpectedFound
{
1396 self.report_and_explain_type_error(trace
, &err
).emit();
1399 pub fn report_conflicting_default_types(&self,
1401 expected
: type_variable
::Default
<'tcx
>,
1402 actual
: type_variable
::Default
<'tcx
>) {
1403 let trace
= TypeTrace
{
1404 origin
: TypeOrigin
::Misc(span
),
1405 values
: Types(ExpectedFound
{
1406 expected
: expected
.ty
,
1411 self.report_and_explain_type_error(
1413 &TypeError
::TyParamDefaultMismatch(ExpectedFound
{
1420 pub fn replace_late_bound_regions_with_fresh_var
<T
>(
1423 lbrct
: LateBoundRegionConversionTime
,
1424 value
: &ty
::Binder
<T
>)
1425 -> (T
, FnvHashMap
<ty
::BoundRegion
,ty
::Region
>)
1426 where T
: TypeFoldable
<'tcx
>
1428 self.tcx
.replace_late_bound_regions(
1430 |br
| self.next_region_var(LateBoundRegion(span
, br
, lbrct
)))
1433 /// See `verify_generic_bound` method in `region_inference`
1434 pub fn verify_generic_bound(&self,
1435 origin
: SubregionOrigin
<'tcx
>,
1436 kind
: GenericKind
<'tcx
>,
1438 bound
: VerifyBound
) {
1439 debug
!("verify_generic_bound({:?}, {:?} <: {:?})",
1444 self.region_vars
.verify_generic_bound(origin
, kind
, a
, bound
);
1447 pub fn can_equate
<'b
,T
>(&'b
self, a
: &T
, b
: &T
) -> UnitResult
<'tcx
>
1448 where T
: Relate
<'b
,'tcx
> + fmt
::Debug
1450 debug
!("can_equate({:?}, {:?})", a
, b
);
1452 // Gin up a dummy trace, since this won't be committed
1453 // anyhow. We should make this typetrace stuff more
1454 // generic so we don't have to do anything quite this
1456 let e
= self.tcx
.types
.err
;
1457 let trace
= TypeTrace
{
1458 origin
: TypeOrigin
::Misc(codemap
::DUMMY_SP
),
1459 values
: Types(expected_found(true, e
, e
))
1461 self.equate(true, trace
, a
, b
)
1465 pub fn node_ty(&self, id
: ast
::NodeId
) -> McResult
<Ty
<'tcx
>> {
1466 let ty
= self.node_type(id
);
1467 self.resolve_type_vars_or_error(&ty
)
1470 pub fn expr_ty_adjusted(&self, expr
: &hir
::Expr
) -> McResult
<Ty
<'tcx
>> {
1471 let ty
= self.adjust_expr_ty(expr
, self.tables
.borrow().adjustments
.get(&expr
.id
));
1472 self.resolve_type_vars_or_error(&ty
)
1475 pub fn tables_are_tcx_tables(&self) -> bool
{
1476 let tables
: &RefCell
<ty
::Tables
> = &self.tables
;
1477 let tcx_tables
: &RefCell
<ty
::Tables
> = &self.tcx
.tables
;
1478 tables
as *const _
== tcx_tables
as *const _
1481 pub fn type_moves_by_default(&self, ty
: Ty
<'tcx
>, span
: Span
) -> bool
{
1482 let ty
= self.resolve_type_vars_if_possible(&ty
);
1483 if ty
.needs_infer() ||
1484 (ty
.has_closure_types() && !self.tables_are_tcx_tables()) {
1485 // this can get called from typeck (by euv), and moves_by_default
1486 // rightly refuses to work with inference variables, but
1487 // moves_by_default has a cache, which we want to use in other
1489 !traits
::type_known_to_meet_builtin_bound(self, ty
, ty
::BoundCopy
, span
)
1491 ty
.moves_by_default(&self.parameter_environment
, span
)
1495 pub fn node_method_ty(&self, method_call
: ty
::MethodCall
)
1496 -> Option
<Ty
<'tcx
>> {
1501 .map(|method
| method
.ty
)
1502 .map(|ty
| self.resolve_type_vars_if_possible(&ty
))
1505 pub fn node_method_id(&self, method_call
: ty
::MethodCall
)
1511 .map(|method
| method
.def_id
)
1514 pub fn adjustments(&self) -> Ref
<NodeMap
<adjustment
::AutoAdjustment
<'tcx
>>> {
1515 fn project_adjustments
<'a
, 'tcx
>(tables
: &'a ty
::Tables
<'tcx
>)
1516 -> &'a NodeMap
<adjustment
::AutoAdjustment
<'tcx
>> {
1520 Ref
::map(self.tables
.borrow(), project_adjustments
)
1523 pub fn is_method_call(&self, id
: ast
::NodeId
) -> bool
{
1524 self.tables
.borrow().method_map
.contains_key(&ty
::MethodCall
::expr(id
))
1527 pub fn temporary_scope(&self, rvalue_id
: ast
::NodeId
) -> Option
<CodeExtent
> {
1528 self.tcx
.region_maps
.temporary_scope(rvalue_id
)
1531 pub fn upvar_capture(&self, upvar_id
: ty
::UpvarId
) -> Option
<ty
::UpvarCapture
> {
1532 self.tables
.borrow().upvar_capture_map
.get(&upvar_id
).cloned()
1535 pub fn param_env
<'b
>(&'b
self) -> &'b ty
::ParameterEnvironment
<'b
,'tcx
> {
1536 &self.parameter_environment
1539 pub fn closure_kind(&self,
1541 -> Option
<ty
::ClosureKind
>
1543 if def_id
.is_local() {
1544 self.tables
.borrow().closure_kinds
.get(&def_id
).cloned()
1546 // During typeck, ALL closures are local. But afterwards,
1547 // during trans, we see closure ids from other traits.
1548 // That may require loading the closure data out of the
1550 Some(ty
::Tables
::closure_kind(&self.tables
, self.tcx
, def_id
))
1554 pub fn closure_type(&self,
1556 substs
: &ty
::ClosureSubsts
<'tcx
>)
1557 -> ty
::ClosureTy
<'tcx
>
1560 ty
::Tables
::closure_type(self.tables
,
1566 normalize_associated_type(&self.tcx
, &closure_ty
)
1573 impl<'tcx
> TypeTrace
<'tcx
> {
1574 pub fn span(&self) -> Span
{
1578 pub fn types(origin
: TypeOrigin
,
1579 a_is_expected
: bool
,
1582 -> TypeTrace
<'tcx
> {
1585 values
: Types(expected_found(a_is_expected
, a
, b
))
1589 pub fn dummy(tcx
: &TyCtxt
<'tcx
>) -> TypeTrace
<'tcx
> {
1591 origin
: TypeOrigin
::Misc(codemap
::DUMMY_SP
),
1592 values
: Types(ExpectedFound
{
1593 expected
: tcx
.types
.err
,
1594 found
: tcx
.types
.err
,
1600 impl<'tcx
> fmt
::Debug
for TypeTrace
<'tcx
> {
1601 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1602 write
!(f
, "TypeTrace({:?})", self.origin
)
1607 pub fn span(&self) -> Span
{
1609 TypeOrigin
::MethodCompatCheck(span
) => span
,
1610 TypeOrigin
::ExprAssignable(span
) => span
,
1611 TypeOrigin
::Misc(span
) => span
,
1612 TypeOrigin
::RelateTraitRefs(span
) => span
,
1613 TypeOrigin
::RelateSelfType(span
) => span
,
1614 TypeOrigin
::RelateOutputImplTypes(span
) => span
,
1615 TypeOrigin
::MatchExpressionArm(match_span
, _
, _
) => match_span
,
1616 TypeOrigin
::IfExpression(span
) => span
,
1617 TypeOrigin
::IfExpressionWithNoElse(span
) => span
,
1618 TypeOrigin
::RangeExpression(span
) => span
,
1619 TypeOrigin
::EquatePredicate(span
) => span
,
1624 impl<'tcx
> SubregionOrigin
<'tcx
> {
1625 pub fn span(&self) -> Span
{
1627 Subtype(ref a
) => a
.span(),
1628 InfStackClosure(a
) => a
,
1629 InvokeClosure(a
) => a
,
1630 DerefPointer(a
) => a
,
1631 FreeVariable(a
, _
) => a
,
1633 RelateObjectBound(a
) => a
,
1634 RelateParamBound(a
, _
) => a
,
1635 RelateRegionParamBound(a
) => a
,
1636 RelateDefaultParamBound(a
, _
) => a
,
1638 ReborrowUpvar(a
, _
) => a
,
1639 DataBorrowed(_
, a
) => a
,
1640 ReferenceOutlivesReferent(_
, a
) => a
,
1641 ParameterInScope(_
, a
) => a
,
1642 ExprTypeIsNotInScope(_
, a
) => a
,
1643 BindingTypeIsNotValidAtDecl(a
) => a
,
1650 SafeDestructor(a
) => a
,
1655 impl RegionVariableOrigin
{
1656 pub fn span(&self) -> Span
{
1658 MiscVariable(a
) => a
,
1659 PatternRegion(a
) => a
,
1660 AddrOfRegion(a
) => a
,
1663 EarlyBoundRegion(a
, _
) => a
,
1664 LateBoundRegion(a
, _
, _
) => a
,
1665 BoundRegionInCoherence(_
) => codemap
::DUMMY_SP
,
1666 UpvarRegion(_
, a
) => a