]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/infer/mod.rs
5b94f5311fd0f6bf54ef99cae2a93898e99abbba
[rust.git] / src / librustc / middle / 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::TypeOrigin::*;
17 pub use self::ValuePairs::*;
18 pub use middle::ty::IntVarValue;
19 pub use self::freshen::TypeFreshener;
20 pub use self::region_inference::{GenericKind, VerifyBound};
21
22 use middle::def_id::DefId;
23 use rustc_front::hir;
24 use middle::free_region::FreeRegionMap;
25 use middle::mem_categorization as mc;
26 use middle::mem_categorization::McResult;
27 use middle::region::CodeExtent;
28 use middle::subst;
29 use middle::subst::Substs;
30 use middle::subst::Subst;
31 use middle::traits::{self, FulfillmentContext, Normalized,
32                      SelectionContext, ObligationCause};
33 use middle::ty::{TyVid, IntVid, FloatVid, RegionVid, UnconstrainedNumeric};
34 use middle::ty::{self, Ty, TypeError, HasTypeFlags};
35 use middle::ty::fold::{TypeFolder, TypeFoldable};
36 use middle::ty::relate::{Relate, RelateResult, TypeRelation};
37 use rustc_data_structures::unify::{self, UnificationTable};
38 use std::cell::{RefCell, Ref};
39 use std::fmt;
40 use std::rc::Rc;
41 use syntax::ast;
42 use syntax::codemap;
43 use syntax::codemap::{Span, DUMMY_SP};
44 use util::nodemap::{FnvHashMap, NodeMap};
45
46 use self::combine::CombineFields;
47 use self::region_inference::{RegionVarBindings, RegionSnapshot};
48 use self::error_reporting::ErrorReporting;
49 use self::unify_key::ToType;
50
51 pub mod bivariate;
52 pub mod combine;
53 pub mod equate;
54 pub mod error_reporting;
55 pub mod glb;
56 mod higher_ranked;
57 pub mod lattice;
58 pub mod lub;
59 pub mod region_inference;
60 pub mod resolve;
61 mod freshen;
62 pub mod sub;
63 pub mod type_variable;
64 pub mod unify_key;
65
66 pub type Bound<T> = Option<T>;
67 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
68 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
69
70 pub struct InferCtxt<'a, 'tcx: 'a> {
71     pub tcx: &'a ty::ctxt<'tcx>,
72
73     pub tables: &'a RefCell<ty::Tables<'tcx>>,
74
75     // We instantiate UnificationTable with bounds<Ty> because the
76     // types that might instantiate a general type variable have an
77     // order, represented by its upper and lower bounds.
78     type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
79
80     // Map from integral variable to the kind of integer it represents
81     int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
82
83     // Map from floating variable to the kind of float it represents
84     float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
85
86     // For region variables.
87     region_vars: RegionVarBindings<'a, 'tcx>,
88
89     pub parameter_environment: ty::ParameterEnvironment<'a, 'tcx>,
90
91     pub fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
92
93     // This is a temporary field used for toggling on normalization in the inference context,
94     // as we move towards the approach described here:
95     // https://internals.rust-lang.org/t/flattening-the-contexts-for-fun-and-profit/2293
96     // At a point sometime in the future normalization will be done by the typing context
97     // directly.
98     normalize: bool,
99
100     err_count_on_creation: usize,
101 }
102
103 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
104 /// region that each late-bound region was replaced with.
105 pub type SkolemizationMap = FnvHashMap<ty::BoundRegion,ty::Region>;
106
107 /// Why did we require that the two types be related?
108 ///
109 /// See `error_reporting.rs` for more details
110 #[derive(Clone, Copy, Debug)]
111 pub enum TypeOrigin {
112     // Not yet categorized in a better way
113     Misc(Span),
114
115     // Checking that method of impl is compatible with trait
116     MethodCompatCheck(Span),
117
118     // Checking that this expression can be assigned where it needs to be
119     // FIXME(eddyb) #11161 is the original Expr required?
120     ExprAssignable(Span),
121
122     // Relating trait refs when resolving vtables
123     RelateTraitRefs(Span),
124
125     // Relating self types when resolving vtables
126     RelateSelfType(Span),
127
128     // Relating trait type parameters to those found in impl etc
129     RelateOutputImplTypes(Span),
130
131     // Computing common supertype in the arms of a match expression
132     MatchExpressionArm(Span, Span),
133
134     // Computing common supertype in an if expression
135     IfExpression(Span),
136
137     // Computing common supertype of an if expression with no else counter-part
138     IfExpressionWithNoElse(Span),
139
140     // Computing common supertype in a range expression
141     RangeExpression(Span),
142
143     // `where a == b`
144     EquatePredicate(Span),
145 }
146
147 impl TypeOrigin {
148     fn as_str(&self) -> &'static str {
149         match self {
150             &TypeOrigin::Misc(_) |
151             &TypeOrigin::RelateSelfType(_) |
152             &TypeOrigin::RelateOutputImplTypes(_) |
153             &TypeOrigin::ExprAssignable(_) => "mismatched types",
154             &TypeOrigin::RelateTraitRefs(_) => "mismatched traits",
155             &TypeOrigin::MethodCompatCheck(_) => "method not compatible with trait",
156             &TypeOrigin::MatchExpressionArm(_, _) => "match arms have incompatible types",
157             &TypeOrigin::IfExpression(_) => "if and else have incompatible types",
158             &TypeOrigin::IfExpressionWithNoElse(_) => "if may be missing an else clause",
159             &TypeOrigin::RangeExpression(_) => "start and end of range have incompatible types",
160             &TypeOrigin::EquatePredicate(_) => "equality predicate not satisfied",
161         }
162     }
163 }
164
165 impl fmt::Display for TypeOrigin {
166     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error> {
167         fmt::Display::fmt(self.as_str(), f)
168     }
169 }
170
171 /// See `error_reporting.rs` for more details
172 #[derive(Clone, Debug)]
173 pub enum ValuePairs<'tcx> {
174     Types(ty::ExpectedFound<Ty<'tcx>>),
175     TraitRefs(ty::ExpectedFound<ty::TraitRef<'tcx>>),
176     PolyTraitRefs(ty::ExpectedFound<ty::PolyTraitRef<'tcx>>),
177 }
178
179 /// The trace designates the path through inference that we took to
180 /// encounter an error or subtyping constraint.
181 ///
182 /// See `error_reporting.rs` for more details.
183 #[derive(Clone)]
184 pub struct TypeTrace<'tcx> {
185     origin: TypeOrigin,
186     values: ValuePairs<'tcx>,
187 }
188
189 /// The origin of a `r1 <= r2` constraint.
190 ///
191 /// See `error_reporting.rs` for more details
192 #[derive(Clone, Debug)]
193 pub enum SubregionOrigin<'tcx> {
194     // Marker to indicate a constraint that only arises due to new
195     // provisions from RFC 1214. This will result in a warning, not an
196     // error.
197     RFC1214Subregion(Rc<SubregionOrigin<'tcx>>),
198
199     // Arose from a subtyping relation
200     Subtype(TypeTrace<'tcx>),
201
202     // Stack-allocated closures cannot outlive innermost loop
203     // or function so as to ensure we only require finite stack
204     InfStackClosure(Span),
205
206     // Invocation of closure must be within its lifetime
207     InvokeClosure(Span),
208
209     // Dereference of reference must be within its lifetime
210     DerefPointer(Span),
211
212     // Closure bound must not outlive captured free variables
213     FreeVariable(Span, ast::NodeId),
214
215     // Index into slice must be within its lifetime
216     IndexSlice(Span),
217
218     // When casting `&'a T` to an `&'b Trait` object,
219     // relating `'a` to `'b`
220     RelateObjectBound(Span),
221
222     // Some type parameter was instantiated with the given type,
223     // and that type must outlive some region.
224     RelateParamBound(Span, Ty<'tcx>),
225
226     // The given region parameter was instantiated with a region
227     // that must outlive some other region.
228     RelateRegionParamBound(Span),
229
230     // A bound placed on type parameters that states that must outlive
231     // the moment of their instantiation.
232     RelateDefaultParamBound(Span, Ty<'tcx>),
233
234     // Creating a pointer `b` to contents of another reference
235     Reborrow(Span),
236
237     // Creating a pointer `b` to contents of an upvar
238     ReborrowUpvar(Span, ty::UpvarId),
239
240     // Data with type `Ty<'tcx>` was borrowed
241     DataBorrowed(Ty<'tcx>, Span),
242
243     // (&'a &'b T) where a >= b
244     ReferenceOutlivesReferent(Ty<'tcx>, Span),
245
246     // Type or region parameters must be in scope.
247     ParameterInScope(ParameterOrigin, Span),
248
249     // The type T of an expression E must outlive the lifetime for E.
250     ExprTypeIsNotInScope(Ty<'tcx>, Span),
251
252     // A `ref b` whose region does not enclose the decl site
253     BindingTypeIsNotValidAtDecl(Span),
254
255     // Regions appearing in a method receiver must outlive method call
256     CallRcvr(Span),
257
258     // Regions appearing in a function argument must outlive func call
259     CallArg(Span),
260
261     // Region in return type of invoked fn must enclose call
262     CallReturn(Span),
263
264     // Operands must be in scope
265     Operand(Span),
266
267     // Region resulting from a `&` expr must enclose the `&` expr
268     AddrOf(Span),
269
270     // An auto-borrow that does not enclose the expr where it occurs
271     AutoBorrow(Span),
272
273     // Region constraint arriving from destructor safety
274     SafeDestructor(Span),
275 }
276
277 /// Places that type/region parameters can appear.
278 #[derive(Clone, Copy, Debug)]
279 pub enum ParameterOrigin {
280     Path, // foo::bar
281     MethodCall, // foo.bar() <-- parameters on impl providing bar()
282     OverloadedOperator, // a + b when overloaded
283     OverloadedDeref, // *a when overloaded
284 }
285
286 /// Times when we replace late-bound regions with variables:
287 #[derive(Clone, Copy, Debug)]
288 pub enum LateBoundRegionConversionTime {
289     /// when a fn is called
290     FnCall,
291
292     /// when two higher-ranked types are compared
293     HigherRankedType,
294
295     /// when projecting an associated type
296     AssocTypeProjection(ast::Name),
297 }
298
299 /// Reasons to create a region inference variable
300 ///
301 /// See `error_reporting.rs` for more details
302 #[derive(Clone, Debug)]
303 pub enum RegionVariableOrigin {
304     // Region variables created for ill-categorized reasons,
305     // mostly indicates places in need of refactoring
306     MiscVariable(Span),
307
308     // Regions created by a `&P` or `[...]` pattern
309     PatternRegion(Span),
310
311     // Regions created by `&` operator
312     AddrOfRegion(Span),
313
314     // Regions created as part of an autoref of a method receiver
315     Autoref(Span),
316
317     // Regions created as part of an automatic coercion
318     Coercion(Span),
319
320     // Region variables created as the values for early-bound regions
321     EarlyBoundRegion(Span, ast::Name),
322
323     // Region variables created for bound regions
324     // in a function or method that is called
325     LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
326
327     UpvarRegion(ty::UpvarId, Span),
328
329     BoundRegionInCoherence(ast::Name),
330 }
331
332 #[derive(Copy, Clone, Debug)]
333 pub enum FixupError {
334     UnresolvedIntTy(IntVid),
335     UnresolvedFloatTy(FloatVid),
336     UnresolvedTy(TyVid)
337 }
338
339 pub fn fixup_err_to_string(f: FixupError) -> String {
340     use self::FixupError::*;
341
342     match f {
343       UnresolvedIntTy(_) => {
344           "cannot determine the type of this integer; add a suffix to \
345            specify the type explicitly".to_string()
346       }
347       UnresolvedFloatTy(_) => {
348           "cannot determine the type of this number; add a suffix to specify \
349            the type explicitly".to_string()
350       }
351       UnresolvedTy(_) => "unconstrained type".to_string(),
352     }
353 }
354
355 /// errors_will_be_reported is required to proxy to the fulfillment context
356 /// FIXME -- a better option would be to hold back on modifying
357 /// the global cache until we know that all dependent obligations
358 /// are also satisfied. In that case, we could actually remove
359 /// this boolean flag, and we'd also avoid the problem of squelching
360 /// duplicate errors that occur across fns.
361 pub fn new_infer_ctxt<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
362                                 tables: &'a RefCell<ty::Tables<'tcx>>,
363                                 param_env: Option<ty::ParameterEnvironment<'a, 'tcx>>,
364                                 errors_will_be_reported: bool)
365                                 -> InferCtxt<'a, 'tcx> {
366     InferCtxt {
367         tcx: tcx,
368         tables: tables,
369         type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
370         int_unification_table: RefCell::new(UnificationTable::new()),
371         float_unification_table: RefCell::new(UnificationTable::new()),
372         region_vars: RegionVarBindings::new(tcx),
373         parameter_environment: param_env.unwrap_or(tcx.empty_parameter_environment()),
374         fulfillment_cx: RefCell::new(traits::FulfillmentContext::new(errors_will_be_reported)),
375         normalize: false,
376         err_count_on_creation: tcx.sess.err_count()
377     }
378 }
379
380 pub fn normalizing_infer_ctxt<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
381                                         tables: &'a RefCell<ty::Tables<'tcx>>)
382                                         -> InferCtxt<'a, 'tcx> {
383     let mut infcx = new_infer_ctxt(tcx, tables, None, false);
384     infcx.normalize = true;
385     infcx
386 }
387
388 /// Computes the least upper-bound of `a` and `b`. If this is not possible, reports an error and
389 /// returns ty::err.
390 pub fn common_supertype<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
391                                   origin: TypeOrigin,
392                                   a_is_expected: bool,
393                                   a: Ty<'tcx>,
394                                   b: Ty<'tcx>)
395                                   -> Ty<'tcx>
396 {
397     debug!("common_supertype({:?}, {:?})",
398            a, b);
399
400     let trace = TypeTrace {
401         origin: origin,
402         values: Types(expected_found(a_is_expected, a, b))
403     };
404
405     let result = cx.commit_if_ok(|_| cx.lub(a_is_expected, trace.clone()).relate(&a, &b));
406     match result {
407         Ok(t) => t,
408         Err(ref err) => {
409             cx.report_and_explain_type_error(trace, err);
410             cx.tcx.types.err
411         }
412     }
413 }
414
415 pub fn mk_subty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
416                           a_is_expected: bool,
417                           origin: TypeOrigin,
418                           a: Ty<'tcx>,
419                           b: Ty<'tcx>)
420                           -> UnitResult<'tcx>
421 {
422     debug!("mk_subty({:?} <: {:?})", a, b);
423     cx.sub_types(a_is_expected, origin, a, b)
424 }
425
426 pub fn can_mk_subty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
427                               a: Ty<'tcx>,
428                               b: Ty<'tcx>)
429                               -> UnitResult<'tcx> {
430     debug!("can_mk_subty({:?} <: {:?})", a, b);
431     cx.probe(|_| {
432         let trace = TypeTrace {
433             origin: Misc(codemap::DUMMY_SP),
434             values: Types(expected_found(true, a, b))
435         };
436         cx.sub(true, trace).relate(&a, &b).map(|_| ())
437     })
438 }
439
440 pub fn can_mk_eqty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>)
441                              -> UnitResult<'tcx>
442 {
443     cx.can_equate(&a, &b)
444 }
445
446 pub fn mk_subr<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
447                          origin: SubregionOrigin<'tcx>,
448                          a: ty::Region,
449                          b: ty::Region) {
450     debug!("mk_subr({:?} <: {:?})", a, b);
451     let snapshot = cx.region_vars.start_snapshot();
452     cx.region_vars.make_subregion(origin, a, b);
453     cx.region_vars.commit(snapshot);
454 }
455
456 pub fn mk_eqty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
457                          a_is_expected: bool,
458                          origin: TypeOrigin,
459                          a: Ty<'tcx>,
460                          b: Ty<'tcx>)
461                          -> UnitResult<'tcx>
462 {
463     debug!("mk_eqty({:?} <: {:?})", a, b);
464     cx.commit_if_ok(|_| cx.eq_types(a_is_expected, origin, a, b))
465 }
466
467 pub fn mk_sub_poly_trait_refs<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
468                                    a_is_expected: bool,
469                                    origin: TypeOrigin,
470                                    a: ty::PolyTraitRef<'tcx>,
471                                    b: ty::PolyTraitRef<'tcx>)
472                                    -> UnitResult<'tcx>
473 {
474     debug!("mk_sub_trait_refs({:?} <: {:?})",
475            a, b);
476     cx.commit_if_ok(|_| cx.sub_poly_trait_refs(a_is_expected, origin, a.clone(), b.clone()))
477 }
478
479 fn expected_found<T>(a_is_expected: bool,
480                      a: T,
481                      b: T)
482                      -> ty::ExpectedFound<T>
483 {
484     if a_is_expected {
485         ty::ExpectedFound {expected: a, found: b}
486     } else {
487         ty::ExpectedFound {expected: b, found: a}
488     }
489 }
490
491 #[must_use = "once you start a snapshot, you should always consume it"]
492 pub struct CombinedSnapshot {
493     type_snapshot: type_variable::Snapshot,
494     int_snapshot: unify::Snapshot<ty::IntVid>,
495     float_snapshot: unify::Snapshot<ty::FloatVid>,
496     region_vars_snapshot: RegionSnapshot,
497 }
498
499 pub fn normalize_associated_type<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> T
500     where T : TypeFoldable<'tcx> + HasTypeFlags
501 {
502     debug!("normalize_associated_type(t={:?})", value);
503
504     let value = erase_regions(tcx, value);
505
506     if !value.has_projection_types() {
507         return value;
508     }
509
510     let infcx = new_infer_ctxt(tcx, &tcx.tables, None, true);
511     let mut selcx = traits::SelectionContext::new(&infcx);
512     let cause = traits::ObligationCause::dummy();
513     let traits::Normalized { value: result, obligations } =
514         traits::normalize(&mut selcx, cause, &value);
515
516     debug!("normalize_associated_type: result={:?} obligations={:?}",
517            result,
518            obligations);
519
520     let mut fulfill_cx = infcx.fulfillment_cx.borrow_mut();
521
522     for obligation in obligations {
523         fulfill_cx.register_predicate_obligation(&infcx, obligation);
524     }
525
526     let result = drain_fulfillment_cx_or_panic(DUMMY_SP, &infcx, &mut fulfill_cx, &result);
527
528     result
529 }
530
531 pub fn drain_fulfillment_cx_or_panic<'a,'tcx,T>(span: Span,
532                                                 infcx: &InferCtxt<'a,'tcx>,
533                                                 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
534                                                 result: &T)
535                                                 -> T
536     where T : TypeFoldable<'tcx>
537 {
538     match drain_fulfillment_cx(infcx, fulfill_cx, result) {
539         Ok(v) => v,
540         Err(errors) => {
541             infcx.tcx.sess.span_bug(
542                 span,
543                 &format!("Encountered errors `{:?}` fulfilling during trans",
544                          errors));
545         }
546     }
547 }
548
549 /// Finishes processes any obligations that remain in the fulfillment
550 /// context, and then "freshens" and returns `result`. This is
551 /// primarily used during normalization and other cases where
552 /// processing the obligations in `fulfill_cx` may cause type
553 /// inference variables that appear in `result` to be unified, and
554 /// hence we need to process those obligations to get the complete
555 /// picture of the type.
556 pub fn drain_fulfillment_cx<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>,
557                                        fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
558                                        result: &T)
559                                        -> Result<T,Vec<traits::FulfillmentError<'tcx>>>
560     where T : TypeFoldable<'tcx>
561 {
562     debug!("drain_fulfillment_cx(result={:?})",
563            result);
564
565     // In principle, we only need to do this so long as `result`
566     // contains unbound type parameters. It could be a slight
567     // optimization to stop iterating early.
568     match fulfill_cx.select_all_or_error(infcx) {
569         Ok(()) => { }
570         Err(errors) => {
571             return Err(errors);
572         }
573     }
574
575     // Use freshen to simultaneously replace all type variables with
576     // their bindings and replace all regions with 'static.  This is
577     // sort of overkill because we do not expect there to be any
578     // unbound type variables, hence no `TyFresh` types should ever be
579     // inserted.
580     Ok(result.fold_with(&mut infcx.freshener()))
581 }
582
583 /// Returns an equivalent value with all free regions removed (note
584 /// that late-bound regions remain, because they are important for
585 /// subtyping, but they are anonymized and normalized as well). This
586 /// is a stronger, caching version of `ty::fold::erase_regions`.
587 pub fn erase_regions<'tcx,T>(cx: &ty::ctxt<'tcx>, value: &T) -> T
588     where T : TypeFoldable<'tcx>
589 {
590     let value1 = value.fold_with(&mut RegionEraser(cx));
591     debug!("erase_regions({:?}) = {:?}",
592            value, value1);
593     return value1;
594
595     struct RegionEraser<'a, 'tcx: 'a>(&'a ty::ctxt<'tcx>);
596
597     impl<'a, 'tcx> TypeFolder<'tcx> for RegionEraser<'a, 'tcx> {
598         fn tcx(&self) -> &ty::ctxt<'tcx> { self.0 }
599
600         fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
601             match self.tcx().normalized_cache.borrow().get(&ty).cloned() {
602                 None => {}
603                 Some(u) => return u
604             }
605
606             let t_norm = ty::fold::super_fold_ty(self, ty);
607             self.tcx().normalized_cache.borrow_mut().insert(ty, t_norm);
608             return t_norm;
609         }
610
611         fn fold_binder<T>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T>
612             where T : TypeFoldable<'tcx>
613         {
614             let u = self.tcx().anonymize_late_bound_regions(t);
615             ty::fold::super_fold_binder(self, &u)
616         }
617
618         fn fold_region(&mut self, r: ty::Region) -> ty::Region {
619             // because late-bound regions affect subtyping, we can't
620             // erase the bound/free distinction, but we can replace
621             // all free regions with 'static.
622             //
623             // Note that we *CAN* replace early-bound regions -- the
624             // type system never "sees" those, they get substituted
625             // away. In trans, they will always be erased to 'static
626             // whenever a substitution occurs.
627             match r {
628                 ty::ReLateBound(..) => r,
629                 _ => ty::ReStatic
630             }
631         }
632
633         fn fold_substs(&mut self,
634                        substs: &subst::Substs<'tcx>)
635                        -> subst::Substs<'tcx> {
636             subst::Substs { regions: subst::ErasedRegions,
637                             types: substs.types.fold_with(self) }
638         }
639     }
640 }
641
642 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
643     pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
644         t.fold_with(&mut self.freshener())
645     }
646
647     pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
648         match ty.sty {
649             ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
650             _ => false
651         }
652     }
653
654     pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
655         freshen::TypeFreshener::new(self)
656     }
657
658     pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
659         use middle::ty::UnconstrainedNumeric::{Neither, UnconstrainedInt, UnconstrainedFloat};
660         match ty.sty {
661             ty::TyInfer(ty::IntVar(vid)) => {
662                 if self.int_unification_table.borrow_mut().has_value(vid) {
663                     Neither
664                 } else {
665                     UnconstrainedInt
666                 }
667             },
668             ty::TyInfer(ty::FloatVar(vid)) => {
669                 if self.float_unification_table.borrow_mut().has_value(vid) {
670                     Neither
671                 } else {
672                     UnconstrainedFloat
673                 }
674             },
675             _ => Neither,
676         }
677     }
678
679     /// Returns a type variable's default fallback if any exists. A default
680     /// must be attached to the variable when created, if it is created
681     /// without a default, this will return None.
682     ///
683     /// This code does not apply to integral or floating point variables,
684     /// only to use declared defaults.
685     ///
686     /// See `new_ty_var_with_default` to create a type variable with a default.
687     /// See `type_variable::Default` for details about what a default entails.
688     pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
689         match ty.sty {
690             ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
691             _ => None
692         }
693     }
694
695     pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
696         let mut variables = Vec::new();
697
698         let unbound_ty_vars = self.type_variables
699                                   .borrow()
700                                   .unsolved_variables()
701                                   .into_iter()
702                                   .map(|t| self.tcx.mk_var(t));
703
704         let unbound_int_vars = self.int_unification_table
705                                    .borrow_mut()
706                                    .unsolved_variables()
707                                    .into_iter()
708                                    .map(|v| self.tcx.mk_int_var(v));
709
710         let unbound_float_vars = self.float_unification_table
711                                      .borrow_mut()
712                                      .unsolved_variables()
713                                      .into_iter()
714                                      .map(|v| self.tcx.mk_float_var(v));
715
716         variables.extend(unbound_ty_vars);
717         variables.extend(unbound_int_vars);
718         variables.extend(unbound_float_vars);
719
720         return variables;
721     }
722
723     fn combine_fields(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
724                       -> CombineFields<'a, 'tcx> {
725         CombineFields {infcx: self,
726                        a_is_expected: a_is_expected,
727                        trace: trace,
728                        cause: None}
729     }
730
731     // public so that it can be used from the rustc_driver unit tests
732     pub fn equate(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
733               -> equate::Equate<'a, 'tcx>
734     {
735         self.combine_fields(a_is_expected, trace).equate()
736     }
737
738     // public so that it can be used from the rustc_driver unit tests
739     pub fn sub(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
740                -> sub::Sub<'a, 'tcx>
741     {
742         self.combine_fields(a_is_expected, trace).sub()
743     }
744
745     // public so that it can be used from the rustc_driver unit tests
746     pub fn lub(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
747                -> lub::Lub<'a, 'tcx>
748     {
749         self.combine_fields(a_is_expected, trace).lub()
750     }
751
752     // public so that it can be used from the rustc_driver unit tests
753     pub fn glb(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
754                -> glb::Glb<'a, 'tcx>
755     {
756         self.combine_fields(a_is_expected, trace).glb()
757     }
758
759     fn start_snapshot(&self) -> CombinedSnapshot {
760         CombinedSnapshot {
761             type_snapshot: self.type_variables.borrow_mut().snapshot(),
762             int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
763             float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
764             region_vars_snapshot: self.region_vars.start_snapshot(),
765         }
766     }
767
768     fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
769         debug!("rollback_to(cause={})", cause);
770         let CombinedSnapshot { type_snapshot,
771                                int_snapshot,
772                                float_snapshot,
773                                region_vars_snapshot } = snapshot;
774
775         self.type_variables
776             .borrow_mut()
777             .rollback_to(type_snapshot);
778         self.int_unification_table
779             .borrow_mut()
780             .rollback_to(int_snapshot);
781         self.float_unification_table
782             .borrow_mut()
783             .rollback_to(float_snapshot);
784         self.region_vars
785             .rollback_to(region_vars_snapshot);
786     }
787
788     fn commit_from(&self, snapshot: CombinedSnapshot) {
789         debug!("commit_from!");
790         let CombinedSnapshot { type_snapshot,
791                                int_snapshot,
792                                float_snapshot,
793                                region_vars_snapshot } = snapshot;
794
795         self.type_variables
796             .borrow_mut()
797             .commit(type_snapshot);
798         self.int_unification_table
799             .borrow_mut()
800             .commit(int_snapshot);
801         self.float_unification_table
802             .borrow_mut()
803             .commit(float_snapshot);
804         self.region_vars
805             .commit(region_vars_snapshot);
806     }
807
808     /// Execute `f` and commit the bindings
809     pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
810         F: FnOnce() -> R,
811     {
812         debug!("commit()");
813         let snapshot = self.start_snapshot();
814         let r = f();
815         self.commit_from(snapshot);
816         r
817     }
818
819     /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
820     pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
821         F: FnOnce(&CombinedSnapshot) -> Result<T, E>
822     {
823         debug!("commit_if_ok()");
824         let snapshot = self.start_snapshot();
825         let r = f(&snapshot);
826         debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
827         match r {
828             Ok(_) => { self.commit_from(snapshot); }
829             Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
830         }
831         r
832     }
833
834     /// Execute `f` and commit only the region bindings if successful.
835     /// The function f must be very careful not to leak any non-region
836     /// variables that get created.
837     pub fn commit_regions_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
838         F: FnOnce() -> Result<T, E>
839     {
840         debug!("commit_regions_if_ok()");
841         let CombinedSnapshot { type_snapshot,
842                                int_snapshot,
843                                float_snapshot,
844                                region_vars_snapshot } = self.start_snapshot();
845
846         let r = self.commit_if_ok(|_| f());
847
848         debug!("commit_regions_if_ok: rolling back everything but regions");
849
850         // Roll back any non-region bindings - they should be resolved
851         // inside `f`, with, e.g. `resolve_type_vars_if_possible`.
852         self.type_variables
853             .borrow_mut()
854             .rollback_to(type_snapshot);
855         self.int_unification_table
856             .borrow_mut()
857             .rollback_to(int_snapshot);
858         self.float_unification_table
859             .borrow_mut()
860             .rollback_to(float_snapshot);
861
862         // Commit region vars that may escape through resolved types.
863         self.region_vars
864             .commit(region_vars_snapshot);
865
866         r
867     }
868
869     /// Execute `f` then unroll any bindings it creates
870     pub fn probe<R, F>(&self, f: F) -> R where
871         F: FnOnce(&CombinedSnapshot) -> R,
872     {
873         debug!("probe()");
874         let snapshot = self.start_snapshot();
875         let r = f(&snapshot);
876         self.rollback_to("probe", snapshot);
877         r
878     }
879
880     pub fn add_given(&self,
881                      sub: ty::FreeRegion,
882                      sup: ty::RegionVid)
883     {
884         self.region_vars.add_given(sub, sup);
885     }
886
887     pub fn sub_types(&self,
888                      a_is_expected: bool,
889                      origin: TypeOrigin,
890                      a: Ty<'tcx>,
891                      b: Ty<'tcx>)
892                      -> UnitResult<'tcx>
893     {
894         debug!("sub_types({:?} <: {:?})", a, b);
895         self.commit_if_ok(|_| {
896             let trace = TypeTrace::types(origin, a_is_expected, a, b);
897             self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
898         })
899     }
900
901     pub fn eq_types(&self,
902                     a_is_expected: bool,
903                     origin: TypeOrigin,
904                     a: Ty<'tcx>,
905                     b: Ty<'tcx>)
906                     -> UnitResult<'tcx>
907     {
908         self.commit_if_ok(|_| {
909             let trace = TypeTrace::types(origin, a_is_expected, a, b);
910             self.equate(a_is_expected, trace).relate(&a, &b).map(|_| ())
911         })
912     }
913
914     pub fn sub_trait_refs(&self,
915                           a_is_expected: bool,
916                           origin: TypeOrigin,
917                           a: ty::TraitRef<'tcx>,
918                           b: ty::TraitRef<'tcx>)
919                           -> UnitResult<'tcx>
920     {
921         debug!("sub_trait_refs({:?} <: {:?})",
922                a,
923                b);
924         self.commit_if_ok(|_| {
925             let trace = TypeTrace {
926                 origin: origin,
927                 values: TraitRefs(expected_found(a_is_expected, a.clone(), b.clone()))
928             };
929             self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
930         })
931     }
932
933     pub fn sub_poly_trait_refs(&self,
934                                a_is_expected: bool,
935                                origin: TypeOrigin,
936                                a: ty::PolyTraitRef<'tcx>,
937                                b: ty::PolyTraitRef<'tcx>)
938                                -> UnitResult<'tcx>
939     {
940         debug!("sub_poly_trait_refs({:?} <: {:?})",
941                a,
942                b);
943         self.commit_if_ok(|_| {
944             let trace = TypeTrace {
945                 origin: origin,
946                 values: PolyTraitRefs(expected_found(a_is_expected, a.clone(), b.clone()))
947             };
948             self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
949         })
950     }
951
952     pub fn skolemize_late_bound_regions<T>(&self,
953                                            value: &ty::Binder<T>,
954                                            snapshot: &CombinedSnapshot)
955                                            -> (T, SkolemizationMap)
956         where T : TypeFoldable<'tcx>
957     {
958         /*! See `higher_ranked::skolemize_late_bound_regions` */
959
960         higher_ranked::skolemize_late_bound_regions(self, value, snapshot)
961     }
962
963     pub fn leak_check(&self,
964                       skol_map: &SkolemizationMap,
965                       snapshot: &CombinedSnapshot)
966                       -> UnitResult<'tcx>
967     {
968         /*! See `higher_ranked::leak_check` */
969
970         match higher_ranked::leak_check(self, skol_map, snapshot) {
971             Ok(()) => Ok(()),
972             Err((br, r)) => Err(TypeError::RegionsInsufficientlyPolymorphic(br, r))
973         }
974     }
975
976     pub fn plug_leaks<T>(&self,
977                          skol_map: SkolemizationMap,
978                          snapshot: &CombinedSnapshot,
979                          value: &T)
980                          -> T
981         where T : TypeFoldable<'tcx> + HasTypeFlags
982     {
983         /*! See `higher_ranked::plug_leaks` */
984
985         higher_ranked::plug_leaks(self, skol_map, snapshot, value)
986     }
987
988     pub fn equality_predicate(&self,
989                               span: Span,
990                               predicate: &ty::PolyEquatePredicate<'tcx>)
991                               -> UnitResult<'tcx> {
992         self.commit_if_ok(|snapshot| {
993             let (ty::EquatePredicate(a, b), skol_map) =
994                 self.skolemize_late_bound_regions(predicate, snapshot);
995             let origin = EquatePredicate(span);
996             let () = try!(mk_eqty(self, false, origin, a, b));
997             self.leak_check(&skol_map, snapshot)
998         })
999     }
1000
1001     pub fn region_outlives_predicate(&self,
1002                                      span: Span,
1003                                      predicate: &ty::PolyRegionOutlivesPredicate)
1004                                      -> UnitResult<'tcx> {
1005         self.commit_if_ok(|snapshot| {
1006             let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1007                 self.skolemize_late_bound_regions(predicate, snapshot);
1008             let origin = RelateRegionParamBound(span);
1009             let () = mk_subr(self, origin, r_b, r_a); // `b : a` ==> `a <= b`
1010             self.leak_check(&skol_map, snapshot)
1011         })
1012     }
1013
1014     pub fn next_ty_var_id(&self, diverging: bool) -> TyVid {
1015         self.type_variables
1016             .borrow_mut()
1017             .new_var(diverging, None)
1018     }
1019
1020     pub fn next_ty_var(&self) -> Ty<'tcx> {
1021         self.tcx.mk_var(self.next_ty_var_id(false))
1022     }
1023
1024     pub fn next_ty_var_with_default(&self,
1025                                     default: Option<type_variable::Default<'tcx>>) -> Ty<'tcx> {
1026         let ty_var_id = self.type_variables
1027                             .borrow_mut()
1028                             .new_var(false, default);
1029
1030         self.tcx.mk_var(ty_var_id)
1031     }
1032
1033     pub fn next_diverging_ty_var(&self) -> Ty<'tcx> {
1034         self.tcx.mk_var(self.next_ty_var_id(true))
1035     }
1036
1037     pub fn next_ty_vars(&self, n: usize) -> Vec<Ty<'tcx>> {
1038         (0..n).map(|_i| self.next_ty_var()).collect()
1039     }
1040
1041     pub fn next_int_var_id(&self) -> IntVid {
1042         self.int_unification_table
1043             .borrow_mut()
1044             .new_key(None)
1045     }
1046
1047     pub fn next_float_var_id(&self) -> FloatVid {
1048         self.float_unification_table
1049             .borrow_mut()
1050             .new_key(None)
1051     }
1052
1053     pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region {
1054         ty::ReVar(self.region_vars.new_region_var(origin))
1055     }
1056
1057     pub fn region_vars_for_defs(&self,
1058                                 span: Span,
1059                                 defs: &[ty::RegionParameterDef])
1060                                 -> Vec<ty::Region> {
1061         defs.iter()
1062             .map(|d| self.next_region_var(EarlyBoundRegion(span, d.name)))
1063             .collect()
1064     }
1065
1066     // We have to take `&mut Substs` in order to provide the correct substitutions for defaults
1067     // along the way, for this reason we don't return them.
1068     pub fn type_vars_for_defs(&self,
1069                               span: Span,
1070                               space: subst::ParamSpace,
1071                               substs: &mut Substs<'tcx>,
1072                               defs: &[ty::TypeParameterDef<'tcx>]) {
1073
1074         let mut vars = Vec::with_capacity(defs.len());
1075
1076         for def in defs.iter() {
1077             let default = def.default.map(|default| {
1078                 type_variable::Default {
1079                     ty: default.subst_spanned(self.tcx, substs, Some(span)),
1080                     origin_span: span,
1081                     def_id: def.default_def_id
1082                 }
1083             });
1084
1085             let ty_var = self.next_ty_var_with_default(default);
1086             substs.types.push(space, ty_var);
1087             vars.push(ty_var)
1088         }
1089     }
1090
1091     /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1092     /// type/region parameter to a fresh inference variable.
1093     pub fn fresh_substs_for_generics(&self,
1094                                      span: Span,
1095                                      generics: &ty::Generics<'tcx>)
1096                                      -> subst::Substs<'tcx>
1097     {
1098         let type_params = subst::VecPerParamSpace::empty();
1099
1100         let region_params =
1101             generics.regions.map(
1102                 |d| self.next_region_var(EarlyBoundRegion(span, d.name)));
1103
1104         let mut substs = subst::Substs::new(type_params, region_params);
1105
1106         for space in subst::ParamSpace::all().iter() {
1107             self.type_vars_for_defs(
1108                 span,
1109                 *space,
1110                 &mut substs,
1111                 generics.types.get_slice(*space));
1112         }
1113
1114         return substs;
1115     }
1116
1117     /// Given a set of generics defined on a trait, returns a substitution mapping each output
1118     /// type/region parameter to a fresh inference variable, and mapping the self type to
1119     /// `self_ty`.
1120     pub fn fresh_substs_for_trait(&self,
1121                                   span: Span,
1122                                   generics: &ty::Generics<'tcx>,
1123                                   self_ty: Ty<'tcx>)
1124                                   -> subst::Substs<'tcx>
1125     {
1126
1127         assert!(generics.types.len(subst::SelfSpace) == 1);
1128         assert!(generics.types.len(subst::FnSpace) == 0);
1129         assert!(generics.regions.len(subst::SelfSpace) == 0);
1130         assert!(generics.regions.len(subst::FnSpace) == 0);
1131
1132         let type_params = Vec::new();
1133
1134         let region_param_defs = generics.regions.get_slice(subst::TypeSpace);
1135         let regions = self.region_vars_for_defs(span, region_param_defs);
1136
1137         let mut substs = subst::Substs::new_trait(type_params, regions, self_ty);
1138
1139         let type_parameter_defs = generics.types.get_slice(subst::TypeSpace);
1140         self.type_vars_for_defs(span, subst::TypeSpace, &mut substs, type_parameter_defs);
1141
1142         return substs;
1143     }
1144
1145     pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region {
1146         self.region_vars.new_bound(debruijn)
1147     }
1148
1149     /// Apply `adjustment` to the type of `expr`
1150     pub fn adjust_expr_ty(&self,
1151                           expr: &hir::Expr,
1152                           adjustment: Option<&ty::AutoAdjustment<'tcx>>)
1153                           -> Ty<'tcx>
1154     {
1155         let raw_ty = self.expr_ty(expr);
1156         let raw_ty = self.shallow_resolve(raw_ty);
1157         let resolve_ty = |ty: Ty<'tcx>| self.resolve_type_vars_if_possible(&ty);
1158         raw_ty.adjust(self.tcx,
1159                       expr.span,
1160                       expr.id,
1161                       adjustment,
1162                       |method_call| self.tables
1163                                         .borrow()
1164                                         .method_map
1165                                         .get(&method_call)
1166                                         .map(|method| resolve_ty(method.ty)))
1167     }
1168
1169     pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1170         match self.tables.borrow().node_types.get(&id) {
1171             Some(&t) => t,
1172             // FIXME
1173             None if self.tcx.sess.err_count() - self.err_count_on_creation != 0 =>
1174                 self.tcx.types.err,
1175             None => {
1176                 self.tcx.sess.bug(
1177                     &format!("no type for node {}: {} in fcx",
1178                             id, self.tcx.map.node_to_string(id)));
1179             }
1180         }
1181     }
1182
1183     pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1184         match self.tables.borrow().node_types.get(&ex.id) {
1185             Some(&t) => t,
1186             None => {
1187                 self.tcx.sess.bug(&format!("no type for expr in fcx"));
1188             }
1189         }
1190     }
1191
1192     pub fn resolve_regions_and_report_errors(&self,
1193                                              free_regions: &FreeRegionMap,
1194                                              subject_node_id: ast::NodeId) {
1195         let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1196         self.report_region_errors(&errors); // see error_reporting.rs
1197     }
1198
1199     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1200         self.resolve_type_vars_if_possible(&t).to_string()
1201     }
1202
1203     pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1204         let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1205         format!("({})", tstrs.join(", "))
1206     }
1207
1208     pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1209         self.resolve_type_vars_if_possible(t).to_string()
1210     }
1211
1212     pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1213         match typ.sty {
1214             ty::TyInfer(ty::TyVar(v)) => {
1215                 // Not entirely obvious: if `typ` is a type variable,
1216                 // it can be resolved to an int/float variable, which
1217                 // can then be recursively resolved, hence the
1218                 // recursion. Note though that we prevent type
1219                 // variables from unifying to other type variables
1220                 // directly (though they may be embedded
1221                 // structurally), and we prevent cycles in any case,
1222                 // so this recursion should always be of very limited
1223                 // depth.
1224                 self.type_variables.borrow()
1225                     .probe(v)
1226                     .map(|t| self.shallow_resolve(t))
1227                     .unwrap_or(typ)
1228             }
1229
1230             ty::TyInfer(ty::IntVar(v)) => {
1231                 self.int_unification_table
1232                     .borrow_mut()
1233                     .probe(v)
1234                     .map(|v| v.to_type(self.tcx))
1235                     .unwrap_or(typ)
1236             }
1237
1238             ty::TyInfer(ty::FloatVar(v)) => {
1239                 self.float_unification_table
1240                     .borrow_mut()
1241                     .probe(v)
1242                     .map(|v| v.to_type(self.tcx))
1243                     .unwrap_or(typ)
1244             }
1245
1246             _ => {
1247                 typ
1248             }
1249         }
1250     }
1251
1252     pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1253         where T: TypeFoldable<'tcx> + HasTypeFlags
1254     {
1255         /*!
1256          * Where possible, replaces type/int/float variables in
1257          * `value` with their final value. Note that region variables
1258          * are unaffected. If a type variable has not been unified, it
1259          * is left as is.  This is an idempotent operation that does
1260          * not affect inference state in any way and so you can do it
1261          * at will.
1262          */
1263
1264         if !value.needs_infer() {
1265             return value.clone(); // avoid duplicated subst-folding
1266         }
1267         let mut r = resolve::OpportunisticTypeResolver::new(self);
1268         value.fold_with(&mut r)
1269     }
1270
1271     /// Resolves all type variables in `t` and then, if any were left
1272     /// unresolved, substitutes an error type. This is used after the
1273     /// main checking when doing a second pass before writeback. The
1274     /// justification is that writeback will produce an error for
1275     /// these unconstrained type variables.
1276     fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1277         let ty = self.resolve_type_vars_if_possible(t);
1278         if ty.references_error() || ty.is_ty_var() {
1279             debug!("resolve_type_vars_or_error: error from {:?}", ty);
1280             Err(())
1281         } else {
1282             Ok(ty)
1283         }
1284     }
1285
1286     pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1287         /*!
1288          * Attempts to resolve all type/region variables in
1289          * `value`. Region inference must have been run already (e.g.,
1290          * by calling `resolve_regions_and_report_errors`).  If some
1291          * variable was never unified, an `Err` results.
1292          *
1293          * This method is idempotent, but it not typically not invoked
1294          * except during the writeback phase.
1295          */
1296
1297         resolve::fully_resolve(self, value)
1298     }
1299
1300     // [Note-Type-error-reporting]
1301     // An invariant is that anytime the expected or actual type is TyError (the special
1302     // error type, meaning that an error occurred when typechecking this expression),
1303     // this is a derived error. The error cascaded from another error (that was already
1304     // reported), so it's not useful to display it to the user.
1305     // The following four methods -- type_error_message_str, type_error_message_str_with_expected,
1306     // type_error_message, and report_mismatched_types -- implement this logic.
1307     // They check if either the actual or expected type is TyError, and don't print the error
1308     // in this case. The typechecker should only ever report type errors involving mismatched
1309     // types using one of these four methods, and should not call span_err directly for such
1310     // errors.
1311     pub fn type_error_message_str<M>(&self,
1312                                      sp: Span,
1313                                      mk_msg: M,
1314                                      actual_ty: String,
1315                                      err: Option<&ty::TypeError<'tcx>>) where
1316         M: FnOnce(Option<String>, String) -> String,
1317     {
1318         self.type_error_message_str_with_expected(sp, mk_msg, None, actual_ty, err)
1319     }
1320
1321     pub fn type_error_message_str_with_expected<M>(&self,
1322                                                    sp: Span,
1323                                                    mk_msg: M,
1324                                                    expected_ty: Option<Ty<'tcx>>,
1325                                                    actual_ty: String,
1326                                                    err: Option<&ty::TypeError<'tcx>>) where
1327         M: FnOnce(Option<String>, String) -> String,
1328     {
1329         debug!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty, actual_ty);
1330
1331         let resolved_expected = expected_ty.map(|e_ty| self.resolve_type_vars_if_possible(&e_ty));
1332
1333         if !resolved_expected.references_error() {
1334             let error_str = err.map_or("".to_string(), |t_err| {
1335                 format!(" ({})", t_err)
1336             });
1337
1338             self.tcx.sess.span_err(sp, &format!("{}{}",
1339                 mk_msg(resolved_expected.map(|t| self.ty_to_string(t)), actual_ty),
1340                 error_str));
1341
1342             if let Some(err) = err {
1343                 self.tcx.note_and_explain_type_err(err, sp)
1344             }
1345         }
1346     }
1347
1348     pub fn type_error_message<M>(&self,
1349                                  sp: Span,
1350                                  mk_msg: M,
1351                                  actual_ty: Ty<'tcx>,
1352                                  err: Option<&ty::TypeError<'tcx>>) where
1353         M: FnOnce(String) -> String,
1354     {
1355         let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1356
1357         // Don't report an error if actual type is TyError.
1358         if actual_ty.references_error() {
1359             return;
1360         }
1361
1362         self.type_error_message_str(sp,
1363             move |_e, a| { mk_msg(a) },
1364             self.ty_to_string(actual_ty), err);
1365     }
1366
1367     pub fn report_mismatched_types(&self,
1368                                    span: Span,
1369                                    expected: Ty<'tcx>,
1370                                    actual: Ty<'tcx>,
1371                                    err: &ty::TypeError<'tcx>) {
1372         let trace = TypeTrace {
1373             origin: Misc(span),
1374             values: Types(ty::ExpectedFound {
1375                 expected: expected,
1376                 found: actual
1377             })
1378         };
1379         self.report_and_explain_type_error(trace, err);
1380     }
1381
1382     pub fn report_conflicting_default_types(&self,
1383                                             span: Span,
1384                                             expected: type_variable::Default<'tcx>,
1385                                             actual: type_variable::Default<'tcx>) {
1386         let trace = TypeTrace {
1387             origin: Misc(span),
1388             values: Types(ty::ExpectedFound {
1389                 expected: expected.ty,
1390                 found: actual.ty
1391             })
1392         };
1393
1394         self.report_and_explain_type_error(trace,
1395             &TypeError::TyParamDefaultMismatch(ty::ExpectedFound {
1396                 expected: expected,
1397                 found: actual
1398         }));
1399     }
1400
1401     pub fn replace_late_bound_regions_with_fresh_var<T>(
1402         &self,
1403         span: Span,
1404         lbrct: LateBoundRegionConversionTime,
1405         value: &ty::Binder<T>)
1406         -> (T, FnvHashMap<ty::BoundRegion,ty::Region>)
1407         where T : TypeFoldable<'tcx>
1408     {
1409         ty::fold::replace_late_bound_regions(
1410             self.tcx,
1411             value,
1412             |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1413     }
1414
1415     /// See `verify_generic_bound` method in `region_inference`
1416     pub fn verify_generic_bound(&self,
1417                                 origin: SubregionOrigin<'tcx>,
1418                                 kind: GenericKind<'tcx>,
1419                                 a: ty::Region,
1420                                 bound: VerifyBound) {
1421         debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1422                kind,
1423                a,
1424                bound);
1425
1426         self.region_vars.verify_generic_bound(origin, kind, a, bound);
1427     }
1428
1429     pub fn can_equate<'b,T>(&'b self, a: &T, b: &T) -> UnitResult<'tcx>
1430         where T: Relate<'b,'tcx> + fmt::Debug
1431     {
1432         debug!("can_equate({:?}, {:?})", a, b);
1433         self.probe(|_| {
1434             // Gin up a dummy trace, since this won't be committed
1435             // anyhow. We should make this typetrace stuff more
1436             // generic so we don't have to do anything quite this
1437             // terrible.
1438             let e = self.tcx.types.err;
1439             let trace = TypeTrace { origin: Misc(codemap::DUMMY_SP),
1440                                     values: Types(expected_found(true, e, e)) };
1441             self.equate(true, trace).relate(a, b)
1442         }).map(|_| ())
1443     }
1444
1445     pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1446         let ty = self.node_type(id);
1447         self.resolve_type_vars_or_error(&ty)
1448     }
1449
1450     pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1451         let ty = self.adjust_expr_ty(expr, self.tables.borrow().adjustments.get(&expr.id));
1452         self.resolve_type_vars_or_error(&ty)
1453     }
1454
1455     pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1456         let ty = self.resolve_type_vars_if_possible(&ty);
1457         if ty.needs_infer() {
1458             // this can get called from typeck (by euv), and moves_by_default
1459             // rightly refuses to work with inference variables, but
1460             // moves_by_default has a cache, which we want to use in other
1461             // cases.
1462             !traits::type_known_to_meet_builtin_bound(self, ty, ty::BoundCopy, span)
1463         } else {
1464             ty.moves_by_default(&self.parameter_environment, span)
1465         }
1466     }
1467
1468     pub fn node_method_ty(&self, method_call: ty::MethodCall)
1469                           -> Option<Ty<'tcx>> {
1470         self.tables
1471             .borrow()
1472             .method_map
1473             .get(&method_call)
1474             .map(|method| method.ty)
1475             .map(|ty| self.resolve_type_vars_if_possible(&ty))
1476     }
1477
1478     pub fn node_method_id(&self, method_call: ty::MethodCall)
1479                           -> Option<DefId> {
1480         self.tables
1481             .borrow()
1482             .method_map
1483             .get(&method_call)
1484             .map(|method| method.def_id)
1485     }
1486
1487     pub fn adjustments(&self) -> Ref<NodeMap<ty::AutoAdjustment<'tcx>>> {
1488         fn project_adjustments<'a, 'tcx>(tables: &'a ty::Tables<'tcx>)
1489                                         -> &'a NodeMap<ty::AutoAdjustment<'tcx>> {
1490             &tables.adjustments
1491         }
1492
1493         Ref::map(self.tables.borrow(), project_adjustments)
1494     }
1495
1496     pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1497         self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1498     }
1499
1500     pub fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<CodeExtent> {
1501         self.tcx.region_maps.temporary_scope(rvalue_id)
1502     }
1503
1504     pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
1505         self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1506     }
1507
1508     pub fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
1509         &self.parameter_environment
1510     }
1511
1512     pub fn closure_kind(&self,
1513                         def_id: DefId)
1514                         -> Option<ty::ClosureKind>
1515     {
1516         self.tables.borrow().closure_kinds.get(&def_id).cloned()
1517     }
1518
1519     pub fn closure_type(&self,
1520                         def_id: DefId,
1521                         substs: &ty::ClosureSubsts<'tcx>)
1522                         -> ty::ClosureTy<'tcx>
1523     {
1524         let closure_ty = self.tables
1525                              .borrow()
1526                              .closure_tys
1527                              .get(&def_id)
1528                              .unwrap()
1529                              .subst(self.tcx, &substs.func_substs);
1530
1531         if self.normalize {
1532             normalize_associated_type(&self.tcx, &closure_ty)
1533         } else {
1534             closure_ty
1535         }
1536     }
1537 }
1538
1539 impl<'tcx> TypeTrace<'tcx> {
1540     pub fn span(&self) -> Span {
1541         self.origin.span()
1542     }
1543
1544     pub fn types(origin: TypeOrigin,
1545                  a_is_expected: bool,
1546                  a: Ty<'tcx>,
1547                  b: Ty<'tcx>)
1548                  -> TypeTrace<'tcx> {
1549         TypeTrace {
1550             origin: origin,
1551             values: Types(expected_found(a_is_expected, a, b))
1552         }
1553     }
1554
1555     pub fn dummy(tcx: &ty::ctxt<'tcx>) -> TypeTrace<'tcx> {
1556         TypeTrace {
1557             origin: Misc(codemap::DUMMY_SP),
1558             values: Types(ty::ExpectedFound {
1559                 expected: tcx.types.err,
1560                 found: tcx.types.err,
1561             })
1562         }
1563     }
1564 }
1565
1566 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1567     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1568         write!(f, "TypeTrace({:?})", self.origin)
1569     }
1570 }
1571
1572 impl TypeOrigin {
1573     pub fn span(&self) -> Span {
1574         match *self {
1575             MethodCompatCheck(span) => span,
1576             ExprAssignable(span) => span,
1577             Misc(span) => span,
1578             RelateTraitRefs(span) => span,
1579             RelateSelfType(span) => span,
1580             RelateOutputImplTypes(span) => span,
1581             MatchExpressionArm(match_span, _) => match_span,
1582             IfExpression(span) => span,
1583             IfExpressionWithNoElse(span) => span,
1584             RangeExpression(span) => span,
1585             EquatePredicate(span) => span,
1586         }
1587     }
1588 }
1589
1590 impl<'tcx> SubregionOrigin<'tcx> {
1591     pub fn span(&self) -> Span {
1592         match *self {
1593             RFC1214Subregion(ref a) => a.span(),
1594             Subtype(ref a) => a.span(),
1595             InfStackClosure(a) => a,
1596             InvokeClosure(a) => a,
1597             DerefPointer(a) => a,
1598             FreeVariable(a, _) => a,
1599             IndexSlice(a) => a,
1600             RelateObjectBound(a) => a,
1601             RelateParamBound(a, _) => a,
1602             RelateRegionParamBound(a) => a,
1603             RelateDefaultParamBound(a, _) => a,
1604             Reborrow(a) => a,
1605             ReborrowUpvar(a, _) => a,
1606             DataBorrowed(_, a) => a,
1607             ReferenceOutlivesReferent(_, a) => a,
1608             ParameterInScope(_, a) => a,
1609             ExprTypeIsNotInScope(_, a) => a,
1610             BindingTypeIsNotValidAtDecl(a) => a,
1611             CallRcvr(a) => a,
1612             CallArg(a) => a,
1613             CallReturn(a) => a,
1614             Operand(a) => a,
1615             AddrOf(a) => a,
1616             AutoBorrow(a) => a,
1617             SafeDestructor(a) => a,
1618         }
1619     }
1620 }
1621
1622 impl RegionVariableOrigin {
1623     pub fn span(&self) -> Span {
1624         match *self {
1625             MiscVariable(a) => a,
1626             PatternRegion(a) => a,
1627             AddrOfRegion(a) => a,
1628             Autoref(a) => a,
1629             Coercion(a) => a,
1630             EarlyBoundRegion(a, _) => a,
1631             LateBoundRegion(a, _, _) => a,
1632             BoundRegionInCoherence(_) => codemap::DUMMY_SP,
1633             UpvarRegion(_, a) => a
1634         }
1635     }
1636 }