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