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