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