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};
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};
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 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 // Arose from a subtyping relation
202 Subtype(TypeTrace<'tcx>),
204 // Stack-allocated closures cannot outlive innermost loop
205 // or function so as to ensure we only require finite stack
206 InfStackClosure(Span),
208 // Invocation of closure must be within its lifetime
211 // Dereference of reference must be within its lifetime
214 // Closure bound must not outlive captured free variables
215 FreeVariable(Span, ast::NodeId),
217 // Index into slice must be within its lifetime
220 // When casting `&'a T` to an `&'b Trait` object,
221 // relating `'a` to `'b`
222 RelateObjectBound(Span),
224 // Some type parameter was instantiated with the given type,
225 // and that type must outlive some region.
226 RelateParamBound(Span, Ty<'tcx>),
228 // The given region parameter was instantiated with a region
229 // that must outlive some other region.
230 RelateRegionParamBound(Span),
232 // A bound placed on type parameters that states that must outlive
233 // the moment of their instantiation.
234 RelateDefaultParamBound(Span, Ty<'tcx>),
236 // Creating a pointer `b` to contents of another reference
239 // Creating a pointer `b` to contents of an upvar
240 ReborrowUpvar(Span, ty::UpvarId),
242 // Data with type `Ty<'tcx>` was borrowed
243 DataBorrowed(Ty<'tcx>, Span),
245 // (&'a &'b T) where a >= b
246 ReferenceOutlivesReferent(Ty<'tcx>, Span),
248 // Type or region parameters must be in scope.
249 ParameterInScope(ParameterOrigin, Span),
251 // The type T of an expression E must outlive the lifetime for E.
252 ExprTypeIsNotInScope(Ty<'tcx>, Span),
254 // A `ref b` whose region does not enclose the decl site
255 BindingTypeIsNotValidAtDecl(Span),
257 // Regions appearing in a method receiver must outlive method call
260 // Regions appearing in a function argument must outlive func call
263 // Region in return type of invoked fn must enclose call
266 // Operands must be in scope
269 // Region resulting from a `&` expr must enclose the `&` expr
272 // An auto-borrow that does not enclose the expr where it occurs
275 // Region constraint arriving from destructor safety
276 SafeDestructor(Span),
279 /// Places that type/region parameters can appear.
280 #[derive(Clone, Copy, Debug)]
281 pub enum ParameterOrigin {
283 MethodCall, // foo.bar() <-- parameters on impl providing bar()
284 OverloadedOperator, // a + b when overloaded
285 OverloadedDeref, // *a when overloaded
288 /// Times when we replace late-bound regions with variables:
289 #[derive(Clone, Copy, Debug)]
290 pub enum LateBoundRegionConversionTime {
291 /// when a fn is called
294 /// when two higher-ranked types are compared
297 /// when projecting an associated type
298 AssocTypeProjection(ast::Name),
301 /// Reasons to create a region inference variable
303 /// See `error_reporting.rs` for more details
304 #[derive(Clone, Debug)]
305 pub enum RegionVariableOrigin {
306 // Region variables created for ill-categorized reasons,
307 // mostly indicates places in need of refactoring
310 // Regions created by a `&P` or `[...]` pattern
313 // Regions created by `&` operator
316 // Regions created as part of an autoref of a method receiver
319 // Regions created as part of an automatic coercion
322 // Region variables created as the values for early-bound regions
323 EarlyBoundRegion(Span, ast::Name),
325 // Region variables created for bound regions
326 // in a function or method that is called
327 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
329 UpvarRegion(ty::UpvarId, Span),
331 BoundRegionInCoherence(ast::Name),
334 #[derive(Copy, Clone, Debug)]
335 pub enum FixupError {
336 UnresolvedIntTy(IntVid),
337 UnresolvedFloatTy(FloatVid),
341 pub fn fixup_err_to_string(f: FixupError) -> String {
342 use self::FixupError::*;
345 UnresolvedIntTy(_) => {
346 "cannot determine the type of this integer; add a suffix to \
347 specify the type explicitly".to_string()
349 UnresolvedFloatTy(_) => {
350 "cannot determine the type of this number; add a suffix to specify \
351 the type explicitly".to_string()
353 UnresolvedTy(_) => "unconstrained type".to_string(),
357 pub fn new_infer_ctxt<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
358 tables: &'a RefCell<ty::Tables<'tcx>>,
359 param_env: Option<ty::ParameterEnvironment<'a, 'tcx>>)
360 -> InferCtxt<'a, 'tcx> {
364 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
365 int_unification_table: RefCell::new(UnificationTable::new()),
366 float_unification_table: RefCell::new(UnificationTable::new()),
367 region_vars: RegionVarBindings::new(tcx),
368 parameter_environment: param_env.unwrap_or(tcx.empty_parameter_environment()),
369 fulfillment_cx: RefCell::new(traits::FulfillmentContext::new()),
370 reported_trait_errors: RefCell::new(FnvHashSet()),
372 err_count_on_creation: tcx.sess.err_count()
376 pub fn normalizing_infer_ctxt<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
377 tables: &'a RefCell<ty::Tables<'tcx>>)
378 -> InferCtxt<'a, 'tcx> {
379 let mut infcx = new_infer_ctxt(tcx, tables, None);
380 infcx.normalize = true;
384 /// Computes the least upper-bound of `a` and `b`. If this is not possible, reports an error and
386 pub fn common_supertype<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
393 debug!("common_supertype({:?}, {:?})",
396 let trace = TypeTrace {
398 values: Types(expected_found(a_is_expected, a, b))
401 let result = cx.commit_if_ok(|_| cx.lub(a_is_expected, trace.clone()).relate(&a, &b));
405 cx.report_and_explain_type_error(trace, err);
411 pub fn mk_subty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
418 debug!("mk_subty({:?} <: {:?})", a, b);
419 cx.sub_types(a_is_expected, origin, a, b)
422 pub fn can_mk_subty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
425 -> UnitResult<'tcx> {
426 debug!("can_mk_subty({:?} <: {:?})", a, b);
428 let trace = TypeTrace {
429 origin: TypeOrigin::Misc(codemap::DUMMY_SP),
430 values: Types(expected_found(true, a, b))
432 cx.sub(true, trace).relate(&a, &b).map(|_| ())
436 pub fn can_mk_eqty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>)
439 cx.can_equate(&a, &b)
442 pub fn mk_subr<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
443 origin: SubregionOrigin<'tcx>,
446 debug!("mk_subr({:?} <: {:?})", a, b);
447 let snapshot = cx.region_vars.start_snapshot();
448 cx.region_vars.make_subregion(origin, a, b);
449 cx.region_vars.commit(snapshot);
452 pub fn mk_eqty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
459 debug!("mk_eqty({:?} <: {:?})", a, b);
460 cx.commit_if_ok(|_| cx.eq_types(a_is_expected, origin, a, b))
463 pub fn mk_eq_trait_refs<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
466 a: ty::TraitRef<'tcx>,
467 b: ty::TraitRef<'tcx>)
470 debug!("mk_eq_trait_refs({:?} <: {:?})",
472 cx.commit_if_ok(|_| cx.eq_trait_refs(a_is_expected, origin, a.clone(), b.clone()))
475 pub fn mk_sub_poly_trait_refs<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
478 a: ty::PolyTraitRef<'tcx>,
479 b: ty::PolyTraitRef<'tcx>)
482 debug!("mk_sub_poly_trait_refs({:?} <: {:?})",
484 cx.commit_if_ok(|_| cx.sub_poly_trait_refs(a_is_expected, origin, a.clone(), b.clone()))
487 fn expected_found<T>(a_is_expected: bool,
493 ExpectedFound {expected: a, found: b}
495 ExpectedFound {expected: b, found: a}
499 #[must_use = "once you start a snapshot, you should always consume it"]
500 pub struct CombinedSnapshot {
501 type_snapshot: type_variable::Snapshot,
502 int_snapshot: unify::Snapshot<ty::IntVid>,
503 float_snapshot: unify::Snapshot<ty::FloatVid>,
504 region_vars_snapshot: RegionSnapshot,
507 pub fn normalize_associated_type<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> T
508 where T : TypeFoldable<'tcx>
510 debug!("normalize_associated_type(t={:?})", value);
512 let value = tcx.erase_regions(value);
514 if !value.has_projection_types() {
518 let infcx = new_infer_ctxt(tcx, &tcx.tables, None);
519 let mut selcx = traits::SelectionContext::new(&infcx);
520 let cause = traits::ObligationCause::dummy();
521 let traits::Normalized { value: result, obligations } =
522 traits::normalize(&mut selcx, cause, &value);
524 debug!("normalize_associated_type: result={:?} obligations={:?}",
528 let mut fulfill_cx = infcx.fulfillment_cx.borrow_mut();
530 for obligation in obligations {
531 fulfill_cx.register_predicate_obligation(&infcx, obligation);
534 drain_fulfillment_cx_or_panic(DUMMY_SP, &infcx, &mut fulfill_cx, &result)
537 pub fn drain_fulfillment_cx_or_panic<'a,'tcx,T>(span: Span,
538 infcx: &InferCtxt<'a,'tcx>,
539 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
542 where T : TypeFoldable<'tcx>
544 match drain_fulfillment_cx(infcx, fulfill_cx, result) {
547 infcx.tcx.sess.span_bug(
549 &format!("Encountered errors `{:?}` fulfilling during trans",
555 /// Finishes processes any obligations that remain in the fulfillment
556 /// context, and then "freshens" and returns `result`. This is
557 /// primarily used during normalization and other cases where
558 /// processing the obligations in `fulfill_cx` may cause type
559 /// inference variables that appear in `result` to be unified, and
560 /// hence we need to process those obligations to get the complete
561 /// picture of the type.
562 pub fn drain_fulfillment_cx<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>,
563 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
565 -> Result<T,Vec<traits::FulfillmentError<'tcx>>>
566 where T : TypeFoldable<'tcx>
568 debug!("drain_fulfillment_cx(result={:?})",
571 // In principle, we only need to do this so long as `result`
572 // contains unbound type parameters. It could be a slight
573 // optimization to stop iterating early.
574 match fulfill_cx.select_all_or_error(infcx) {
581 let result = infcx.resolve_type_vars_if_possible(result);
582 Ok(infcx.tcx.erase_regions(&result))
585 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
586 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
587 t.fold_with(&mut self.freshener())
590 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
592 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
597 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
598 freshen::TypeFreshener::new(self)
601 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
602 use middle::ty::error::UnconstrainedNumeric::Neither;
603 use middle::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
605 ty::TyInfer(ty::IntVar(vid)) => {
606 if self.int_unification_table.borrow_mut().has_value(vid) {
612 ty::TyInfer(ty::FloatVar(vid)) => {
613 if self.float_unification_table.borrow_mut().has_value(vid) {
623 /// Returns a type variable's default fallback if any exists. A default
624 /// must be attached to the variable when created, if it is created
625 /// without a default, this will return None.
627 /// This code does not apply to integral or floating point variables,
628 /// only to use declared defaults.
630 /// See `new_ty_var_with_default` to create a type variable with a default.
631 /// See `type_variable::Default` for details about what a default entails.
632 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
634 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
639 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
640 let mut variables = Vec::new();
642 let unbound_ty_vars = self.type_variables
644 .unsolved_variables()
646 .map(|t| self.tcx.mk_var(t));
648 let unbound_int_vars = self.int_unification_table
650 .unsolved_variables()
652 .map(|v| self.tcx.mk_int_var(v));
654 let unbound_float_vars = self.float_unification_table
656 .unsolved_variables()
658 .map(|v| self.tcx.mk_float_var(v));
660 variables.extend(unbound_ty_vars);
661 variables.extend(unbound_int_vars);
662 variables.extend(unbound_float_vars);
667 fn combine_fields(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
668 -> CombineFields<'a, 'tcx> {
669 CombineFields {infcx: self,
670 a_is_expected: a_is_expected,
675 // public so that it can be used from the rustc_driver unit tests
676 pub fn equate(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
677 -> equate::Equate<'a, 'tcx>
679 self.combine_fields(a_is_expected, trace).equate()
682 // public so that it can be used from the rustc_driver unit tests
683 pub fn sub(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
684 -> sub::Sub<'a, 'tcx>
686 self.combine_fields(a_is_expected, trace).sub()
689 // public so that it can be used from the rustc_driver unit tests
690 pub fn lub(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
691 -> lub::Lub<'a, 'tcx>
693 self.combine_fields(a_is_expected, trace).lub()
696 // public so that it can be used from the rustc_driver unit tests
697 pub fn glb(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
698 -> glb::Glb<'a, 'tcx>
700 self.combine_fields(a_is_expected, trace).glb()
703 fn start_snapshot(&self) -> CombinedSnapshot {
705 type_snapshot: self.type_variables.borrow_mut().snapshot(),
706 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
707 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
708 region_vars_snapshot: self.region_vars.start_snapshot(),
712 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
713 debug!("rollback_to(cause={})", cause);
714 let CombinedSnapshot { type_snapshot,
717 region_vars_snapshot } = snapshot;
721 .rollback_to(type_snapshot);
722 self.int_unification_table
724 .rollback_to(int_snapshot);
725 self.float_unification_table
727 .rollback_to(float_snapshot);
729 .rollback_to(region_vars_snapshot);
732 fn commit_from(&self, snapshot: CombinedSnapshot) {
733 debug!("commit_from!");
734 let CombinedSnapshot { type_snapshot,
737 region_vars_snapshot } = snapshot;
741 .commit(type_snapshot);
742 self.int_unification_table
744 .commit(int_snapshot);
745 self.float_unification_table
747 .commit(float_snapshot);
749 .commit(region_vars_snapshot);
752 /// Execute `f` and commit the bindings
753 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
757 let snapshot = self.start_snapshot();
759 self.commit_from(snapshot);
763 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
764 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
765 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
767 debug!("commit_if_ok()");
768 let snapshot = self.start_snapshot();
769 let r = f(&snapshot);
770 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
772 Ok(_) => { self.commit_from(snapshot); }
773 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
778 /// Execute `f` and commit only the region bindings if successful.
779 /// The function f must be very careful not to leak any non-region
780 /// variables that get created.
781 pub fn commit_regions_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
782 F: FnOnce() -> Result<T, E>
784 debug!("commit_regions_if_ok()");
785 let CombinedSnapshot { type_snapshot,
788 region_vars_snapshot } = self.start_snapshot();
790 let r = self.commit_if_ok(|_| f());
792 debug!("commit_regions_if_ok: rolling back everything but regions");
794 // Roll back any non-region bindings - they should be resolved
795 // inside `f`, with, e.g. `resolve_type_vars_if_possible`.
798 .rollback_to(type_snapshot);
799 self.int_unification_table
801 .rollback_to(int_snapshot);
802 self.float_unification_table
804 .rollback_to(float_snapshot);
806 // Commit region vars that may escape through resolved types.
808 .commit(region_vars_snapshot);
813 /// Execute `f` then unroll any bindings it creates
814 pub fn probe<R, F>(&self, f: F) -> R where
815 F: FnOnce(&CombinedSnapshot) -> R,
818 let snapshot = self.start_snapshot();
819 let r = f(&snapshot);
820 self.rollback_to("probe", snapshot);
824 pub fn add_given(&self,
828 self.region_vars.add_given(sub, sup);
831 pub fn sub_types(&self,
838 debug!("sub_types({:?} <: {:?})", a, b);
839 self.commit_if_ok(|_| {
840 let trace = TypeTrace::types(origin, a_is_expected, a, b);
841 self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
845 pub fn eq_types(&self,
852 self.commit_if_ok(|_| {
853 let trace = TypeTrace::types(origin, a_is_expected, a, b);
854 self.equate(a_is_expected, trace).relate(&a, &b).map(|_| ())
858 pub fn eq_trait_refs(&self,
861 a: ty::TraitRef<'tcx>,
862 b: ty::TraitRef<'tcx>)
865 debug!("eq_trait_refs({:?} <: {:?})",
868 self.commit_if_ok(|_| {
869 let trace = TypeTrace {
871 values: TraitRefs(expected_found(a_is_expected, a.clone(), b.clone()))
873 self.equate(a_is_expected, trace).relate(&a, &b).map(|_| ())
877 pub fn sub_poly_trait_refs(&self,
880 a: ty::PolyTraitRef<'tcx>,
881 b: ty::PolyTraitRef<'tcx>)
884 debug!("sub_poly_trait_refs({:?} <: {:?})",
887 self.commit_if_ok(|_| {
888 let trace = TypeTrace {
890 values: PolyTraitRefs(expected_found(a_is_expected, a.clone(), b.clone()))
892 self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
896 pub fn skolemize_late_bound_regions<T>(&self,
897 value: &ty::Binder<T>,
898 snapshot: &CombinedSnapshot)
899 -> (T, SkolemizationMap)
900 where T : TypeFoldable<'tcx>
902 /*! See `higher_ranked::skolemize_late_bound_regions` */
904 higher_ranked::skolemize_late_bound_regions(self, value, snapshot)
907 pub fn leak_check(&self,
908 skol_map: &SkolemizationMap,
909 snapshot: &CombinedSnapshot)
912 /*! See `higher_ranked::leak_check` */
914 match higher_ranked::leak_check(self, skol_map, snapshot) {
916 Err((br, r)) => Err(TypeError::RegionsInsufficientlyPolymorphic(br, r))
920 pub fn plug_leaks<T>(&self,
921 skol_map: SkolemizationMap,
922 snapshot: &CombinedSnapshot,
925 where T : TypeFoldable<'tcx>
927 /*! See `higher_ranked::plug_leaks` */
929 higher_ranked::plug_leaks(self, skol_map, snapshot, value)
932 pub fn equality_predicate(&self,
934 predicate: &ty::PolyEquatePredicate<'tcx>)
935 -> UnitResult<'tcx> {
936 self.commit_if_ok(|snapshot| {
937 let (ty::EquatePredicate(a, b), skol_map) =
938 self.skolemize_late_bound_regions(predicate, snapshot);
939 let origin = TypeOrigin::EquatePredicate(span);
940 let () = try!(mk_eqty(self, false, origin, a, b));
941 self.leak_check(&skol_map, snapshot)
945 pub fn region_outlives_predicate(&self,
947 predicate: &ty::PolyRegionOutlivesPredicate)
948 -> UnitResult<'tcx> {
949 self.commit_if_ok(|snapshot| {
950 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
951 self.skolemize_late_bound_regions(predicate, snapshot);
952 let origin = RelateRegionParamBound(span);
953 let () = mk_subr(self, origin, r_b, r_a); // `b : a` ==> `a <= b`
954 self.leak_check(&skol_map, snapshot)
958 pub fn next_ty_var_id(&self, diverging: bool) -> TyVid {
961 .new_var(diverging, None)
964 pub fn next_ty_var(&self) -> Ty<'tcx> {
965 self.tcx.mk_var(self.next_ty_var_id(false))
968 pub fn next_ty_var_with_default(&self,
969 default: Option<type_variable::Default<'tcx>>) -> Ty<'tcx> {
970 let ty_var_id = self.type_variables
972 .new_var(false, default);
974 self.tcx.mk_var(ty_var_id)
977 pub fn next_diverging_ty_var(&self) -> Ty<'tcx> {
978 self.tcx.mk_var(self.next_ty_var_id(true))
981 pub fn next_ty_vars(&self, n: usize) -> Vec<Ty<'tcx>> {
982 (0..n).map(|_i| self.next_ty_var()).collect()
985 pub fn next_int_var_id(&self) -> IntVid {
986 self.int_unification_table
991 pub fn next_float_var_id(&self) -> FloatVid {
992 self.float_unification_table
997 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region {
998 ty::ReVar(self.region_vars.new_region_var(origin))
1001 pub fn region_vars_for_defs(&self,
1003 defs: &[ty::RegionParameterDef])
1004 -> Vec<ty::Region> {
1006 .map(|d| self.next_region_var(EarlyBoundRegion(span, d.name)))
1010 // We have to take `&mut Substs` in order to provide the correct substitutions for defaults
1011 // along the way, for this reason we don't return them.
1012 pub fn type_vars_for_defs(&self,
1014 space: subst::ParamSpace,
1015 substs: &mut Substs<'tcx>,
1016 defs: &[ty::TypeParameterDef<'tcx>]) {
1018 let mut vars = Vec::with_capacity(defs.len());
1020 for def in defs.iter() {
1021 let default = def.default.map(|default| {
1022 type_variable::Default {
1023 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1025 def_id: def.default_def_id
1029 let ty_var = self.next_ty_var_with_default(default);
1030 substs.types.push(space, ty_var);
1035 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1036 /// type/region parameter to a fresh inference variable.
1037 pub fn fresh_substs_for_generics(&self,
1039 generics: &ty::Generics<'tcx>)
1040 -> subst::Substs<'tcx>
1042 let type_params = subst::VecPerParamSpace::empty();
1045 generics.regions.map(
1046 |d| self.next_region_var(EarlyBoundRegion(span, d.name)));
1048 let mut substs = subst::Substs::new(type_params, region_params);
1050 for space in subst::ParamSpace::all().iter() {
1051 self.type_vars_for_defs(
1055 generics.types.get_slice(*space));
1061 /// Given a set of generics defined on a trait, returns a substitution mapping each output
1062 /// type/region parameter to a fresh inference variable, and mapping the self type to
1064 pub fn fresh_substs_for_trait(&self,
1066 generics: &ty::Generics<'tcx>,
1068 -> subst::Substs<'tcx>
1071 assert!(generics.types.len(subst::SelfSpace) == 1);
1072 assert!(generics.types.len(subst::FnSpace) == 0);
1073 assert!(generics.regions.len(subst::SelfSpace) == 0);
1074 assert!(generics.regions.len(subst::FnSpace) == 0);
1076 let type_params = Vec::new();
1078 let region_param_defs = generics.regions.get_slice(subst::TypeSpace);
1079 let regions = self.region_vars_for_defs(span, region_param_defs);
1081 let mut substs = subst::Substs::new_trait(type_params, regions, self_ty);
1083 let type_parameter_defs = generics.types.get_slice(subst::TypeSpace);
1084 self.type_vars_for_defs(span, subst::TypeSpace, &mut substs, type_parameter_defs);
1089 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region {
1090 self.region_vars.new_bound(debruijn)
1093 /// Apply `adjustment` to the type of `expr`
1094 pub fn adjust_expr_ty(&self,
1096 adjustment: Option<&adjustment::AutoAdjustment<'tcx>>)
1099 let raw_ty = self.expr_ty(expr);
1100 let raw_ty = self.shallow_resolve(raw_ty);
1101 let resolve_ty = |ty: Ty<'tcx>| self.resolve_type_vars_if_possible(&ty);
1102 raw_ty.adjust(self.tcx,
1106 |method_call| self.tables
1110 .map(|method| resolve_ty(method.ty)))
1113 pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1114 match self.tables.borrow().node_types.get(&id) {
1117 None if self.tcx.sess.err_count() - self.err_count_on_creation != 0 =>
1121 &format!("no type for node {}: {} in fcx",
1122 id, self.tcx.map.node_to_string(id)));
1127 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1128 match self.tables.borrow().node_types.get(&ex.id) {
1131 self.tcx.sess.bug("no type for expr in fcx");
1136 pub fn resolve_regions_and_report_errors(&self,
1137 free_regions: &FreeRegionMap,
1138 subject_node_id: ast::NodeId) {
1139 let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1140 self.report_region_errors(&errors); // see error_reporting.rs
1143 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1144 self.resolve_type_vars_if_possible(&t).to_string()
1147 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1148 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1149 format!("({})", tstrs.join(", "))
1152 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1153 self.resolve_type_vars_if_possible(t).to_string()
1156 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1158 ty::TyInfer(ty::TyVar(v)) => {
1159 // Not entirely obvious: if `typ` is a type variable,
1160 // it can be resolved to an int/float variable, which
1161 // can then be recursively resolved, hence the
1162 // recursion. Note though that we prevent type
1163 // variables from unifying to other type variables
1164 // directly (though they may be embedded
1165 // structurally), and we prevent cycles in any case,
1166 // so this recursion should always be of very limited
1168 self.type_variables.borrow()
1170 .map(|t| self.shallow_resolve(t))
1174 ty::TyInfer(ty::IntVar(v)) => {
1175 self.int_unification_table
1178 .map(|v| v.to_type(self.tcx))
1182 ty::TyInfer(ty::FloatVar(v)) => {
1183 self.float_unification_table
1186 .map(|v| v.to_type(self.tcx))
1196 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1197 where T: TypeFoldable<'tcx>
1200 * Where possible, replaces type/int/float variables in
1201 * `value` with their final value. Note that region variables
1202 * are unaffected. If a type variable has not been unified, it
1203 * is left as is. This is an idempotent operation that does
1204 * not affect inference state in any way and so you can do it
1208 if !value.needs_infer() {
1209 return value.clone(); // avoid duplicated subst-folding
1211 let mut r = resolve::OpportunisticTypeResolver::new(self);
1212 value.fold_with(&mut r)
1215 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1216 where T: TypeFoldable<'tcx>
1218 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1219 value.fold_with(&mut r)
1222 /// Resolves all type variables in `t` and then, if any were left
1223 /// unresolved, substitutes an error type. This is used after the
1224 /// main checking when doing a second pass before writeback. The
1225 /// justification is that writeback will produce an error for
1226 /// these unconstrained type variables.
1227 fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1228 let ty = self.resolve_type_vars_if_possible(t);
1229 if ty.references_error() || ty.is_ty_var() {
1230 debug!("resolve_type_vars_or_error: error from {:?}", ty);
1237 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1239 * Attempts to resolve all type/region variables in
1240 * `value`. Region inference must have been run already (e.g.,
1241 * by calling `resolve_regions_and_report_errors`). If some
1242 * variable was never unified, an `Err` results.
1244 * This method is idempotent, but it not typically not invoked
1245 * except during the writeback phase.
1248 resolve::fully_resolve(self, value)
1251 // [Note-Type-error-reporting]
1252 // An invariant is that anytime the expected or actual type is TyError (the special
1253 // error type, meaning that an error occurred when typechecking this expression),
1254 // this is a derived error. The error cascaded from another error (that was already
1255 // reported), so it's not useful to display it to the user.
1256 // The following four methods -- type_error_message_str, type_error_message_str_with_expected,
1257 // type_error_message, and report_mismatched_types -- implement this logic.
1258 // They check if either the actual or expected type is TyError, and don't print the error
1259 // in this case. The typechecker should only ever report type errors involving mismatched
1260 // types using one of these four methods, and should not call span_err directly for such
1262 pub fn type_error_message_str<M>(&self,
1266 err: Option<&TypeError<'tcx>>)
1267 where M: FnOnce(Option<String>, String) -> String,
1269 self.type_error_message_str_with_expected(sp, mk_msg, None, actual_ty, err)
1272 pub fn type_error_struct_str<M>(&self,
1276 err: Option<&TypeError<'tcx>>)
1277 -> DiagnosticBuilder<'tcx>
1278 where M: FnOnce(Option<String>, String) -> String,
1280 self.type_error_struct_str_with_expected(sp, mk_msg, None, actual_ty, err)
1283 pub fn type_error_message_str_with_expected<M>(&self,
1286 expected_ty: Option<Ty<'tcx>>,
1288 err: Option<&TypeError<'tcx>>)
1289 where M: FnOnce(Option<String>, String) -> String,
1291 self.type_error_struct_str_with_expected(sp, mk_msg, expected_ty, actual_ty, err)
1295 pub fn type_error_struct_str_with_expected<M>(&self,
1298 expected_ty: Option<Ty<'tcx>>,
1300 err: Option<&TypeError<'tcx>>)
1301 -> DiagnosticBuilder<'tcx>
1302 where M: FnOnce(Option<String>, String) -> String,
1304 debug!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty, actual_ty);
1306 let resolved_expected = expected_ty.map(|e_ty| self.resolve_type_vars_if_possible(&e_ty));
1308 if !resolved_expected.references_error() {
1309 let error_str = err.map_or("".to_string(), |t_err| {
1310 format!(" ({})", t_err)
1313 let mut db = self.tcx.sess.struct_span_err(sp, &format!("{}{}",
1314 mk_msg(resolved_expected.map(|t| self.ty_to_string(t)), actual_ty),
1317 if let Some(err) = err {
1318 self.tcx.note_and_explain_type_err(&mut db, err, sp);
1322 self.tcx.sess.diagnostic().struct_dummy()
1326 pub fn type_error_message<M>(&self,
1329 actual_ty: Ty<'tcx>,
1330 err: Option<&TypeError<'tcx>>)
1331 where M: FnOnce(String) -> String,
1333 self.type_error_struct(sp, mk_msg, actual_ty, err).emit();
1336 pub fn type_error_struct<M>(&self,
1339 actual_ty: Ty<'tcx>,
1340 err: Option<&TypeError<'tcx>>)
1341 -> DiagnosticBuilder<'tcx>
1342 where M: FnOnce(String) -> String,
1344 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1346 // Don't report an error if actual type is TyError.
1347 if actual_ty.references_error() {
1348 return self.tcx.sess.diagnostic().struct_dummy();
1351 self.type_error_struct_str(sp,
1352 move |_e, a| { mk_msg(a) },
1353 self.ty_to_string(actual_ty), err)
1356 pub fn report_mismatched_types(&self,
1360 err: &TypeError<'tcx>) {
1361 let trace = TypeTrace {
1362 origin: TypeOrigin::Misc(span),
1363 values: Types(ExpectedFound {
1368 self.report_and_explain_type_error(trace, err);
1371 pub fn report_conflicting_default_types(&self,
1373 expected: type_variable::Default<'tcx>,
1374 actual: type_variable::Default<'tcx>) {
1375 let trace = TypeTrace {
1376 origin: TypeOrigin::Misc(span),
1377 values: Types(ExpectedFound {
1378 expected: expected.ty,
1383 self.report_and_explain_type_error(trace,
1384 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1390 pub fn replace_late_bound_regions_with_fresh_var<T>(
1393 lbrct: LateBoundRegionConversionTime,
1394 value: &ty::Binder<T>)
1395 -> (T, FnvHashMap<ty::BoundRegion,ty::Region>)
1396 where T : TypeFoldable<'tcx>
1398 self.tcx.replace_late_bound_regions(
1400 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1403 /// See `verify_generic_bound` method in `region_inference`
1404 pub fn verify_generic_bound(&self,
1405 origin: SubregionOrigin<'tcx>,
1406 kind: GenericKind<'tcx>,
1408 bound: VerifyBound) {
1409 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1414 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1417 pub fn can_equate<'b,T>(&'b self, a: &T, b: &T) -> UnitResult<'tcx>
1418 where T: Relate<'b,'tcx> + fmt::Debug
1420 debug!("can_equate({:?}, {:?})", a, b);
1422 // Gin up a dummy trace, since this won't be committed
1423 // anyhow. We should make this typetrace stuff more
1424 // generic so we don't have to do anything quite this
1426 let e = self.tcx.types.err;
1427 let trace = TypeTrace {
1428 origin: TypeOrigin::Misc(codemap::DUMMY_SP),
1429 values: Types(expected_found(true, e, e))
1431 self.equate(true, trace).relate(a, b)
1435 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1436 let ty = self.node_type(id);
1437 self.resolve_type_vars_or_error(&ty)
1440 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1441 let ty = self.adjust_expr_ty(expr, self.tables.borrow().adjustments.get(&expr.id));
1442 self.resolve_type_vars_or_error(&ty)
1445 pub fn tables_are_tcx_tables(&self) -> bool {
1446 let tables: &RefCell<ty::Tables> = &self.tables;
1447 let tcx_tables: &RefCell<ty::Tables> = &self.tcx.tables;
1448 tables as *const _ == tcx_tables as *const _
1451 pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1452 let ty = self.resolve_type_vars_if_possible(&ty);
1453 if ty.needs_infer() ||
1454 (ty.has_closure_types() && !self.tables_are_tcx_tables()) {
1455 // this can get called from typeck (by euv), and moves_by_default
1456 // rightly refuses to work with inference variables, but
1457 // moves_by_default has a cache, which we want to use in other
1459 !traits::type_known_to_meet_builtin_bound(self, ty, ty::BoundCopy, span)
1461 ty.moves_by_default(&self.parameter_environment, span)
1465 pub fn node_method_ty(&self, method_call: ty::MethodCall)
1466 -> Option<Ty<'tcx>> {
1471 .map(|method| method.ty)
1472 .map(|ty| self.resolve_type_vars_if_possible(&ty))
1475 pub fn node_method_id(&self, method_call: ty::MethodCall)
1481 .map(|method| method.def_id)
1484 pub fn adjustments(&self) -> Ref<NodeMap<adjustment::AutoAdjustment<'tcx>>> {
1485 fn project_adjustments<'a, 'tcx>(tables: &'a ty::Tables<'tcx>)
1486 -> &'a NodeMap<adjustment::AutoAdjustment<'tcx>> {
1490 Ref::map(self.tables.borrow(), project_adjustments)
1493 pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1494 self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1497 pub fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<CodeExtent> {
1498 self.tcx.region_maps.temporary_scope(rvalue_id)
1501 pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
1502 self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1505 pub fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
1506 &self.parameter_environment
1509 pub fn closure_kind(&self,
1511 -> Option<ty::ClosureKind>
1513 if def_id.is_local() {
1514 self.tables.borrow().closure_kinds.get(&def_id).cloned()
1516 // During typeck, ALL closures are local. But afterwards,
1517 // during trans, we see closure ids from other traits.
1518 // That may require loading the closure data out of the
1520 Some(ty::Tables::closure_kind(&self.tables, self.tcx, def_id))
1524 pub fn closure_type(&self,
1526 substs: &ty::ClosureSubsts<'tcx>)
1527 -> ty::ClosureTy<'tcx>
1530 ty::Tables::closure_type(self.tables,
1536 normalize_associated_type(&self.tcx, &closure_ty)
1543 impl<'tcx> TypeTrace<'tcx> {
1544 pub fn span(&self) -> Span {
1548 pub fn types(origin: TypeOrigin,
1549 a_is_expected: bool,
1552 -> TypeTrace<'tcx> {
1555 values: Types(expected_found(a_is_expected, a, b))
1559 pub fn dummy(tcx: &ty::ctxt<'tcx>) -> TypeTrace<'tcx> {
1561 origin: TypeOrigin::Misc(codemap::DUMMY_SP),
1562 values: Types(ExpectedFound {
1563 expected: tcx.types.err,
1564 found: tcx.types.err,
1570 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1571 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1572 write!(f, "TypeTrace({:?})", self.origin)
1577 pub fn span(&self) -> Span {
1579 TypeOrigin::MethodCompatCheck(span) => span,
1580 TypeOrigin::ExprAssignable(span) => span,
1581 TypeOrigin::Misc(span) => span,
1582 TypeOrigin::RelateTraitRefs(span) => span,
1583 TypeOrigin::RelateSelfType(span) => span,
1584 TypeOrigin::RelateOutputImplTypes(span) => span,
1585 TypeOrigin::MatchExpressionArm(match_span, _, _) => match_span,
1586 TypeOrigin::IfExpression(span) => span,
1587 TypeOrigin::IfExpressionWithNoElse(span) => span,
1588 TypeOrigin::RangeExpression(span) => span,
1589 TypeOrigin::EquatePredicate(span) => span,
1594 impl<'tcx> SubregionOrigin<'tcx> {
1595 pub fn span(&self) -> Span {
1597 Subtype(ref a) => a.span(),
1598 InfStackClosure(a) => a,
1599 InvokeClosure(a) => a,
1600 DerefPointer(a) => a,
1601 FreeVariable(a, _) => a,
1603 RelateObjectBound(a) => a,
1604 RelateParamBound(a, _) => a,
1605 RelateRegionParamBound(a) => a,
1606 RelateDefaultParamBound(a, _) => a,
1608 ReborrowUpvar(a, _) => a,
1609 DataBorrowed(_, a) => a,
1610 ReferenceOutlivesReferent(_, a) => a,
1611 ParameterInScope(_, a) => a,
1612 ExprTypeIsNotInScope(_, a) => a,
1613 BindingTypeIsNotValidAtDecl(a) => a,
1620 SafeDestructor(a) => a,
1625 impl RegionVariableOrigin {
1626 pub fn span(&self) -> Span {
1628 MiscVariable(a) => a,
1629 PatternRegion(a) => a,
1630 AddrOfRegion(a) => a,
1633 EarlyBoundRegion(a, _) => a,
1634 LateBoundRegion(a, _, _) => a,
1635 BoundRegionInCoherence(_) => codemap::DUMMY_SP,
1636 UpvarRegion(_, a) => a