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