]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/mod.rs
strip param-env from infcx
[rust.git] / src / librustc / infer / mod.rs
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.
4 //
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.
10
11 //! See the Book for more information.
12
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};
20
21 use hir::def_id::DefId;
22 use hir;
23 use middle::free_region::{FreeRegionMap, RegionRelations};
24 use middle::region::RegionMaps;
25 use middle::mem_categorization as mc;
26 use middle::mem_categorization::McResult;
27 use middle::lang_items;
28 use mir::tcx::LvalueTy;
29 use ty::subst::{Kind, Subst, Substs};
30 use ty::{TyVid, IntVid, FloatVid};
31 use ty::{self, Ty, TyCtxt};
32 use ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
33 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
34 use ty::relate::{Relate, RelateResult, TypeRelation};
35 use traits::{self, ObligationCause, PredicateObligations, Reveal};
36 use rustc_data_structures::unify::{self, UnificationTable};
37 use std::cell::{Cell, RefCell, Ref, RefMut};
38 use std::fmt;
39 use std::ops::Deref;
40 use syntax::ast;
41 use errors::DiagnosticBuilder;
42 use syntax_pos::{self, Span, DUMMY_SP};
43 use util::nodemap::{FxHashMap, FxHashSet};
44 use arena::DroplessArena;
45
46 use self::combine::CombineFields;
47 use self::higher_ranked::HrMatchResult;
48 use self::region_inference::{RegionVarBindings, RegionSnapshot};
49 use self::type_variable::TypeVariableOrigin;
50 use self::unify_key::ToType;
51
52 mod combine;
53 mod equate;
54 pub mod error_reporting;
55 mod fudge;
56 mod glb;
57 mod higher_ranked;
58 pub mod lattice;
59 mod lub;
60 pub mod region_inference;
61 pub mod resolve;
62 mod freshen;
63 mod sub;
64 pub mod type_variable;
65 pub mod unify_key;
66
67 #[must_use]
68 pub struct InferOk<'tcx, T> {
69     pub value: T,
70     pub obligations: PredicateObligations<'tcx>,
71 }
72 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
73
74 pub type Bound<T> = Option<T>;
75 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
76 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
77
78 /// A version of &ty::TypeckTables which can be `Missing` (not needed),
79 /// `InProgress` (during typeck) or `Interned` (result of typeck).
80 /// Only the `InProgress` version supports `borrow_mut`.
81 #[derive(Copy, Clone)]
82 pub enum InferTables<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
83     Interned(&'a ty::TypeckTables<'gcx>),
84     InProgress(&'a RefCell<ty::TypeckTables<'tcx>>),
85     Missing
86 }
87
88 pub enum InferTablesRef<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
89     Interned(&'a ty::TypeckTables<'gcx>),
90     InProgress(Ref<'a, ty::TypeckTables<'tcx>>)
91 }
92
93 impl<'a, 'gcx, 'tcx> Deref for InferTablesRef<'a, 'gcx, 'tcx> {
94     type Target = ty::TypeckTables<'tcx>;
95     fn deref(&self) -> &Self::Target {
96         match *self {
97             InferTablesRef::Interned(tables) => tables,
98             InferTablesRef::InProgress(ref tables) => tables
99         }
100     }
101 }
102
103 impl<'a, 'gcx, 'tcx> InferTables<'a, 'gcx, 'tcx> {
104     pub fn borrow(self) -> InferTablesRef<'a, 'gcx, 'tcx> {
105         match self {
106             InferTables::Interned(tables) => InferTablesRef::Interned(tables),
107             InferTables::InProgress(tables) => InferTablesRef::InProgress(tables.borrow()),
108             InferTables::Missing => {
109                 bug!("InferTables: infcx.tables.borrow() with no tables")
110             }
111         }
112     }
113
114     pub fn expect_interned(self) -> &'a ty::TypeckTables<'gcx> {
115         match self {
116             InferTables::Interned(tables) => tables,
117             InferTables::InProgress(_) => {
118                 bug!("InferTables: infcx.tables.expect_interned() during type-checking");
119             }
120             InferTables::Missing => {
121                 bug!("InferTables: infcx.tables.expect_interned() with no tables")
122             }
123         }
124     }
125
126     pub fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> {
127         match self {
128             InferTables::Interned(_) => {
129                 bug!("InferTables: infcx.tables.borrow_mut() outside of type-checking");
130             }
131             InferTables::InProgress(tables) => tables.borrow_mut(),
132             InferTables::Missing => {
133                 bug!("InferTables: infcx.tables.borrow_mut() with no tables")
134             }
135         }
136     }
137 }
138
139 pub struct InferCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
140     pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
141
142     pub tables: InferTables<'a, 'gcx, 'tcx>,
143
144     // Cache for projections. This cache is snapshotted along with the
145     // infcx.
146     //
147     // Public so that `traits::project` can use it.
148     pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
149
150     // We instantiate UnificationTable with bounds<Ty> because the
151     // types that might instantiate a general type variable have an
152     // order, represented by its upper and lower bounds.
153     pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
154
155     // Map from integral variable to the kind of integer it represents
156     int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
157
158     // Map from floating variable to the kind of float it represents
159     float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
160
161     // For region variables.
162     region_vars: RegionVarBindings<'a, 'gcx, 'tcx>,
163
164     /// Caches the results of trait selection. This cache is used
165     /// for things that have to do with the parameters in scope.
166     pub selection_cache: traits::SelectionCache<'tcx>,
167
168     /// Caches the results of trait evaluation.
169     pub evaluation_cache: traits::EvaluationCache<'tcx>,
170
171     // the set of predicates on which errors have been reported, to
172     // avoid reporting the same error twice.
173     pub reported_trait_errors: RefCell<FxHashSet<traits::TraitErrorKey<'tcx>>>,
174
175     // When an error occurs, we want to avoid reporting "derived"
176     // errors that are due to this original failure. Normally, we
177     // handle this with the `err_count_on_creation` count, which
178     // basically just tracks how many errors were reported when we
179     // started type-checking a fn and checks to see if any new errors
180     // have been reported since then. Not great, but it works.
181     //
182     // However, when errors originated in other passes -- notably
183     // resolve -- this heuristic breaks down. Therefore, we have this
184     // auxiliary flag that one can set whenever one creates a
185     // type-error that is due to an error in a prior pass.
186     //
187     // Don't read this flag directly, call `is_tainted_by_errors()`
188     // and `set_tainted_by_errors()`.
189     tainted_by_errors_flag: Cell<bool>,
190
191     // Track how many errors were reported when this infcx is created.
192     // If the number of errors increases, that's also a sign (line
193     // `tained_by_errors`) to avoid reporting certain kinds of errors.
194     err_count_on_creation: usize,
195
196     // This flag is true while there is an active snapshot.
197     in_snapshot: Cell<bool>,
198 }
199
200 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
201 /// region that each late-bound region was replaced with.
202 pub type SkolemizationMap<'tcx> = FxHashMap<ty::BoundRegion, ty::Region<'tcx>>;
203
204 /// See `error_reporting` module for more details
205 #[derive(Clone, Debug)]
206 pub enum ValuePairs<'tcx> {
207     Types(ExpectedFound<Ty<'tcx>>),
208     TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
209     PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
210 }
211
212 /// The trace designates the path through inference that we took to
213 /// encounter an error or subtyping constraint.
214 ///
215 /// See `error_reporting` module for more details.
216 #[derive(Clone)]
217 pub struct TypeTrace<'tcx> {
218     cause: ObligationCause<'tcx>,
219     values: ValuePairs<'tcx>,
220 }
221
222 /// The origin of a `r1 <= r2` constraint.
223 ///
224 /// See `error_reporting` module for more details
225 #[derive(Clone, Debug)]
226 pub enum SubregionOrigin<'tcx> {
227     // Arose from a subtyping relation
228     Subtype(TypeTrace<'tcx>),
229
230     // Stack-allocated closures cannot outlive innermost loop
231     // or function so as to ensure we only require finite stack
232     InfStackClosure(Span),
233
234     // Invocation of closure must be within its lifetime
235     InvokeClosure(Span),
236
237     // Dereference of reference must be within its lifetime
238     DerefPointer(Span),
239
240     // Closure bound must not outlive captured free variables
241     FreeVariable(Span, ast::NodeId),
242
243     // Index into slice must be within its lifetime
244     IndexSlice(Span),
245
246     // When casting `&'a T` to an `&'b Trait` object,
247     // relating `'a` to `'b`
248     RelateObjectBound(Span),
249
250     // Some type parameter was instantiated with the given type,
251     // and that type must outlive some region.
252     RelateParamBound(Span, Ty<'tcx>),
253
254     // The given region parameter was instantiated with a region
255     // that must outlive some other region.
256     RelateRegionParamBound(Span),
257
258     // A bound placed on type parameters that states that must outlive
259     // the moment of their instantiation.
260     RelateDefaultParamBound(Span, Ty<'tcx>),
261
262     // Creating a pointer `b` to contents of another reference
263     Reborrow(Span),
264
265     // Creating a pointer `b` to contents of an upvar
266     ReborrowUpvar(Span, ty::UpvarId),
267
268     // Data with type `Ty<'tcx>` was borrowed
269     DataBorrowed(Ty<'tcx>, Span),
270
271     // (&'a &'b T) where a >= b
272     ReferenceOutlivesReferent(Ty<'tcx>, Span),
273
274     // Type or region parameters must be in scope.
275     ParameterInScope(ParameterOrigin, Span),
276
277     // The type T of an expression E must outlive the lifetime for E.
278     ExprTypeIsNotInScope(Ty<'tcx>, Span),
279
280     // A `ref b` whose region does not enclose the decl site
281     BindingTypeIsNotValidAtDecl(Span),
282
283     // Regions appearing in a method receiver must outlive method call
284     CallRcvr(Span),
285
286     // Regions appearing in a function argument must outlive func call
287     CallArg(Span),
288
289     // Region in return type of invoked fn must enclose call
290     CallReturn(Span),
291
292     // Operands must be in scope
293     Operand(Span),
294
295     // Region resulting from a `&` expr must enclose the `&` expr
296     AddrOf(Span),
297
298     // An auto-borrow that does not enclose the expr where it occurs
299     AutoBorrow(Span),
300
301     // Region constraint arriving from destructor safety
302     SafeDestructor(Span),
303
304     // Comparing the signature and requirements of an impl method against
305     // the containing trait.
306     CompareImplMethodObligation {
307         span: Span,
308         item_name: ast::Name,
309         impl_item_def_id: DefId,
310         trait_item_def_id: DefId,
311
312         // this is `Some(_)` if this error arises from the bug fix for
313         // #18937. This is a temporary measure.
314         lint_id: Option<ast::NodeId>,
315     },
316 }
317
318 /// Places that type/region parameters can appear.
319 #[derive(Clone, Copy, Debug)]
320 pub enum ParameterOrigin {
321     Path, // foo::bar
322     MethodCall, // foo.bar() <-- parameters on impl providing bar()
323     OverloadedOperator, // a + b when overloaded
324     OverloadedDeref, // *a when overloaded
325 }
326
327 /// Times when we replace late-bound regions with variables:
328 #[derive(Clone, Copy, Debug)]
329 pub enum LateBoundRegionConversionTime {
330     /// when a fn is called
331     FnCall,
332
333     /// when two higher-ranked types are compared
334     HigherRankedType,
335
336     /// when projecting an associated type
337     AssocTypeProjection(ast::Name),
338 }
339
340 /// Reasons to create a region inference variable
341 ///
342 /// See `error_reporting` module for more details
343 #[derive(Clone, Debug)]
344 pub enum RegionVariableOrigin {
345     // Region variables created for ill-categorized reasons,
346     // mostly indicates places in need of refactoring
347     MiscVariable(Span),
348
349     // Regions created by a `&P` or `[...]` pattern
350     PatternRegion(Span),
351
352     // Regions created by `&` operator
353     AddrOfRegion(Span),
354
355     // Regions created as part of an autoref of a method receiver
356     Autoref(Span),
357
358     // Regions created as part of an automatic coercion
359     Coercion(Span),
360
361     // Region variables created as the values for early-bound regions
362     EarlyBoundRegion(Span, ast::Name, Option<ty::Issue32330>),
363
364     // Region variables created for bound regions
365     // in a function or method that is called
366     LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
367
368     UpvarRegion(ty::UpvarId, Span),
369
370     BoundRegionInCoherence(ast::Name),
371 }
372
373 #[derive(Copy, Clone, Debug)]
374 pub enum FixupError {
375     UnresolvedIntTy(IntVid),
376     UnresolvedFloatTy(FloatVid),
377     UnresolvedTy(TyVid)
378 }
379
380 impl fmt::Display for FixupError {
381     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
382         use self::FixupError::*;
383
384         match *self {
385             UnresolvedIntTy(_) => {
386                 write!(f, "cannot determine the type of this integer; \
387                            add a suffix to specify the type explicitly")
388             }
389             UnresolvedFloatTy(_) => {
390                 write!(f, "cannot determine the type of this number; \
391                            add a suffix to specify the type explicitly")
392             }
393             UnresolvedTy(_) => write!(f, "unconstrained type")
394         }
395     }
396 }
397
398 pub trait InferEnv<'a, 'tcx> {
399     fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
400                 -> (Option<&'a ty::TypeckTables<'tcx>>,
401                     Option<ty::TypeckTables<'tcx>>);
402 }
403
404 impl<'a, 'tcx> InferEnv<'a, 'tcx> for () {
405     fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
406                 -> (Option<&'a ty::TypeckTables<'tcx>>,
407                     Option<ty::TypeckTables<'tcx>>) {
408         (None, None)
409     }
410 }
411
412 impl<'a, 'tcx> InferEnv<'a, 'tcx> for &'a ty::TypeckTables<'tcx> {
413     fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
414                 -> (Option<&'a ty::TypeckTables<'tcx>>,
415                     Option<ty::TypeckTables<'tcx>>) {
416         (Some(self), None)
417     }
418 }
419
420 impl<'a, 'tcx> InferEnv<'a, 'tcx> for ty::TypeckTables<'tcx> {
421     fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
422                 -> (Option<&'a ty::TypeckTables<'tcx>>,
423                     Option<ty::TypeckTables<'tcx>>) {
424         (None, Some(self))
425     }
426 }
427
428 impl<'a, 'tcx> InferEnv<'a, 'tcx> for hir::BodyId {
429     fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
430                 -> (Option<&'a ty::TypeckTables<'tcx>>,
431                     Option<ty::TypeckTables<'tcx>>) {
432         let def_id = tcx.hir.body_owner_def_id(self);
433         (Some(tcx.typeck_tables_of(def_id)), None)
434     }
435 }
436
437 /// Helper type of a temporary returned by tcx.infer_ctxt(...).
438 /// Necessary because we can't write the following bound:
439 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
440 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
441     global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
442     arena: DroplessArena,
443     fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
444     tables: Option<&'a ty::TypeckTables<'gcx>>,
445 }
446
447 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
448     pub fn infer_ctxt<E: InferEnv<'a, 'gcx>>(self, env: E) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
449         let (tables, fresh_tables) = env.to_parts(self);
450         InferCtxtBuilder {
451             global_tcx: self,
452             arena: DroplessArena::new(),
453             fresh_tables: fresh_tables.map(RefCell::new),
454             tables: tables,
455         }
456     }
457
458     /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
459     /// for MemCategorizationContext/ExprUseVisitor.
460     /// If any inference functionality is used, ICEs will occur.
461     pub fn borrowck_fake_infer_ctxt(self, body: hir::BodyId)
462                                     -> InferCtxt<'a, 'gcx, 'gcx> {
463         let (tables, _) = body.to_parts(self);
464         InferCtxt {
465             tcx: self,
466             tables: InferTables::Interned(tables.unwrap()),
467             type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
468             int_unification_table: RefCell::new(UnificationTable::new()),
469             float_unification_table: RefCell::new(UnificationTable::new()),
470             region_vars: RegionVarBindings::new(self),
471             selection_cache: traits::SelectionCache::new(),
472             evaluation_cache: traits::EvaluationCache::new(),
473             projection_cache: RefCell::new(traits::ProjectionCache::new()),
474             reported_trait_errors: RefCell::new(FxHashSet()),
475             tainted_by_errors_flag: Cell::new(false),
476             err_count_on_creation: self.sess.err_count(),
477             in_snapshot: Cell::new(false),
478         }
479     }
480 }
481
482 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
483     pub fn enter<F, R>(&'tcx mut self, f: F) -> R
484         where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
485     {
486         let InferCtxtBuilder {
487             global_tcx,
488             ref arena,
489             ref fresh_tables,
490             tables,
491         } = *self;
492         let tables = tables.map(InferTables::Interned).unwrap_or_else(|| {
493             fresh_tables.as_ref().map_or(InferTables::Missing, InferTables::InProgress)
494         });
495         global_tcx.enter_local(arena, |tcx| f(InferCtxt {
496             tcx: tcx,
497             tables: tables,
498             projection_cache: RefCell::new(traits::ProjectionCache::new()),
499             type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
500             int_unification_table: RefCell::new(UnificationTable::new()),
501             float_unification_table: RefCell::new(UnificationTable::new()),
502             region_vars: RegionVarBindings::new(tcx),
503             selection_cache: traits::SelectionCache::new(),
504             evaluation_cache: traits::EvaluationCache::new(),
505             reported_trait_errors: RefCell::new(FxHashSet()),
506             tainted_by_errors_flag: Cell::new(false),
507             err_count_on_creation: tcx.sess.err_count(),
508             in_snapshot: Cell::new(false),
509         }))
510     }
511 }
512
513 impl<T> ExpectedFound<T> {
514     pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
515         if a_is_expected {
516             ExpectedFound {expected: a, found: b}
517         } else {
518             ExpectedFound {expected: b, found: a}
519         }
520     }
521 }
522
523 impl<'tcx, T> InferOk<'tcx, T> {
524     pub fn unit(self) -> InferOk<'tcx, ()> {
525         InferOk { value: (), obligations: self.obligations }
526     }
527 }
528
529 #[must_use = "once you start a snapshot, you should always consume it"]
530 pub struct CombinedSnapshot<'a, 'tcx:'a> {
531     projection_cache_snapshot: traits::ProjectionCacheSnapshot,
532     type_snapshot: type_variable::Snapshot,
533     int_snapshot: unify::Snapshot<ty::IntVid>,
534     float_snapshot: unify::Snapshot<ty::FloatVid>,
535     region_vars_snapshot: RegionSnapshot,
536     was_in_snapshot: bool,
537     _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
538 }
539
540 /// Helper trait for shortening the lifetimes inside a
541 /// value for post-type-checking normalization.
542 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
543     fn trans_normalize<'a, 'tcx>(&self,
544                                  infcx: &InferCtxt<'a, 'gcx, 'tcx>,
545                                  param_env: ty::ParamEnv<'tcx>)
546                                  -> Self;
547 }
548
549 macro_rules! items { ($($item:item)+) => ($($item)+) }
550 macro_rules! impl_trans_normalize {
551     ($lt_gcx:tt, $($ty:ty),+) => {
552         items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
553             fn trans_normalize<'a, 'tcx>(&self,
554                                          infcx: &InferCtxt<'a, $lt_gcx, 'tcx>,
555                                          param_env: ty::ParamEnv<'tcx>)
556                                          -> Self {
557                 infcx.normalize_projections_in(param_env, self)
558             }
559         })+);
560     }
561 }
562
563 impl_trans_normalize!('gcx,
564     Ty<'gcx>,
565     &'gcx Substs<'gcx>,
566     ty::FnSig<'gcx>,
567     ty::PolyFnSig<'gcx>,
568     ty::ClosureSubsts<'gcx>,
569     ty::PolyTraitRef<'gcx>,
570     ty::ExistentialTraitRef<'gcx>
571 );
572
573 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
574     fn trans_normalize<'a, 'tcx>(&self,
575                                  infcx: &InferCtxt<'a, 'gcx, 'tcx>,
576                                  param_env: ty::ParamEnv<'tcx>)
577                                  -> Self {
578         match *self {
579             LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx, param_env) },
580             LvalueTy::Downcast { adt_def, substs, variant_index } => {
581                 LvalueTy::Downcast {
582                     adt_def: adt_def,
583                     substs: substs.trans_normalize(infcx, param_env),
584                     variant_index: variant_index
585                 }
586             }
587         }
588     }
589 }
590
591 // NOTE: Callable from trans only!
592 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
593     /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
594     /// each time we erase them in translation, we need to normalize
595     /// the contents.
596     pub fn erase_late_bound_regions_and_normalize<T>(self, value: &ty::Binder<T>)
597         -> T
598         where T: TransNormalize<'tcx>
599     {
600         assert!(!value.needs_subst());
601         let value = self.erase_late_bound_regions(value);
602         self.normalize_associated_type(&value)
603     }
604
605     /// Fully normalizes any associated types in `value`, using an
606     /// empty environment and `Reveal::All` mode (therefore, suitable
607     /// only for monomorphized code during trans, basically).
608     pub fn normalize_associated_type<T>(self, value: &T) -> T
609         where T: TransNormalize<'tcx>
610     {
611         debug!("normalize_associated_type(t={:?})", value);
612
613         let param_env = ty::ParamEnv::empty(Reveal::All);
614         let value = self.erase_regions(value);
615
616         if !value.has_projection_types() {
617             return value;
618         }
619
620         self.infer_ctxt(()).enter(|infcx| {
621             value.trans_normalize(&infcx, param_env)
622         })
623     }
624
625     /// Does a best-effort to normalize any associated types in
626     /// `value`; this includes revealing specializable types, so this
627     /// should be not be used during type-checking, but only during
628     /// optimization and code generation.
629     pub fn normalize_associated_type_in_env<T>(
630         self, value: &T, env: ty::ParamEnv<'tcx>
631     ) -> T
632         where T: TransNormalize<'tcx>
633     {
634         debug!("normalize_associated_type_in_env(t={:?})", value);
635
636         let value = self.erase_regions(value);
637
638         if !value.has_projection_types() {
639             return value;
640         }
641
642         self.infer_ctxt(()).enter(|infcx| {
643             value.trans_normalize(&infcx, env.reveal_all())
644        })
645     }
646 }
647
648 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
649     fn normalize_projections_in<T>(&self, param_env: ty::ParamEnv<'tcx>, value: &T) -> T::Lifted
650         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
651     {
652         let mut selcx = traits::SelectionContext::new(self);
653         let cause = traits::ObligationCause::dummy();
654         let traits::Normalized { value: result, obligations } =
655             traits::normalize(&mut selcx, param_env, cause, value);
656
657         debug!("normalize_projections_in: result={:?} obligations={:?}",
658                 result, obligations);
659
660         let mut fulfill_cx = traits::FulfillmentContext::new();
661
662         for obligation in obligations {
663             fulfill_cx.register_predicate_obligation(self, obligation);
664         }
665
666         self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
667     }
668
669     /// Finishes processes any obligations that remain in the
670     /// fulfillment context, and then returns the result with all type
671     /// variables removed and regions erased. Because this is intended
672     /// for use after type-check has completed, if any errors occur,
673     /// it will panic. It is used during normalization and other cases
674     /// where processing the obligations in `fulfill_cx` may cause
675     /// type inference variables that appear in `result` to be
676     /// unified, and hence we need to process those obligations to get
677     /// the complete picture of the type.
678     pub fn drain_fulfillment_cx_or_panic<T>(&self,
679                                             span: Span,
680                                             fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
681                                             result: &T)
682                                             -> T::Lifted
683         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
684     {
685         debug!("drain_fulfillment_cx_or_panic()");
686
687         // In principle, we only need to do this so long as `result`
688         // contains unbound type parameters. It could be a slight
689         // optimization to stop iterating early.
690         match fulfill_cx.select_all_or_error(self) {
691             Ok(()) => { }
692             Err(errors) => {
693                 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
694                           errors);
695             }
696         }
697
698         let result = self.resolve_type_vars_if_possible(result);
699         let result = self.tcx.erase_regions(&result);
700
701         match self.tcx.lift_to_global(&result) {
702             Some(result) => result,
703             None => {
704                 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
705             }
706         }
707     }
708
709     pub fn is_in_snapshot(&self) -> bool {
710         self.in_snapshot.get()
711     }
712
713     pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
714         t.fold_with(&mut self.freshener())
715     }
716
717     pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
718         match ty.sty {
719             ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
720             _ => false
721         }
722     }
723
724     pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
725         freshen::TypeFreshener::new(self)
726     }
727
728     pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
729         use ty::error::UnconstrainedNumeric::Neither;
730         use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
731         match ty.sty {
732             ty::TyInfer(ty::IntVar(vid)) => {
733                 if self.int_unification_table.borrow_mut().has_value(vid) {
734                     Neither
735                 } else {
736                     UnconstrainedInt
737                 }
738             },
739             ty::TyInfer(ty::FloatVar(vid)) => {
740                 if self.float_unification_table.borrow_mut().has_value(vid) {
741                     Neither
742                 } else {
743                     UnconstrainedFloat
744                 }
745             },
746             _ => Neither,
747         }
748     }
749
750     /// Returns a type variable's default fallback if any exists. A default
751     /// must be attached to the variable when created, if it is created
752     /// without a default, this will return None.
753     ///
754     /// This code does not apply to integral or floating point variables,
755     /// only to use declared defaults.
756     ///
757     /// See `new_ty_var_with_default` to create a type variable with a default.
758     /// See `type_variable::Default` for details about what a default entails.
759     pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
760         match ty.sty {
761             ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
762             _ => None
763         }
764     }
765
766     pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
767         let mut variables = Vec::new();
768
769         let unbound_ty_vars = self.type_variables
770                                   .borrow_mut()
771                                   .unsolved_variables()
772                                   .into_iter()
773                                   .map(|t| self.tcx.mk_var(t));
774
775         let unbound_int_vars = self.int_unification_table
776                                    .borrow_mut()
777                                    .unsolved_variables()
778                                    .into_iter()
779                                    .map(|v| self.tcx.mk_int_var(v));
780
781         let unbound_float_vars = self.float_unification_table
782                                      .borrow_mut()
783                                      .unsolved_variables()
784                                      .into_iter()
785                                      .map(|v| self.tcx.mk_float_var(v));
786
787         variables.extend(unbound_ty_vars);
788         variables.extend(unbound_int_vars);
789         variables.extend(unbound_float_vars);
790
791         return variables;
792     }
793
794     fn combine_fields(&'a self, trace: TypeTrace<'tcx>, param_env: ty::ParamEnv<'tcx>)
795                       -> CombineFields<'a, 'gcx, 'tcx> {
796         CombineFields {
797             infcx: self,
798             trace: trace,
799             cause: None,
800             param_env,
801             obligations: PredicateObligations::new(),
802         }
803     }
804
805     pub fn equate<T>(&'a self,
806                      a_is_expected: bool,
807                      trace: TypeTrace<'tcx>,
808                      param_env: ty::ParamEnv<'tcx>,
809                      a: &T,
810                      b: &T)
811         -> InferResult<'tcx, T>
812         where T: Relate<'tcx>
813     {
814         let mut fields = self.combine_fields(trace, param_env);
815         let result = fields.equate(a_is_expected).relate(a, b);
816         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
817     }
818
819     pub fn sub<T>(&'a self,
820                   a_is_expected: bool,
821                   trace: TypeTrace<'tcx>,
822                   param_env: ty::ParamEnv<'tcx>,
823                   a: &T,
824                   b: &T)
825         -> InferResult<'tcx, T>
826         where T: Relate<'tcx>
827     {
828         let mut fields = self.combine_fields(trace, param_env);
829         let result = fields.sub(a_is_expected).relate(a, b);
830         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
831     }
832
833     pub fn lub<T>(&'a self,
834                   a_is_expected: bool,
835                   trace: TypeTrace<'tcx>,
836                   param_env: ty::ParamEnv<'tcx>,
837                   a: &T,
838                   b: &T)
839         -> InferResult<'tcx, T>
840         where T: Relate<'tcx>
841     {
842         let mut fields = self.combine_fields(trace, param_env);
843         let result = fields.lub(a_is_expected).relate(a, b);
844         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
845     }
846
847     pub fn glb<T>(&'a self,
848                   a_is_expected: bool,
849                   trace: TypeTrace<'tcx>,
850                   param_env: ty::ParamEnv<'tcx>,
851                   a: &T,
852                   b: &T)
853         -> InferResult<'tcx, T>
854         where T: Relate<'tcx>
855     {
856         let mut fields = self.combine_fields(trace, param_env);
857         let result = fields.glb(a_is_expected).relate(a, b);
858         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
859     }
860
861     // Clear the "currently in a snapshot" flag, invoke the closure,
862     // then restore the flag to its original value. This flag is a
863     // debugging measure designed to detect cases where we start a
864     // snapshot, create type variables, and register obligations
865     // which may involve those type variables in the fulfillment cx,
866     // potentially leaving "dangling type variables" behind.
867     // In such cases, an assertion will fail when attempting to
868     // register obligations, within a snapshot. Very useful, much
869     // better than grovelling through megabytes of RUST_LOG output.
870     //
871     // HOWEVER, in some cases the flag is unhelpful. In particular, we
872     // sometimes create a "mini-fulfilment-cx" in which we enroll
873     // obligations. As long as this fulfillment cx is fully drained
874     // before we return, this is not a problem, as there won't be any
875     // escaping obligations in the main cx. In those cases, you can
876     // use this function.
877     pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
878         where F: FnOnce(&Self) -> R
879     {
880         let flag = self.in_snapshot.get();
881         self.in_snapshot.set(false);
882         let result = func(self);
883         self.in_snapshot.set(flag);
884         result
885     }
886
887     fn start_snapshot<'b>(&'b self) -> CombinedSnapshot<'b, 'tcx> {
888         debug!("start_snapshot()");
889
890         let in_snapshot = self.in_snapshot.get();
891         self.in_snapshot.set(true);
892
893         CombinedSnapshot {
894             projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
895             type_snapshot: self.type_variables.borrow_mut().snapshot(),
896             int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
897             float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
898             region_vars_snapshot: self.region_vars.start_snapshot(),
899             was_in_snapshot: in_snapshot,
900             // Borrow tables "in progress" (i.e. during typeck)
901             // to ban writes from within a snapshot to them.
902             _in_progress_tables: match self.tables {
903                 InferTables::InProgress(ref tables) => tables.try_borrow().ok(),
904                 _ => None
905             }
906         }
907     }
908
909     fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
910         debug!("rollback_to(cause={})", cause);
911         let CombinedSnapshot { projection_cache_snapshot,
912                                type_snapshot,
913                                int_snapshot,
914                                float_snapshot,
915                                region_vars_snapshot,
916                                was_in_snapshot,
917                                _in_progress_tables } = snapshot;
918
919         self.in_snapshot.set(was_in_snapshot);
920
921         self.projection_cache
922             .borrow_mut()
923             .rollback_to(projection_cache_snapshot);
924         self.type_variables
925             .borrow_mut()
926             .rollback_to(type_snapshot);
927         self.int_unification_table
928             .borrow_mut()
929             .rollback_to(int_snapshot);
930         self.float_unification_table
931             .borrow_mut()
932             .rollback_to(float_snapshot);
933         self.region_vars
934             .rollback_to(region_vars_snapshot);
935     }
936
937     fn commit_from(&self, snapshot: CombinedSnapshot) {
938         debug!("commit_from()");
939         let CombinedSnapshot { projection_cache_snapshot,
940                                type_snapshot,
941                                int_snapshot,
942                                float_snapshot,
943                                region_vars_snapshot,
944                                was_in_snapshot,
945                                _in_progress_tables } = snapshot;
946
947         self.in_snapshot.set(was_in_snapshot);
948
949         self.projection_cache
950             .borrow_mut()
951             .commit(projection_cache_snapshot);
952         self.type_variables
953             .borrow_mut()
954             .commit(type_snapshot);
955         self.int_unification_table
956             .borrow_mut()
957             .commit(int_snapshot);
958         self.float_unification_table
959             .borrow_mut()
960             .commit(float_snapshot);
961         self.region_vars
962             .commit(region_vars_snapshot);
963     }
964
965     /// Execute `f` and commit the bindings
966     pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
967         F: FnOnce() -> R,
968     {
969         debug!("commit()");
970         let snapshot = self.start_snapshot();
971         let r = f();
972         self.commit_from(snapshot);
973         r
974     }
975
976     /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
977     pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
978         F: FnOnce(&CombinedSnapshot) -> Result<T, E>
979     {
980         debug!("commit_if_ok()");
981         let snapshot = self.start_snapshot();
982         let r = f(&snapshot);
983         debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
984         match r {
985             Ok(_) => { self.commit_from(snapshot); }
986             Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
987         }
988         r
989     }
990
991     // Execute `f` in a snapshot, and commit the bindings it creates
992     pub fn in_snapshot<T, F>(&self, f: F) -> T where
993         F: FnOnce(&CombinedSnapshot) -> T
994     {
995         debug!("in_snapshot()");
996         let snapshot = self.start_snapshot();
997         let r = f(&snapshot);
998         self.commit_from(snapshot);
999         r
1000     }
1001
1002     /// Execute `f` then unroll any bindings it creates
1003     pub fn probe<R, F>(&self, f: F) -> R where
1004         F: FnOnce(&CombinedSnapshot) -> R,
1005     {
1006         debug!("probe()");
1007         let snapshot = self.start_snapshot();
1008         let r = f(&snapshot);
1009         self.rollback_to("probe", snapshot);
1010         r
1011     }
1012
1013     pub fn add_given(&self,
1014                      sub: ty::Region<'tcx>,
1015                      sup: ty::RegionVid)
1016     {
1017         self.region_vars.add_given(sub, sup);
1018     }
1019
1020     pub fn sub_types(&self,
1021                      a_is_expected: bool,
1022                      cause: &ObligationCause<'tcx>,
1023                      param_env: ty::ParamEnv<'tcx>,
1024                      a: Ty<'tcx>,
1025                      b: Ty<'tcx>)
1026                      -> InferResult<'tcx, ()>
1027     {
1028         debug!("sub_types({:?} <: {:?})", a, b);
1029         self.commit_if_ok(|_| {
1030             let trace = TypeTrace::types(cause, a_is_expected, a, b);
1031             self.sub(a_is_expected, trace, param_env, &a, &b).map(|ok| ok.unit())
1032         })
1033     }
1034
1035     pub fn can_sub_types(&self,
1036                          param_env: ty::ParamEnv<'tcx>,
1037                          a: Ty<'tcx>,
1038                          b: Ty<'tcx>)
1039                          -> UnitResult<'tcx>
1040     {
1041         self.probe(|_| {
1042             let origin = &ObligationCause::dummy();
1043             let trace = TypeTrace::types(origin, true, a, b);
1044             self.sub(true, trace, param_env, &a, &b).map(|InferOk { obligations: _, .. }| {
1045                 // Ignore obligations, since we are unrolling
1046                 // everything anyway.
1047             })
1048         })
1049     }
1050
1051     pub fn eq_types(&self,
1052                     a_is_expected: bool,
1053                     cause: &ObligationCause<'tcx>,
1054                     param_env: ty::ParamEnv<'tcx>,
1055                     a: Ty<'tcx>,
1056                     b: Ty<'tcx>)
1057         -> InferResult<'tcx, ()>
1058     {
1059         self.commit_if_ok(|_| {
1060             let trace = TypeTrace::types(cause, a_is_expected, a, b);
1061             self.equate(a_is_expected, trace, param_env, &a, &b).map(|ok| ok.unit())
1062         })
1063     }
1064
1065     pub fn eq_trait_refs(&self,
1066                          a_is_expected: bool,
1067                          cause: &ObligationCause<'tcx>,
1068                          param_env: ty::ParamEnv<'tcx>,
1069                          a: ty::TraitRef<'tcx>,
1070                          b: ty::TraitRef<'tcx>)
1071         -> InferResult<'tcx, ()>
1072     {
1073         debug!("eq_trait_refs({:?} = {:?})", a, b);
1074         self.commit_if_ok(|_| {
1075             let trace = TypeTrace {
1076                 cause: cause.clone(),
1077                 values: TraitRefs(ExpectedFound::new(a_is_expected, a, b))
1078             };
1079             self.equate(a_is_expected, trace, param_env, &a, &b).map(|ok| ok.unit())
1080         })
1081     }
1082
1083     pub fn eq_impl_headers(&self,
1084                            a_is_expected: bool,
1085                            cause: &ObligationCause<'tcx>,
1086                            param_env: ty::ParamEnv<'tcx>,
1087                            a: &ty::ImplHeader<'tcx>,
1088                            b: &ty::ImplHeader<'tcx>)
1089                            -> InferResult<'tcx, ()>
1090     {
1091         debug!("eq_impl_header({:?} = {:?})", a, b);
1092         match (a.trait_ref, b.trait_ref) {
1093             (Some(a_ref), Some(b_ref)) =>
1094                 self.eq_trait_refs(a_is_expected, cause, param_env, a_ref, b_ref),
1095             (None, None) =>
1096                 self.eq_types(a_is_expected, cause, param_env, a.self_ty, b.self_ty),
1097             _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
1098         }
1099     }
1100
1101     pub fn sub_poly_trait_refs(&self,
1102                                a_is_expected: bool,
1103                                cause: ObligationCause<'tcx>,
1104                                param_env: ty::ParamEnv<'tcx>,
1105                                a: ty::PolyTraitRef<'tcx>,
1106                                b: ty::PolyTraitRef<'tcx>)
1107         -> InferResult<'tcx, ()>
1108     {
1109         debug!("sub_poly_trait_refs({:?} <: {:?})", a, b);
1110         self.commit_if_ok(|_| {
1111             let trace = TypeTrace {
1112                 cause: cause,
1113                 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b))
1114             };
1115             self.sub(a_is_expected, trace, param_env, &a, &b).map(|ok| ok.unit())
1116         })
1117     }
1118
1119     pub fn sub_regions(&self,
1120                        origin: SubregionOrigin<'tcx>,
1121                        a: ty::Region<'tcx>,
1122                        b: ty::Region<'tcx>) {
1123         debug!("sub_regions({:?} <: {:?})", a, b);
1124         self.region_vars.make_subregion(origin, a, b);
1125     }
1126
1127     pub fn equality_predicate(&self,
1128                               cause: &ObligationCause<'tcx>,
1129                               param_env: ty::ParamEnv<'tcx>,
1130                               predicate: &ty::PolyEquatePredicate<'tcx>)
1131         -> InferResult<'tcx, ()>
1132     {
1133         self.commit_if_ok(|snapshot| {
1134             let (ty::EquatePredicate(a, b), skol_map) =
1135                 self.skolemize_late_bound_regions(predicate, snapshot);
1136             let cause_span = cause.span;
1137             let eqty_ok = self.eq_types(false, cause, param_env, a, b)?;
1138             self.leak_check(false, cause_span, &skol_map, snapshot)?;
1139             self.pop_skolemized(skol_map, snapshot);
1140             Ok(eqty_ok.unit())
1141         })
1142     }
1143
1144     pub fn subtype_predicate(&self,
1145                              cause: &ObligationCause<'tcx>,
1146                              param_env: ty::ParamEnv<'tcx>,
1147                              predicate: &ty::PolySubtypePredicate<'tcx>)
1148         -> Option<InferResult<'tcx, ()>>
1149     {
1150         // Subtle: it's ok to skip the binder here and resolve because
1151         // `shallow_resolve` just ignores anything that is not a type
1152         // variable, and because type variable's can't (at present, at
1153         // least) capture any of the things bound by this binder.
1154         //
1155         // Really, there is no *particular* reason to do this
1156         // `shallow_resolve` here except as a
1157         // micro-optimization. Naturally I could not
1158         // resist. -nmatsakis
1159         let two_unbound_type_vars = {
1160             let a = self.shallow_resolve(predicate.skip_binder().a);
1161             let b = self.shallow_resolve(predicate.skip_binder().b);
1162             a.is_ty_var() && b.is_ty_var()
1163         };
1164
1165         if two_unbound_type_vars {
1166             // Two unbound type variables? Can't make progress.
1167             return None;
1168         }
1169
1170         Some(self.commit_if_ok(|snapshot| {
1171             let (ty::SubtypePredicate { a_is_expected, a, b}, skol_map) =
1172                 self.skolemize_late_bound_regions(predicate, snapshot);
1173
1174             let cause_span = cause.span;
1175             let ok = self.sub_types(a_is_expected, cause, param_env, a, b)?;
1176             self.leak_check(false, cause_span, &skol_map, snapshot)?;
1177             self.pop_skolemized(skol_map, snapshot);
1178             Ok(ok.unit())
1179         }))
1180     }
1181
1182     pub fn region_outlives_predicate(&self,
1183                                      cause: &traits::ObligationCause<'tcx>,
1184                                      predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1185         -> UnitResult<'tcx>
1186     {
1187         self.commit_if_ok(|snapshot| {
1188             let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1189                 self.skolemize_late_bound_regions(predicate, snapshot);
1190             let origin =
1191                 SubregionOrigin::from_obligation_cause(cause,
1192                                                        || RelateRegionParamBound(cause.span));
1193             self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1194             self.leak_check(false, cause.span, &skol_map, snapshot)?;
1195             Ok(self.pop_skolemized(skol_map, snapshot))
1196         })
1197     }
1198
1199     pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1200         self.type_variables
1201             .borrow_mut()
1202             .new_var(diverging, origin, None)
1203     }
1204
1205     pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1206         self.tcx.mk_var(self.next_ty_var_id(false, origin))
1207     }
1208
1209     pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1210         self.tcx.mk_var(self.next_ty_var_id(true, origin))
1211     }
1212
1213     pub fn next_int_var_id(&self) -> IntVid {
1214         self.int_unification_table
1215             .borrow_mut()
1216             .new_key(None)
1217     }
1218
1219     pub fn next_float_var_id(&self) -> FloatVid {
1220         self.float_unification_table
1221             .borrow_mut()
1222             .new_key(None)
1223     }
1224
1225     pub fn next_region_var(&self, origin: RegionVariableOrigin)
1226                            -> ty::Region<'tcx> {
1227         self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
1228     }
1229
1230     /// Create a region inference variable for the given
1231     /// region parameter definition.
1232     pub fn region_var_for_def(&self,
1233                               span: Span,
1234                               def: &ty::RegionParameterDef)
1235                               -> ty::Region<'tcx> {
1236         self.next_region_var(EarlyBoundRegion(span, def.name, def.issue_32330))
1237     }
1238
1239     /// Create a type inference variable for the given
1240     /// type parameter definition. The substitutions are
1241     /// for actual parameters that may be referred to by
1242     /// the default of this type parameter, if it exists.
1243     /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1244     /// used in a path such as `Foo::<T, U>::new()` will
1245     /// use an inference variable for `C` with `[T, U]`
1246     /// as the substitutions for the default, `(T, U)`.
1247     pub fn type_var_for_def(&self,
1248                             span: Span,
1249                             def: &ty::TypeParameterDef,
1250                             substs: &[Kind<'tcx>])
1251                             -> Ty<'tcx> {
1252         let default = if def.has_default {
1253             let default = self.tcx.type_of(def.def_id);
1254             Some(type_variable::Default {
1255                 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1256                 origin_span: span,
1257                 def_id: def.def_id
1258             })
1259         } else {
1260             None
1261         };
1262
1263
1264         let ty_var_id = self.type_variables
1265                             .borrow_mut()
1266                             .new_var(false,
1267                                      TypeVariableOrigin::TypeParameterDefinition(span, def.name),
1268                                      default);
1269
1270         self.tcx.mk_var(ty_var_id)
1271     }
1272
1273     /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1274     /// type/region parameter to a fresh inference variable.
1275     pub fn fresh_substs_for_item(&self,
1276                                  span: Span,
1277                                  def_id: DefId)
1278                                  -> &'tcx Substs<'tcx> {
1279         Substs::for_item(self.tcx, def_id, |def, _| {
1280             self.region_var_for_def(span, def)
1281         }, |def, substs| {
1282             self.type_var_for_def(span, def, substs)
1283         })
1284     }
1285
1286     pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region<'tcx> {
1287         self.region_vars.new_bound(debruijn)
1288     }
1289
1290     /// True if errors have been reported since this infcx was
1291     /// created.  This is sometimes used as a heuristic to skip
1292     /// reporting errors that often occur as a result of earlier
1293     /// errors, but where it's hard to be 100% sure (e.g., unresolved
1294     /// inference variables, regionck errors).
1295     pub fn is_tainted_by_errors(&self) -> bool {
1296         debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1297                 tainted_by_errors_flag={})",
1298                self.tcx.sess.err_count(),
1299                self.err_count_on_creation,
1300                self.tainted_by_errors_flag.get());
1301
1302         if self.tcx.sess.err_count() > self.err_count_on_creation {
1303             return true; // errors reported since this infcx was made
1304         }
1305         self.tainted_by_errors_flag.get()
1306     }
1307
1308     /// Set the "tainted by errors" flag to true. We call this when we
1309     /// observe an error from a prior pass.
1310     pub fn set_tainted_by_errors(&self) {
1311         debug!("set_tainted_by_errors()");
1312         self.tainted_by_errors_flag.set(true)
1313     }
1314
1315     pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1316         match self.tables.borrow().node_types.get(&id) {
1317             Some(&t) => t,
1318             // FIXME
1319             None if self.is_tainted_by_errors() =>
1320                 self.tcx.types.err,
1321             None => {
1322                 bug!("no type for node {}: {} in fcx",
1323                      id, self.tcx.hir.node_to_string(id));
1324             }
1325         }
1326     }
1327
1328     pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1329         match self.tables.borrow().node_types.get(&ex.id) {
1330             Some(&t) => t,
1331             None => {
1332                 bug!("no type for expr in fcx");
1333             }
1334         }
1335     }
1336
1337     pub fn resolve_regions_and_report_errors(&self,
1338                                              region_context: DefId,
1339                                              region_map: &RegionMaps,
1340                                              free_regions: &FreeRegionMap<'tcx>) {
1341         let region_rels = RegionRelations::new(self.tcx,
1342                                                region_context,
1343                                                region_map,
1344                                                free_regions);
1345         let errors = self.region_vars.resolve_regions(&region_rels);
1346         if !self.is_tainted_by_errors() {
1347             // As a heuristic, just skip reporting region errors
1348             // altogether if other errors have been reported while
1349             // this infcx was in use.  This is totally hokey but
1350             // otherwise we have a hard time separating legit region
1351             // errors from silly ones.
1352             self.report_region_errors(&errors); // see error_reporting module
1353         }
1354     }
1355
1356     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1357         self.resolve_type_vars_if_possible(&t).to_string()
1358     }
1359
1360     pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1361         let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1362         format!("({})", tstrs.join(", "))
1363     }
1364
1365     pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1366         self.resolve_type_vars_if_possible(t).to_string()
1367     }
1368
1369     pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1370         match typ.sty {
1371             ty::TyInfer(ty::TyVar(v)) => {
1372                 // Not entirely obvious: if `typ` is a type variable,
1373                 // it can be resolved to an int/float variable, which
1374                 // can then be recursively resolved, hence the
1375                 // recursion. Note though that we prevent type
1376                 // variables from unifying to other type variables
1377                 // directly (though they may be embedded
1378                 // structurally), and we prevent cycles in any case,
1379                 // so this recursion should always be of very limited
1380                 // depth.
1381                 self.type_variables.borrow_mut()
1382                     .probe(v)
1383                     .map(|t| self.shallow_resolve(t))
1384                     .unwrap_or(typ)
1385             }
1386
1387             ty::TyInfer(ty::IntVar(v)) => {
1388                 self.int_unification_table
1389                     .borrow_mut()
1390                     .probe(v)
1391                     .map(|v| v.to_type(self.tcx))
1392                     .unwrap_or(typ)
1393             }
1394
1395             ty::TyInfer(ty::FloatVar(v)) => {
1396                 self.float_unification_table
1397                     .borrow_mut()
1398                     .probe(v)
1399                     .map(|v| v.to_type(self.tcx))
1400                     .unwrap_or(typ)
1401             }
1402
1403             _ => {
1404                 typ
1405             }
1406         }
1407     }
1408
1409     pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1410         where T: TypeFoldable<'tcx>
1411     {
1412         /*!
1413          * Where possible, replaces type/int/float variables in
1414          * `value` with their final value. Note that region variables
1415          * are unaffected. If a type variable has not been unified, it
1416          * is left as is.  This is an idempotent operation that does
1417          * not affect inference state in any way and so you can do it
1418          * at will.
1419          */
1420
1421         if !value.needs_infer() {
1422             return value.clone(); // avoid duplicated subst-folding
1423         }
1424         let mut r = resolve::OpportunisticTypeResolver::new(self);
1425         value.fold_with(&mut r)
1426     }
1427
1428     pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1429         where T: TypeFoldable<'tcx>
1430     {
1431         let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1432         value.fold_with(&mut r)
1433     }
1434
1435     /// Resolves all type variables in `t` and then, if any were left
1436     /// unresolved, substitutes an error type. This is used after the
1437     /// main checking when doing a second pass before writeback. The
1438     /// justification is that writeback will produce an error for
1439     /// these unconstrained type variables.
1440     fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1441         let ty = self.resolve_type_vars_if_possible(t);
1442         if ty.references_error() || ty.is_ty_var() {
1443             debug!("resolve_type_vars_or_error: error from {:?}", ty);
1444             Err(())
1445         } else {
1446             Ok(ty)
1447         }
1448     }
1449
1450     pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1451         /*!
1452          * Attempts to resolve all type/region variables in
1453          * `value`. Region inference must have been run already (e.g.,
1454          * by calling `resolve_regions_and_report_errors`).  If some
1455          * variable was never unified, an `Err` results.
1456          *
1457          * This method is idempotent, but it not typically not invoked
1458          * except during the writeback phase.
1459          */
1460
1461         resolve::fully_resolve(self, value)
1462     }
1463
1464     // [Note-Type-error-reporting]
1465     // An invariant is that anytime the expected or actual type is TyError (the special
1466     // error type, meaning that an error occurred when typechecking this expression),
1467     // this is a derived error. The error cascaded from another error (that was already
1468     // reported), so it's not useful to display it to the user.
1469     // The following methods implement this logic.
1470     // They check if either the actual or expected type is TyError, and don't print the error
1471     // in this case. The typechecker should only ever report type errors involving mismatched
1472     // types using one of these methods, and should not call span_err directly for such
1473     // errors.
1474
1475     pub fn type_error_message<M>(&self,
1476                                  sp: Span,
1477                                  mk_msg: M,
1478                                  actual_ty: Ty<'tcx>)
1479         where M: FnOnce(String) -> String,
1480     {
1481         self.type_error_struct(sp, mk_msg, actual_ty).emit();
1482     }
1483
1484     // FIXME: this results in errors without an error code. Deprecate?
1485     pub fn type_error_struct<M>(&self,
1486                                 sp: Span,
1487                                 mk_msg: M,
1488                                 actual_ty: Ty<'tcx>)
1489                                 -> DiagnosticBuilder<'tcx>
1490         where M: FnOnce(String) -> String,
1491     {
1492         self.type_error_struct_with_diag(sp, |actual_ty| {
1493             self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1494         }, actual_ty)
1495     }
1496
1497     pub fn type_error_struct_with_diag<M>(&self,
1498                                           sp: Span,
1499                                           mk_diag: M,
1500                                           actual_ty: Ty<'tcx>)
1501                                           -> DiagnosticBuilder<'tcx>
1502         where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1503     {
1504         let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1505         debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1506
1507         // Don't report an error if actual type is TyError.
1508         if actual_ty.references_error() {
1509             return self.tcx.sess.diagnostic().struct_dummy();
1510         }
1511
1512         mk_diag(self.ty_to_string(actual_ty))
1513     }
1514
1515     pub fn report_mismatched_types(&self,
1516                                    cause: &ObligationCause<'tcx>,
1517                                    expected: Ty<'tcx>,
1518                                    actual: Ty<'tcx>,
1519                                    err: TypeError<'tcx>)
1520                                    -> DiagnosticBuilder<'tcx> {
1521         let trace = TypeTrace::types(cause, true, expected, actual);
1522         self.report_and_explain_type_error(trace, &err)
1523     }
1524
1525     pub fn report_conflicting_default_types(&self,
1526                                             span: Span,
1527                                             body_id: ast::NodeId,
1528                                             expected: type_variable::Default<'tcx>,
1529                                             actual: type_variable::Default<'tcx>) {
1530         let trace = TypeTrace {
1531             cause: ObligationCause::misc(span, body_id),
1532             values: Types(ExpectedFound {
1533                 expected: expected.ty,
1534                 found: actual.ty
1535             })
1536         };
1537
1538         self.report_and_explain_type_error(
1539             trace,
1540             &TypeError::TyParamDefaultMismatch(ExpectedFound {
1541                 expected: expected,
1542                 found: actual
1543             }))
1544             .emit();
1545     }
1546
1547     pub fn replace_late_bound_regions_with_fresh_var<T>(
1548         &self,
1549         span: Span,
1550         lbrct: LateBoundRegionConversionTime,
1551         value: &ty::Binder<T>)
1552         -> (T, FxHashMap<ty::BoundRegion, ty::Region<'tcx>>)
1553         where T : TypeFoldable<'tcx>
1554     {
1555         self.tcx.replace_late_bound_regions(
1556             value,
1557             |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1558     }
1559
1560     /// Given a higher-ranked projection predicate like:
1561     ///
1562     ///     for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1563     ///
1564     /// and a target trait-ref like:
1565     ///
1566     ///     <T as Fn<&'x u32>>
1567     ///
1568     /// find a substitution `S` for the higher-ranked regions (here,
1569     /// `['a => 'x]`) such that the predicate matches the trait-ref,
1570     /// and then return the value (here, `&'a u32`) but with the
1571     /// substitution applied (hence, `&'x u32`).
1572     ///
1573     /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1574     /// details.
1575     pub fn match_poly_projection_predicate(&self,
1576                                            cause: ObligationCause<'tcx>,
1577                                            param_env: ty::ParamEnv<'tcx>,
1578                                            match_a: ty::PolyProjectionPredicate<'tcx>,
1579                                            match_b: ty::TraitRef<'tcx>)
1580                                            -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1581     {
1582         let span = cause.span;
1583         let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1584         let trace = TypeTrace {
1585             cause: cause,
1586             values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1587         };
1588
1589         let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1590         let mut combine = self.combine_fields(trace, param_env);
1591         let result = combine.higher_ranked_match(span, &match_pair, &match_b, true)?;
1592         Ok(InferOk { value: result, obligations: combine.obligations })
1593     }
1594
1595     /// See `verify_generic_bound` method in `region_inference`
1596     pub fn verify_generic_bound(&self,
1597                                 origin: SubregionOrigin<'tcx>,
1598                                 kind: GenericKind<'tcx>,
1599                                 a: ty::Region<'tcx>,
1600                                 bound: VerifyBound<'tcx>) {
1601         debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1602                kind,
1603                a,
1604                bound);
1605
1606         self.region_vars.verify_generic_bound(origin, kind, a, bound);
1607     }
1608
1609     pub fn can_equate<T>(&self, param_env: ty::ParamEnv<'tcx>, a: &T, b: &T) -> UnitResult<'tcx>
1610         where T: Relate<'tcx> + fmt::Debug
1611     {
1612         debug!("can_equate({:?}, {:?})", a, b);
1613         self.probe(|_| {
1614             // Gin up a dummy trace, since this won't be committed
1615             // anyhow. We should make this typetrace stuff more
1616             // generic so we don't have to do anything quite this
1617             // terrible.
1618             let trace = TypeTrace::dummy(self.tcx);
1619             self.equate(true, trace, param_env, a, b).map(|InferOk { obligations: _, .. }| {
1620                 // We can intentionally ignore obligations here, since
1621                 // this is part of a simple test for general
1622                 // "equatability". However, it's not entirely clear
1623                 // that we *ought* to be, perhaps a better thing would
1624                 // be to use a mini-fulfillment context or something
1625                 // like that.
1626             })
1627         })
1628     }
1629
1630     pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1631         let ty = self.node_type(id);
1632         self.resolve_type_vars_or_error(&ty)
1633     }
1634
1635     pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1636         let ty = self.tables.borrow().expr_ty_adjusted(expr);
1637         self.resolve_type_vars_or_error(&ty)
1638     }
1639
1640     pub fn type_moves_by_default(&self,
1641                                  param_env: ty::ParamEnv<'tcx>,
1642                                  ty: Ty<'tcx>,
1643                                  span: Span)
1644                                  -> bool {
1645         let ty = self.resolve_type_vars_if_possible(&ty);
1646         if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1647             // Even if the type may have no inference variables, during
1648             // type-checking closure types are in local tables only.
1649             let local_closures = match self.tables {
1650                 InferTables::InProgress(_) => ty.has_closure_types(),
1651                 _ => false
1652             };
1653             if !local_closures {
1654                 return ty.moves_by_default(self.tcx.global_tcx(), param_env, span);
1655             }
1656         }
1657
1658         let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1659
1660         // this can get called from typeck (by euv), and moves_by_default
1661         // rightly refuses to work with inference variables, but
1662         // moves_by_default has a cache, which we want to use in other
1663         // cases.
1664         !traits::type_known_to_meet_bound(self, param_env, ty, copy_def_id, span)
1665     }
1666
1667     pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
1668         self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1669     }
1670
1671     pub fn closure_kind(&self,
1672                         def_id: DefId)
1673                         -> Option<ty::ClosureKind>
1674     {
1675         if let InferTables::InProgress(tables) = self.tables {
1676             if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1677                 return tables.borrow()
1678                              .closure_kinds
1679                              .get(&id)
1680                              .cloned()
1681                              .map(|(kind, _)| kind);
1682             }
1683         }
1684
1685         // During typeck, ALL closures are local. But afterwards,
1686         // during trans, we see closure ids from other traits.
1687         // That may require loading the closure data out of the
1688         // cstore.
1689         Some(self.tcx.closure_kind(def_id))
1690     }
1691
1692     pub fn closure_type(&self, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1693         if let InferTables::InProgress(tables) = self.tables {
1694             if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1695                 if let Some(&ty) = tables.borrow().closure_tys.get(&id) {
1696                     return ty;
1697                 }
1698             }
1699         }
1700
1701         self.tcx.closure_type(def_id)
1702     }
1703 }
1704
1705 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1706     pub fn span(&self) -> Span {
1707         self.cause.span
1708     }
1709
1710     pub fn types(cause: &ObligationCause<'tcx>,
1711                  a_is_expected: bool,
1712                  a: Ty<'tcx>,
1713                  b: Ty<'tcx>)
1714                  -> TypeTrace<'tcx> {
1715         TypeTrace {
1716             cause: cause.clone(),
1717             values: Types(ExpectedFound::new(a_is_expected, a, b))
1718         }
1719     }
1720
1721     pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1722         TypeTrace {
1723             cause: ObligationCause::dummy(),
1724             values: Types(ExpectedFound {
1725                 expected: tcx.types.err,
1726                 found: tcx.types.err,
1727             })
1728         }
1729     }
1730 }
1731
1732 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1733     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1734         write!(f, "TypeTrace({:?})", self.cause)
1735     }
1736 }
1737
1738 impl<'tcx> SubregionOrigin<'tcx> {
1739     pub fn span(&self) -> Span {
1740         match *self {
1741             Subtype(ref a) => a.span(),
1742             InfStackClosure(a) => a,
1743             InvokeClosure(a) => a,
1744             DerefPointer(a) => a,
1745             FreeVariable(a, _) => a,
1746             IndexSlice(a) => a,
1747             RelateObjectBound(a) => a,
1748             RelateParamBound(a, _) => a,
1749             RelateRegionParamBound(a) => a,
1750             RelateDefaultParamBound(a, _) => a,
1751             Reborrow(a) => a,
1752             ReborrowUpvar(a, _) => a,
1753             DataBorrowed(_, a) => a,
1754             ReferenceOutlivesReferent(_, a) => a,
1755             ParameterInScope(_, a) => a,
1756             ExprTypeIsNotInScope(_, a) => a,
1757             BindingTypeIsNotValidAtDecl(a) => a,
1758             CallRcvr(a) => a,
1759             CallArg(a) => a,
1760             CallReturn(a) => a,
1761             Operand(a) => a,
1762             AddrOf(a) => a,
1763             AutoBorrow(a) => a,
1764             SafeDestructor(a) => a,
1765             CompareImplMethodObligation { span, .. } => span,
1766         }
1767     }
1768
1769     pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>,
1770                                     default: F)
1771                                     -> Self
1772         where F: FnOnce() -> Self
1773     {
1774         match cause.code {
1775             traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
1776                 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span),
1777
1778             traits::ObligationCauseCode::CompareImplMethodObligation { item_name,
1779                                                                        impl_item_def_id,
1780                                                                        trait_item_def_id,
1781                                                                        lint_id } =>
1782                 SubregionOrigin::CompareImplMethodObligation {
1783                     span: cause.span,
1784                     item_name: item_name,
1785                     impl_item_def_id: impl_item_def_id,
1786                     trait_item_def_id: trait_item_def_id,
1787                     lint_id: lint_id,
1788                 },
1789
1790             _ => default(),
1791         }
1792     }
1793 }
1794
1795 impl RegionVariableOrigin {
1796     pub fn span(&self) -> Span {
1797         match *self {
1798             MiscVariable(a) => a,
1799             PatternRegion(a) => a,
1800             AddrOfRegion(a) => a,
1801             Autoref(a) => a,
1802             Coercion(a) => a,
1803             EarlyBoundRegion(a, ..) => a,
1804             LateBoundRegion(a, ..) => a,
1805             BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1806             UpvarRegion(_, a) => a
1807         }
1808     }
1809 }
1810
1811 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1812     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1813         match *self {
1814             ValuePairs::Types(ref ef) => {
1815                 ValuePairs::Types(ef.fold_with(folder))
1816             }
1817             ValuePairs::TraitRefs(ref ef) => {
1818                 ValuePairs::TraitRefs(ef.fold_with(folder))
1819             }
1820             ValuePairs::PolyTraitRefs(ref ef) => {
1821                 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1822             }
1823         }
1824     }
1825
1826     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1827         match *self {
1828             ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1829             ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1830             ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1831         }
1832     }
1833 }
1834
1835 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1836     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1837         TypeTrace {
1838             cause: self.cause.fold_with(folder),
1839             values: self.values.fold_with(folder)
1840         }
1841     }
1842
1843     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1844         self.cause.visit_with(visitor) || self.values.visit_with(visitor)
1845     }
1846 }