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