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::TypeOrigin::*;
17 pub use self::ValuePairs::*;
18 pub use middle::ty::IntVarValue;
19 pub use self::freshen::TypeFreshener;
20 pub use self::region_inference::{GenericKind, VerifyBound};
22 use middle::def_id::DefId;
24 use middle::free_region::FreeRegionMap;
25 use middle::mem_categorization as mc;
26 use middle::mem_categorization::McResult;
27 use middle::region::CodeExtent;
29 use middle::subst::Substs;
30 use middle::subst::Subst;
31 use middle::traits::{self, FulfillmentContext, Normalized,
32 SelectionContext, ObligationCause};
33 use middle::ty::adjustment;
34 use middle::ty::{TyVid, IntVid, FloatVid, RegionVid};
35 use middle::ty::{self, Ty, HasTypeFlags};
36 use middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
37 use middle::ty::fold::{TypeFolder, TypeFoldable};
38 use middle::ty::relate::{Relate, RelateResult, TypeRelation};
39 use rustc_data_structures::unify::{self, UnificationTable};
40 use std::cell::{RefCell, Ref};
45 use syntax::codemap::{Span, DUMMY_SP};
46 use util::nodemap::{FnvHashMap, FnvHashSet, NodeMap};
48 use self::combine::CombineFields;
49 use self::region_inference::{RegionVarBindings, RegionSnapshot};
50 use self::error_reporting::ErrorReporting;
51 use self::unify_key::ToType;
56 pub mod error_reporting;
61 pub mod region_inference;
65 pub mod type_variable;
68 pub type Bound<T> = Option<T>;
69 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
70 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
72 pub struct InferCtxt<'a, 'tcx: 'a> {
73 pub tcx: &'a ty::ctxt<'tcx>,
75 pub tables: &'a RefCell<ty::Tables<'tcx>>,
77 // We instantiate UnificationTable with bounds<Ty> because the
78 // types that might instantiate a general type variable have an
79 // order, represented by its upper and lower bounds.
80 type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
82 // Map from integral variable to the kind of integer it represents
83 int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
85 // Map from floating variable to the kind of float it represents
86 float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
88 // For region variables.
89 region_vars: RegionVarBindings<'a, 'tcx>,
91 pub parameter_environment: ty::ParameterEnvironment<'a, 'tcx>,
93 pub fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
95 // the set of predicates on which errors have been reported, to
96 // avoid reporting the same error twice.
97 pub reported_trait_errors: RefCell<FnvHashSet<traits::TraitErrorKey<'tcx>>>,
99 // This is a temporary field used for toggling on normalization in the inference context,
100 // as we move towards the approach described here:
101 // https://internals.rust-lang.org/t/flattening-the-contexts-for-fun-and-profit/2293
102 // At a point sometime in the future normalization will be done by the typing context
106 err_count_on_creation: usize,
109 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
110 /// region that each late-bound region was replaced with.
111 pub type SkolemizationMap = FnvHashMap<ty::BoundRegion,ty::Region>;
113 /// Why did we require that the two types be related?
115 /// See `error_reporting.rs` for more details
116 #[derive(Clone, Copy, Debug)]
117 pub enum TypeOrigin {
118 // Not yet categorized in a better way
121 // Checking that method of impl is compatible with trait
122 MethodCompatCheck(Span),
124 // Checking that this expression can be assigned where it needs to be
125 // FIXME(eddyb) #11161 is the original Expr required?
126 ExprAssignable(Span),
128 // Relating trait refs when resolving vtables
129 RelateTraitRefs(Span),
131 // Relating self types when resolving vtables
132 RelateSelfType(Span),
134 // Relating trait type parameters to those found in impl etc
135 RelateOutputImplTypes(Span),
137 // Computing common supertype in the arms of a match expression
138 MatchExpressionArm(Span, Span),
140 // Computing common supertype in an if expression
143 // Computing common supertype of an if expression with no else counter-part
144 IfExpressionWithNoElse(Span),
146 // Computing common supertype in a range expression
147 RangeExpression(Span),
150 EquatePredicate(Span),
154 fn as_str(&self) -> &'static str {
156 &TypeOrigin::Misc(_) |
157 &TypeOrigin::RelateSelfType(_) |
158 &TypeOrigin::RelateOutputImplTypes(_) |
159 &TypeOrigin::ExprAssignable(_) => "mismatched types",
160 &TypeOrigin::RelateTraitRefs(_) => "mismatched traits",
161 &TypeOrigin::MethodCompatCheck(_) => "method not compatible with trait",
162 &TypeOrigin::MatchExpressionArm(_, _) => "match arms have incompatible types",
163 &TypeOrigin::IfExpression(_) => "if and else have incompatible types",
164 &TypeOrigin::IfExpressionWithNoElse(_) => "if may be missing an else clause",
165 &TypeOrigin::RangeExpression(_) => "start and end of range have incompatible types",
166 &TypeOrigin::EquatePredicate(_) => "equality predicate not satisfied",
171 impl fmt::Display for TypeOrigin {
172 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error> {
173 fmt::Display::fmt(self.as_str(), f)
177 /// See `error_reporting.rs` for more details
178 #[derive(Clone, Debug)]
179 pub enum ValuePairs<'tcx> {
180 Types(ExpectedFound<Ty<'tcx>>),
181 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
182 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
185 /// The trace designates the path through inference that we took to
186 /// encounter an error or subtyping constraint.
188 /// See `error_reporting.rs` for more details.
190 pub struct TypeTrace<'tcx> {
192 values: ValuePairs<'tcx>,
195 /// The origin of a `r1 <= r2` constraint.
197 /// See `error_reporting.rs` for more details
198 #[derive(Clone, Debug)]
199 pub enum SubregionOrigin<'tcx> {
200 // Marker to indicate a constraint that only arises due to new
201 // provisions from RFC 1214. This will result in a warning, not an
203 RFC1214Subregion(Rc<SubregionOrigin<'tcx>>),
205 // Arose from a subtyping relation
206 Subtype(TypeTrace<'tcx>),
208 // Stack-allocated closures cannot outlive innermost loop
209 // or function so as to ensure we only require finite stack
210 InfStackClosure(Span),
212 // Invocation of closure must be within its lifetime
215 // Dereference of reference must be within its lifetime
218 // Closure bound must not outlive captured free variables
219 FreeVariable(Span, ast::NodeId),
221 // Index into slice must be within its lifetime
224 // When casting `&'a T` to an `&'b Trait` object,
225 // relating `'a` to `'b`
226 RelateObjectBound(Span),
228 // Some type parameter was instantiated with the given type,
229 // and that type must outlive some region.
230 RelateParamBound(Span, Ty<'tcx>),
232 // The given region parameter was instantiated with a region
233 // that must outlive some other region.
234 RelateRegionParamBound(Span),
236 // A bound placed on type parameters that states that must outlive
237 // the moment of their instantiation.
238 RelateDefaultParamBound(Span, Ty<'tcx>),
240 // Creating a pointer `b` to contents of another reference
243 // Creating a pointer `b` to contents of an upvar
244 ReborrowUpvar(Span, ty::UpvarId),
246 // Data with type `Ty<'tcx>` was borrowed
247 DataBorrowed(Ty<'tcx>, Span),
249 // (&'a &'b T) where a >= b
250 ReferenceOutlivesReferent(Ty<'tcx>, Span),
252 // Type or region parameters must be in scope.
253 ParameterInScope(ParameterOrigin, Span),
255 // The type T of an expression E must outlive the lifetime for E.
256 ExprTypeIsNotInScope(Ty<'tcx>, Span),
258 // A `ref b` whose region does not enclose the decl site
259 BindingTypeIsNotValidAtDecl(Span),
261 // Regions appearing in a method receiver must outlive method call
264 // Regions appearing in a function argument must outlive func call
267 // Region in return type of invoked fn must enclose call
270 // Operands must be in scope
273 // Region resulting from a `&` expr must enclose the `&` expr
276 // An auto-borrow that does not enclose the expr where it occurs
279 // Region constraint arriving from destructor safety
280 SafeDestructor(Span),
283 /// Places that type/region parameters can appear.
284 #[derive(Clone, Copy, Debug)]
285 pub enum ParameterOrigin {
287 MethodCall, // foo.bar() <-- parameters on impl providing bar()
288 OverloadedOperator, // a + b when overloaded
289 OverloadedDeref, // *a when overloaded
292 /// Times when we replace late-bound regions with variables:
293 #[derive(Clone, Copy, Debug)]
294 pub enum LateBoundRegionConversionTime {
295 /// when a fn is called
298 /// when two higher-ranked types are compared
301 /// when projecting an associated type
302 AssocTypeProjection(ast::Name),
305 /// Reasons to create a region inference variable
307 /// See `error_reporting.rs` for more details
308 #[derive(Clone, Debug)]
309 pub enum RegionVariableOrigin {
310 // Region variables created for ill-categorized reasons,
311 // mostly indicates places in need of refactoring
314 // Regions created by a `&P` or `[...]` pattern
317 // Regions created by `&` operator
320 // Regions created as part of an autoref of a method receiver
323 // Regions created as part of an automatic coercion
326 // Region variables created as the values for early-bound regions
327 EarlyBoundRegion(Span, ast::Name),
329 // Region variables created for bound regions
330 // in a function or method that is called
331 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
333 UpvarRegion(ty::UpvarId, Span),
335 BoundRegionInCoherence(ast::Name),
338 #[derive(Copy, Clone, Debug)]
339 pub enum FixupError {
340 UnresolvedIntTy(IntVid),
341 UnresolvedFloatTy(FloatVid),
345 pub fn fixup_err_to_string(f: FixupError) -> String {
346 use self::FixupError::*;
349 UnresolvedIntTy(_) => {
350 "cannot determine the type of this integer; add a suffix to \
351 specify the type explicitly".to_string()
353 UnresolvedFloatTy(_) => {
354 "cannot determine the type of this number; add a suffix to specify \
355 the type explicitly".to_string()
357 UnresolvedTy(_) => "unconstrained type".to_string(),
361 /// errors_will_be_reported is required to proxy to the fulfillment context
362 /// FIXME -- a better option would be to hold back on modifying
363 /// the global cache until we know that all dependent obligations
364 /// are also satisfied. In that case, we could actually remove
365 /// this boolean flag, and we'd also avoid the problem of squelching
366 /// duplicate errors that occur across fns.
367 pub fn new_infer_ctxt<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
368 tables: &'a RefCell<ty::Tables<'tcx>>,
369 param_env: Option<ty::ParameterEnvironment<'a, 'tcx>>,
370 errors_will_be_reported: bool)
371 -> InferCtxt<'a, 'tcx> {
375 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
376 int_unification_table: RefCell::new(UnificationTable::new()),
377 float_unification_table: RefCell::new(UnificationTable::new()),
378 region_vars: RegionVarBindings::new(tcx),
379 parameter_environment: param_env.unwrap_or(tcx.empty_parameter_environment()),
380 fulfillment_cx: RefCell::new(traits::FulfillmentContext::new(errors_will_be_reported)),
381 reported_trait_errors: RefCell::new(FnvHashSet()),
383 err_count_on_creation: tcx.sess.err_count()
387 pub fn normalizing_infer_ctxt<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
388 tables: &'a RefCell<ty::Tables<'tcx>>)
389 -> InferCtxt<'a, 'tcx> {
390 let mut infcx = new_infer_ctxt(tcx, tables, None, false);
391 infcx.normalize = true;
395 /// Computes the least upper-bound of `a` and `b`. If this is not possible, reports an error and
397 pub fn common_supertype<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
404 debug!("common_supertype({:?}, {:?})",
407 let trace = TypeTrace {
409 values: Types(expected_found(a_is_expected, a, b))
412 let result = cx.commit_if_ok(|_| cx.lub(a_is_expected, trace.clone()).relate(&a, &b));
416 cx.report_and_explain_type_error(trace, err);
422 pub fn mk_subty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
429 debug!("mk_subty({:?} <: {:?})", a, b);
430 cx.sub_types(a_is_expected, origin, a, b)
433 pub fn can_mk_subty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
436 -> UnitResult<'tcx> {
437 debug!("can_mk_subty({:?} <: {:?})", a, b);
439 let trace = TypeTrace {
440 origin: Misc(codemap::DUMMY_SP),
441 values: Types(expected_found(true, a, b))
443 cx.sub(true, trace).relate(&a, &b).map(|_| ())
447 pub fn can_mk_eqty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>)
450 cx.can_equate(&a, &b)
453 pub fn mk_subr<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
454 origin: SubregionOrigin<'tcx>,
457 debug!("mk_subr({:?} <: {:?})", a, b);
458 let snapshot = cx.region_vars.start_snapshot();
459 cx.region_vars.make_subregion(origin, a, b);
460 cx.region_vars.commit(snapshot);
463 pub fn mk_eqty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
470 debug!("mk_eqty({:?} <: {:?})", a, b);
471 cx.commit_if_ok(|_| cx.eq_types(a_is_expected, origin, a, b))
474 pub fn mk_sub_poly_trait_refs<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
477 a: ty::PolyTraitRef<'tcx>,
478 b: ty::PolyTraitRef<'tcx>)
481 debug!("mk_sub_trait_refs({:?} <: {:?})",
483 cx.commit_if_ok(|_| cx.sub_poly_trait_refs(a_is_expected, origin, a.clone(), b.clone()))
486 fn expected_found<T>(a_is_expected: bool,
492 ExpectedFound {expected: a, found: b}
494 ExpectedFound {expected: b, found: a}
498 #[must_use = "once you start a snapshot, you should always consume it"]
499 pub struct CombinedSnapshot {
500 type_snapshot: type_variable::Snapshot,
501 int_snapshot: unify::Snapshot<ty::IntVid>,
502 float_snapshot: unify::Snapshot<ty::FloatVid>,
503 region_vars_snapshot: RegionSnapshot,
506 pub fn normalize_associated_type<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> T
507 where T : TypeFoldable<'tcx> + HasTypeFlags
509 debug!("normalize_associated_type(t={:?})", value);
511 let value = tcx.erase_regions(value);
513 if !value.has_projection_types() {
517 let infcx = new_infer_ctxt(tcx, &tcx.tables, None, true);
518 let mut selcx = traits::SelectionContext::new(&infcx);
519 let cause = traits::ObligationCause::dummy();
520 let traits::Normalized { value: result, obligations } =
521 traits::normalize(&mut selcx, cause, &value);
523 debug!("normalize_associated_type: result={:?} obligations={:?}",
527 let mut fulfill_cx = infcx.fulfillment_cx.borrow_mut();
529 for obligation in obligations {
530 fulfill_cx.register_predicate_obligation(&infcx, obligation);
533 drain_fulfillment_cx_or_panic(DUMMY_SP, &infcx, &mut fulfill_cx, &result)
536 pub fn drain_fulfillment_cx_or_panic<'a,'tcx,T>(span: Span,
537 infcx: &InferCtxt<'a,'tcx>,
538 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
541 where T : TypeFoldable<'tcx> + HasTypeFlags
543 match drain_fulfillment_cx(infcx, fulfill_cx, result) {
546 infcx.tcx.sess.span_bug(
548 &format!("Encountered errors `{:?}` fulfilling during trans",
554 /// Finishes processes any obligations that remain in the fulfillment
555 /// context, and then "freshens" and returns `result`. This is
556 /// primarily used during normalization and other cases where
557 /// processing the obligations in `fulfill_cx` may cause type
558 /// inference variables that appear in `result` to be unified, and
559 /// hence we need to process those obligations to get the complete
560 /// picture of the type.
561 pub fn drain_fulfillment_cx<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>,
562 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
564 -> Result<T,Vec<traits::FulfillmentError<'tcx>>>
565 where T : TypeFoldable<'tcx> + HasTypeFlags
567 debug!("drain_fulfillment_cx(result={:?})",
570 // In principle, we only need to do this so long as `result`
571 // contains unbound type parameters. It could be a slight
572 // optimization to stop iterating early.
573 match fulfill_cx.select_all_or_error(infcx) {
580 let result = infcx.resolve_type_vars_if_possible(result);
581 Ok(infcx.tcx.erase_regions(&result))
584 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
585 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
586 t.fold_with(&mut self.freshener())
589 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
591 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
596 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
597 freshen::TypeFreshener::new(self)
600 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
601 use middle::ty::error::UnconstrainedNumeric::Neither;
602 use middle::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
604 ty::TyInfer(ty::IntVar(vid)) => {
605 if self.int_unification_table.borrow_mut().has_value(vid) {
611 ty::TyInfer(ty::FloatVar(vid)) => {
612 if self.float_unification_table.borrow_mut().has_value(vid) {
622 /// Returns a type variable's default fallback if any exists. A default
623 /// must be attached to the variable when created, if it is created
624 /// without a default, this will return None.
626 /// This code does not apply to integral or floating point variables,
627 /// only to use declared defaults.
629 /// See `new_ty_var_with_default` to create a type variable with a default.
630 /// See `type_variable::Default` for details about what a default entails.
631 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
633 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
638 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
639 let mut variables = Vec::new();
641 let unbound_ty_vars = self.type_variables
643 .unsolved_variables()
645 .map(|t| self.tcx.mk_var(t));
647 let unbound_int_vars = self.int_unification_table
649 .unsolved_variables()
651 .map(|v| self.tcx.mk_int_var(v));
653 let unbound_float_vars = self.float_unification_table
655 .unsolved_variables()
657 .map(|v| self.tcx.mk_float_var(v));
659 variables.extend(unbound_ty_vars);
660 variables.extend(unbound_int_vars);
661 variables.extend(unbound_float_vars);
666 fn combine_fields(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
667 -> CombineFields<'a, 'tcx> {
668 CombineFields {infcx: self,
669 a_is_expected: a_is_expected,
674 // public so that it can be used from the rustc_driver unit tests
675 pub fn equate(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
676 -> equate::Equate<'a, 'tcx>
678 self.combine_fields(a_is_expected, trace).equate()
681 // public so that it can be used from the rustc_driver unit tests
682 pub fn sub(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
683 -> sub::Sub<'a, 'tcx>
685 self.combine_fields(a_is_expected, trace).sub()
688 // public so that it can be used from the rustc_driver unit tests
689 pub fn lub(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
690 -> lub::Lub<'a, 'tcx>
692 self.combine_fields(a_is_expected, trace).lub()
695 // public so that it can be used from the rustc_driver unit tests
696 pub fn glb(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
697 -> glb::Glb<'a, 'tcx>
699 self.combine_fields(a_is_expected, trace).glb()
702 fn start_snapshot(&self) -> CombinedSnapshot {
704 type_snapshot: self.type_variables.borrow_mut().snapshot(),
705 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
706 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
707 region_vars_snapshot: self.region_vars.start_snapshot(),
711 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
712 debug!("rollback_to(cause={})", cause);
713 let CombinedSnapshot { type_snapshot,
716 region_vars_snapshot } = snapshot;
720 .rollback_to(type_snapshot);
721 self.int_unification_table
723 .rollback_to(int_snapshot);
724 self.float_unification_table
726 .rollback_to(float_snapshot);
728 .rollback_to(region_vars_snapshot);
731 fn commit_from(&self, snapshot: CombinedSnapshot) {
732 debug!("commit_from!");
733 let CombinedSnapshot { type_snapshot,
736 region_vars_snapshot } = snapshot;
740 .commit(type_snapshot);
741 self.int_unification_table
743 .commit(int_snapshot);
744 self.float_unification_table
746 .commit(float_snapshot);
748 .commit(region_vars_snapshot);
751 /// Execute `f` and commit the bindings
752 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
756 let snapshot = self.start_snapshot();
758 self.commit_from(snapshot);
762 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
763 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
764 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
766 debug!("commit_if_ok()");
767 let snapshot = self.start_snapshot();
768 let r = f(&snapshot);
769 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
771 Ok(_) => { self.commit_from(snapshot); }
772 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
777 /// Execute `f` and commit only the region bindings if successful.
778 /// The function f must be very careful not to leak any non-region
779 /// variables that get created.
780 pub fn commit_regions_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
781 F: FnOnce() -> Result<T, E>
783 debug!("commit_regions_if_ok()");
784 let CombinedSnapshot { type_snapshot,
787 region_vars_snapshot } = self.start_snapshot();
789 let r = self.commit_if_ok(|_| f());
791 debug!("commit_regions_if_ok: rolling back everything but regions");
793 // Roll back any non-region bindings - they should be resolved
794 // inside `f`, with, e.g. `resolve_type_vars_if_possible`.
797 .rollback_to(type_snapshot);
798 self.int_unification_table
800 .rollback_to(int_snapshot);
801 self.float_unification_table
803 .rollback_to(float_snapshot);
805 // Commit region vars that may escape through resolved types.
807 .commit(region_vars_snapshot);
812 /// Execute `f` then unroll any bindings it creates
813 pub fn probe<R, F>(&self, f: F) -> R where
814 F: FnOnce(&CombinedSnapshot) -> R,
817 let snapshot = self.start_snapshot();
818 let r = f(&snapshot);
819 self.rollback_to("probe", snapshot);
823 pub fn add_given(&self,
827 self.region_vars.add_given(sub, sup);
830 pub fn sub_types(&self,
837 debug!("sub_types({:?} <: {:?})", a, b);
838 self.commit_if_ok(|_| {
839 let trace = TypeTrace::types(origin, a_is_expected, a, b);
840 self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
844 pub fn eq_types(&self,
851 self.commit_if_ok(|_| {
852 let trace = TypeTrace::types(origin, a_is_expected, a, b);
853 self.equate(a_is_expected, trace).relate(&a, &b).map(|_| ())
857 pub fn sub_trait_refs(&self,
860 a: ty::TraitRef<'tcx>,
861 b: ty::TraitRef<'tcx>)
864 debug!("sub_trait_refs({:?} <: {:?})",
867 self.commit_if_ok(|_| {
868 let trace = TypeTrace {
870 values: TraitRefs(expected_found(a_is_expected, a.clone(), b.clone()))
872 self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
876 pub fn sub_poly_trait_refs(&self,
879 a: ty::PolyTraitRef<'tcx>,
880 b: ty::PolyTraitRef<'tcx>)
883 debug!("sub_poly_trait_refs({:?} <: {:?})",
886 self.commit_if_ok(|_| {
887 let trace = TypeTrace {
889 values: PolyTraitRefs(expected_found(a_is_expected, a.clone(), b.clone()))
891 self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
895 pub fn skolemize_late_bound_regions<T>(&self,
896 value: &ty::Binder<T>,
897 snapshot: &CombinedSnapshot)
898 -> (T, SkolemizationMap)
899 where T : TypeFoldable<'tcx>
901 /*! See `higher_ranked::skolemize_late_bound_regions` */
903 higher_ranked::skolemize_late_bound_regions(self, value, snapshot)
906 pub fn leak_check(&self,
907 skol_map: &SkolemizationMap,
908 snapshot: &CombinedSnapshot)
911 /*! See `higher_ranked::leak_check` */
913 match higher_ranked::leak_check(self, skol_map, snapshot) {
915 Err((br, r)) => Err(TypeError::RegionsInsufficientlyPolymorphic(br, r))
919 pub fn plug_leaks<T>(&self,
920 skol_map: SkolemizationMap,
921 snapshot: &CombinedSnapshot,
924 where T : TypeFoldable<'tcx> + HasTypeFlags
926 /*! See `higher_ranked::plug_leaks` */
928 higher_ranked::plug_leaks(self, skol_map, snapshot, value)
931 pub fn equality_predicate(&self,
933 predicate: &ty::PolyEquatePredicate<'tcx>)
934 -> UnitResult<'tcx> {
935 self.commit_if_ok(|snapshot| {
936 let (ty::EquatePredicate(a, b), skol_map) =
937 self.skolemize_late_bound_regions(predicate, snapshot);
938 let origin = EquatePredicate(span);
939 let () = try!(mk_eqty(self, false, origin, a, b));
940 self.leak_check(&skol_map, snapshot)
944 pub fn region_outlives_predicate(&self,
946 predicate: &ty::PolyRegionOutlivesPredicate)
947 -> UnitResult<'tcx> {
948 self.commit_if_ok(|snapshot| {
949 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
950 self.skolemize_late_bound_regions(predicate, snapshot);
951 let origin = RelateRegionParamBound(span);
952 let () = mk_subr(self, origin, r_b, r_a); // `b : a` ==> `a <= b`
953 self.leak_check(&skol_map, snapshot)
957 pub fn next_ty_var_id(&self, diverging: bool) -> TyVid {
960 .new_var(diverging, None)
963 pub fn next_ty_var(&self) -> Ty<'tcx> {
964 self.tcx.mk_var(self.next_ty_var_id(false))
967 pub fn next_ty_var_with_default(&self,
968 default: Option<type_variable::Default<'tcx>>) -> Ty<'tcx> {
969 let ty_var_id = self.type_variables
971 .new_var(false, default);
973 self.tcx.mk_var(ty_var_id)
976 pub fn next_diverging_ty_var(&self) -> Ty<'tcx> {
977 self.tcx.mk_var(self.next_ty_var_id(true))
980 pub fn next_ty_vars(&self, n: usize) -> Vec<Ty<'tcx>> {
981 (0..n).map(|_i| self.next_ty_var()).collect()
984 pub fn next_int_var_id(&self) -> IntVid {
985 self.int_unification_table
990 pub fn next_float_var_id(&self) -> FloatVid {
991 self.float_unification_table
996 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region {
997 ty::ReVar(self.region_vars.new_region_var(origin))
1000 pub fn region_vars_for_defs(&self,
1002 defs: &[ty::RegionParameterDef])
1003 -> Vec<ty::Region> {
1005 .map(|d| self.next_region_var(EarlyBoundRegion(span, d.name)))
1009 // We have to take `&mut Substs` in order to provide the correct substitutions for defaults
1010 // along the way, for this reason we don't return them.
1011 pub fn type_vars_for_defs(&self,
1013 space: subst::ParamSpace,
1014 substs: &mut Substs<'tcx>,
1015 defs: &[ty::TypeParameterDef<'tcx>]) {
1017 let mut vars = Vec::with_capacity(defs.len());
1019 for def in defs.iter() {
1020 let default = def.default.map(|default| {
1021 type_variable::Default {
1022 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1024 def_id: def.default_def_id
1028 let ty_var = self.next_ty_var_with_default(default);
1029 substs.types.push(space, ty_var);
1034 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1035 /// type/region parameter to a fresh inference variable.
1036 pub fn fresh_substs_for_generics(&self,
1038 generics: &ty::Generics<'tcx>)
1039 -> subst::Substs<'tcx>
1041 let type_params = subst::VecPerParamSpace::empty();
1044 generics.regions.map(
1045 |d| self.next_region_var(EarlyBoundRegion(span, d.name)));
1047 let mut substs = subst::Substs::new(type_params, region_params);
1049 for space in subst::ParamSpace::all().iter() {
1050 self.type_vars_for_defs(
1054 generics.types.get_slice(*space));
1060 /// Given a set of generics defined on a trait, returns a substitution mapping each output
1061 /// type/region parameter to a fresh inference variable, and mapping the self type to
1063 pub fn fresh_substs_for_trait(&self,
1065 generics: &ty::Generics<'tcx>,
1067 -> subst::Substs<'tcx>
1070 assert!(generics.types.len(subst::SelfSpace) == 1);
1071 assert!(generics.types.len(subst::FnSpace) == 0);
1072 assert!(generics.regions.len(subst::SelfSpace) == 0);
1073 assert!(generics.regions.len(subst::FnSpace) == 0);
1075 let type_params = Vec::new();
1077 let region_param_defs = generics.regions.get_slice(subst::TypeSpace);
1078 let regions = self.region_vars_for_defs(span, region_param_defs);
1080 let mut substs = subst::Substs::new_trait(type_params, regions, self_ty);
1082 let type_parameter_defs = generics.types.get_slice(subst::TypeSpace);
1083 self.type_vars_for_defs(span, subst::TypeSpace, &mut substs, type_parameter_defs);
1088 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region {
1089 self.region_vars.new_bound(debruijn)
1092 /// Apply `adjustment` to the type of `expr`
1093 pub fn adjust_expr_ty(&self,
1095 adjustment: Option<&adjustment::AutoAdjustment<'tcx>>)
1098 let raw_ty = self.expr_ty(expr);
1099 let raw_ty = self.shallow_resolve(raw_ty);
1100 let resolve_ty = |ty: Ty<'tcx>| self.resolve_type_vars_if_possible(&ty);
1101 raw_ty.adjust(self.tcx,
1105 |method_call| self.tables
1109 .map(|method| resolve_ty(method.ty)))
1112 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1113 match self.tables.borrow().node_types.get(&id) {
1116 None if self.tcx.sess.err_count() - self.err_count_on_creation != 0 =>
1120 &format!("no type for node {}: {} in fcx",
1121 id, self.tcx.map.node_to_string(id)));
1126 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1127 match self.tables.borrow().node_types.get(&ex.id) {
1130 self.tcx.sess.bug(&format!("no type for expr in fcx"));
1135 pub fn resolve_regions_and_report_errors(&self,
1136 free_regions: &FreeRegionMap,
1137 subject_node_id: ast::NodeId) {
1138 let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1139 self.report_region_errors(&errors); // see error_reporting.rs
1142 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1143 self.resolve_type_vars_if_possible(&t).to_string()
1146 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1147 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1148 format!("({})", tstrs.join(", "))
1151 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1152 self.resolve_type_vars_if_possible(t).to_string()
1155 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1157 ty::TyInfer(ty::TyVar(v)) => {
1158 // Not entirely obvious: if `typ` is a type variable,
1159 // it can be resolved to an int/float variable, which
1160 // can then be recursively resolved, hence the
1161 // recursion. Note though that we prevent type
1162 // variables from unifying to other type variables
1163 // directly (though they may be embedded
1164 // structurally), and we prevent cycles in any case,
1165 // so this recursion should always be of very limited
1167 self.type_variables.borrow()
1169 .map(|t| self.shallow_resolve(t))
1173 ty::TyInfer(ty::IntVar(v)) => {
1174 self.int_unification_table
1177 .map(|v| v.to_type(self.tcx))
1181 ty::TyInfer(ty::FloatVar(v)) => {
1182 self.float_unification_table
1185 .map(|v| v.to_type(self.tcx))
1195 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1196 where T: TypeFoldable<'tcx> + HasTypeFlags
1199 * Where possible, replaces type/int/float variables in
1200 * `value` with their final value. Note that region variables
1201 * are unaffected. If a type variable has not been unified, it
1202 * is left as is. This is an idempotent operation that does
1203 * not affect inference state in any way and so you can do it
1207 if !value.needs_infer() {
1208 return value.clone(); // avoid duplicated subst-folding
1210 let mut r = resolve::OpportunisticTypeResolver::new(self);
1211 value.fold_with(&mut r)
1214 /// Resolves all type variables in `t` and then, if any were left
1215 /// unresolved, substitutes an error type. This is used after the
1216 /// main checking when doing a second pass before writeback. The
1217 /// justification is that writeback will produce an error for
1218 /// these unconstrained type variables.
1219 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1220 let ty = self.resolve_type_vars_if_possible(t);
1221 if ty.references_error() || ty.is_ty_var() {
1222 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1229 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1231 * Attempts to resolve all type/region variables in
1232 * `value`. Region inference must have been run already (e.g.,
1233 * by calling `resolve_regions_and_report_errors`). If some
1234 * variable was never unified, an `Err` results.
1236 * This method is idempotent, but it not typically not invoked
1237 * except during the writeback phase.
1240 resolve::fully_resolve(self, value)
1243 // [Note-Type-error-reporting]
1244 // An invariant is that anytime the expected or actual type is TyError (the special
1245 // error type, meaning that an error occurred when typechecking this expression),
1246 // this is a derived error. The error cascaded from another error (that was already
1247 // reported), so it's not useful to display it to the user.
1248 // The following four methods -- type_error_message_str, type_error_message_str_with_expected,
1249 // type_error_message, and report_mismatched_types -- implement this logic.
1250 // They check if either the actual or expected type is TyError, and don't print the error
1251 // in this case. The typechecker should only ever report type errors involving mismatched
1252 // types using one of these four methods, and should not call span_err directly for such
1254 pub fn type_error_message_str<M>(&self,
1258 err: Option<&TypeError<'tcx>>) where
1259 M: FnOnce(Option<String>, String) -> String,
1261 self.type_error_message_str_with_expected(sp, mk_msg, None, actual_ty, err)
1264 pub fn type_error_message_str_with_expected<M>(&self,
1267 expected_ty: Option<Ty<'tcx>>,
1269 err: Option<&TypeError<'tcx>>) where
1270 M: FnOnce(Option<String>, String) -> String,
1272 debug!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty, actual_ty);
1274 let resolved_expected = expected_ty.map(|e_ty| self.resolve_type_vars_if_possible(&e_ty));
1276 if !resolved_expected.references_error() {
1277 let error_str = err.map_or("".to_string(), |t_err| {
1278 format!(" ({})", t_err)
1281 self.tcx.sess.span_err(sp, &format!("{}{}",
1282 mk_msg(resolved_expected.map(|t| self.ty_to_string(t)), actual_ty),
1285 if let Some(err) = err {
1286 self.tcx.note_and_explain_type_err(err, sp)
1291 pub fn type_error_message<M>(&self,
1294 actual_ty: Ty<'tcx>,
1295 err: Option<&TypeError<'tcx>>) where
1296 M: FnOnce(String) -> String,
1298 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1300 // Don't report an error if actual type is TyError.
1301 if actual_ty.references_error() {
1305 self.type_error_message_str(sp,
1306 move |_e, a| { mk_msg(a) },
1307 self.ty_to_string(actual_ty), err);
1310 pub fn report_mismatched_types(&self,
1314 err: &TypeError<'tcx>) {
1315 let trace = TypeTrace {
1317 values: Types(ExpectedFound {
1322 self.report_and_explain_type_error(trace, err);
1325 pub fn report_conflicting_default_types(&self,
1327 expected: type_variable::Default<'tcx>,
1328 actual: type_variable::Default<'tcx>) {
1329 let trace = TypeTrace {
1331 values: Types(ExpectedFound {
1332 expected: expected.ty,
1337 self.report_and_explain_type_error(trace,
1338 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1344 pub fn replace_late_bound_regions_with_fresh_var<T>(
1347 lbrct: LateBoundRegionConversionTime,
1348 value: &ty::Binder<T>)
1349 -> (T, FnvHashMap<ty::BoundRegion,ty::Region>)
1350 where T : TypeFoldable<'tcx>
1352 self.tcx.replace_late_bound_regions(
1354 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1357 /// See `verify_generic_bound` method in `region_inference`
1358 pub fn verify_generic_bound(&self,
1359 origin: SubregionOrigin<'tcx>,
1360 kind: GenericKind<'tcx>,
1362 bound: VerifyBound) {
1363 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1368 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1371 pub fn can_equate<'b,T>(&'b self, a: &T, b: &T) -> UnitResult<'tcx>
1372 where T: Relate<'b,'tcx> + fmt::Debug
1374 debug!("can_equate({:?}, {:?})", a, b);
1376 // Gin up a dummy trace, since this won't be committed
1377 // anyhow. We should make this typetrace stuff more
1378 // generic so we don't have to do anything quite this
1380 let e = self.tcx.types.err;
1381 let trace = TypeTrace { origin: Misc(codemap::DUMMY_SP),
1382 values: Types(expected_found(true, e, e)) };
1383 self.equate(true, trace).relate(a, b)
1387 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1388 let ty = self.node_type(id);
1389 self.resolve_type_vars_or_error(&ty)
1392 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1393 let ty = self.adjust_expr_ty(expr, self.tables.borrow().adjustments.get(&expr.id));
1394 self.resolve_type_vars_or_error(&ty)
1397 pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1398 let ty = self.resolve_type_vars_if_possible(&ty);
1399 if ty.needs_infer() {
1400 // this can get called from typeck (by euv), and moves_by_default
1401 // rightly refuses to work with inference variables, but
1402 // moves_by_default has a cache, which we want to use in other
1404 !traits::type_known_to_meet_builtin_bound(self, ty, ty::BoundCopy, span)
1406 ty.moves_by_default(&self.parameter_environment, span)
1410 pub fn node_method_ty(&self, method_call: ty::MethodCall)
1411 -> Option<Ty<'tcx>> {
1416 .map(|method| method.ty)
1417 .map(|ty| self.resolve_type_vars_if_possible(&ty))
1420 pub fn node_method_id(&self, method_call: ty::MethodCall)
1426 .map(|method| method.def_id)
1429 pub fn adjustments(&self) -> Ref<NodeMap<adjustment::AutoAdjustment<'tcx>>> {
1430 fn project_adjustments<'a, 'tcx>(tables: &'a ty::Tables<'tcx>)
1431 -> &'a NodeMap<adjustment::AutoAdjustment<'tcx>> {
1435 Ref::map(self.tables.borrow(), project_adjustments)
1438 pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1439 self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1442 pub fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<CodeExtent> {
1443 self.tcx.region_maps.temporary_scope(rvalue_id)
1446 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
1447 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1450 pub fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
1451 &self.parameter_environment
1454 pub fn closure_kind(&self,
1456 -> Option<ty::ClosureKind>
1458 if def_id.is_local() {
1459 self.tables.borrow().closure_kinds.get(&def_id).cloned()
1461 // During typeck, ALL closures are local. But afterwards,
1462 // during trans, we see closure ids from other traits.
1463 // That may require loading the closure data out of the
1465 Some(ty::Tables::closure_kind(&self.tables, self.tcx, def_id))
1469 pub fn closure_type(&self,
1471 substs: &ty::ClosureSubsts<'tcx>)
1472 -> ty::ClosureTy<'tcx>
1475 ty::Tables::closure_type(self.tables,
1481 normalize_associated_type(&self.tcx, &closure_ty)
1488 impl<'tcx> TypeTrace<'tcx> {
1489 pub fn span(&self) -> Span {
1493 pub fn types(origin: TypeOrigin,
1494 a_is_expected: bool,
1497 -> TypeTrace<'tcx> {
1500 values: Types(expected_found(a_is_expected, a, b))
1504 pub fn dummy(tcx: &ty::ctxt<'tcx>) -> TypeTrace<'tcx> {
1506 origin: Misc(codemap::DUMMY_SP),
1507 values: Types(ExpectedFound {
1508 expected: tcx.types.err,
1509 found: tcx.types.err,
1515 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1516 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1517 write!(f, "TypeTrace({:?})", self.origin)
1522 pub fn span(&self) -> Span {
1524 MethodCompatCheck(span) => span,
1525 ExprAssignable(span) => span,
1527 RelateTraitRefs(span) => span,
1528 RelateSelfType(span) => span,
1529 RelateOutputImplTypes(span) => span,
1530 MatchExpressionArm(match_span, _) => match_span,
1531 IfExpression(span) => span,
1532 IfExpressionWithNoElse(span) => span,
1533 RangeExpression(span) => span,
1534 EquatePredicate(span) => span,
1539 impl<'tcx> SubregionOrigin<'tcx> {
1540 pub fn span(&self) -> Span {
1542 RFC1214Subregion(ref a) => a.span(),
1543 Subtype(ref a) => a.span(),
1544 InfStackClosure(a) => a,
1545 InvokeClosure(a) => a,
1546 DerefPointer(a) => a,
1547 FreeVariable(a, _) => a,
1549 RelateObjectBound(a) => a,
1550 RelateParamBound(a, _) => a,
1551 RelateRegionParamBound(a) => a,
1552 RelateDefaultParamBound(a, _) => a,
1554 ReborrowUpvar(a, _) => a,
1555 DataBorrowed(_, a) => a,
1556 ReferenceOutlivesReferent(_, a) => a,
1557 ParameterInScope(_, a) => a,
1558 ExprTypeIsNotInScope(_, a) => a,
1559 BindingTypeIsNotValidAtDecl(a) => a,
1566 SafeDestructor(a) => a,
1571 impl RegionVariableOrigin {
1572 pub fn span(&self) -> Span {
1574 MiscVariable(a) => a,
1575 PatternRegion(a) => a,
1576 AddrOfRegion(a) => a,
1579 EarlyBoundRegion(a, _) => a,
1580 LateBoundRegion(a, _, _) => a,
1581 BoundRegionInCoherence(_) => codemap::DUMMY_SP,
1582 UpvarRegion(_, a) => a