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