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