]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/mod.rs
remove `normalize_infer_ctxt` constructor
[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     /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
472     /// for MemCategorizationContext/ExprUseVisitor.
473     /// If any inference functionality is used, ICEs will occur.
474     pub fn borrowck_fake_infer_ctxt(self, param_env: ty::ParameterEnvironment<'gcx>)
475                                     -> InferCtxt<'a, 'gcx, 'gcx> {
476         InferCtxt {
477             tcx: self,
478             tables: InferTables::Global(&self.tables),
479             type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
480             int_unification_table: RefCell::new(UnificationTable::new()),
481             float_unification_table: RefCell::new(UnificationTable::new()),
482             region_vars: RegionVarBindings::new(self),
483             parameter_environment: param_env,
484             selection_cache: traits::SelectionCache::new(),
485             evaluation_cache: traits::EvaluationCache::new(),
486             projection_cache: RefCell::new(traits::ProjectionCache::new()),
487             reported_trait_errors: RefCell::new(FnvHashSet()),
488             projection_mode: Reveal::NotSpecializable,
489             tainted_by_errors_flag: Cell::new(false),
490             err_count_on_creation: self.sess.err_count(),
491             obligations_in_snapshot: Cell::new(false),
492         }
493     }
494 }
495
496 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
497     pub fn enter<F, R>(&'tcx mut self, f: F) -> R
498         where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
499     {
500         let InferCtxtBuilder {
501             global_tcx,
502             ref arenas,
503             ref tables,
504             ref mut param_env,
505             projection_mode,
506         } = *self;
507         let tables = if let Some(ref tables) = *tables {
508             InferTables::Local(tables)
509         } else {
510             InferTables::Global(&global_tcx.tables)
511         };
512         let param_env = param_env.take().unwrap_or_else(|| {
513             global_tcx.empty_parameter_environment()
514         });
515         global_tcx.enter_local(arenas, |tcx| f(InferCtxt {
516             tcx: tcx,
517             tables: tables,
518             projection_cache: RefCell::new(traits::ProjectionCache::new()),
519             type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
520             int_unification_table: RefCell::new(UnificationTable::new()),
521             float_unification_table: RefCell::new(UnificationTable::new()),
522             region_vars: RegionVarBindings::new(tcx),
523             parameter_environment: param_env,
524             selection_cache: traits::SelectionCache::new(),
525             evaluation_cache: traits::EvaluationCache::new(),
526             reported_trait_errors: RefCell::new(FnvHashSet()),
527             projection_mode: projection_mode,
528             tainted_by_errors_flag: Cell::new(false),
529             err_count_on_creation: tcx.sess.err_count(),
530             obligations_in_snapshot: Cell::new(false),
531         }))
532     }
533 }
534
535 impl<T> ExpectedFound<T> {
536     fn new(a_is_expected: bool, a: T, b: T) -> Self {
537         if a_is_expected {
538             ExpectedFound {expected: a, found: b}
539         } else {
540             ExpectedFound {expected: b, found: a}
541         }
542     }
543 }
544
545 impl<'tcx, T> InferOk<'tcx, T> {
546     pub fn unit(self) -> InferOk<'tcx, ()> {
547         InferOk { value: (), obligations: self.obligations }
548     }
549 }
550
551 #[must_use = "once you start a snapshot, you should always consume it"]
552 pub struct CombinedSnapshot {
553     projection_cache_snapshot: traits::ProjectionCacheSnapshot,
554     type_snapshot: type_variable::Snapshot,
555     int_snapshot: unify::Snapshot<ty::IntVid>,
556     float_snapshot: unify::Snapshot<ty::FloatVid>,
557     region_vars_snapshot: RegionSnapshot,
558     obligations_in_snapshot: bool,
559 }
560
561 /// Helper trait for shortening the lifetimes inside a
562 /// value for post-type-checking normalization.
563 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
564     fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self;
565 }
566
567 macro_rules! items { ($($item:item)+) => ($($item)+) }
568 macro_rules! impl_trans_normalize {
569     ($lt_gcx:tt, $($ty:ty),+) => {
570         items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
571             fn trans_normalize<'a, 'tcx>(&self,
572                                          infcx: &InferCtxt<'a, $lt_gcx, 'tcx>)
573                                          -> Self {
574                 infcx.normalize_projections_in(self)
575             }
576         })+);
577     }
578 }
579
580 impl_trans_normalize!('gcx,
581     Ty<'gcx>,
582     &'gcx Substs<'gcx>,
583     ty::FnSig<'gcx>,
584     &'gcx ty::BareFnTy<'gcx>,
585     ty::ClosureSubsts<'gcx>,
586     ty::PolyTraitRef<'gcx>
587 );
588
589 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
590     fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self {
591         match *self {
592             LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx) },
593             LvalueTy::Downcast { adt_def, substs, variant_index } => {
594                 LvalueTy::Downcast {
595                     adt_def: adt_def,
596                     substs: substs.trans_normalize(infcx),
597                     variant_index: variant_index
598                 }
599             }
600         }
601     }
602 }
603
604 // NOTE: Callable from trans only!
605 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
606     pub fn normalize_associated_type<T>(self, value: &T) -> T
607         where T: TransNormalize<'tcx>
608     {
609         debug!("normalize_associated_type(t={:?})", value);
610
611         let value = self.erase_regions(value);
612
613         if !value.has_projection_types() {
614             return value;
615         }
616
617         self.infer_ctxt(None, None, Reveal::All).enter(|infcx| {
618             value.trans_normalize(&infcx)
619         })
620     }
621
622     pub fn normalize_associated_type_in_env<T>(
623         self, value: &T, env: &'a ty::ParameterEnvironment<'tcx>
624     ) -> T
625         where T: TransNormalize<'tcx>
626     {
627         debug!("normalize_associated_type_in_env(t={:?})", value);
628
629         let value = self.erase_regions(value);
630
631         if !value.has_projection_types() {
632             return value;
633         }
634
635         self.infer_ctxt(None, Some(env.clone()), Reveal::All).enter(|infcx| {
636             value.trans_normalize(&infcx)
637        })
638     }
639 }
640
641 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
642     fn normalize_projections_in<T>(&self, value: &T) -> T::Lifted
643         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
644     {
645         let mut selcx = traits::SelectionContext::new(self);
646         let cause = traits::ObligationCause::dummy();
647         let traits::Normalized { value: result, obligations } =
648             traits::normalize(&mut selcx, cause, value);
649
650         debug!("normalize_projections_in: result={:?} obligations={:?}",
651                 result, obligations);
652
653         let mut fulfill_cx = traits::FulfillmentContext::new();
654
655         for obligation in obligations {
656             fulfill_cx.register_predicate_obligation(self, obligation);
657         }
658
659         self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
660     }
661
662     /// Finishes processes any obligations that remain in the
663     /// fulfillment context, and then returns the result with all type
664     /// variables removed and regions erased. Because this is intended
665     /// for use after type-check has completed, if any errors occur,
666     /// it will panic. It is used during normalization and other cases
667     /// where processing the obligations in `fulfill_cx` may cause
668     /// type inference variables that appear in `result` to be
669     /// unified, and hence we need to process those obligations to get
670     /// the complete picture of the type.
671     pub fn drain_fulfillment_cx_or_panic<T>(&self,
672                                             span: Span,
673                                             fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
674                                             result: &T)
675                                             -> T::Lifted
676         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
677     {
678         debug!("drain_fulfillment_cx_or_panic()");
679
680         // In principle, we only need to do this so long as `result`
681         // contains unbound type parameters. It could be a slight
682         // optimization to stop iterating early.
683         match fulfill_cx.select_all_or_error(self) {
684             Ok(()) => { }
685             Err(errors) => {
686                 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
687                           errors);
688             }
689         }
690
691         let result = self.resolve_type_vars_if_possible(result);
692         let result = self.tcx.erase_regions(&result);
693
694         match self.tcx.lift_to_global(&result) {
695             Some(result) => result,
696             None => {
697                 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
698             }
699         }
700     }
701
702     pub fn projection_mode(&self) -> Reveal {
703         self.projection_mode
704     }
705
706     pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
707         t.fold_with(&mut self.freshener())
708     }
709
710     pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
711         match ty.sty {
712             ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
713             _ => false
714         }
715     }
716
717     pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
718         freshen::TypeFreshener::new(self)
719     }
720
721     pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
722         use ty::error::UnconstrainedNumeric::Neither;
723         use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
724         match ty.sty {
725             ty::TyInfer(ty::IntVar(vid)) => {
726                 if self.int_unification_table.borrow_mut().has_value(vid) {
727                     Neither
728                 } else {
729                     UnconstrainedInt
730                 }
731             },
732             ty::TyInfer(ty::FloatVar(vid)) => {
733                 if self.float_unification_table.borrow_mut().has_value(vid) {
734                     Neither
735                 } else {
736                     UnconstrainedFloat
737                 }
738             },
739             _ => Neither,
740         }
741     }
742
743     /// Returns a type variable's default fallback if any exists. A default
744     /// must be attached to the variable when created, if it is created
745     /// without a default, this will return None.
746     ///
747     /// This code does not apply to integral or floating point variables,
748     /// only to use declared defaults.
749     ///
750     /// See `new_ty_var_with_default` to create a type variable with a default.
751     /// See `type_variable::Default` for details about what a default entails.
752     pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
753         match ty.sty {
754             ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
755             _ => None
756         }
757     }
758
759     pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
760         let mut variables = Vec::new();
761
762         let unbound_ty_vars = self.type_variables
763                                   .borrow_mut()
764                                   .unsolved_variables()
765                                   .into_iter()
766                                   .map(|t| self.tcx.mk_var(t));
767
768         let unbound_int_vars = self.int_unification_table
769                                    .borrow_mut()
770                                    .unsolved_variables()
771                                    .into_iter()
772                                    .map(|v| self.tcx.mk_int_var(v));
773
774         let unbound_float_vars = self.float_unification_table
775                                      .borrow_mut()
776                                      .unsolved_variables()
777                                      .into_iter()
778                                      .map(|v| self.tcx.mk_float_var(v));
779
780         variables.extend(unbound_ty_vars);
781         variables.extend(unbound_int_vars);
782         variables.extend(unbound_float_vars);
783
784         return variables;
785     }
786
787     fn combine_fields(&'a self, trace: TypeTrace<'tcx>)
788                       -> CombineFields<'a, 'gcx, 'tcx> {
789         CombineFields {
790             infcx: self,
791             trace: trace,
792             cause: None,
793             obligations: PredicateObligations::new(),
794         }
795     }
796
797     pub fn equate<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
798         -> InferResult<'tcx, T>
799         where T: Relate<'tcx>
800     {
801         let mut fields = self.combine_fields(trace);
802         let result = fields.equate(a_is_expected).relate(a, b);
803         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
804     }
805
806     pub fn sub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
807         -> InferResult<'tcx, T>
808         where T: Relate<'tcx>
809     {
810         let mut fields = self.combine_fields(trace);
811         let result = fields.sub(a_is_expected).relate(a, b);
812         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
813     }
814
815     pub fn lub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
816         -> InferResult<'tcx, T>
817         where T: Relate<'tcx>
818     {
819         let mut fields = self.combine_fields(trace);
820         let result = fields.lub(a_is_expected).relate(a, b);
821         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
822     }
823
824     pub fn glb<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
825         -> InferResult<'tcx, T>
826         where T: Relate<'tcx>
827     {
828         let mut fields = self.combine_fields(trace);
829         let result = fields.glb(a_is_expected).relate(a, b);
830         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
831     }
832
833     fn start_snapshot(&self) -> CombinedSnapshot {
834         debug!("start_snapshot()");
835
836         let obligations_in_snapshot = self.obligations_in_snapshot.get();
837         self.obligations_in_snapshot.set(false);
838
839         CombinedSnapshot {
840             projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
841             type_snapshot: self.type_variables.borrow_mut().snapshot(),
842             int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
843             float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
844             region_vars_snapshot: self.region_vars.start_snapshot(),
845             obligations_in_snapshot: obligations_in_snapshot,
846         }
847     }
848
849     fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
850         debug!("rollback_to(cause={})", cause);
851         let CombinedSnapshot { projection_cache_snapshot,
852                                type_snapshot,
853                                int_snapshot,
854                                float_snapshot,
855                                region_vars_snapshot,
856                                obligations_in_snapshot } = snapshot;
857
858         assert!(!self.obligations_in_snapshot.get());
859         self.obligations_in_snapshot.set(obligations_in_snapshot);
860
861         self.projection_cache
862             .borrow_mut()
863             .rollback_to(projection_cache_snapshot);
864         self.type_variables
865             .borrow_mut()
866             .rollback_to(type_snapshot);
867         self.int_unification_table
868             .borrow_mut()
869             .rollback_to(int_snapshot);
870         self.float_unification_table
871             .borrow_mut()
872             .rollback_to(float_snapshot);
873         self.region_vars
874             .rollback_to(region_vars_snapshot);
875     }
876
877     fn commit_from(&self, snapshot: CombinedSnapshot) {
878         debug!("commit_from()");
879         let CombinedSnapshot { projection_cache_snapshot,
880                                type_snapshot,
881                                int_snapshot,
882                                float_snapshot,
883                                region_vars_snapshot,
884                                obligations_in_snapshot } = snapshot;
885
886         self.obligations_in_snapshot.set(obligations_in_snapshot);
887
888         self.projection_cache
889             .borrow_mut()
890             .commit(projection_cache_snapshot);
891         self.type_variables
892             .borrow_mut()
893             .commit(type_snapshot);
894         self.int_unification_table
895             .borrow_mut()
896             .commit(int_snapshot);
897         self.float_unification_table
898             .borrow_mut()
899             .commit(float_snapshot);
900         self.region_vars
901             .commit(region_vars_snapshot);
902     }
903
904     /// Execute `f` and commit the bindings
905     pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
906         F: FnOnce() -> R,
907     {
908         debug!("commit()");
909         let snapshot = self.start_snapshot();
910         let r = f();
911         self.commit_from(snapshot);
912         r
913     }
914
915     /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
916     pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
917         F: FnOnce(&CombinedSnapshot) -> Result<T, E>
918     {
919         debug!("commit_if_ok()");
920         let snapshot = self.start_snapshot();
921         let r = f(&snapshot);
922         debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
923         match r {
924             Ok(_) => { self.commit_from(snapshot); }
925             Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
926         }
927         r
928     }
929
930     // Execute `f` in a snapshot, and commit the bindings it creates
931     pub fn in_snapshot<T, F>(&self, f: F) -> T where
932         F: FnOnce(&CombinedSnapshot) -> T
933     {
934         debug!("in_snapshot()");
935         let snapshot = self.start_snapshot();
936         let r = f(&snapshot);
937         self.commit_from(snapshot);
938         r
939     }
940
941     /// Execute `f` and commit only the region bindings if successful.
942     /// The function f must be very careful not to leak any non-region
943     /// variables that get created.
944     pub fn commit_regions_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
945         F: FnOnce() -> Result<T, E>
946     {
947         debug!("commit_regions_if_ok()");
948         let CombinedSnapshot { projection_cache_snapshot,
949                                type_snapshot,
950                                int_snapshot,
951                                float_snapshot,
952                                region_vars_snapshot,
953                                obligations_in_snapshot } = self.start_snapshot();
954
955         let r = self.commit_if_ok(|_| f());
956
957         debug!("commit_regions_if_ok: rolling back everything but regions");
958
959         assert!(!self.obligations_in_snapshot.get());
960         self.obligations_in_snapshot.set(obligations_in_snapshot);
961
962         // Roll back any non-region bindings - they should be resolved
963         // inside `f`, with, e.g. `resolve_type_vars_if_possible`.
964         self.projection_cache
965             .borrow_mut()
966             .rollback_to(projection_cache_snapshot);
967         self.type_variables
968             .borrow_mut()
969             .rollback_to(type_snapshot);
970         self.int_unification_table
971             .borrow_mut()
972             .rollback_to(int_snapshot);
973         self.float_unification_table
974             .borrow_mut()
975             .rollback_to(float_snapshot);
976
977         // Commit region vars that may escape through resolved types.
978         self.region_vars
979             .commit(region_vars_snapshot);
980
981         r
982     }
983
984     /// Execute `f` then unroll any bindings it creates
985     pub fn probe<R, F>(&self, f: F) -> R where
986         F: FnOnce(&CombinedSnapshot) -> R,
987     {
988         debug!("probe()");
989         let snapshot = self.start_snapshot();
990         let r = f(&snapshot);
991         self.rollback_to("probe", snapshot);
992         r
993     }
994
995     pub fn add_given(&self,
996                      sub: ty::FreeRegion,
997                      sup: ty::RegionVid)
998     {
999         self.region_vars.add_given(sub, sup);
1000     }
1001
1002     pub fn sub_types(&self,
1003                      a_is_expected: bool,
1004                      origin: TypeOrigin,
1005                      a: Ty<'tcx>,
1006                      b: Ty<'tcx>)
1007         -> InferResult<'tcx, ()>
1008     {
1009         debug!("sub_types({:?} <: {:?})", a, b);
1010         self.commit_if_ok(|_| {
1011             let trace = TypeTrace::types(origin, a_is_expected, a, b);
1012             self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1013         })
1014     }
1015
1016     pub fn can_sub_types(&self,
1017                          a: Ty<'tcx>,
1018                          b: Ty<'tcx>)
1019                          -> UnitResult<'tcx>
1020     {
1021         self.probe(|_| {
1022             let origin = TypeOrigin::Misc(syntax_pos::DUMMY_SP);
1023             let trace = TypeTrace::types(origin, true, a, b);
1024             self.sub(true, trace, &a, &b).map(|_| ())
1025         })
1026     }
1027
1028     pub fn eq_types(&self,
1029                     a_is_expected: bool,
1030                     origin: TypeOrigin,
1031                     a: Ty<'tcx>,
1032                     b: Ty<'tcx>)
1033         -> InferResult<'tcx, ()>
1034     {
1035         self.commit_if_ok(|_| {
1036             let trace = TypeTrace::types(origin, a_is_expected, a, b);
1037             self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1038         })
1039     }
1040
1041     pub fn eq_trait_refs(&self,
1042                           a_is_expected: bool,
1043                           origin: TypeOrigin,
1044                           a: ty::TraitRef<'tcx>,
1045                           b: ty::TraitRef<'tcx>)
1046         -> InferResult<'tcx, ()>
1047     {
1048         debug!("eq_trait_refs({:?} = {:?})", a, b);
1049         self.commit_if_ok(|_| {
1050             let trace = TypeTrace {
1051                 origin: origin,
1052                 values: TraitRefs(ExpectedFound::new(a_is_expected, a, b))
1053             };
1054             self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1055         })
1056     }
1057
1058     pub fn eq_impl_headers(&self,
1059                            a_is_expected: bool,
1060                            origin: TypeOrigin,
1061                            a: &ty::ImplHeader<'tcx>,
1062                            b: &ty::ImplHeader<'tcx>)
1063                            -> InferResult<'tcx, ()>
1064     {
1065         debug!("eq_impl_header({:?} = {:?})", a, b);
1066         match (a.trait_ref, b.trait_ref) {
1067             (Some(a_ref), Some(b_ref)) => self.eq_trait_refs(a_is_expected, origin, a_ref, b_ref),
1068             (None, None) => self.eq_types(a_is_expected, origin, a.self_ty, b.self_ty),
1069             _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
1070         }
1071     }
1072
1073     pub fn sub_poly_trait_refs(&self,
1074                                a_is_expected: bool,
1075                                origin: TypeOrigin,
1076                                a: ty::PolyTraitRef<'tcx>,
1077                                b: ty::PolyTraitRef<'tcx>)
1078         -> InferResult<'tcx, ()>
1079     {
1080         debug!("sub_poly_trait_refs({:?} <: {:?})", a, b);
1081         self.commit_if_ok(|_| {
1082             let trace = TypeTrace {
1083                 origin: origin,
1084                 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b))
1085             };
1086             self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1087         })
1088     }
1089
1090     pub fn sub_regions(&self,
1091                        origin: SubregionOrigin<'tcx>,
1092                        a: &'tcx ty::Region,
1093                        b: &'tcx ty::Region) {
1094         debug!("sub_regions({:?} <: {:?})", a, b);
1095         self.region_vars.make_subregion(origin, a, b);
1096     }
1097
1098     pub fn equality_predicate(&self,
1099                               span: Span,
1100                               predicate: &ty::PolyEquatePredicate<'tcx>)
1101         -> InferResult<'tcx, ()>
1102     {
1103         self.commit_if_ok(|snapshot| {
1104             let (ty::EquatePredicate(a, b), skol_map) =
1105                 self.skolemize_late_bound_regions(predicate, snapshot);
1106             let origin = TypeOrigin::EquatePredicate(span);
1107             let eqty_ok = self.eq_types(false, origin, a, b)?;
1108             self.leak_check(false, span, &skol_map, snapshot)?;
1109             self.pop_skolemized(skol_map, snapshot);
1110             Ok(eqty_ok.unit())
1111         })
1112     }
1113
1114     pub fn region_outlives_predicate(&self,
1115                                      span: Span,
1116                                      predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1117         -> UnitResult<'tcx>
1118     {
1119         self.commit_if_ok(|snapshot| {
1120             let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1121                 self.skolemize_late_bound_regions(predicate, snapshot);
1122             let origin = RelateRegionParamBound(span);
1123             self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1124             self.leak_check(false, span, &skol_map, snapshot)?;
1125             Ok(self.pop_skolemized(skol_map, snapshot))
1126         })
1127     }
1128
1129     pub fn next_ty_var_id(&self, diverging: bool) -> TyVid {
1130         self.type_variables
1131             .borrow_mut()
1132             .new_var(diverging, None)
1133     }
1134
1135     pub fn next_ty_var(&self) -> Ty<'tcx> {
1136         self.tcx.mk_var(self.next_ty_var_id(false))
1137     }
1138
1139     pub fn next_diverging_ty_var(&self) -> Ty<'tcx> {
1140         self.tcx.mk_var(self.next_ty_var_id(true))
1141     }
1142
1143     pub fn next_ty_vars(&self, n: usize) -> Vec<Ty<'tcx>> {
1144         (0..n).map(|_i| self.next_ty_var()).collect()
1145     }
1146
1147     pub fn next_int_var_id(&self) -> IntVid {
1148         self.int_unification_table
1149             .borrow_mut()
1150             .new_key(None)
1151     }
1152
1153     pub fn next_float_var_id(&self) -> FloatVid {
1154         self.float_unification_table
1155             .borrow_mut()
1156             .new_key(None)
1157     }
1158
1159     pub fn next_region_var(&self, origin: RegionVariableOrigin)
1160                            -> &'tcx ty::Region {
1161         self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
1162     }
1163
1164     /// Create a region inference variable for the given
1165     /// region parameter definition.
1166     pub fn region_var_for_def(&self,
1167                               span: Span,
1168                               def: &ty::RegionParameterDef)
1169                               -> &'tcx ty::Region {
1170         self.next_region_var(EarlyBoundRegion(span, def.name))
1171     }
1172
1173     /// Create a type inference variable for the given
1174     /// type parameter definition. The substitutions are
1175     /// for actual parameters that may be referred to by
1176     /// the default of this type parameter, if it exists.
1177     /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1178     /// used in a path such as `Foo::<T, U>::new()` will
1179     /// use an inference variable for `C` with `[T, U]`
1180     /// as the substitutions for the default, `(T, U)`.
1181     pub fn type_var_for_def(&self,
1182                             span: Span,
1183                             def: &ty::TypeParameterDef<'tcx>,
1184                             substs: &Substs<'tcx>)
1185                             -> Ty<'tcx> {
1186         let default = def.default.map(|default| {
1187             type_variable::Default {
1188                 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1189                 origin_span: span,
1190                 def_id: def.default_def_id
1191             }
1192         });
1193
1194
1195         let ty_var_id = self.type_variables
1196                             .borrow_mut()
1197                             .new_var(false, default);
1198
1199         self.tcx.mk_var(ty_var_id)
1200     }
1201
1202     /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1203     /// type/region parameter to a fresh inference variable.
1204     pub fn fresh_substs_for_item(&self,
1205                                  span: Span,
1206                                  def_id: DefId)
1207                                  -> &'tcx Substs<'tcx> {
1208         Substs::for_item(self.tcx, def_id, |def, _| {
1209             self.region_var_for_def(span, def)
1210         }, |def, substs| {
1211             self.type_var_for_def(span, def, substs)
1212         })
1213     }
1214
1215     pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> &'tcx ty::Region {
1216         self.region_vars.new_bound(debruijn)
1217     }
1218
1219     /// Apply `adjustment` to the type of `expr`
1220     pub fn adjust_expr_ty(&self,
1221                           expr: &hir::Expr,
1222                           adjustment: Option<&adjustment::AutoAdjustment<'tcx>>)
1223                           -> Ty<'tcx>
1224     {
1225         let raw_ty = self.expr_ty(expr);
1226         let raw_ty = self.shallow_resolve(raw_ty);
1227         let resolve_ty = |ty: Ty<'tcx>| self.resolve_type_vars_if_possible(&ty);
1228         raw_ty.adjust(self.tcx,
1229                       expr.span,
1230                       expr.id,
1231                       adjustment,
1232                       |method_call| self.tables
1233                                         .borrow()
1234                                         .method_map
1235                                         .get(&method_call)
1236                                         .map(|method| resolve_ty(method.ty)))
1237     }
1238
1239     /// True if errors have been reported since this infcx was
1240     /// created.  This is sometimes used as a heuristic to skip
1241     /// reporting errors that often occur as a result of earlier
1242     /// errors, but where it's hard to be 100% sure (e.g., unresolved
1243     /// inference variables, regionck errors).
1244     pub fn is_tainted_by_errors(&self) -> bool {
1245         debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1246                 tainted_by_errors_flag={})",
1247                self.tcx.sess.err_count(),
1248                self.err_count_on_creation,
1249                self.tainted_by_errors_flag.get());
1250
1251         if self.tcx.sess.err_count() > self.err_count_on_creation {
1252             return true; // errors reported since this infcx was made
1253         }
1254         self.tainted_by_errors_flag.get()
1255     }
1256
1257     /// Set the "tainted by errors" flag to true. We call this when we
1258     /// observe an error from a prior pass.
1259     pub fn set_tainted_by_errors(&self) {
1260         debug!("set_tainted_by_errors()");
1261         self.tainted_by_errors_flag.set(true)
1262     }
1263
1264     pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1265         match self.tables.borrow().node_types.get(&id) {
1266             Some(&t) => t,
1267             // FIXME
1268             None if self.is_tainted_by_errors() =>
1269                 self.tcx.types.err,
1270             None => {
1271                 bug!("no type for node {}: {} in fcx",
1272                      id, self.tcx.map.node_to_string(id));
1273             }
1274         }
1275     }
1276
1277     pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1278         match self.tables.borrow().node_types.get(&ex.id) {
1279             Some(&t) => t,
1280             None => {
1281                 bug!("no type for expr in fcx");
1282             }
1283         }
1284     }
1285
1286     pub fn resolve_regions_and_report_errors(&self,
1287                                              free_regions: &FreeRegionMap,
1288                                              subject_node_id: ast::NodeId) {
1289         let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1290         if !self.is_tainted_by_errors() {
1291             // As a heuristic, just skip reporting region errors
1292             // altogether if other errors have been reported while
1293             // this infcx was in use.  This is totally hokey but
1294             // otherwise we have a hard time separating legit region
1295             // errors from silly ones.
1296             self.report_region_errors(&errors); // see error_reporting.rs
1297         }
1298     }
1299
1300     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1301         self.resolve_type_vars_if_possible(&t).to_string()
1302     }
1303
1304     pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1305         let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1306         format!("({})", tstrs.join(", "))
1307     }
1308
1309     pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1310         self.resolve_type_vars_if_possible(t).to_string()
1311     }
1312
1313     pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1314         match typ.sty {
1315             ty::TyInfer(ty::TyVar(v)) => {
1316                 // Not entirely obvious: if `typ` is a type variable,
1317                 // it can be resolved to an int/float variable, which
1318                 // can then be recursively resolved, hence the
1319                 // recursion. Note though that we prevent type
1320                 // variables from unifying to other type variables
1321                 // directly (though they may be embedded
1322                 // structurally), and we prevent cycles in any case,
1323                 // so this recursion should always be of very limited
1324                 // depth.
1325                 self.type_variables.borrow_mut()
1326                     .probe(v)
1327                     .map(|t| self.shallow_resolve(t))
1328                     .unwrap_or(typ)
1329             }
1330
1331             ty::TyInfer(ty::IntVar(v)) => {
1332                 self.int_unification_table
1333                     .borrow_mut()
1334                     .probe(v)
1335                     .map(|v| v.to_type(self.tcx))
1336                     .unwrap_or(typ)
1337             }
1338
1339             ty::TyInfer(ty::FloatVar(v)) => {
1340                 self.float_unification_table
1341                     .borrow_mut()
1342                     .probe(v)
1343                     .map(|v| v.to_type(self.tcx))
1344                     .unwrap_or(typ)
1345             }
1346
1347             _ => {
1348                 typ
1349             }
1350         }
1351     }
1352
1353     pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1354         where T: TypeFoldable<'tcx>
1355     {
1356         /*!
1357          * Where possible, replaces type/int/float variables in
1358          * `value` with their final value. Note that region variables
1359          * are unaffected. If a type variable has not been unified, it
1360          * is left as is.  This is an idempotent operation that does
1361          * not affect inference state in any way and so you can do it
1362          * at will.
1363          */
1364
1365         if !value.needs_infer() {
1366             return value.clone(); // avoid duplicated subst-folding
1367         }
1368         let mut r = resolve::OpportunisticTypeResolver::new(self);
1369         value.fold_with(&mut r)
1370     }
1371
1372     pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1373         where T: TypeFoldable<'tcx>
1374     {
1375         let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1376         value.fold_with(&mut r)
1377     }
1378
1379     /// Resolves all type variables in `t` and then, if any were left
1380     /// unresolved, substitutes an error type. This is used after the
1381     /// main checking when doing a second pass before writeback. The
1382     /// justification is that writeback will produce an error for
1383     /// these unconstrained type variables.
1384     fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1385         let ty = self.resolve_type_vars_if_possible(t);
1386         if ty.references_error() || ty.is_ty_var() {
1387             debug!("resolve_type_vars_or_error: error from {:?}", ty);
1388             Err(())
1389         } else {
1390             Ok(ty)
1391         }
1392     }
1393
1394     pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1395         /*!
1396          * Attempts to resolve all type/region variables in
1397          * `value`. Region inference must have been run already (e.g.,
1398          * by calling `resolve_regions_and_report_errors`).  If some
1399          * variable was never unified, an `Err` results.
1400          *
1401          * This method is idempotent, but it not typically not invoked
1402          * except during the writeback phase.
1403          */
1404
1405         resolve::fully_resolve(self, value)
1406     }
1407
1408     // [Note-Type-error-reporting]
1409     // An invariant is that anytime the expected or actual type is TyError (the special
1410     // error type, meaning that an error occurred when typechecking this expression),
1411     // this is a derived error. The error cascaded from another error (that was already
1412     // reported), so it's not useful to display it to the user.
1413     // The following methods implement this logic.
1414     // They check if either the actual or expected type is TyError, and don't print the error
1415     // in this case. The typechecker should only ever report type errors involving mismatched
1416     // types using one of these methods, and should not call span_err directly for such
1417     // errors.
1418
1419     pub fn type_error_message<M>(&self,
1420                                  sp: Span,
1421                                  mk_msg: M,
1422                                  actual_ty: Ty<'tcx>)
1423         where M: FnOnce(String) -> String,
1424     {
1425         self.type_error_struct(sp, mk_msg, actual_ty).emit();
1426     }
1427
1428     // FIXME: this results in errors without an error code. Deprecate?
1429     pub fn type_error_struct<M>(&self,
1430                                 sp: Span,
1431                                 mk_msg: M,
1432                                 actual_ty: Ty<'tcx>)
1433                                 -> DiagnosticBuilder<'tcx>
1434         where M: FnOnce(String) -> String,
1435     {
1436         self.type_error_struct_with_diag(sp, |actual_ty| {
1437             self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1438         }, actual_ty)
1439     }
1440
1441     pub fn type_error_struct_with_diag<M>(&self,
1442                                           sp: Span,
1443                                           mk_diag: M,
1444                                           actual_ty: Ty<'tcx>)
1445                                           -> DiagnosticBuilder<'tcx>
1446         where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1447     {
1448         let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1449         debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1450
1451         // Don't report an error if actual type is TyError.
1452         if actual_ty.references_error() {
1453             return self.tcx.sess.diagnostic().struct_dummy();
1454         }
1455
1456         mk_diag(self.ty_to_string(actual_ty))
1457     }
1458
1459     pub fn report_mismatched_types(&self,
1460                                    origin: TypeOrigin,
1461                                    expected: Ty<'tcx>,
1462                                    actual: Ty<'tcx>,
1463                                    err: TypeError<'tcx>) {
1464         let trace = TypeTrace {
1465             origin: origin,
1466             values: Types(ExpectedFound {
1467                 expected: expected,
1468                 found: actual
1469             })
1470         };
1471         self.report_and_explain_type_error(trace, &err).emit();
1472     }
1473
1474     pub fn report_conflicting_default_types(&self,
1475                                             span: Span,
1476                                             expected: type_variable::Default<'tcx>,
1477                                             actual: type_variable::Default<'tcx>) {
1478         let trace = TypeTrace {
1479             origin: TypeOrigin::Misc(span),
1480             values: Types(ExpectedFound {
1481                 expected: expected.ty,
1482                 found: actual.ty
1483             })
1484         };
1485
1486         self.report_and_explain_type_error(
1487             trace,
1488             &TypeError::TyParamDefaultMismatch(ExpectedFound {
1489                 expected: expected,
1490                 found: actual
1491             }))
1492             .emit();
1493     }
1494
1495     pub fn replace_late_bound_regions_with_fresh_var<T>(
1496         &self,
1497         span: Span,
1498         lbrct: LateBoundRegionConversionTime,
1499         value: &ty::Binder<T>)
1500         -> (T, FnvHashMap<ty::BoundRegion, &'tcx ty::Region>)
1501         where T : TypeFoldable<'tcx>
1502     {
1503         self.tcx.replace_late_bound_regions(
1504             value,
1505             |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1506     }
1507
1508     /// Given a higher-ranked projection predicate like:
1509     ///
1510     ///     for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1511     ///
1512     /// and a target trait-ref like:
1513     ///
1514     ///     <T as Fn<&'x u32>>
1515     ///
1516     /// find a substitution `S` for the higher-ranked regions (here,
1517     /// `['a => 'x]`) such that the predicate matches the trait-ref,
1518     /// and then return the value (here, `&'a u32`) but with the
1519     /// substitution applied (hence, `&'x u32`).
1520     ///
1521     /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1522     /// details.
1523     pub fn match_poly_projection_predicate(&self,
1524                                            origin: TypeOrigin,
1525                                            match_a: ty::PolyProjectionPredicate<'tcx>,
1526                                            match_b: ty::TraitRef<'tcx>)
1527                                            -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1528     {
1529         let span = origin.span();
1530         let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1531         let trace = TypeTrace {
1532             origin: origin,
1533             values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1534         };
1535
1536         let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1537         let mut combine = self.combine_fields(trace);
1538         let result = combine.higher_ranked_match(span, &match_pair, &match_b, true)?;
1539         Ok(InferOk { value: result, obligations: combine.obligations })
1540     }
1541
1542     /// See `verify_generic_bound` method in `region_inference`
1543     pub fn verify_generic_bound(&self,
1544                                 origin: SubregionOrigin<'tcx>,
1545                                 kind: GenericKind<'tcx>,
1546                                 a: &'tcx ty::Region,
1547                                 bound: VerifyBound<'tcx>) {
1548         debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1549                kind,
1550                a,
1551                bound);
1552
1553         self.region_vars.verify_generic_bound(origin, kind, a, bound);
1554     }
1555
1556     pub fn can_equate<T>(&self, a: &T, b: &T) -> UnitResult<'tcx>
1557         where T: Relate<'tcx> + fmt::Debug
1558     {
1559         debug!("can_equate({:?}, {:?})", a, b);
1560         self.probe(|_| {
1561             // Gin up a dummy trace, since this won't be committed
1562             // anyhow. We should make this typetrace stuff more
1563             // generic so we don't have to do anything quite this
1564             // terrible.
1565             self.equate(true, TypeTrace::dummy(self.tcx), a, b)
1566         }).map(|_| ())
1567     }
1568
1569     pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1570         let ty = self.node_type(id);
1571         self.resolve_type_vars_or_error(&ty)
1572     }
1573
1574     pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1575         let ty = self.adjust_expr_ty(expr, self.tables.borrow().adjustments.get(&expr.id));
1576         self.resolve_type_vars_or_error(&ty)
1577     }
1578
1579     pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1580         let ty = self.resolve_type_vars_if_possible(&ty);
1581         if let Some(ty) = self.tcx.lift_to_global(&ty) {
1582             // Even if the type may have no inference variables, during
1583             // type-checking closure types are in local tables only.
1584             let local_closures = match self.tables {
1585                 InferTables::Local(_) => ty.has_closure_types(),
1586                 InferTables::Global(_) => false
1587             };
1588             if !local_closures {
1589                 return ty.moves_by_default(self.tcx.global_tcx(), self.param_env(), span);
1590             }
1591         }
1592
1593         // this can get called from typeck (by euv), and moves_by_default
1594         // rightly refuses to work with inference variables, but
1595         // moves_by_default has a cache, which we want to use in other
1596         // cases.
1597         !traits::type_known_to_meet_builtin_bound(self, ty, ty::BoundCopy, span)
1598     }
1599
1600     pub fn node_method_ty(&self, method_call: ty::MethodCall)
1601                           -> Option<Ty<'tcx>> {
1602         self.tables
1603             .borrow()
1604             .method_map
1605             .get(&method_call)
1606             .map(|method| method.ty)
1607             .map(|ty| self.resolve_type_vars_if_possible(&ty))
1608     }
1609
1610     pub fn node_method_id(&self, method_call: ty::MethodCall)
1611                           -> Option<DefId> {
1612         self.tables
1613             .borrow()
1614             .method_map
1615             .get(&method_call)
1616             .map(|method| method.def_id)
1617     }
1618
1619     pub fn adjustments(&self) -> Ref<NodeMap<adjustment::AutoAdjustment<'tcx>>> {
1620         fn project_adjustments<'a, 'tcx>(tables: &'a ty::Tables<'tcx>)
1621                                         -> &'a NodeMap<adjustment::AutoAdjustment<'tcx>> {
1622             &tables.adjustments
1623         }
1624
1625         Ref::map(self.tables.borrow(), project_adjustments)
1626     }
1627
1628     pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1629         self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1630     }
1631
1632     pub fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<CodeExtent> {
1633         self.tcx.region_maps.temporary_scope(rvalue_id)
1634     }
1635
1636     pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
1637         self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1638     }
1639
1640     pub fn param_env(&self) -> &ty::ParameterEnvironment<'gcx> {
1641         &self.parameter_environment
1642     }
1643
1644     pub fn closure_kind(&self,
1645                         def_id: DefId)
1646                         -> Option<ty::ClosureKind>
1647     {
1648         if def_id.is_local() {
1649             self.tables.borrow().closure_kinds.get(&def_id).cloned()
1650         } else {
1651             // During typeck, ALL closures are local. But afterwards,
1652             // during trans, we see closure ids from other traits.
1653             // That may require loading the closure data out of the
1654             // cstore.
1655             Some(self.tcx.closure_kind(def_id))
1656         }
1657     }
1658
1659     pub fn closure_type(&self,
1660                         def_id: DefId,
1661                         substs: ty::ClosureSubsts<'tcx>)
1662                         -> ty::ClosureTy<'tcx>
1663     {
1664         if let InferTables::Local(tables) = self.tables {
1665             if let Some(ty) = tables.borrow().closure_tys.get(&def_id) {
1666                 return ty.subst(self.tcx, substs.func_substs);
1667             }
1668         }
1669
1670         let closure_ty = self.tcx.closure_type(def_id, substs);
1671         closure_ty
1672     }
1673 }
1674
1675 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1676     pub fn span(&self) -> Span {
1677         self.origin.span()
1678     }
1679
1680     pub fn types(origin: TypeOrigin,
1681                  a_is_expected: bool,
1682                  a: Ty<'tcx>,
1683                  b: Ty<'tcx>)
1684                  -> TypeTrace<'tcx> {
1685         TypeTrace {
1686             origin: origin,
1687             values: Types(ExpectedFound::new(a_is_expected, a, b))
1688         }
1689     }
1690
1691     pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1692         TypeTrace {
1693             origin: TypeOrigin::Misc(syntax_pos::DUMMY_SP),
1694             values: Types(ExpectedFound {
1695                 expected: tcx.types.err,
1696                 found: tcx.types.err,
1697             })
1698         }
1699     }
1700 }
1701
1702 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1703     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1704         write!(f, "TypeTrace({:?})", self.origin)
1705     }
1706 }
1707
1708 impl TypeOrigin {
1709     pub fn span(&self) -> Span {
1710         match *self {
1711             TypeOrigin::MethodCompatCheck(span) => span,
1712             TypeOrigin::ExprAssignable(span) => span,
1713             TypeOrigin::Misc(span) => span,
1714             TypeOrigin::RelateOutputImplTypes(span) => span,
1715             TypeOrigin::MatchExpressionArm(match_span, _, _) => match_span,
1716             TypeOrigin::IfExpression(span) => span,
1717             TypeOrigin::IfExpressionWithNoElse(span) => span,
1718             TypeOrigin::RangeExpression(span) => span,
1719             TypeOrigin::EquatePredicate(span) => span,
1720             TypeOrigin::MainFunctionType(span) => span,
1721             TypeOrigin::StartFunctionType(span) => span,
1722             TypeOrigin::IntrinsicType(span) => span,
1723             TypeOrigin::MethodReceiver(span) => span,
1724         }
1725     }
1726 }
1727
1728 impl<'tcx> SubregionOrigin<'tcx> {
1729     pub fn span(&self) -> Span {
1730         match *self {
1731             Subtype(ref a) => a.span(),
1732             InfStackClosure(a) => a,
1733             InvokeClosure(a) => a,
1734             DerefPointer(a) => a,
1735             FreeVariable(a, _) => a,
1736             IndexSlice(a) => a,
1737             RelateObjectBound(a) => a,
1738             RelateParamBound(a, _) => a,
1739             RelateRegionParamBound(a) => a,
1740             RelateDefaultParamBound(a, _) => a,
1741             Reborrow(a) => a,
1742             ReborrowUpvar(a, _) => a,
1743             DataBorrowed(_, a) => a,
1744             ReferenceOutlivesReferent(_, a) => a,
1745             ParameterInScope(_, a) => a,
1746             ExprTypeIsNotInScope(_, a) => a,
1747             BindingTypeIsNotValidAtDecl(a) => a,
1748             CallRcvr(a) => a,
1749             CallArg(a) => a,
1750             CallReturn(a) => a,
1751             Operand(a) => a,
1752             AddrOf(a) => a,
1753             AutoBorrow(a) => a,
1754             SafeDestructor(a) => a,
1755         }
1756     }
1757 }
1758
1759 impl RegionVariableOrigin {
1760     pub fn span(&self) -> Span {
1761         match *self {
1762             MiscVariable(a) => a,
1763             PatternRegion(a) => a,
1764             AddrOfRegion(a) => a,
1765             Autoref(a) => a,
1766             Coercion(a) => a,
1767             EarlyBoundRegion(a, _) => a,
1768             LateBoundRegion(a, _, _) => a,
1769             BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1770             UpvarRegion(_, a) => a
1771         }
1772     }
1773 }
1774
1775 impl<'tcx> TypeFoldable<'tcx> for TypeOrigin {
1776     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _folder: &mut F) -> Self {
1777         self.clone()
1778     }
1779
1780     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> bool {
1781         false
1782     }
1783 }
1784
1785 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1786     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1787         match *self {
1788             ValuePairs::Types(ref ef) => {
1789                 ValuePairs::Types(ef.fold_with(folder))
1790             }
1791             ValuePairs::TraitRefs(ref ef) => {
1792                 ValuePairs::TraitRefs(ef.fold_with(folder))
1793             }
1794             ValuePairs::PolyTraitRefs(ref ef) => {
1795                 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1796             }
1797         }
1798     }
1799
1800     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1801         match *self {
1802             ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1803             ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1804             ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1805         }
1806     }
1807 }
1808
1809 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1810     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1811         TypeTrace {
1812             origin: self.origin.fold_with(folder),
1813             values: self.values.fold_with(folder)
1814         }
1815     }
1816
1817     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1818         self.origin.visit_with(visitor) || self.values.visit_with(visitor)
1819     }
1820 }