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