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