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