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