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