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