]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/infer/mod.rs
Change some instances of .connect() to .join()
[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 #![allow(non_camel_case_types)]
14
15 pub use self::LateBoundRegionConversionTime::*;
16 pub use self::RegionVariableOrigin::*;
17 pub use self::SubregionOrigin::*;
18 pub use self::TypeOrigin::*;
19 pub use self::ValuePairs::*;
20 pub use self::fixup_err::*;
21 pub use middle::ty::IntVarValue;
22 pub use self::freshen::TypeFreshener;
23 pub use self::region_inference::GenericKind;
24
25 use middle::free_region::FreeRegionMap;
26 use middle::mem_categorization as mc;
27 use middle::mem_categorization::McResult;
28 use middle::region::CodeExtent;
29 use middle::subst;
30 use middle::subst::Substs;
31 use middle::subst::Subst;
32 use middle::traits::{self, FulfillmentContext, Normalized,
33                      SelectionContext, ObligationCause};
34 use middle::ty::{TyVid, IntVid, FloatVid, RegionVid, UnconstrainedNumeric};
35 use middle::ty::{self, Ty, HasTypeFlags};
36 use middle::ty_fold::{self, TypeFolder, TypeFoldable};
37 use middle::ty_relate::{Relate, RelateResult, TypeRelation};
38 use rustc_data_structures::unify::{self, UnificationTable};
39 use std::cell::{RefCell, Ref};
40 use std::fmt;
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 fres<T> = Result<T, fixup_err>; // "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::expected_found<Ty<'tcx>>),
175     TraitRefs(ty::expected_found<ty::TraitRef<'tcx>>),
176     PolyTraitRefs(ty::expected_found<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     // Arose from a subtyping relation
198     DefaultExistentialBound(TypeTrace<'tcx>),
199
200     // Stack-allocated closures cannot outlive innermost loop
201     // or function so as to ensure we only require finite stack
202     InfStackClosure(Span),
203
204     // Invocation of closure must be within its lifetime
205     InvokeClosure(Span),
206
207     // Dereference of reference must be within its lifetime
208     DerefPointer(Span),
209
210     // Closure bound must not outlive captured free variables
211     FreeVariable(Span, ast::NodeId),
212
213     // Index into slice must be within its lifetime
214     IndexSlice(Span),
215
216     // When casting `&'a T` to an `&'b Trait` object,
217     // relating `'a` to `'b`
218     RelateObjectBound(Span),
219
220     // Some type parameter was instantiated with the given type,
221     // and that type must outlive some region.
222     RelateParamBound(Span, Ty<'tcx>),
223
224     // The given region parameter was instantiated with a region
225     // that must outlive some other region.
226     RelateRegionParamBound(Span),
227
228     // A bound placed on type parameters that states that must outlive
229     // the moment of their instantiation.
230     RelateDefaultParamBound(Span, Ty<'tcx>),
231
232     // Creating a pointer `b` to contents of another reference
233     Reborrow(Span),
234
235     // Creating a pointer `b` to contents of an upvar
236     ReborrowUpvar(Span, ty::UpvarId),
237
238     // (&'a &'b T) where a >= b
239     ReferenceOutlivesReferent(Ty<'tcx>, Span),
240
241     // The type T of an expression E must outlive the lifetime for E.
242     ExprTypeIsNotInScope(Ty<'tcx>, Span),
243
244     // A `ref b` whose region does not enclose the decl site
245     BindingTypeIsNotValidAtDecl(Span),
246
247     // Regions appearing in a method receiver must outlive method call
248     CallRcvr(Span),
249
250     // Regions appearing in a function argument must outlive func call
251     CallArg(Span),
252
253     // Region in return type of invoked fn must enclose call
254     CallReturn(Span),
255
256     // Operands must be in scope
257     Operand(Span),
258
259     // Region resulting from a `&` expr must enclose the `&` expr
260     AddrOf(Span),
261
262     // An auto-borrow that does not enclose the expr where it occurs
263     AutoBorrow(Span),
264
265     // Region constraint arriving from destructor safety
266     SafeDestructor(Span),
267 }
268
269 /// Times when we replace late-bound regions with variables:
270 #[derive(Clone, Copy, Debug)]
271 pub enum LateBoundRegionConversionTime {
272     /// when a fn is called
273     FnCall,
274
275     /// when two higher-ranked types are compared
276     HigherRankedType,
277
278     /// when projecting an associated type
279     AssocTypeProjection(ast::Name),
280 }
281
282 /// Reasons to create a region inference variable
283 ///
284 /// See `error_reporting.rs` for more details
285 #[derive(Clone, Debug)]
286 pub enum RegionVariableOrigin {
287     // Region variables created for ill-categorized reasons,
288     // mostly indicates places in need of refactoring
289     MiscVariable(Span),
290
291     // Regions created by a `&P` or `[...]` pattern
292     PatternRegion(Span),
293
294     // Regions created by `&` operator
295     AddrOfRegion(Span),
296
297     // Regions created as part of an autoref of a method receiver
298     Autoref(Span),
299
300     // Regions created as part of an automatic coercion
301     Coercion(Span),
302
303     // Region variables created as the values for early-bound regions
304     EarlyBoundRegion(Span, ast::Name),
305
306     // Region variables created for bound regions
307     // in a function or method that is called
308     LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
309
310     UpvarRegion(ty::UpvarId, Span),
311
312     BoundRegionInCoherence(ast::Name),
313 }
314
315 #[derive(Copy, Clone, Debug)]
316 pub enum fixup_err {
317     unresolved_int_ty(IntVid),
318     unresolved_float_ty(FloatVid),
319     unresolved_ty(TyVid)
320 }
321
322 pub fn fixup_err_to_string(f: fixup_err) -> String {
323     match f {
324       unresolved_int_ty(_) => {
325           "cannot determine the type of this integer; add a suffix to \
326            specify the type explicitly".to_string()
327       }
328       unresolved_float_ty(_) => {
329           "cannot determine the type of this number; add a suffix to specify \
330            the type explicitly".to_string()
331       }
332       unresolved_ty(_) => "unconstrained type".to_string(),
333     }
334 }
335
336 /// errors_will_be_reported is required to proxy to the fulfillment context
337 /// FIXME -- a better option would be to hold back on modifying
338 /// the global cache until we know that all dependent obligations
339 /// are also satisfied. In that case, we could actually remove
340 /// this boolean flag, and we'd also avoid the problem of squelching
341 /// duplicate errors that occur across fns.
342 pub fn new_infer_ctxt<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
343                                 tables: &'a RefCell<ty::Tables<'tcx>>,
344                                 param_env: Option<ty::ParameterEnvironment<'a, 'tcx>>,
345                                 errors_will_be_reported: bool)
346                                 -> InferCtxt<'a, 'tcx> {
347     InferCtxt {
348         tcx: tcx,
349         tables: tables,
350         type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
351         int_unification_table: RefCell::new(UnificationTable::new()),
352         float_unification_table: RefCell::new(UnificationTable::new()),
353         region_vars: RegionVarBindings::new(tcx),
354         parameter_environment: param_env.unwrap_or(tcx.empty_parameter_environment()),
355         fulfillment_cx: RefCell::new(traits::FulfillmentContext::new(errors_will_be_reported)),
356         normalize: false,
357         err_count_on_creation: tcx.sess.err_count()
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::expected_found<T>
464 {
465     if a_is_expected {
466         ty::expected_found {expected: a, found: b}
467     } else {
468         ty::expected_found {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     fn combine_fields(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
661                       -> CombineFields<'a, 'tcx> {
662         CombineFields {infcx: self,
663                        a_is_expected: a_is_expected,
664                        trace: trace,
665                        cause: None}
666     }
667
668     // public so that it can be used from the rustc_driver unit tests
669     pub fn equate(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
670               -> equate::Equate<'a, 'tcx>
671     {
672         self.combine_fields(a_is_expected, trace).equate()
673     }
674
675     // public so that it can be used from the rustc_driver unit tests
676     pub fn sub(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
677                -> sub::Sub<'a, 'tcx>
678     {
679         self.combine_fields(a_is_expected, trace).sub()
680     }
681
682     // public so that it can be used from the rustc_driver unit tests
683     pub fn lub(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
684                -> lub::Lub<'a, 'tcx>
685     {
686         self.combine_fields(a_is_expected, trace).lub()
687     }
688
689     // public so that it can be used from the rustc_driver unit tests
690     pub fn glb(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>)
691                -> glb::Glb<'a, 'tcx>
692     {
693         self.combine_fields(a_is_expected, trace).glb()
694     }
695
696     fn start_snapshot(&self) -> CombinedSnapshot {
697         CombinedSnapshot {
698             type_snapshot: self.type_variables.borrow_mut().snapshot(),
699             int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
700             float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
701             region_vars_snapshot: self.region_vars.start_snapshot(),
702         }
703     }
704
705     fn rollback_to(&self, snapshot: CombinedSnapshot) {
706         debug!("rollback!");
707         let CombinedSnapshot { type_snapshot,
708                                int_snapshot,
709                                float_snapshot,
710                                region_vars_snapshot } = snapshot;
711
712         self.type_variables
713             .borrow_mut()
714             .rollback_to(type_snapshot);
715         self.int_unification_table
716             .borrow_mut()
717             .rollback_to(int_snapshot);
718         self.float_unification_table
719             .borrow_mut()
720             .rollback_to(float_snapshot);
721         self.region_vars
722             .rollback_to(region_vars_snapshot);
723     }
724
725     fn commit_from(&self, snapshot: CombinedSnapshot) {
726         debug!("commit_from!");
727         let CombinedSnapshot { type_snapshot,
728                                int_snapshot,
729                                float_snapshot,
730                                region_vars_snapshot } = snapshot;
731
732         self.type_variables
733             .borrow_mut()
734             .commit(type_snapshot);
735         self.int_unification_table
736             .borrow_mut()
737             .commit(int_snapshot);
738         self.float_unification_table
739             .borrow_mut()
740             .commit(float_snapshot);
741         self.region_vars
742             .commit(region_vars_snapshot);
743     }
744
745     /// Execute `f` and commit the bindings
746     pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
747         F: FnOnce() -> R,
748     {
749         debug!("commit()");
750         let snapshot = self.start_snapshot();
751         let r = f();
752         self.commit_from(snapshot);
753         r
754     }
755
756     /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
757     pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
758         F: FnOnce(&CombinedSnapshot) -> Result<T, E>
759     {
760         debug!("commit_if_ok()");
761         let snapshot = self.start_snapshot();
762         let r = f(&snapshot);
763         debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
764         match r {
765             Ok(_) => { self.commit_from(snapshot); }
766             Err(_) => { self.rollback_to(snapshot); }
767         }
768         r
769     }
770
771     /// Execute `f` and commit only the region bindings if successful.
772     /// The function f must be very careful not to leak any non-region
773     /// variables that get created.
774     pub fn commit_regions_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
775         F: FnOnce() -> Result<T, E>
776     {
777         debug!("commit_regions_if_ok()");
778         let CombinedSnapshot { type_snapshot,
779                                int_snapshot,
780                                float_snapshot,
781                                region_vars_snapshot } = self.start_snapshot();
782
783         let r = self.commit_if_ok(|_| f());
784
785         // Roll back any non-region bindings - they should be resolved
786         // inside `f`, with, e.g. `resolve_type_vars_if_possible`.
787         self.type_variables
788             .borrow_mut()
789             .rollback_to(type_snapshot);
790         self.int_unification_table
791             .borrow_mut()
792             .rollback_to(int_snapshot);
793         self.float_unification_table
794             .borrow_mut()
795             .rollback_to(float_snapshot);
796
797         // Commit region vars that may escape through resolved types.
798         self.region_vars
799             .commit(region_vars_snapshot);
800
801         r
802     }
803
804     /// Execute `f` then unroll any bindings it creates
805     pub fn probe<R, F>(&self, f: F) -> R where
806         F: FnOnce(&CombinedSnapshot) -> R,
807     {
808         debug!("probe()");
809         let snapshot = self.start_snapshot();
810         let r = f(&snapshot);
811         self.rollback_to(snapshot);
812         r
813     }
814
815     pub fn add_given(&self,
816                      sub: ty::FreeRegion,
817                      sup: ty::RegionVid)
818     {
819         self.region_vars.add_given(sub, sup);
820     }
821
822     pub fn sub_types(&self,
823                      a_is_expected: bool,
824                      origin: TypeOrigin,
825                      a: Ty<'tcx>,
826                      b: Ty<'tcx>)
827                      -> UnitResult<'tcx>
828     {
829         debug!("sub_types({:?} <: {:?})", a, b);
830         self.commit_if_ok(|_| {
831             let trace = TypeTrace::types(origin, a_is_expected, a, b);
832             self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
833         })
834     }
835
836     pub fn eq_types(&self,
837                     a_is_expected: bool,
838                     origin: TypeOrigin,
839                     a: Ty<'tcx>,
840                     b: Ty<'tcx>)
841                     -> UnitResult<'tcx>
842     {
843         self.commit_if_ok(|_| {
844             let trace = TypeTrace::types(origin, a_is_expected, a, b);
845             self.equate(a_is_expected, trace).relate(&a, &b).map(|_| ())
846         })
847     }
848
849     pub fn sub_trait_refs(&self,
850                           a_is_expected: bool,
851                           origin: TypeOrigin,
852                           a: ty::TraitRef<'tcx>,
853                           b: ty::TraitRef<'tcx>)
854                           -> UnitResult<'tcx>
855     {
856         debug!("sub_trait_refs({:?} <: {:?})",
857                a,
858                b);
859         self.commit_if_ok(|_| {
860             let trace = TypeTrace {
861                 origin: origin,
862                 values: TraitRefs(expected_found(a_is_expected, a.clone(), b.clone()))
863             };
864             self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
865         })
866     }
867
868     pub fn sub_poly_trait_refs(&self,
869                                a_is_expected: bool,
870                                origin: TypeOrigin,
871                                a: ty::PolyTraitRef<'tcx>,
872                                b: ty::PolyTraitRef<'tcx>)
873                                -> UnitResult<'tcx>
874     {
875         debug!("sub_poly_trait_refs({:?} <: {:?})",
876                a,
877                b);
878         self.commit_if_ok(|_| {
879             let trace = TypeTrace {
880                 origin: origin,
881                 values: PolyTraitRefs(expected_found(a_is_expected, a.clone(), b.clone()))
882             };
883             self.sub(a_is_expected, trace).relate(&a, &b).map(|_| ())
884         })
885     }
886
887     pub fn construct_skolemized_subst(&self,
888                                       generics: &ty::Generics<'tcx>,
889                                       snapshot: &CombinedSnapshot)
890                                       -> (subst::Substs<'tcx>, SkolemizationMap) {
891         /*! See `higher_ranked::construct_skolemized_subst` */
892
893         higher_ranked::construct_skolemized_substs(self, generics, snapshot)
894     }
895
896     pub fn skolemize_late_bound_regions<T>(&self,
897                                            value: &ty::Binder<T>,
898                                            snapshot: &CombinedSnapshot)
899                                            -> (T, SkolemizationMap)
900         where T : TypeFoldable<'tcx>
901     {
902         /*! See `higher_ranked::skolemize_late_bound_regions` */
903
904         higher_ranked::skolemize_late_bound_regions(self, value, snapshot)
905     }
906
907     pub fn leak_check(&self,
908                       skol_map: &SkolemizationMap,
909                       snapshot: &CombinedSnapshot)
910                       -> UnitResult<'tcx>
911     {
912         /*! See `higher_ranked::leak_check` */
913
914         match higher_ranked::leak_check(self, skol_map, snapshot) {
915             Ok(()) => Ok(()),
916             Err((br, r)) => Err(ty::terr_regions_insufficiently_polymorphic(br, r))
917         }
918     }
919
920     pub fn plug_leaks<T>(&self,
921                          skol_map: SkolemizationMap,
922                          snapshot: &CombinedSnapshot,
923                          value: &T)
924                          -> T
925         where T : TypeFoldable<'tcx>
926     {
927         /*! See `higher_ranked::plug_leaks` */
928
929         higher_ranked::plug_leaks(self, skol_map, snapshot, value)
930     }
931
932     pub fn equality_predicate(&self,
933                               span: Span,
934                               predicate: &ty::PolyEquatePredicate<'tcx>)
935                               -> UnitResult<'tcx> {
936         self.commit_if_ok(|snapshot| {
937             let (ty::EquatePredicate(a, b), skol_map) =
938                 self.skolemize_late_bound_regions(predicate, snapshot);
939             let origin = EquatePredicate(span);
940             let () = try!(mk_eqty(self, false, origin, a, b));
941             self.leak_check(&skol_map, snapshot)
942         })
943     }
944
945     pub fn region_outlives_predicate(&self,
946                                      span: Span,
947                                      predicate: &ty::PolyRegionOutlivesPredicate)
948                                      -> UnitResult<'tcx> {
949         self.commit_if_ok(|snapshot| {
950             let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
951                 self.skolemize_late_bound_regions(predicate, snapshot);
952             let origin = RelateRegionParamBound(span);
953             let () = mk_subr(self, origin, r_b, r_a); // `b : a` ==> `a <= b`
954             self.leak_check(&skol_map, snapshot)
955         })
956     }
957
958     pub fn next_ty_var_id(&self, diverging: bool) -> TyVid {
959         self.type_variables
960             .borrow_mut()
961             .new_var(diverging)
962     }
963
964     pub fn next_ty_var(&self) -> Ty<'tcx> {
965         self.tcx.mk_var(self.next_ty_var_id(false))
966     }
967
968     pub fn next_diverging_ty_var(&self) -> Ty<'tcx> {
969         self.tcx.mk_var(self.next_ty_var_id(true))
970     }
971
972     pub fn next_ty_vars(&self, n: usize) -> Vec<Ty<'tcx>> {
973         (0..n).map(|_i| self.next_ty_var()).collect()
974     }
975
976     pub fn next_int_var_id(&self) -> IntVid {
977         self.int_unification_table
978             .borrow_mut()
979             .new_key(None)
980     }
981
982     pub fn next_float_var_id(&self) -> FloatVid {
983         self.float_unification_table
984             .borrow_mut()
985             .new_key(None)
986     }
987
988     pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region {
989         ty::ReInfer(ty::ReVar(self.region_vars.new_region_var(origin)))
990     }
991
992     pub fn region_vars_for_defs(&self,
993                                 span: Span,
994                                 defs: &[ty::RegionParameterDef])
995                                 -> Vec<ty::Region> {
996         defs.iter()
997             .map(|d| self.next_region_var(EarlyBoundRegion(span, d.name)))
998             .collect()
999     }
1000
1001     /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1002     /// type/region parameter to a fresh inference variable.
1003     pub fn fresh_substs_for_generics(&self,
1004                                      span: Span,
1005                                      generics: &ty::Generics<'tcx>)
1006                                      -> subst::Substs<'tcx>
1007     {
1008         let type_params =
1009             generics.types.map(
1010                 |_| self.next_ty_var());
1011         let region_params =
1012             generics.regions.map(
1013                 |d| self.next_region_var(EarlyBoundRegion(span, d.name)));
1014         subst::Substs::new(type_params, region_params)
1015     }
1016
1017     /// Given a set of generics defined on a trait, returns a substitution mapping each output
1018     /// type/region parameter to a fresh inference variable, and mapping the self type to
1019     /// `self_ty`.
1020     pub fn fresh_substs_for_trait(&self,
1021                                   span: Span,
1022                                   generics: &ty::Generics<'tcx>,
1023                                   self_ty: Ty<'tcx>)
1024                                   -> subst::Substs<'tcx>
1025     {
1026
1027         assert!(generics.types.len(subst::SelfSpace) == 1);
1028         assert!(generics.types.len(subst::FnSpace) == 0);
1029         assert!(generics.regions.len(subst::SelfSpace) == 0);
1030         assert!(generics.regions.len(subst::FnSpace) == 0);
1031
1032         let type_parameter_count = generics.types.len(subst::TypeSpace);
1033         let type_parameters = self.next_ty_vars(type_parameter_count);
1034
1035         let region_param_defs = generics.regions.get_slice(subst::TypeSpace);
1036         let regions = self.region_vars_for_defs(span, region_param_defs);
1037
1038         subst::Substs::new_trait(type_parameters, regions, self_ty)
1039     }
1040
1041     pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> ty::Region {
1042         self.region_vars.new_bound(debruijn)
1043     }
1044
1045     /// Apply `adjustment` to the type of `expr`
1046     pub fn adjust_expr_ty(&self,
1047                           expr: &ast::Expr,
1048                           adjustment: Option<&ty::AutoAdjustment<'tcx>>)
1049                           -> Ty<'tcx>
1050     {
1051         let raw_ty = self.expr_ty(expr);
1052         let raw_ty = self.shallow_resolve(raw_ty);
1053         let resolve_ty = |ty: Ty<'tcx>| self.resolve_type_vars_if_possible(&ty);
1054         raw_ty.adjust(self.tcx,
1055                       expr.span,
1056                       expr.id,
1057                       adjustment,
1058                       |method_call| self.tables
1059                                         .borrow()
1060                                         .method_map
1061                                         .get(&method_call)
1062                                         .map(|method| resolve_ty(method.ty)))
1063     }
1064
1065     pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1066         match self.tables.borrow().node_types.get(&id) {
1067             Some(&t) => t,
1068             // FIXME
1069             None if self.tcx.sess.err_count() - self.err_count_on_creation != 0 =>
1070                 self.tcx.types.err,
1071             None => {
1072                 self.tcx.sess.bug(
1073                     &format!("no type for node {}: {} in fcx",
1074                             id, self.tcx.map.node_to_string(id)));
1075             }
1076         }
1077     }
1078
1079     pub fn expr_ty(&self, ex: &ast::Expr) -> Ty<'tcx> {
1080         match self.tables.borrow().node_types.get(&ex.id) {
1081             Some(&t) => t,
1082             None => {
1083                 self.tcx.sess.bug(&format!("no type for expr in fcx"));
1084             }
1085         }
1086     }
1087
1088     pub fn resolve_regions_and_report_errors(&self,
1089                                              free_regions: &FreeRegionMap,
1090                                              subject_node_id: ast::NodeId) {
1091         let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1092         self.report_region_errors(&errors); // see error_reporting.rs
1093     }
1094
1095     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1096         self.resolve_type_vars_if_possible(&t).to_string()
1097     }
1098
1099     pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1100         let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1101         format!("({})", tstrs.join(", "))
1102     }
1103
1104     pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1105         self.resolve_type_vars_if_possible(t).to_string()
1106     }
1107
1108     pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1109         match typ.sty {
1110             ty::TyInfer(ty::TyVar(v)) => {
1111                 // Not entirely obvious: if `typ` is a type variable,
1112                 // it can be resolved to an int/float variable, which
1113                 // can then be recursively resolved, hence the
1114                 // recursion. Note though that we prevent type
1115                 // variables from unifying to other type variables
1116                 // directly (though they may be embedded
1117                 // structurally), and we prevent cycles in any case,
1118                 // so this recursion should always be of very limited
1119                 // depth.
1120                 self.type_variables.borrow()
1121                     .probe(v)
1122                     .map(|t| self.shallow_resolve(t))
1123                     .unwrap_or(typ)
1124             }
1125
1126             ty::TyInfer(ty::IntVar(v)) => {
1127                 self.int_unification_table
1128                     .borrow_mut()
1129                     .probe(v)
1130                     .map(|v| v.to_type(self.tcx))
1131                     .unwrap_or(typ)
1132             }
1133
1134             ty::TyInfer(ty::FloatVar(v)) => {
1135                 self.float_unification_table
1136                     .borrow_mut()
1137                     .probe(v)
1138                     .map(|v| v.to_type(self.tcx))
1139                     .unwrap_or(typ)
1140             }
1141
1142             _ => {
1143                 typ
1144             }
1145         }
1146     }
1147
1148     pub fn resolve_type_vars_if_possible<T:TypeFoldable<'tcx>>(&self, value: &T) -> T {
1149         /*!
1150          * Where possible, replaces type/int/float variables in
1151          * `value` with their final value. Note that region variables
1152          * are unaffected. If a type variable has not been unified, it
1153          * is left as is.  This is an idempotent operation that does
1154          * not affect inference state in any way and so you can do it
1155          * at will.
1156          */
1157
1158         let mut r = resolve::OpportunisticTypeResolver::new(self);
1159         value.fold_with(&mut r)
1160     }
1161
1162     /// Resolves all type variables in `t` and then, if any were left
1163     /// unresolved, substitutes an error type. This is used after the
1164     /// main checking when doing a second pass before writeback. The
1165     /// justification is that writeback will produce an error for
1166     /// these unconstrained type variables.
1167     fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1168         let ty = self.resolve_type_vars_if_possible(t);
1169         if ty.has_infer_types() || ty.references_error() { Err(()) } else { Ok(ty) }
1170     }
1171
1172     pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> fres<T> {
1173         /*!
1174          * Attempts to resolve all type/region variables in
1175          * `value`. Region inference must have been run already (e.g.,
1176          * by calling `resolve_regions_and_report_errors`).  If some
1177          * variable was never unified, an `Err` results.
1178          *
1179          * This method is idempotent, but it not typically not invoked
1180          * except during the writeback phase.
1181          */
1182
1183         resolve::fully_resolve(self, value)
1184     }
1185
1186     // [Note-Type-error-reporting]
1187     // An invariant is that anytime the expected or actual type is TyError (the special
1188     // error type, meaning that an error occurred when typechecking this expression),
1189     // this is a derived error. The error cascaded from another error (that was already
1190     // reported), so it's not useful to display it to the user.
1191     // The following four methods -- type_error_message_str, type_error_message_str_with_expected,
1192     // type_error_message, and report_mismatched_types -- implement this logic.
1193     // They check if either the actual or expected type is TyError, and don't print the error
1194     // in this case. The typechecker should only ever report type errors involving mismatched
1195     // types using one of these four methods, and should not call span_err directly for such
1196     // errors.
1197     pub fn type_error_message_str<M>(&self,
1198                                      sp: Span,
1199                                      mk_msg: M,
1200                                      actual_ty: String,
1201                                      err: Option<&ty::type_err<'tcx>>) where
1202         M: FnOnce(Option<String>, String) -> String,
1203     {
1204         self.type_error_message_str_with_expected(sp, mk_msg, None, actual_ty, err)
1205     }
1206
1207     pub fn type_error_message_str_with_expected<M>(&self,
1208                                                    sp: Span,
1209                                                    mk_msg: M,
1210                                                    expected_ty: Option<Ty<'tcx>>,
1211                                                    actual_ty: String,
1212                                                    err: Option<&ty::type_err<'tcx>>) where
1213         M: FnOnce(Option<String>, String) -> String,
1214     {
1215         debug!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty, actual_ty);
1216
1217         let resolved_expected = expected_ty.map(|e_ty| self.resolve_type_vars_if_possible(&e_ty));
1218
1219         if !resolved_expected.references_error() {
1220             let error_str = err.map_or("".to_string(), |t_err| {
1221                 format!(" ({})", t_err)
1222             });
1223
1224             self.tcx.sess.span_err(sp, &format!("{}{}",
1225                 mk_msg(resolved_expected.map(|t| self.ty_to_string(t)), actual_ty),
1226                 error_str));
1227
1228             if let Some(err) = err {
1229                 self.tcx.note_and_explain_type_err(err, sp)
1230             }
1231         }
1232     }
1233
1234     pub fn type_error_message<M>(&self,
1235                                  sp: Span,
1236                                  mk_msg: M,
1237                                  actual_ty: Ty<'tcx>,
1238                                  err: Option<&ty::type_err<'tcx>>) where
1239         M: FnOnce(String) -> String,
1240     {
1241         let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1242
1243         // Don't report an error if actual type is TyError.
1244         if actual_ty.references_error() {
1245             return;
1246         }
1247
1248         self.type_error_message_str(sp,
1249             move |_e, a| { mk_msg(a) },
1250             self.ty_to_string(actual_ty), err);
1251     }
1252
1253     pub fn report_mismatched_types(&self,
1254                                    span: Span,
1255                                    expected: Ty<'tcx>,
1256                                    actual: Ty<'tcx>,
1257                                    err: &ty::type_err<'tcx>) {
1258         let trace = TypeTrace {
1259             origin: Misc(span),
1260             values: Types(ty::expected_found {
1261                 expected: expected,
1262                 found: actual
1263             })
1264         };
1265         self.report_and_explain_type_error(trace, err);
1266     }
1267
1268     pub fn replace_late_bound_regions_with_fresh_var<T>(
1269         &self,
1270         span: Span,
1271         lbrct: LateBoundRegionConversionTime,
1272         value: &ty::Binder<T>)
1273         -> (T, FnvHashMap<ty::BoundRegion,ty::Region>)
1274         where T : TypeFoldable<'tcx>
1275     {
1276         ty_fold::replace_late_bound_regions(
1277             self.tcx,
1278             value,
1279             |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1280     }
1281
1282     /// See `verify_generic_bound` method in `region_inference`
1283     pub fn verify_generic_bound(&self,
1284                                 origin: SubregionOrigin<'tcx>,
1285                                 kind: GenericKind<'tcx>,
1286                                 a: ty::Region,
1287                                 bs: Vec<ty::Region>) {
1288         debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1289                kind,
1290                a,
1291                bs);
1292
1293         self.region_vars.verify_generic_bound(origin, kind, a, bs);
1294     }
1295
1296     pub fn can_equate<'b,T>(&'b self, a: &T, b: &T) -> UnitResult<'tcx>
1297         where T: Relate<'b,'tcx> + fmt::Debug
1298     {
1299         debug!("can_equate({:?}, {:?})", a, b);
1300         self.probe(|_| {
1301             // Gin up a dummy trace, since this won't be committed
1302             // anyhow. We should make this typetrace stuff more
1303             // generic so we don't have to do anything quite this
1304             // terrible.
1305             let e = self.tcx.types.err;
1306             let trace = TypeTrace { origin: Misc(codemap::DUMMY_SP),
1307                                     values: Types(expected_found(true, e, e)) };
1308             self.equate(true, trace).relate(a, b)
1309         }).map(|_| ())
1310     }
1311
1312     pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1313         let ty = self.node_type(id);
1314         self.resolve_type_vars_or_error(&ty)
1315     }
1316
1317     pub fn expr_ty_adjusted(&self, expr: &ast::Expr) -> McResult<Ty<'tcx>> {
1318         let ty = self.adjust_expr_ty(expr, self.tables.borrow().adjustments.get(&expr.id));
1319         self.resolve_type_vars_or_error(&ty)
1320     }
1321
1322     pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1323         let ty = self.resolve_type_vars_if_possible(&ty);
1324         !traits::type_known_to_meet_builtin_bound(self, ty, ty::BoundCopy, span)
1325         // FIXME(@jroesch): should be able to use:
1326         // ty.moves_by_default(&self.parameter_environment, span)
1327     }
1328
1329     pub fn node_method_ty(&self, method_call: ty::MethodCall)
1330                           -> Option<Ty<'tcx>> {
1331         self.tables
1332             .borrow()
1333             .method_map
1334             .get(&method_call)
1335             .map(|method| method.ty)
1336             .map(|ty| self.resolve_type_vars_if_possible(&ty))
1337     }
1338
1339     pub fn node_method_id(&self, method_call: ty::MethodCall)
1340                           -> Option<ast::DefId> {
1341         self.tables
1342             .borrow()
1343             .method_map
1344             .get(&method_call)
1345             .map(|method| method.def_id)
1346     }
1347
1348     pub fn adjustments(&self) -> Ref<NodeMap<ty::AutoAdjustment<'tcx>>> {
1349         fn project_adjustments<'a, 'tcx>(tables: &'a ty::Tables<'tcx>)
1350                                         -> &'a NodeMap<ty::AutoAdjustment<'tcx>> {
1351             &tables.adjustments
1352         }
1353
1354         Ref::map(self.tables.borrow(), project_adjustments)
1355     }
1356
1357     pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1358         self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1359     }
1360
1361     pub fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<CodeExtent> {
1362         self.tcx.region_maps.temporary_scope(rvalue_id)
1363     }
1364
1365     pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
1366         self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1367     }
1368
1369     pub fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
1370         &self.parameter_environment
1371     }
1372
1373     pub fn closure_kind(&self,
1374                         def_id: ast::DefId)
1375                         -> Option<ty::ClosureKind>
1376     {
1377         self.tables.borrow().closure_kinds.get(&def_id).cloned()
1378     }
1379
1380     pub fn closure_type(&self,
1381                     def_id: ast::DefId,
1382                     substs: &subst::Substs<'tcx>)
1383                     -> ty::ClosureTy<'tcx>
1384     {
1385
1386         let closure_ty = self.tables
1387                              .borrow()
1388                              .closure_tys
1389                              .get(&def_id)
1390                              .unwrap()
1391                              .subst(self.tcx, substs);
1392
1393         if self.normalize {
1394             normalize_associated_type(&self.tcx, &closure_ty)
1395         } else {
1396             closure_ty
1397         }
1398     }
1399
1400     pub fn closure_upvars(&self,
1401                           def_id: ast::DefId,
1402                           substs: &Substs<'tcx>)
1403                           -> Option<Vec<ty::ClosureUpvar<'tcx>>>
1404     {
1405         let result = ty::ctxt::closure_upvars(self, def_id, substs);
1406
1407         if self.normalize {
1408             normalize_associated_type(&self.tcx, &result)
1409         } else {
1410             result
1411         }
1412     }
1413 }
1414
1415 impl<'tcx> TypeTrace<'tcx> {
1416     pub fn span(&self) -> Span {
1417         self.origin.span()
1418     }
1419
1420     pub fn types(origin: TypeOrigin,
1421                  a_is_expected: bool,
1422                  a: Ty<'tcx>,
1423                  b: Ty<'tcx>)
1424                  -> TypeTrace<'tcx> {
1425         TypeTrace {
1426             origin: origin,
1427             values: Types(expected_found(a_is_expected, a, b))
1428         }
1429     }
1430
1431     pub fn dummy(tcx: &ty::ctxt<'tcx>) -> TypeTrace<'tcx> {
1432         TypeTrace {
1433             origin: Misc(codemap::DUMMY_SP),
1434             values: Types(ty::expected_found {
1435                 expected: tcx.types.err,
1436                 found: tcx.types.err,
1437             })
1438         }
1439     }
1440 }
1441
1442 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1443     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1444         write!(f, "TypeTrace({:?})", self.origin)
1445     }
1446 }
1447
1448 impl TypeOrigin {
1449     pub fn span(&self) -> Span {
1450         match *self {
1451             MethodCompatCheck(span) => span,
1452             ExprAssignable(span) => span,
1453             Misc(span) => span,
1454             RelateTraitRefs(span) => span,
1455             RelateSelfType(span) => span,
1456             RelateOutputImplTypes(span) => span,
1457             MatchExpressionArm(match_span, _) => match_span,
1458             IfExpression(span) => span,
1459             IfExpressionWithNoElse(span) => span,
1460             RangeExpression(span) => span,
1461             EquatePredicate(span) => span,
1462         }
1463     }
1464 }
1465
1466 impl<'tcx> SubregionOrigin<'tcx> {
1467     pub fn span(&self) -> Span {
1468         match *self {
1469             Subtype(ref a) => a.span(),
1470             DefaultExistentialBound(ref a) => a.span(),
1471             InfStackClosure(a) => a,
1472             InvokeClosure(a) => a,
1473             DerefPointer(a) => a,
1474             FreeVariable(a, _) => a,
1475             IndexSlice(a) => a,
1476             RelateObjectBound(a) => a,
1477             RelateParamBound(a, _) => a,
1478             RelateRegionParamBound(a) => a,
1479             RelateDefaultParamBound(a, _) => a,
1480             Reborrow(a) => a,
1481             ReborrowUpvar(a, _) => a,
1482             ReferenceOutlivesReferent(_, a) => a,
1483             ExprTypeIsNotInScope(_, a) => a,
1484             BindingTypeIsNotValidAtDecl(a) => a,
1485             CallRcvr(a) => a,
1486             CallArg(a) => a,
1487             CallReturn(a) => a,
1488             Operand(a) => a,
1489             AddrOf(a) => a,
1490             AutoBorrow(a) => a,
1491             SafeDestructor(a) => a,
1492         }
1493     }
1494 }
1495
1496 impl RegionVariableOrigin {
1497     pub fn span(&self) -> Span {
1498         match *self {
1499             MiscVariable(a) => a,
1500             PatternRegion(a) => a,
1501             AddrOfRegion(a) => a,
1502             Autoref(a) => a,
1503             Coercion(a) => a,
1504             EarlyBoundRegion(a, _) => a,
1505             LateBoundRegion(a, _, _) => a,
1506             BoundRegionInCoherence(_) => codemap::DUMMY_SP,
1507             UpvarRegion(_, a) => a
1508         }
1509     }
1510 }