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