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