1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See the Book for more information.
13 pub use self::LateBoundRegionConversionTime::*;
14 pub use self::RegionVariableOrigin::*;
15 pub use self::SubregionOrigin::*;
16 pub use self::ValuePairs::*;
17 pub use ty::IntVarValue;
18 pub use self::freshen::TypeFreshener;
19 pub use self::region_inference::{GenericKind, VerifyBound};
21 use hir::def_id::DefId;
22 use middle::free_region::{FreeRegionMap, RegionRelations};
24 use middle::lang_items;
25 use mir::tcx::LvalueTy;
26 use ty::subst::{Kind, Subst, Substs};
27 use ty::{TyVid, IntVid, FloatVid};
28 use ty::{self, Ty, TyCtxt};
29 use ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
30 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
31 use ty::relate::RelateResult;
32 use traits::{self, ObligationCause, PredicateObligations, Reveal};
33 use rustc_data_structures::unify::{self, UnificationTable};
34 use std::cell::{Cell, RefCell, Ref};
37 use errors::DiagnosticBuilder;
38 use syntax_pos::{self, Span, DUMMY_SP};
39 use util::nodemap::FxHashMap;
40 use arena::DroplessArena;
42 use self::combine::CombineFields;
43 use self::higher_ranked::HrMatchResult;
44 use self::region_inference::{RegionVarBindings, RegionSnapshot};
45 use self::type_variable::TypeVariableOrigin;
46 use self::unify_key::ToType;
51 pub mod error_reporting;
57 pub mod region_inference;
61 pub mod type_variable;
65 pub struct InferOk<'tcx, T> {
67 pub obligations: PredicateObligations<'tcx>,
69 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
71 pub type Bound<T> = Option<T>;
72 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
73 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
75 pub struct InferCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
76 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
78 /// During type-checking/inference of a body, `in_progress_tables`
79 /// contains a reference to the tables being built up, which are
80 /// used for reading closure kinds/signatures as they are inferred,
81 /// and for error reporting logic to read arbitrary node types.
82 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
84 // Cache for projections. This cache is snapshotted along with the
87 // Public so that `traits::project` can use it.
88 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
90 // We instantiate UnificationTable with bounds<Ty> because the
91 // types that might instantiate a general type variable have an
92 // order, represented by its upper and lower bounds.
93 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
95 // Map from integral variable to the kind of integer it represents
96 int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
98 // Map from floating variable to the kind of float it represents
99 float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
101 // For region variables.
102 region_vars: RegionVarBindings<'a, 'gcx, 'tcx>,
104 /// Caches the results of trait selection. This cache is used
105 /// for things that have to do with the parameters in scope.
106 pub selection_cache: traits::SelectionCache<'tcx>,
108 /// Caches the results of trait evaluation.
109 pub evaluation_cache: traits::EvaluationCache<'tcx>,
111 // the set of predicates on which errors have been reported, to
112 // avoid reporting the same error twice.
113 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
115 // When an error occurs, we want to avoid reporting "derived"
116 // errors that are due to this original failure. Normally, we
117 // handle this with the `err_count_on_creation` count, which
118 // basically just tracks how many errors were reported when we
119 // started type-checking a fn and checks to see if any new errors
120 // have been reported since then. Not great, but it works.
122 // However, when errors originated in other passes -- notably
123 // resolve -- this heuristic breaks down. Therefore, we have this
124 // auxiliary flag that one can set whenever one creates a
125 // type-error that is due to an error in a prior pass.
127 // Don't read this flag directly, call `is_tainted_by_errors()`
128 // and `set_tainted_by_errors()`.
129 tainted_by_errors_flag: Cell<bool>,
131 // Track how many errors were reported when this infcx is created.
132 // If the number of errors increases, that's also a sign (line
133 // `tained_by_errors`) to avoid reporting certain kinds of errors.
134 err_count_on_creation: usize,
136 // This flag is true while there is an active snapshot.
137 in_snapshot: Cell<bool>,
140 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
141 /// region that each late-bound region was replaced with.
142 pub type SkolemizationMap<'tcx> = FxHashMap<ty::BoundRegion, ty::Region<'tcx>>;
144 /// See `error_reporting` module for more details
145 #[derive(Clone, Debug)]
146 pub enum ValuePairs<'tcx> {
147 Types(ExpectedFound<Ty<'tcx>>),
148 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
149 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
152 /// The trace designates the path through inference that we took to
153 /// encounter an error or subtyping constraint.
155 /// See `error_reporting` module for more details.
157 pub struct TypeTrace<'tcx> {
158 cause: ObligationCause<'tcx>,
159 values: ValuePairs<'tcx>,
162 /// The origin of a `r1 <= r2` constraint.
164 /// See `error_reporting` module for more details
165 #[derive(Clone, Debug)]
166 pub enum SubregionOrigin<'tcx> {
167 // Arose from a subtyping relation
168 Subtype(TypeTrace<'tcx>),
170 // Stack-allocated closures cannot outlive innermost loop
171 // or function so as to ensure we only require finite stack
172 InfStackClosure(Span),
174 // Invocation of closure must be within its lifetime
177 // Dereference of reference must be within its lifetime
180 // Closure bound must not outlive captured free variables
181 FreeVariable(Span, ast::NodeId),
183 // Index into slice must be within its lifetime
186 // When casting `&'a T` to an `&'b Trait` object,
187 // relating `'a` to `'b`
188 RelateObjectBound(Span),
190 // Some type parameter was instantiated with the given type,
191 // and that type must outlive some region.
192 RelateParamBound(Span, Ty<'tcx>),
194 // The given region parameter was instantiated with a region
195 // that must outlive some other region.
196 RelateRegionParamBound(Span),
198 // A bound placed on type parameters that states that must outlive
199 // the moment of their instantiation.
200 RelateDefaultParamBound(Span, Ty<'tcx>),
202 // Creating a pointer `b` to contents of another reference
205 // Creating a pointer `b` to contents of an upvar
206 ReborrowUpvar(Span, ty::UpvarId),
208 // Data with type `Ty<'tcx>` was borrowed
209 DataBorrowed(Ty<'tcx>, Span),
211 // (&'a &'b T) where a >= b
212 ReferenceOutlivesReferent(Ty<'tcx>, Span),
214 // Type or region parameters must be in scope.
215 ParameterInScope(ParameterOrigin, Span),
217 // The type T of an expression E must outlive the lifetime for E.
218 ExprTypeIsNotInScope(Ty<'tcx>, Span),
220 // A `ref b` whose region does not enclose the decl site
221 BindingTypeIsNotValidAtDecl(Span),
223 // Regions appearing in a method receiver must outlive method call
226 // Regions appearing in a function argument must outlive func call
229 // Region in return type of invoked fn must enclose call
232 // Operands must be in scope
235 // Region resulting from a `&` expr must enclose the `&` expr
238 // An auto-borrow that does not enclose the expr where it occurs
241 // Region constraint arriving from destructor safety
242 SafeDestructor(Span),
244 // Comparing the signature and requirements of an impl method against
245 // the containing trait.
246 CompareImplMethodObligation {
248 item_name: ast::Name,
249 impl_item_def_id: DefId,
250 trait_item_def_id: DefId,
252 // this is `Some(_)` if this error arises from the bug fix for
253 // #18937. This is a temporary measure.
254 lint_id: Option<ast::NodeId>,
258 /// Places that type/region parameters can appear.
259 #[derive(Clone, Copy, Debug)]
260 pub enum ParameterOrigin {
262 MethodCall, // foo.bar() <-- parameters on impl providing bar()
263 OverloadedOperator, // a + b when overloaded
264 OverloadedDeref, // *a when overloaded
267 /// Times when we replace late-bound regions with variables:
268 #[derive(Clone, Copy, Debug)]
269 pub enum LateBoundRegionConversionTime {
270 /// when a fn is called
273 /// when two higher-ranked types are compared
276 /// when projecting an associated type
277 AssocTypeProjection(DefId),
280 /// Reasons to create a region inference variable
282 /// See `error_reporting` module for more details
283 #[derive(Clone, Debug)]
284 pub enum RegionVariableOrigin {
285 // Region variables created for ill-categorized reasons,
286 // mostly indicates places in need of refactoring
289 // Regions created by a `&P` or `[...]` pattern
292 // Regions created by `&` operator
295 // Regions created as part of an autoref of a method receiver
298 // Regions created as part of an automatic coercion
301 // Region variables created as the values for early-bound regions
302 EarlyBoundRegion(Span, ast::Name),
304 // Region variables created for bound regions
305 // in a function or method that is called
306 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
308 UpvarRegion(ty::UpvarId, Span),
310 BoundRegionInCoherence(ast::Name),
313 #[derive(Copy, Clone, Debug)]
314 pub enum FixupError {
315 UnresolvedIntTy(IntVid),
316 UnresolvedFloatTy(FloatVid),
320 impl fmt::Display for FixupError {
321 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
322 use self::FixupError::*;
325 UnresolvedIntTy(_) => {
326 write!(f, "cannot determine the type of this integer; \
327 add a suffix to specify the type explicitly")
329 UnresolvedFloatTy(_) => {
330 write!(f, "cannot determine the type of this number; \
331 add a suffix to specify the type explicitly")
333 UnresolvedTy(_) => write!(f, "unconstrained type")
338 /// Helper type of a temporary returned by tcx.infer_ctxt().
339 /// Necessary because we can't write the following bound:
340 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
341 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
342 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
343 arena: DroplessArena,
344 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
347 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
348 pub fn infer_ctxt(self) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
351 arena: DroplessArena::new(),
358 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
359 /// Used only by `rustc_typeck` during body type-checking/inference,
360 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
361 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
362 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
366 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
367 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
369 let InferCtxtBuilder {
374 let in_progress_tables = fresh_tables.as_ref();
375 global_tcx.enter_local(arena, |tcx| f(InferCtxt {
378 projection_cache: RefCell::new(traits::ProjectionCache::new()),
379 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
380 int_unification_table: RefCell::new(UnificationTable::new()),
381 float_unification_table: RefCell::new(UnificationTable::new()),
382 region_vars: RegionVarBindings::new(tcx),
383 selection_cache: traits::SelectionCache::new(),
384 evaluation_cache: traits::EvaluationCache::new(),
385 reported_trait_errors: RefCell::new(FxHashMap()),
386 tainted_by_errors_flag: Cell::new(false),
387 err_count_on_creation: tcx.sess.err_count(),
388 in_snapshot: Cell::new(false),
393 impl<T> ExpectedFound<T> {
394 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
396 ExpectedFound {expected: a, found: b}
398 ExpectedFound {expected: b, found: a}
403 impl<'tcx, T> InferOk<'tcx, T> {
404 pub fn unit(self) -> InferOk<'tcx, ()> {
405 InferOk { value: (), obligations: self.obligations }
409 #[must_use = "once you start a snapshot, you should always consume it"]
410 pub struct CombinedSnapshot<'a, 'tcx:'a> {
411 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
412 type_snapshot: type_variable::Snapshot,
413 int_snapshot: unify::Snapshot<ty::IntVid>,
414 float_snapshot: unify::Snapshot<ty::FloatVid>,
415 region_vars_snapshot: RegionSnapshot,
416 was_in_snapshot: bool,
417 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
420 /// Helper trait for shortening the lifetimes inside a
421 /// value for post-type-checking normalization.
422 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
423 fn trans_normalize<'a, 'tcx>(&self,
424 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
425 param_env: ty::ParamEnv<'tcx>)
429 macro_rules! items { ($($item:item)+) => ($($item)+) }
430 macro_rules! impl_trans_normalize {
431 ($lt_gcx:tt, $($ty:ty),+) => {
432 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
433 fn trans_normalize<'a, 'tcx>(&self,
434 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>,
435 param_env: ty::ParamEnv<'tcx>)
437 infcx.normalize_projections_in(param_env, self)
443 impl_trans_normalize!('gcx,
445 &'gcx ty::Const<'gcx>,
449 ty::ClosureSubsts<'gcx>,
450 ty::PolyTraitRef<'gcx>,
451 ty::ExistentialTraitRef<'gcx>
454 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
455 fn trans_normalize<'a, 'tcx>(&self,
456 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
457 param_env: ty::ParamEnv<'tcx>)
460 LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx, param_env) },
461 LvalueTy::Downcast { adt_def, substs, variant_index } => {
464 substs: substs.trans_normalize(infcx, param_env),
472 // NOTE: Callable from trans only!
473 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
474 /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
475 /// each time we erase them in translation, we need to normalize
477 pub fn erase_late_bound_regions_and_normalize<T>(self, value: &ty::Binder<T>)
479 where T: TransNormalize<'tcx>
481 assert!(!value.needs_subst());
482 let value = self.erase_late_bound_regions(value);
483 self.normalize_associated_type(&value)
486 /// Fully normalizes any associated types in `value`, using an
487 /// empty environment and `Reveal::All` mode (therefore, suitable
488 /// only for monomorphized code during trans, basically).
489 pub fn normalize_associated_type<T>(self, value: &T) -> T
490 where T: TransNormalize<'tcx>
492 debug!("normalize_associated_type(t={:?})", value);
494 let param_env = ty::ParamEnv::empty(Reveal::All);
495 let value = self.erase_regions(value);
497 if !value.has_projections() {
501 self.infer_ctxt().enter(|infcx| {
502 value.trans_normalize(&infcx, param_env)
506 /// Does a best-effort to normalize any associated types in
507 /// `value`; this includes revealing specializable types, so this
508 /// should be not be used during type-checking, but only during
509 /// optimization and code generation.
510 pub fn normalize_associated_type_in_env<T>(
511 self, value: &T, env: ty::ParamEnv<'tcx>
513 where T: TransNormalize<'tcx>
515 debug!("normalize_associated_type_in_env(t={:?})", value);
517 let value = self.erase_regions(value);
519 if !value.has_projections() {
523 self.infer_ctxt().enter(|infcx| {
524 value.trans_normalize(&infcx, env.reveal_all())
529 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
530 fn normalize_projections_in<T>(&self, param_env: ty::ParamEnv<'tcx>, value: &T) -> T::Lifted
531 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
533 let mut selcx = traits::SelectionContext::new(self);
534 let cause = traits::ObligationCause::dummy();
535 let traits::Normalized { value: result, obligations } =
536 traits::normalize(&mut selcx, param_env, cause, value);
538 debug!("normalize_projections_in: result={:?} obligations={:?}",
539 result, obligations);
541 let mut fulfill_cx = traits::FulfillmentContext::new();
543 for obligation in obligations {
544 fulfill_cx.register_predicate_obligation(self, obligation);
547 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
550 /// Finishes processes any obligations that remain in the
551 /// fulfillment context, and then returns the result with all type
552 /// variables removed and regions erased. Because this is intended
553 /// for use after type-check has completed, if any errors occur,
554 /// it will panic. It is used during normalization and other cases
555 /// where processing the obligations in `fulfill_cx` may cause
556 /// type inference variables that appear in `result` to be
557 /// unified, and hence we need to process those obligations to get
558 /// the complete picture of the type.
559 pub fn drain_fulfillment_cx_or_panic<T>(&self,
561 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
564 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
566 debug!("drain_fulfillment_cx_or_panic()");
568 // In principle, we only need to do this so long as `result`
569 // contains unbound type parameters. It could be a slight
570 // optimization to stop iterating early.
571 match fulfill_cx.select_all_or_error(self) {
574 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
579 let result = self.resolve_type_vars_if_possible(result);
580 let result = self.tcx.erase_regions(&result);
582 match self.tcx.lift_to_global(&result) {
583 Some(result) => result,
585 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
590 pub fn is_in_snapshot(&self) -> bool {
591 self.in_snapshot.get()
594 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
595 t.fold_with(&mut self.freshener())
598 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
600 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
605 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
606 freshen::TypeFreshener::new(self)
609 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
610 use ty::error::UnconstrainedNumeric::Neither;
611 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
613 ty::TyInfer(ty::IntVar(vid)) => {
614 if self.int_unification_table.borrow_mut().has_value(vid) {
620 ty::TyInfer(ty::FloatVar(vid)) => {
621 if self.float_unification_table.borrow_mut().has_value(vid) {
631 /// Returns a type variable's default fallback if any exists. A default
632 /// must be attached to the variable when created, if it is created
633 /// without a default, this will return None.
635 /// This code does not apply to integral or floating point variables,
636 /// only to use declared defaults.
638 /// See `new_ty_var_with_default` to create a type variable with a default.
639 /// See `type_variable::Default` for details about what a default entails.
640 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
642 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
647 pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
648 let mut variables = Vec::new();
650 let unbound_ty_vars = self.type_variables
652 .unsolved_variables()
654 .map(|t| self.tcx.mk_var(t));
656 let unbound_int_vars = self.int_unification_table
658 .unsolved_variables()
660 .map(|v| self.tcx.mk_int_var(v));
662 let unbound_float_vars = self.float_unification_table
664 .unsolved_variables()
666 .map(|v| self.tcx.mk_float_var(v));
668 variables.extend(unbound_ty_vars);
669 variables.extend(unbound_int_vars);
670 variables.extend(unbound_float_vars);
675 fn combine_fields(&'a self, trace: TypeTrace<'tcx>, param_env: ty::ParamEnv<'tcx>)
676 -> CombineFields<'a, 'gcx, 'tcx> {
682 obligations: PredicateObligations::new(),
686 // Clear the "currently in a snapshot" flag, invoke the closure,
687 // then restore the flag to its original value. This flag is a
688 // debugging measure designed to detect cases where we start a
689 // snapshot, create type variables, and register obligations
690 // which may involve those type variables in the fulfillment cx,
691 // potentially leaving "dangling type variables" behind.
692 // In such cases, an assertion will fail when attempting to
693 // register obligations, within a snapshot. Very useful, much
694 // better than grovelling through megabytes of RUST_LOG output.
696 // HOWEVER, in some cases the flag is unhelpful. In particular, we
697 // sometimes create a "mini-fulfilment-cx" in which we enroll
698 // obligations. As long as this fulfillment cx is fully drained
699 // before we return, this is not a problem, as there won't be any
700 // escaping obligations in the main cx. In those cases, you can
701 // use this function.
702 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
703 where F: FnOnce(&Self) -> R
705 let flag = self.in_snapshot.get();
706 self.in_snapshot.set(false);
707 let result = func(self);
708 self.in_snapshot.set(flag);
712 fn start_snapshot<'b>(&'b self) -> CombinedSnapshot<'b, 'tcx> {
713 debug!("start_snapshot()");
715 let in_snapshot = self.in_snapshot.get();
716 self.in_snapshot.set(true);
719 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
720 type_snapshot: self.type_variables.borrow_mut().snapshot(),
721 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
722 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
723 region_vars_snapshot: self.region_vars.start_snapshot(),
724 was_in_snapshot: in_snapshot,
725 // Borrow tables "in progress" (i.e. during typeck)
726 // to ban writes from within a snapshot to them.
727 _in_progress_tables: self.in_progress_tables.map(|tables| {
733 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
734 debug!("rollback_to(cause={})", cause);
735 let CombinedSnapshot { projection_cache_snapshot,
739 region_vars_snapshot,
741 _in_progress_tables } = snapshot;
743 self.in_snapshot.set(was_in_snapshot);
745 self.projection_cache
747 .rollback_to(projection_cache_snapshot);
750 .rollback_to(type_snapshot);
751 self.int_unification_table
753 .rollback_to(int_snapshot);
754 self.float_unification_table
756 .rollback_to(float_snapshot);
758 .rollback_to(region_vars_snapshot);
761 fn commit_from(&self, snapshot: CombinedSnapshot) {
762 debug!("commit_from()");
763 let CombinedSnapshot { projection_cache_snapshot,
767 region_vars_snapshot,
769 _in_progress_tables } = snapshot;
771 self.in_snapshot.set(was_in_snapshot);
773 self.projection_cache
775 .commit(projection_cache_snapshot);
778 .commit(type_snapshot);
779 self.int_unification_table
781 .commit(int_snapshot);
782 self.float_unification_table
784 .commit(float_snapshot);
786 .commit(region_vars_snapshot);
789 /// Execute `f` and commit the bindings
790 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
794 let snapshot = self.start_snapshot();
796 self.commit_from(snapshot);
800 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
801 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
802 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
804 debug!("commit_if_ok()");
805 let snapshot = self.start_snapshot();
806 let r = f(&snapshot);
807 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
809 Ok(_) => { self.commit_from(snapshot); }
810 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
815 // Execute `f` in a snapshot, and commit the bindings it creates
816 pub fn in_snapshot<T, F>(&self, f: F) -> T where
817 F: FnOnce(&CombinedSnapshot) -> T
819 debug!("in_snapshot()");
820 let snapshot = self.start_snapshot();
821 let r = f(&snapshot);
822 self.commit_from(snapshot);
826 /// Execute `f` then unroll any bindings it creates
827 pub fn probe<R, F>(&self, f: F) -> R where
828 F: FnOnce(&CombinedSnapshot) -> R,
831 let snapshot = self.start_snapshot();
832 let r = f(&snapshot);
833 self.rollback_to("probe", snapshot);
837 pub fn add_given(&self,
838 sub: ty::Region<'tcx>,
841 self.region_vars.add_given(sub, sup);
844 pub fn can_sub<T>(&self,
845 param_env: ty::ParamEnv<'tcx>,
849 where T: at::ToTrace<'tcx>
851 let origin = &ObligationCause::dummy();
853 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
854 // Ignore obligations, since we are unrolling
855 // everything anyway.
860 pub fn can_eq<T>(&self,
861 param_env: ty::ParamEnv<'tcx>,
865 where T: at::ToTrace<'tcx>
867 let origin = &ObligationCause::dummy();
869 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
870 // Ignore obligations, since we are unrolling
871 // everything anyway.
876 pub fn sub_regions(&self,
877 origin: SubregionOrigin<'tcx>,
879 b: ty::Region<'tcx>) {
880 debug!("sub_regions({:?} <: {:?})", a, b);
881 self.region_vars.make_subregion(origin, a, b);
884 pub fn equality_predicate(&self,
885 cause: &ObligationCause<'tcx>,
886 param_env: ty::ParamEnv<'tcx>,
887 predicate: &ty::PolyEquatePredicate<'tcx>)
888 -> InferResult<'tcx, ()>
890 self.commit_if_ok(|snapshot| {
891 let (ty::EquatePredicate(a, b), skol_map) =
892 self.skolemize_late_bound_regions(predicate, snapshot);
893 let cause_span = cause.span;
894 let eqty_ok = self.at(cause, param_env).eq(b, a)?;
895 self.leak_check(false, cause_span, &skol_map, snapshot)?;
896 self.pop_skolemized(skol_map, snapshot);
901 pub fn subtype_predicate(&self,
902 cause: &ObligationCause<'tcx>,
903 param_env: ty::ParamEnv<'tcx>,
904 predicate: &ty::PolySubtypePredicate<'tcx>)
905 -> Option<InferResult<'tcx, ()>>
907 // Subtle: it's ok to skip the binder here and resolve because
908 // `shallow_resolve` just ignores anything that is not a type
909 // variable, and because type variable's can't (at present, at
910 // least) capture any of the things bound by this binder.
912 // Really, there is no *particular* reason to do this
913 // `shallow_resolve` here except as a
914 // micro-optimization. Naturally I could not
915 // resist. -nmatsakis
916 let two_unbound_type_vars = {
917 let a = self.shallow_resolve(predicate.skip_binder().a);
918 let b = self.shallow_resolve(predicate.skip_binder().b);
919 a.is_ty_var() && b.is_ty_var()
922 if two_unbound_type_vars {
923 // Two unbound type variables? Can't make progress.
927 Some(self.commit_if_ok(|snapshot| {
928 let (ty::SubtypePredicate { a_is_expected, a, b}, skol_map) =
929 self.skolemize_late_bound_regions(predicate, snapshot);
931 let cause_span = cause.span;
932 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
933 self.leak_check(false, cause_span, &skol_map, snapshot)?;
934 self.pop_skolemized(skol_map, snapshot);
939 pub fn region_outlives_predicate(&self,
940 cause: &traits::ObligationCause<'tcx>,
941 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
944 self.commit_if_ok(|snapshot| {
945 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
946 self.skolemize_late_bound_regions(predicate, snapshot);
948 SubregionOrigin::from_obligation_cause(cause,
949 || RelateRegionParamBound(cause.span));
950 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
951 self.leak_check(false, cause.span, &skol_map, snapshot)?;
952 Ok(self.pop_skolemized(skol_map, snapshot))
956 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
959 .new_var(diverging, origin, None)
962 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
963 self.tcx.mk_var(self.next_ty_var_id(false, origin))
966 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
967 self.tcx.mk_var(self.next_ty_var_id(true, origin))
970 pub fn next_int_var_id(&self) -> IntVid {
971 self.int_unification_table
976 pub fn next_float_var_id(&self) -> FloatVid {
977 self.float_unification_table
982 pub fn next_region_var(&self, origin: RegionVariableOrigin)
983 -> ty::Region<'tcx> {
984 self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
987 /// Create a region inference variable for the given
988 /// region parameter definition.
989 pub fn region_var_for_def(&self,
991 def: &ty::RegionParameterDef)
992 -> ty::Region<'tcx> {
993 self.next_region_var(EarlyBoundRegion(span, def.name))
996 /// Create a type inference variable for the given
997 /// type parameter definition. The substitutions are
998 /// for actual parameters that may be referred to by
999 /// the default of this type parameter, if it exists.
1000 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1001 /// used in a path such as `Foo::<T, U>::new()` will
1002 /// use an inference variable for `C` with `[T, U]`
1003 /// as the substitutions for the default, `(T, U)`.
1004 pub fn type_var_for_def(&self,
1006 def: &ty::TypeParameterDef,
1007 substs: &[Kind<'tcx>])
1009 let default = if def.has_default {
1010 let default = self.tcx.type_of(def.def_id);
1011 Some(type_variable::Default {
1012 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1021 let ty_var_id = self.type_variables
1024 TypeVariableOrigin::TypeParameterDefinition(span, def.name),
1027 self.tcx.mk_var(ty_var_id)
1030 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1031 /// type/region parameter to a fresh inference variable.
1032 pub fn fresh_substs_for_item(&self,
1035 -> &'tcx Substs<'tcx> {
1036 Substs::for_item(self.tcx, def_id, |def, _| {
1037 self.region_var_for_def(span, def)
1039 self.type_var_for_def(span, def, substs)
1043 pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region<'tcx> {
1044 self.region_vars.new_bound(debruijn)
1047 /// True if errors have been reported since this infcx was
1048 /// created. This is sometimes used as a heuristic to skip
1049 /// reporting errors that often occur as a result of earlier
1050 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1051 /// inference variables, regionck errors).
1052 pub fn is_tainted_by_errors(&self) -> bool {
1053 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1054 tainted_by_errors_flag={})",
1055 self.tcx.sess.err_count(),
1056 self.err_count_on_creation,
1057 self.tainted_by_errors_flag.get());
1059 if self.tcx.sess.err_count() > self.err_count_on_creation {
1060 return true; // errors reported since this infcx was made
1062 self.tainted_by_errors_flag.get()
1065 /// Set the "tainted by errors" flag to true. We call this when we
1066 /// observe an error from a prior pass.
1067 pub fn set_tainted_by_errors(&self) {
1068 debug!("set_tainted_by_errors()");
1069 self.tainted_by_errors_flag.set(true)
1072 pub fn resolve_regions_and_report_errors(&self,
1073 region_context: DefId,
1074 region_map: ®ion::ScopeTree,
1075 free_regions: &FreeRegionMap<'tcx>) {
1076 let region_rels = RegionRelations::new(self.tcx,
1080 let errors = self.region_vars.resolve_regions(®ion_rels);
1082 if !self.is_tainted_by_errors() {
1083 // As a heuristic, just skip reporting region errors
1084 // altogether if other errors have been reported while
1085 // this infcx was in use. This is totally hokey but
1086 // otherwise we have a hard time separating legit region
1087 // errors from silly ones.
1088 self.report_region_errors(region_map, &errors); // see error_reporting module
1092 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1093 self.resolve_type_vars_if_possible(&t).to_string()
1096 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1097 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1098 format!("({})", tstrs.join(", "))
1101 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1102 self.resolve_type_vars_if_possible(t).to_string()
1105 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1107 ty::TyInfer(ty::TyVar(v)) => {
1108 // Not entirely obvious: if `typ` is a type variable,
1109 // it can be resolved to an int/float variable, which
1110 // can then be recursively resolved, hence the
1111 // recursion. Note though that we prevent type
1112 // variables from unifying to other type variables
1113 // directly (though they may be embedded
1114 // structurally), and we prevent cycles in any case,
1115 // so this recursion should always be of very limited
1117 self.type_variables.borrow_mut()
1119 .map(|t| self.shallow_resolve(t))
1123 ty::TyInfer(ty::IntVar(v)) => {
1124 self.int_unification_table
1127 .map(|v| v.to_type(self.tcx))
1131 ty::TyInfer(ty::FloatVar(v)) => {
1132 self.float_unification_table
1135 .map(|v| v.to_type(self.tcx))
1145 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1146 where T: TypeFoldable<'tcx>
1149 * Where possible, replaces type/int/float variables in
1150 * `value` with their final value. Note that region variables
1151 * are unaffected. If a type variable has not been unified, it
1152 * is left as is. This is an idempotent operation that does
1153 * not affect inference state in any way and so you can do it
1157 if !value.needs_infer() {
1158 return value.clone(); // avoid duplicated subst-folding
1160 let mut r = resolve::OpportunisticTypeResolver::new(self);
1161 value.fold_with(&mut r)
1164 /// Returns true if `T` contains unresolved type variables. In the
1165 /// process of visiting `T`, this will resolve (where possible)
1166 /// type variables in `T`, but it never constructs the final,
1167 /// resolved type, so it's more efficient than
1168 /// `resolve_type_vars_if_possible()`.
1169 pub fn any_unresolved_type_vars<T>(&self, value: &T) -> bool
1170 where T: TypeFoldable<'tcx>
1172 let mut r = resolve::UnresolvedTypeFinder::new(self);
1173 value.visit_with(&mut r)
1176 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1177 where T: TypeFoldable<'tcx>
1179 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1180 value.fold_with(&mut r)
1183 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1185 * Attempts to resolve all type/region variables in
1186 * `value`. Region inference must have been run already (e.g.,
1187 * by calling `resolve_regions_and_report_errors`). If some
1188 * variable was never unified, an `Err` results.
1190 * This method is idempotent, but it not typically not invoked
1191 * except during the writeback phase.
1194 resolve::fully_resolve(self, value)
1197 // [Note-Type-error-reporting]
1198 // An invariant is that anytime the expected or actual type is TyError (the special
1199 // error type, meaning that an error occurred when typechecking this expression),
1200 // this is a derived error. The error cascaded from another error (that was already
1201 // reported), so it's not useful to display it to the user.
1202 // The following methods implement this logic.
1203 // They check if either the actual or expected type is TyError, and don't print the error
1204 // in this case. The typechecker should only ever report type errors involving mismatched
1205 // types using one of these methods, and should not call span_err directly for such
1208 pub fn type_error_struct_with_diag<M>(&self,
1211 actual_ty: Ty<'tcx>)
1212 -> DiagnosticBuilder<'tcx>
1213 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1215 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1216 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1218 // Don't report an error if actual type is TyError.
1219 if actual_ty.references_error() {
1220 return self.tcx.sess.diagnostic().struct_dummy();
1223 mk_diag(self.ty_to_string(actual_ty))
1226 pub fn report_mismatched_types(&self,
1227 cause: &ObligationCause<'tcx>,
1230 err: TypeError<'tcx>)
1231 -> DiagnosticBuilder<'tcx> {
1232 let trace = TypeTrace::types(cause, true, expected, actual);
1233 self.report_and_explain_type_error(trace, &err)
1236 pub fn report_conflicting_default_types(&self,
1238 body_id: ast::NodeId,
1239 expected: type_variable::Default<'tcx>,
1240 actual: type_variable::Default<'tcx>) {
1241 let trace = TypeTrace {
1242 cause: ObligationCause::misc(span, body_id),
1243 values: Types(ExpectedFound {
1244 expected: expected.ty,
1249 self.report_and_explain_type_error(
1251 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1258 pub fn replace_late_bound_regions_with_fresh_var<T>(
1261 lbrct: LateBoundRegionConversionTime,
1262 value: &ty::Binder<T>)
1263 -> (T, FxHashMap<ty::BoundRegion, ty::Region<'tcx>>)
1264 where T : TypeFoldable<'tcx>
1266 self.tcx.replace_late_bound_regions(
1268 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1271 /// Given a higher-ranked projection predicate like:
1273 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1275 /// and a target trait-ref like:
1277 /// <T as Fn<&'x u32>>
1279 /// find a substitution `S` for the higher-ranked regions (here,
1280 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1281 /// and then return the value (here, `&'a u32`) but with the
1282 /// substitution applied (hence, `&'x u32`).
1284 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1286 pub fn match_poly_projection_predicate(&self,
1287 cause: ObligationCause<'tcx>,
1288 param_env: ty::ParamEnv<'tcx>,
1289 match_a: ty::PolyProjectionPredicate<'tcx>,
1290 match_b: ty::TraitRef<'tcx>)
1291 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1293 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref(self.tcx), p.ty));
1294 let trace = TypeTrace {
1296 values: TraitRefs(ExpectedFound::new(true, match_pair.skip_binder().0, match_b))
1299 let mut combine = self.combine_fields(trace, param_env);
1300 let result = combine.higher_ranked_match(&match_pair, &match_b, true)?;
1301 Ok(InferOk { value: result, obligations: combine.obligations })
1304 /// See `verify_generic_bound` method in `region_inference`
1305 pub fn verify_generic_bound(&self,
1306 origin: SubregionOrigin<'tcx>,
1307 kind: GenericKind<'tcx>,
1308 a: ty::Region<'tcx>,
1309 bound: VerifyBound<'tcx>) {
1310 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1315 self.region_vars.verify_generic_bound(origin, kind, a, bound);
1318 pub fn type_moves_by_default(&self,
1319 param_env: ty::ParamEnv<'tcx>,
1323 let ty = self.resolve_type_vars_if_possible(&ty);
1324 // Even if the type may have no inference variables, during
1325 // type-checking closure types are in local tables only.
1326 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1327 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1328 return ty.moves_by_default(self.tcx.global_tcx(), param_env, span);
1332 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1334 // this can get called from typeck (by euv), and moves_by_default
1335 // rightly refuses to work with inference variables, but
1336 // moves_by_default has a cache, which we want to use in other
1338 !traits::type_known_to_meet_bound(self, param_env, ty, copy_def_id, span)
1341 pub fn closure_kind(&self,
1343 -> Option<ty::ClosureKind>
1345 if let Some(tables) = self.in_progress_tables {
1346 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1347 let hir_id = self.tcx.hir.node_to_hir_id(id);
1348 return tables.borrow()
1352 .map(|(kind, _)| kind);
1356 // During typeck, ALL closures are local. But afterwards,
1357 // during trans, we see closure ids from other traits.
1358 // That may require loading the closure data out of the
1360 Some(self.tcx.closure_kind(def_id))
1363 /// Obtain the signature of a function or closure.
1364 /// For closures, unlike `tcx.fn_sig(def_id)`, this method will
1365 /// work during the type-checking of the enclosing function and
1366 /// return the closure signature in its partially inferred state.
1367 pub fn fn_sig(&self, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1368 if let Some(tables) = self.in_progress_tables {
1369 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1370 let hir_id = self.tcx.hir.node_to_hir_id(id);
1371 if let Some(&ty) = tables.borrow().closure_tys().get(hir_id) {
1377 self.tcx.fn_sig(def_id)
1380 pub fn generator_sig(&self, def_id: DefId) -> Option<ty::PolyGenSig<'tcx>> {
1381 if let Some(tables) = self.in_progress_tables {
1382 if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1383 let hir_id = self.tcx.hir.node_to_hir_id(id);
1384 if let Some(&ty) = tables.borrow().generator_sigs().get(hir_id) {
1385 return ty.map(|t| ty::Binder(t));
1390 self.tcx.generator_sig(def_id)
1394 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1395 pub fn span(&self) -> Span {
1399 pub fn types(cause: &ObligationCause<'tcx>,
1400 a_is_expected: bool,
1403 -> TypeTrace<'tcx> {
1405 cause: cause.clone(),
1406 values: Types(ExpectedFound::new(a_is_expected, a, b))
1410 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1412 cause: ObligationCause::dummy(),
1413 values: Types(ExpectedFound {
1414 expected: tcx.types.err,
1415 found: tcx.types.err,
1421 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1422 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1423 write!(f, "TypeTrace({:?})", self.cause)
1427 impl<'tcx> SubregionOrigin<'tcx> {
1428 pub fn span(&self) -> Span {
1430 Subtype(ref a) => a.span(),
1431 InfStackClosure(a) => a,
1432 InvokeClosure(a) => a,
1433 DerefPointer(a) => a,
1434 FreeVariable(a, _) => a,
1436 RelateObjectBound(a) => a,
1437 RelateParamBound(a, _) => a,
1438 RelateRegionParamBound(a) => a,
1439 RelateDefaultParamBound(a, _) => a,
1441 ReborrowUpvar(a, _) => a,
1442 DataBorrowed(_, a) => a,
1443 ReferenceOutlivesReferent(_, a) => a,
1444 ParameterInScope(_, a) => a,
1445 ExprTypeIsNotInScope(_, a) => a,
1446 BindingTypeIsNotValidAtDecl(a) => a,
1453 SafeDestructor(a) => a,
1454 CompareImplMethodObligation { span, .. } => span,
1458 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>,
1461 where F: FnOnce() -> Self
1464 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
1465 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span),
1467 traits::ObligationCauseCode::CompareImplMethodObligation { item_name,
1471 SubregionOrigin::CompareImplMethodObligation {
1484 impl RegionVariableOrigin {
1485 pub fn span(&self) -> Span {
1487 MiscVariable(a) => a,
1488 PatternRegion(a) => a,
1489 AddrOfRegion(a) => a,
1492 EarlyBoundRegion(a, ..) => a,
1493 LateBoundRegion(a, ..) => a,
1494 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1495 UpvarRegion(_, a) => a
1500 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1501 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1503 ValuePairs::Types(ref ef) => {
1504 ValuePairs::Types(ef.fold_with(folder))
1506 ValuePairs::TraitRefs(ref ef) => {
1507 ValuePairs::TraitRefs(ef.fold_with(folder))
1509 ValuePairs::PolyTraitRefs(ref ef) => {
1510 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1515 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1517 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1518 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1519 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1524 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1525 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1527 cause: self.cause.fold_with(folder),
1528 values: self.values.fold_with(folder)
1532 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1533 self.cause.visit_with(visitor) || self.values.visit_with(visitor)