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