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