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