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