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 middle::ty::IntVarValue;
18 pub use self::freshen::TypeFreshener;
19 pub use self::region_inference::{GenericKind, VerifyBound};
21 use middle::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 middle::subst::Substs;
29 use middle::subst::Subst;
31 use middle::ty::adjustment;
32 use middle::ty::{TyVid, IntVid, FloatVid};
33 use middle::ty::{self, Ty, HasTypeFlags};
34 use middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
35 use middle::ty::fold::{TypeFolder, TypeFoldable};
36 use middle::ty::relate::{Relate, RelateResult, TypeRelation};
37 use rustc_data_structures::unify::{self, UnificationTable};
38 use std::cell::{RefCell, Ref};
43 use syntax::codemap::{Span, DUMMY_SP};
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 type Bound<T> = Option<T>;
67 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
68 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
70 pub struct InferCtxt<'a, 'tcx: 'a> {
71 pub tcx: &'a ty::ctxt<'tcx>,
73 pub tables: &'a RefCell<ty::Tables<'tcx>>,
75 // We instantiate UnificationTable with bounds<Ty> because the
76 // types that might instantiate a general type variable have an
77 // order, represented by its upper and lower bounds.
78 type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
80 // Map from integral variable to the kind of integer it represents
81 int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
83 // Map from floating variable to the kind of float it represents
84 float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
86 // For region variables.
87 region_vars: RegionVarBindings<'a, 'tcx>,
89 pub parameter_environment: ty::ParameterEnvironment<'a, 'tcx>,
91 pub fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
93 // the set of predicates on which errors have been reported, to
94 // avoid reporting the same error twice.
95 pub reported_trait_errors: RefCell<FnvHashSet<traits::TraitErrorKey<'tcx>>>,
97 // This is a temporary field used for toggling on normalization in the inference context,
98 // as we move towards the approach described here:
99 // https://internals.rust-lang.org/t/flattening-the-contexts-for-fun-and-profit/2293
100 // At a point sometime in the future normalization will be done by the typing context
104 err_count_on_creation: usize,
107 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
108 /// region that each late-bound region was replaced with.
109 pub type SkolemizationMap = FnvHashMap<ty::BoundRegion,ty::Region>;
111 /// Why did we require that the two types be related?
113 /// See `error_reporting.rs` for more details
114 #[derive(Clone, Copy, Debug)]
115 pub enum TypeOrigin {
116 // Not yet categorized in a better way
119 // Checking that method of impl is compatible with trait
120 MethodCompatCheck(Span),
122 // Checking that this expression can be assigned where it needs to be
123 // FIXME(eddyb) #11161 is the original Expr required?
124 ExprAssignable(Span),
126 // Relating trait refs when resolving vtables
127 RelateTraitRefs(Span),
129 // Relating self types when resolving vtables
130 RelateSelfType(Span),
132 // Relating trait type parameters to those found in impl etc
133 RelateOutputImplTypes(Span),
135 // Computing common supertype in the arms of a match expression
136 MatchExpressionArm(Span, Span, hir::MatchSource),
138 // Computing common supertype in an if expression
141 // Computing common supertype of an if expression with no else counter-part
142 IfExpressionWithNoElse(Span),
144 // Computing common supertype in a range expression
145 RangeExpression(Span),
148 EquatePredicate(Span),
152 fn as_str(&self) -> &'static str {
154 &TypeOrigin::Misc(_) |
155 &TypeOrigin::RelateSelfType(_) |
156 &TypeOrigin::RelateOutputImplTypes(_) |
157 &TypeOrigin::ExprAssignable(_) => "mismatched types",
158 &TypeOrigin::RelateTraitRefs(_) => "mismatched traits",
159 &TypeOrigin::MethodCompatCheck(_) => "method not compatible with trait",
160 &TypeOrigin::MatchExpressionArm(_, _, source) => match source {
161 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
162 _ => "match arms have incompatible types",
164 &TypeOrigin::IfExpression(_) => "if and else have incompatible types",
165 &TypeOrigin::IfExpressionWithNoElse(_) => "if may be missing an else clause",
166 &TypeOrigin::RangeExpression(_) => "start and end of range have incompatible types",
167 &TypeOrigin::EquatePredicate(_) => "equality predicate not satisfied",
172 impl fmt::Display for TypeOrigin {
173 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error> {
174 fmt::Display::fmt(self.as_str(), f)
178 /// See `error_reporting.rs` for more details
179 #[derive(Clone, Debug)]
180 pub enum ValuePairs<'tcx> {
181 Types(ExpectedFound<Ty<'tcx>>),
182 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
183 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
186 /// The trace designates the path through inference that we took to
187 /// encounter an error or subtyping constraint.
189 /// See `error_reporting.rs` for more details.
191 pub struct TypeTrace<'tcx> {
193 values: ValuePairs<'tcx>,
196 /// The origin of a `r1 <= r2` constraint.
198 /// See `error_reporting.rs` for more details
199 #[derive(Clone, Debug)]
200 pub enum SubregionOrigin<'tcx> {
201 // Marker to indicate a constraint that only arises due to new
202 // provisions from RFC 1214. This will result in a warning, not an
204 RFC1214Subregion(Rc<SubregionOrigin<'tcx>>),
206 // Arose from a subtyping relation
207 Subtype(TypeTrace<'tcx>),
209 // Stack-allocated closures cannot outlive innermost loop
210 // or function so as to ensure we only require finite stack
211 InfStackClosure(Span),
213 // Invocation of closure must be within its lifetime
216 // Dereference of reference must be within its lifetime
219 // Closure bound must not outlive captured free variables
220 FreeVariable(Span, ast::NodeId),
222 // Index into slice must be within its lifetime
225 // When casting `&'a T` to an `&'b Trait` object,
226 // relating `'a` to `'b`
227 RelateObjectBound(Span),
229 // Some type parameter was instantiated with the given type,
230 // and that type must outlive some region.
231 RelateParamBound(Span, Ty<'tcx>),
233 // The given region parameter was instantiated with a region
234 // that must outlive some other region.
235 RelateRegionParamBound(Span),
237 // A bound placed on type parameters that states that must outlive
238 // the moment of their instantiation.
239 RelateDefaultParamBound(Span, Ty<'tcx>),
241 // Creating a pointer `b` to contents of another reference
244 // Creating a pointer `b` to contents of an upvar
245 ReborrowUpvar(Span, ty::UpvarId),
247 // Data with type `Ty<'tcx>` was borrowed
248 DataBorrowed(Ty<'tcx>, Span),
250 // (&'a &'b T) where a >= b
251 ReferenceOutlivesReferent(Ty<'tcx>, Span),
253 // Type or region parameters must be in scope.
254 ParameterInScope(ParameterOrigin, Span),
256 // The type T of an expression E must outlive the lifetime for E.
257 ExprTypeIsNotInScope(Ty<'tcx>, Span),
259 // A `ref b` whose region does not enclose the decl site
260 BindingTypeIsNotValidAtDecl(Span),
262 // Regions appearing in a method receiver must outlive method call
265 // Regions appearing in a function argument must outlive func call
268 // Region in return type of invoked fn must enclose call
271 // Operands must be in scope
274 // Region resulting from a `&` expr must enclose the `&` expr
277 // An auto-borrow that does not enclose the expr where it occurs
280 // Region constraint arriving from destructor safety
281 SafeDestructor(Span),
284 /// Places that type/region parameters can appear.
285 #[derive(Clone, Copy, Debug)]
286 pub enum ParameterOrigin {
288 MethodCall, // foo.bar() <-- parameters on impl providing bar()
289 OverloadedOperator, // a + b when overloaded
290 OverloadedDeref, // *a when overloaded
293 /// Times when we replace late-bound regions with variables:
294 #[derive(Clone, Copy, Debug)]
295 pub enum LateBoundRegionConversionTime {
296 /// when a fn is called
299 /// when two higher-ranked types are compared
302 /// when projecting an associated type
303 AssocTypeProjection(ast::Name),
306 /// Reasons to create a region inference variable
308 /// See `error_reporting.rs` for more details
309 #[derive(Clone, Debug)]
310 pub enum RegionVariableOrigin {
311 // Region variables created for ill-categorized reasons,
312 // mostly indicates places in need of refactoring
315 // Regions created by a `&P` or `[...]` pattern
318 // Regions created by `&` operator
321 // Regions created as part of an autoref of a method receiver
324 // Regions created as part of an automatic coercion
327 // Region variables created as the values for early-bound regions
328 EarlyBoundRegion(Span, ast::Name),
330 // Region variables created for bound regions
331 // in a function or method that is called
332 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
334 UpvarRegion(ty::UpvarId, Span),
336 BoundRegionInCoherence(ast::Name),
339 #[derive(Copy, Clone, Debug)]
340 pub enum FixupError {
341 UnresolvedIntTy(IntVid),
342 UnresolvedFloatTy(FloatVid),
346 pub fn fixup_err_to_string(f: FixupError) -> String {
347 use self::FixupError::*;
350 UnresolvedIntTy(_) => {
351 "cannot determine the type of this integer; add a suffix to \
352 specify the type explicitly".to_string()
354 UnresolvedFloatTy(_) => {
355 "cannot determine the type of this number; add a suffix to specify \
356 the type explicitly".to_string()
358 UnresolvedTy(_) => "unconstrained type".to_string(),
362 /// errors_will_be_reported is required to proxy to the fulfillment context
363 /// FIXME -- a better option would be to hold back on modifying
364 /// the global cache until we know that all dependent obligations
365 /// are also satisfied. In that case, we could actually remove
366 /// this boolean flag, and we'd also avoid the problem of squelching
367 /// duplicate errors that occur across fns.
368 pub fn new_infer_ctxt<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
369 tables: &'a RefCell<ty::Tables<'tcx>>,
370 param_env: Option<ty::ParameterEnvironment<'a, 'tcx>>,
371 errors_will_be_reported: bool)
372 -> InferCtxt<'a, 'tcx> {
376 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
377 int_unification_table: RefCell::new(UnificationTable::new()),
378 float_unification_table: RefCell::new(UnificationTable::new()),
379 region_vars: RegionVarBindings::new(tcx),
380 parameter_environment: param_env.unwrap_or(tcx.empty_parameter_environment()),
381 fulfillment_cx: RefCell::new(traits::FulfillmentContext::new(errors_will_be_reported)),
382 reported_trait_errors: RefCell::new(FnvHashSet()),
384 err_count_on_creation: tcx.sess.err_count()
388 pub fn normalizing_infer_ctxt<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
389 tables: &'a RefCell<ty::Tables<'tcx>>)
390 -> InferCtxt<'a, 'tcx> {
391 let mut infcx = new_infer_ctxt(tcx, tables, None, false);
392 infcx.normalize = true;
396 /// Computes the least upper-bound of `a` and `b`. If this is not possible, reports an error and
398 pub fn common_supertype<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
405 debug!("common_supertype({:?}, {:?})",
408 let trace = TypeTrace {
410 values: Types(expected_found(a_is_expected, a, b))
413 let result = cx.commit_if_ok(|_| cx.lub(a_is_expected, trace.clone()).relate(&a, &b));
417 cx.report_and_explain_type_error(trace, err);
423 pub fn mk_subty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
430 debug!("mk_subty({:?} <: {:?})", a, b);
431 cx.sub_types(a_is_expected, origin, a, b)
434 pub fn can_mk_subty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
437 -> UnitResult<'tcx> {
438 debug!("can_mk_subty({:?} <: {:?})", a, b);
440 let trace = TypeTrace {
441 origin: TypeOrigin::Misc(codemap::DUMMY_SP),
442 values: Types(expected_found(true, a, b))
444 cx.sub(true, trace).relate(&a, &b).map(|_| ())
448 pub fn can_mk_eqty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>)
451 cx.can_equate(&a, &b)
454 pub fn mk_subr<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
455 origin: SubregionOrigin<'tcx>,
458 debug!("mk_subr({:?} <: {:?})", a, b);
459 let snapshot = cx.region_vars.start_snapshot();
460 cx.region_vars.make_subregion(origin, a, b);
461 cx.region_vars.commit(snapshot);
464 pub fn mk_eqty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
471 debug!("mk_eqty({:?} <: {:?})", a, b);
472 cx.commit_if_ok(|_| cx.eq_types(a_is_expected, origin, a, b))
475 pub fn mk_eq_trait_refs<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
478 a: ty::TraitRef<'tcx>,
479 b: ty::TraitRef<'tcx>)
482 debug!("mk_eq_trait_refs({:?} <: {:?})",
484 cx.commit_if_ok(|_| cx.eq_trait_refs(a_is_expected, origin, a.clone(), b.clone()))
487 pub fn mk_sub_poly_trait_refs<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
490 a: ty::PolyTraitRef<'tcx>,
491 b: ty::PolyTraitRef<'tcx>)
494 debug!("mk_sub_poly_trait_refs({:?} <: {:?})",
496 cx.commit_if_ok(|_| cx.sub_poly_trait_refs(a_is_expected, origin, a.clone(), b.clone()))
499 fn expected_found<T>(a_is_expected: bool,
505 ExpectedFound {expected: a, found: b}
507 ExpectedFound {expected: b, found: a}
511 #[must_use = "once you start a snapshot, you should always consume it"]
512 pub struct CombinedSnapshot {
513 type_snapshot: type_variable::Snapshot,
514 int_snapshot: unify::Snapshot<ty::IntVid>,
515 float_snapshot: unify::Snapshot<ty::FloatVid>,
516 region_vars_snapshot: RegionSnapshot,
519 pub fn normalize_associated_type<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> T
520 where T : TypeFoldable<'tcx> + HasTypeFlags
522 debug!("normalize_associated_type(t={:?})", value);
524 let value = tcx.erase_regions(value);
526 if !value.has_projection_types() {
530 let infcx = new_infer_ctxt(tcx, &tcx.tables, None, true);
531 let mut selcx = traits::SelectionContext::new(&infcx);
532 let cause = traits::ObligationCause::dummy();
533 let traits::Normalized { value: result, obligations } =
534 traits::normalize(&mut selcx, cause, &value);
536 debug!("normalize_associated_type: result={:?} obligations={:?}",
540 let mut fulfill_cx = infcx.fulfillment_cx.borrow_mut();
542 for obligation in obligations {
543 fulfill_cx.register_predicate_obligation(&infcx, obligation);
546 drain_fulfillment_cx_or_panic(DUMMY_SP, &infcx, &mut fulfill_cx, &result)
549 pub fn drain_fulfillment_cx_or_panic<'a,'tcx,T>(span: Span,
550 infcx: &InferCtxt<'a,'tcx>,
551 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
554 where T : TypeFoldable<'tcx> + HasTypeFlags
556 match drain_fulfillment_cx(infcx, fulfill_cx, result) {
559 infcx.tcx.sess.span_bug(
561 &format!("Encountered errors `{:?}` fulfilling during trans",
567 /// Finishes processes any obligations that remain in the fulfillment
568 /// context, and then "freshens" and returns `result`. This is
569 /// primarily used during normalization and other cases where
570 /// processing the obligations in `fulfill_cx` may cause type
571 /// inference variables that appear in `result` to be unified, and
572 /// hence we need to process those obligations to get the complete
573 /// picture of the type.
574 pub fn drain_fulfillment_cx<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>,
575 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
577 -> Result<T,Vec<traits::FulfillmentError<'tcx>>>
578 where T : TypeFoldable<'tcx> + HasTypeFlags
580 debug!("drain_fulfillment_cx(result={:?})",
583 // In principle, we only need to do this so long as `result`
584 // contains unbound type parameters. It could be a slight
585 // optimization to stop iterating early.
586 match fulfill_cx.select_all_or_error(infcx) {
593 let result = infcx.resolve_type_vars_if_possible(result);
594 Ok(infcx.tcx.erase_regions(&result))
597 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
598 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
599 t.fold_with(&mut self.freshener())
602 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
604 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
609 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
610 freshen::TypeFreshener::new(self)
613 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
614 use middle::ty::error::UnconstrainedNumeric::Neither;
615 use middle::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
617 ty::TyInfer(ty::IntVar(vid)) => {
618 if self.int_unification_table.borrow_mut().has_value(vid) {
624 ty::TyInfer(ty::FloatVar(vid)) => {
625 if self.float_unification_table.borrow_mut().has_value(vid) {
635 /// Returns a type variable's default fallback if any exists. A default
636 /// must be attached to the variable when created, if it is created
637 /// without a default, this will return None.
639 /// This code does not apply to integral or floating point variables,
640 /// only to use declared defaults.
642 /// See `new_ty_var_with_default` to create a type variable with a default.
643 /// See `type_variable::Default` for details about what a default entails.
644 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
646 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
651 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
652 let mut variables = Vec::new();
654 let unbound_ty_vars = self.type_variables
656 .unsolved_variables()
658 .map(|t| self.tcx.mk_var(t));
660 let unbound_int_vars = self.int_unification_table
662 .unsolved_variables()
664 .map(|v| self.tcx.mk_int_var(v));
666 let unbound_float_vars = self.float_unification_table
668 .unsolved_variables()
670 .map(|v| self.tcx.mk_float_var(v));
672 variables.extend(unbound_ty_vars);
673 variables.extend(unbound_int_vars);
674 variables.extend(unbound_float_vars);
679 fn combine_fields(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
680 -> CombineFields<'a, 'tcx> {
681 CombineFields {infcx: self,
682 a_is_expected: a_is_expected,
687 // public so that it can be used from the rustc_driver unit tests
688 pub fn equate(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
689 -> equate::Equate<'a, 'tcx>
691 self.combine_fields(a_is_expected, trace).equate()
694 // public so that it can be used from the rustc_driver unit tests
695 pub fn sub(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
696 -> sub::Sub<'a, 'tcx>
698 self.combine_fields(a_is_expected, trace).sub()
701 // public so that it can be used from the rustc_driver unit tests
702 pub fn lub(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
703 -> lub::Lub<'a, 'tcx>
705 self.combine_fields(a_is_expected, trace).lub()
708 // public so that it can be used from the rustc_driver unit tests
709 pub fn glb(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
710 -> glb::Glb<'a, 'tcx>
712 self.combine_fields(a_is_expected, trace).glb()
715 fn start_snapshot(&self) -> CombinedSnapshot {
717 type_snapshot: self.type_variables.borrow_mut().snapshot(),
718 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
719 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
720 region_vars_snapshot: self.region_vars.start_snapshot(),
724 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
725 debug!("rollback_to(cause={})", cause);
726 let CombinedSnapshot { type_snapshot,
729 region_vars_snapshot } = snapshot;
733 .rollback_to(type_snapshot);
734 self.int_unification_table
736 .rollback_to(int_snapshot);
737 self.float_unification_table
739 .rollback_to(float_snapshot);
741 .rollback_to(region_vars_snapshot);
744 fn commit_from(&self, snapshot: CombinedSnapshot) {
745 debug!("commit_from!");
746 let CombinedSnapshot { type_snapshot,
749 region_vars_snapshot } = snapshot;
753 .commit(type_snapshot);
754 self.int_unification_table
756 .commit(int_snapshot);
757 self.float_unification_table
759 .commit(float_snapshot);
761 .commit(region_vars_snapshot);
764 /// Execute `f` and commit the bindings
765 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
769 let snapshot = self.start_snapshot();
771 self.commit_from(snapshot);
775 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
776 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
777 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
779 debug!("commit_if_ok()");
780 let snapshot = self.start_snapshot();
781 let r = f(&snapshot);
782 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
784 Ok(_) => { self.commit_from(snapshot); }
785 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
790 /// Execute `f` and commit only the region bindings if successful.
791 /// The function f must be very careful not to leak any non-region
792 /// variables that get created.
793 pub fn commit_regions_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
794 F: FnOnce() -> Result<T, E>
796 debug!("commit_regions_if_ok()");
797 let CombinedSnapshot { type_snapshot,
800 region_vars_snapshot } = self.start_snapshot();
802 let r = self.commit_if_ok(|_| f());
804 debug!("commit_regions_if_ok: rolling back everything but regions");
806 // Roll back any non-region bindings - they should be resolved
807 // inside `f`, with, e.g. `resolve_type_vars_if_possible`.
810 .rollback_to(type_snapshot);
811 self.int_unification_table
813 .rollback_to(int_snapshot);
814 self.float_unification_table
816 .rollback_to(float_snapshot);
818 // Commit region vars that may escape through resolved types.
820 .commit(region_vars_snapshot);
825 /// Execute `f` then unroll any bindings it creates
826 pub fn probe<R, F>(&self, f: F) -> R where
827 F: FnOnce(&CombinedSnapshot) -> R,
830 let snapshot = self.start_snapshot();
831 let r = f(&snapshot);
832 self.rollback_to("probe", snapshot);
836 pub fn add_given(&self,
840 self.region_vars.add_given(sub, sup);
843 pub fn sub_types(&self,
850 debug!("sub_types({:?} <: {:?})", a, b);
851 self.commit_if_ok(|_| {
852 let trace = TypeTrace::types(origin, a_is_expected, a, b);
853 self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
857 pub fn eq_types(&self,
864 self.commit_if_ok(|_| {
865 let trace = TypeTrace::types(origin, a_is_expected, a, b);
866 self.equate(a_is_expected, trace).relate(&a, &b).map(|_| ())
870 pub fn eq_trait_refs(&self,
873 a: ty::TraitRef<'tcx>,
874 b: ty::TraitRef<'tcx>)
877 debug!("eq_trait_refs({:?} <: {:?})",
880 self.commit_if_ok(|_| {
881 let trace = TypeTrace {
883 values: TraitRefs(expected_found(a_is_expected, a.clone(), b.clone()))
885 self.equate(a_is_expected, trace).relate(&a, &b).map(|_| ())
889 pub fn sub_poly_trait_refs(&self,
892 a: ty::PolyTraitRef<'tcx>,
893 b: ty::PolyTraitRef<'tcx>)
896 debug!("sub_poly_trait_refs({:?} <: {:?})",
899 self.commit_if_ok(|_| {
900 let trace = TypeTrace {
902 values: PolyTraitRefs(expected_found(a_is_expected, a.clone(), b.clone()))
904 self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
908 pub fn skolemize_late_bound_regions<T>(&self,
909 value: &ty::Binder<T>,
910 snapshot: &CombinedSnapshot)
911 -> (T, SkolemizationMap)
912 where T : TypeFoldable<'tcx>
914 /*! See `higher_ranked::skolemize_late_bound_regions` */
916 higher_ranked::skolemize_late_bound_regions(self, value, snapshot)
919 pub fn leak_check(&self,
920 skol_map: &SkolemizationMap,
921 snapshot: &CombinedSnapshot)
924 /*! See `higher_ranked::leak_check` */
926 match higher_ranked::leak_check(self, skol_map, snapshot) {
928 Err((br, r)) => Err(TypeError::RegionsInsufficientlyPolymorphic(br, r))
932 pub fn plug_leaks<T>(&self,
933 skol_map: SkolemizationMap,
934 snapshot: &CombinedSnapshot,
937 where T : TypeFoldable<'tcx> + HasTypeFlags
939 /*! See `higher_ranked::plug_leaks` */
941 higher_ranked::plug_leaks(self, skol_map, snapshot, value)
944 pub fn equality_predicate(&self,
946 predicate: &ty::PolyEquatePredicate<'tcx>)
947 -> UnitResult<'tcx> {
948 self.commit_if_ok(|snapshot| {
949 let (ty::EquatePredicate(a, b), skol_map) =
950 self.skolemize_late_bound_regions(predicate, snapshot);
951 let origin = TypeOrigin::EquatePredicate(span);
952 let () = try!(mk_eqty(self, false, origin, a, b));
953 self.leak_check(&skol_map, snapshot)
957 pub fn region_outlives_predicate(&self,
959 predicate: &ty::PolyRegionOutlivesPredicate)
960 -> UnitResult<'tcx> {
961 self.commit_if_ok(|snapshot| {
962 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
963 self.skolemize_late_bound_regions(predicate, snapshot);
964 let origin = RelateRegionParamBound(span);
965 let () = mk_subr(self, origin, r_b, r_a); // `b : a` ==> `a <= b`
966 self.leak_check(&skol_map, snapshot)
970 pub fn next_ty_var_id(&self, diverging: bool) -> TyVid {
973 .new_var(diverging, None)
976 pub fn next_ty_var(&self) -> Ty<'tcx> {
977 self.tcx.mk_var(self.next_ty_var_id(false))
980 pub fn next_ty_var_with_default(&self,
981 default: Option<type_variable::Default<'tcx>>) -> Ty<'tcx> {
982 let ty_var_id = self.type_variables
984 .new_var(false, default);
986 self.tcx.mk_var(ty_var_id)
989 pub fn next_diverging_ty_var(&self) -> Ty<'tcx> {
990 self.tcx.mk_var(self.next_ty_var_id(true))
993 pub fn next_ty_vars(&self, n: usize) -> Vec<Ty<'tcx>> {
994 (0..n).map(|_i| self.next_ty_var()).collect()
997 pub fn next_int_var_id(&self) -> IntVid {
998 self.int_unification_table
1003 pub fn next_float_var_id(&self) -> FloatVid {
1004 self.float_unification_table
1009 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region {
1010 ty::ReVar(self.region_vars.new_region_var(origin))
1013 pub fn region_vars_for_defs(&self,
1015 defs: &[ty::RegionParameterDef])
1016 -> Vec<ty::Region> {
1018 .map(|d| self.next_region_var(EarlyBoundRegion(span, d.name)))
1022 // We have to take `&mut Substs` in order to provide the correct substitutions for defaults
1023 // along the way, for this reason we don't return them.
1024 pub fn type_vars_for_defs(&self,
1026 space: subst::ParamSpace,
1027 substs: &mut Substs<'tcx>,
1028 defs: &[ty::TypeParameterDef<'tcx>]) {
1030 let mut vars = Vec::with_capacity(defs.len());
1032 for def in defs.iter() {
1033 let default = def.default.map(|default| {
1034 type_variable::Default {
1035 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1037 def_id: def.default_def_id
1041 let ty_var = self.next_ty_var_with_default(default);
1042 substs.types.push(space, ty_var);
1047 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1048 /// type/region parameter to a fresh inference variable.
1049 pub fn fresh_substs_for_generics(&self,
1051 generics: &ty::Generics<'tcx>)
1052 -> subst::Substs<'tcx>
1054 let type_params = subst::VecPerParamSpace::empty();
1057 generics.regions.map(
1058 |d| self.next_region_var(EarlyBoundRegion(span, d.name)));
1060 let mut substs = subst::Substs::new(type_params, region_params);
1062 for space in subst::ParamSpace::all().iter() {
1063 self.type_vars_for_defs(
1067 generics.types.get_slice(*space));
1073 /// Given a set of generics defined on a trait, returns a substitution mapping each output
1074 /// type/region parameter to a fresh inference variable, and mapping the self type to
1076 pub fn fresh_substs_for_trait(&self,
1078 generics: &ty::Generics<'tcx>,
1080 -> subst::Substs<'tcx>
1083 assert!(generics.types.len(subst::SelfSpace) == 1);
1084 assert!(generics.types.len(subst::FnSpace) == 0);
1085 assert!(generics.regions.len(subst::SelfSpace) == 0);
1086 assert!(generics.regions.len(subst::FnSpace) == 0);
1088 let type_params = Vec::new();
1090 let region_param_defs = generics.regions.get_slice(subst::TypeSpace);
1091 let regions = self.region_vars_for_defs(span, region_param_defs);
1093 let mut substs = subst::Substs::new_trait(type_params, regions, self_ty);
1095 let type_parameter_defs = generics.types.get_slice(subst::TypeSpace);
1096 self.type_vars_for_defs(span, subst::TypeSpace, &mut substs, type_parameter_defs);
1101 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region {
1102 self.region_vars.new_bound(debruijn)
1105 /// Apply `adjustment` to the type of `expr`
1106 pub fn adjust_expr_ty(&self,
1108 adjustment: Option<&adjustment::AutoAdjustment<'tcx>>)
1111 let raw_ty = self.expr_ty(expr);
1112 let raw_ty = self.shallow_resolve(raw_ty);
1113 let resolve_ty = |ty: Ty<'tcx>| self.resolve_type_vars_if_possible(&ty);
1114 raw_ty.adjust(self.tcx,
1118 |method_call| self.tables
1122 .map(|method| resolve_ty(method.ty)))
1125 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1126 match self.tables.borrow().node_types.get(&id) {
1129 None if self.tcx.sess.err_count() - self.err_count_on_creation != 0 =>
1133 &format!("no type for node {}: {} in fcx",
1134 id, self.tcx.map.node_to_string(id)));
1139 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1140 match self.tables.borrow().node_types.get(&ex.id) {
1143 self.tcx.sess.bug("no type for expr in fcx");
1148 pub fn resolve_regions_and_report_errors(&self,
1149 free_regions: &FreeRegionMap,
1150 subject_node_id: ast::NodeId) {
1151 let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1152 self.report_region_errors(&errors); // see error_reporting.rs
1155 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1156 self.resolve_type_vars_if_possible(&t).to_string()
1159 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1160 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1161 format!("({})", tstrs.join(", "))
1164 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1165 self.resolve_type_vars_if_possible(t).to_string()
1168 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1170 ty::TyInfer(ty::TyVar(v)) => {
1171 // Not entirely obvious: if `typ` is a type variable,
1172 // it can be resolved to an int/float variable, which
1173 // can then be recursively resolved, hence the
1174 // recursion. Note though that we prevent type
1175 // variables from unifying to other type variables
1176 // directly (though they may be embedded
1177 // structurally), and we prevent cycles in any case,
1178 // so this recursion should always be of very limited
1180 self.type_variables.borrow()
1182 .map(|t| self.shallow_resolve(t))
1186 ty::TyInfer(ty::IntVar(v)) => {
1187 self.int_unification_table
1190 .map(|v| v.to_type(self.tcx))
1194 ty::TyInfer(ty::FloatVar(v)) => {
1195 self.float_unification_table
1198 .map(|v| v.to_type(self.tcx))
1208 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1209 where T: TypeFoldable<'tcx> + HasTypeFlags
1212 * Where possible, replaces type/int/float variables in
1213 * `value` with their final value. Note that region variables
1214 * are unaffected. If a type variable has not been unified, it
1215 * is left as is. This is an idempotent operation that does
1216 * not affect inference state in any way and so you can do it
1220 if !value.needs_infer() {
1221 return value.clone(); // avoid duplicated subst-folding
1223 let mut r = resolve::OpportunisticTypeResolver::new(self);
1224 value.fold_with(&mut r)
1227 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1228 where T: TypeFoldable<'tcx>
1230 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1231 value.fold_with(&mut r)
1234 /// Resolves all type variables in `t` and then, if any were left
1235 /// unresolved, substitutes an error type. This is used after the
1236 /// main checking when doing a second pass before writeback. The
1237 /// justification is that writeback will produce an error for
1238 /// these unconstrained type variables.
1239 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1240 let ty = self.resolve_type_vars_if_possible(t);
1241 if ty.references_error() || ty.is_ty_var() {
1242 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1249 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1251 * Attempts to resolve all type/region variables in
1252 * `value`. Region inference must have been run already (e.g.,
1253 * by calling `resolve_regions_and_report_errors`). If some
1254 * variable was never unified, an `Err` results.
1256 * This method is idempotent, but it not typically not invoked
1257 * except during the writeback phase.
1260 resolve::fully_resolve(self, value)
1263 // [Note-Type-error-reporting]
1264 // An invariant is that anytime the expected or actual type is TyError (the special
1265 // error type, meaning that an error occurred when typechecking this expression),
1266 // this is a derived error. The error cascaded from another error (that was already
1267 // reported), so it's not useful to display it to the user.
1268 // The following four methods -- type_error_message_str, type_error_message_str_with_expected,
1269 // type_error_message, and report_mismatched_types -- implement this logic.
1270 // They check if either the actual or expected type is TyError, and don't print the error
1271 // in this case. The typechecker should only ever report type errors involving mismatched
1272 // types using one of these four methods, and should not call span_err directly for such
1274 pub fn type_error_message_str<M>(&self,
1278 err: Option<&TypeError<'tcx>>) where
1279 M: FnOnce(Option<String>, String) -> String,
1281 self.type_error_message_str_with_expected(sp, mk_msg, None, actual_ty, err)
1284 pub fn type_error_message_str_with_expected<M>(&self,
1287 expected_ty: Option<Ty<'tcx>>,
1289 err: Option<&TypeError<'tcx>>) where
1290 M: FnOnce(Option<String>, String) -> String,
1292 debug!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty, actual_ty);
1294 let resolved_expected = expected_ty.map(|e_ty| self.resolve_type_vars_if_possible(&e_ty));
1296 if !resolved_expected.references_error() {
1297 let error_str = err.map_or("".to_string(), |t_err| {
1298 format!(" ({})", t_err)
1301 self.tcx.sess.span_err(sp, &format!("{}{}",
1302 mk_msg(resolved_expected.map(|t| self.ty_to_string(t)), actual_ty),
1305 if let Some(err) = err {
1306 self.tcx.note_and_explain_type_err(err, sp)
1311 pub fn type_error_message<M>(&self,
1314 actual_ty: Ty<'tcx>,
1315 err: Option<&TypeError<'tcx>>) where
1316 M: FnOnce(String) -> String,
1318 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1320 // Don't report an error if actual type is TyError.
1321 if actual_ty.references_error() {
1325 self.type_error_message_str(sp,
1326 move |_e, a| { mk_msg(a) },
1327 self.ty_to_string(actual_ty), err);
1330 pub fn report_mismatched_types(&self,
1334 err: &TypeError<'tcx>) {
1335 let trace = TypeTrace {
1336 origin: TypeOrigin::Misc(span),
1337 values: Types(ExpectedFound {
1342 self.report_and_explain_type_error(trace, err);
1345 pub fn report_conflicting_default_types(&self,
1347 expected: type_variable::Default<'tcx>,
1348 actual: type_variable::Default<'tcx>) {
1349 let trace = TypeTrace {
1350 origin: TypeOrigin::Misc(span),
1351 values: Types(ExpectedFound {
1352 expected: expected.ty,
1357 self.report_and_explain_type_error(trace,
1358 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1364 pub fn replace_late_bound_regions_with_fresh_var<T>(
1367 lbrct: LateBoundRegionConversionTime,
1368 value: &ty::Binder<T>)
1369 -> (T, FnvHashMap<ty::BoundRegion,ty::Region>)
1370 where T : TypeFoldable<'tcx>
1372 self.tcx.replace_late_bound_regions(
1374 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1377 /// See `verify_generic_bound` method in `region_inference`
1378 pub fn verify_generic_bound(&self,
1379 origin: SubregionOrigin<'tcx>,
1380 kind: GenericKind<'tcx>,
1382 bound: VerifyBound) {
1383 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1388 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1391 pub fn can_equate<'b,T>(&'b self, a: &T, b: &T) -> UnitResult<'tcx>
1392 where T: Relate<'b,'tcx> + fmt::Debug
1394 debug!("can_equate({:?}, {:?})", a, b);
1396 // Gin up a dummy trace, since this won't be committed
1397 // anyhow. We should make this typetrace stuff more
1398 // generic so we don't have to do anything quite this
1400 let e = self.tcx.types.err;
1401 let trace = TypeTrace {
1402 origin: TypeOrigin::Misc(codemap::DUMMY_SP),
1403 values: Types(expected_found(true, e, e))
1405 self.equate(true, trace).relate(a, b)
1409 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1410 let ty = self.node_type(id);
1411 self.resolve_type_vars_or_error(&ty)
1414 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1415 let ty = self.adjust_expr_ty(expr, self.tables.borrow().adjustments.get(&expr.id));
1416 self.resolve_type_vars_or_error(&ty)
1419 pub fn tables_are_tcx_tables(&self) -> bool {
1420 let tables: &RefCell<ty::Tables> = &self.tables;
1421 let tcx_tables: &RefCell<ty::Tables> = &self.tcx.tables;
1422 tables as *const _ == tcx_tables as *const _
1425 pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1426 let ty = self.resolve_type_vars_if_possible(&ty);
1427 if ty.needs_infer() ||
1428 (ty.has_closure_types() && !self.tables_are_tcx_tables()) {
1429 // this can get called from typeck (by euv), and moves_by_default
1430 // rightly refuses to work with inference variables, but
1431 // moves_by_default has a cache, which we want to use in other
1433 !traits::type_known_to_meet_builtin_bound(self, ty, ty::BoundCopy, span)
1435 ty.moves_by_default(&self.parameter_environment, span)
1439 pub fn node_method_ty(&self, method_call: ty::MethodCall)
1440 -> Option<Ty<'tcx>> {
1445 .map(|method| method.ty)
1446 .map(|ty| self.resolve_type_vars_if_possible(&ty))
1449 pub fn node_method_id(&self, method_call: ty::MethodCall)
1455 .map(|method| method.def_id)
1458 pub fn adjustments(&self) -> Ref<NodeMap<adjustment::AutoAdjustment<'tcx>>> {
1459 fn project_adjustments<'a, 'tcx>(tables: &'a ty::Tables<'tcx>)
1460 -> &'a NodeMap<adjustment::AutoAdjustment<'tcx>> {
1464 Ref::map(self.tables.borrow(), project_adjustments)
1467 pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1468 self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1471 pub fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<CodeExtent> {
1472 self.tcx.region_maps.temporary_scope(rvalue_id)
1475 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
1476 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1479 pub fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
1480 &self.parameter_environment
1483 pub fn closure_kind(&self,
1485 -> Option<ty::ClosureKind>
1487 if def_id.is_local() {
1488 self.tables.borrow().closure_kinds.get(&def_id).cloned()
1490 // During typeck, ALL closures are local. But afterwards,
1491 // during trans, we see closure ids from other traits.
1492 // That may require loading the closure data out of the
1494 Some(ty::Tables::closure_kind(&self.tables, self.tcx, def_id))
1498 pub fn closure_type(&self,
1500 substs: &ty::ClosureSubsts<'tcx>)
1501 -> ty::ClosureTy<'tcx>
1504 ty::Tables::closure_type(self.tables,
1510 normalize_associated_type(&self.tcx, &closure_ty)
1517 impl<'tcx> TypeTrace<'tcx> {
1518 pub fn span(&self) -> Span {
1522 pub fn types(origin: TypeOrigin,
1523 a_is_expected: bool,
1526 -> TypeTrace<'tcx> {
1529 values: Types(expected_found(a_is_expected, a, b))
1533 pub fn dummy(tcx: &ty::ctxt<'tcx>) -> TypeTrace<'tcx> {
1535 origin: TypeOrigin::Misc(codemap::DUMMY_SP),
1536 values: Types(ExpectedFound {
1537 expected: tcx.types.err,
1538 found: tcx.types.err,
1544 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1545 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1546 write!(f, "TypeTrace({:?})", self.origin)
1551 pub fn span(&self) -> Span {
1553 TypeOrigin::MethodCompatCheck(span) => span,
1554 TypeOrigin::ExprAssignable(span) => span,
1555 TypeOrigin::Misc(span) => span,
1556 TypeOrigin::RelateTraitRefs(span) => span,
1557 TypeOrigin::RelateSelfType(span) => span,
1558 TypeOrigin::RelateOutputImplTypes(span) => span,
1559 TypeOrigin::MatchExpressionArm(match_span, _, _) => match_span,
1560 TypeOrigin::IfExpression(span) => span,
1561 TypeOrigin::IfExpressionWithNoElse(span) => span,
1562 TypeOrigin::RangeExpression(span) => span,
1563 TypeOrigin::EquatePredicate(span) => span,
1568 impl<'tcx> SubregionOrigin<'tcx> {
1569 pub fn span(&self) -> Span {
1571 RFC1214Subregion(ref a) => a.span(),
1572 Subtype(ref a) => a.span(),
1573 InfStackClosure(a) => a,
1574 InvokeClosure(a) => a,
1575 DerefPointer(a) => a,
1576 FreeVariable(a, _) => a,
1578 RelateObjectBound(a) => a,
1579 RelateParamBound(a, _) => a,
1580 RelateRegionParamBound(a) => a,
1581 RelateDefaultParamBound(a, _) => a,
1583 ReborrowUpvar(a, _) => a,
1584 DataBorrowed(_, a) => a,
1585 ReferenceOutlivesReferent(_, a) => a,
1586 ParameterInScope(_, a) => a,
1587 ExprTypeIsNotInScope(_, a) => a,
1588 BindingTypeIsNotValidAtDecl(a) => a,
1595 SafeDestructor(a) => a,
1600 impl RegionVariableOrigin {
1601 pub fn span(&self) -> Span {
1603 MiscVariable(a) => a,
1604 PatternRegion(a) => a,
1605 AddrOfRegion(a) => a,
1608 EarlyBoundRegion(a, _) => a,
1609 LateBoundRegion(a, _, _) => a,
1610 BoundRegionInCoherence(_) => codemap::DUMMY_SP,
1611 UpvarRegion(_, a) => a