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