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