]> git.proxmox.com Git - rustc.git/blob - src/librustc/infer/mod.rs
New upstream version 1.24.1+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
20 use hir::def_id::DefId;
21 use middle::free_region::RegionRelations;
22 use middle::region;
23 use middle::lang_items;
24 use mir::tcx::PlaceTy;
25 use ty::subst::{Kind, Subst, Substs};
26 use ty::{TyVid, IntVid, FloatVid};
27 use ty::{self, Ty, TyCtxt};
28 use ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
29 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
30 use ty::relate::RelateResult;
31 use traits::{self, ObligationCause, PredicateObligations, Reveal};
32 use rustc_data_structures::unify::{self, UnificationTable};
33 use std::cell::{Cell, RefCell, Ref, RefMut};
34 use std::collections::BTreeMap;
35 use std::fmt;
36 use syntax::ast;
37 use errors::DiagnosticBuilder;
38 use syntax_pos::{self, Span, DUMMY_SP};
39 use util::nodemap::FxHashMap;
40 use arena::DroplessArena;
41
42 use self::combine::CombineFields;
43 use self::higher_ranked::HrMatchResult;
44 use self::region_constraints::{RegionConstraintCollector, RegionSnapshot};
45 use self::region_constraints::{GenericKind, VerifyBound, RegionConstraintData, VarOrigins};
46 use self::lexical_region_resolve::LexicalRegionResolutions;
47 use self::outlives::env::OutlivesEnvironment;
48 use self::type_variable::TypeVariableOrigin;
49 use self::unify_key::ToType;
50
51 pub mod anon_types;
52 pub mod at;
53 mod combine;
54 mod equate;
55 pub mod error_reporting;
56 mod fudge;
57 mod glb;
58 mod higher_ranked;
59 pub mod lattice;
60 mod lub;
61 pub mod region_constraints;
62 mod lexical_region_resolve;
63 pub mod outlives;
64 pub mod resolve;
65 mod freshen;
66 mod sub;
67 pub mod type_variable;
68 pub mod unify_key;
69
70 #[must_use]
71 pub struct InferOk<'tcx, T> {
72 pub value: T,
73 pub obligations: PredicateObligations<'tcx>,
74 }
75 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
76
77 pub type Bound<T> = Option<T>;
78 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
79 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
80
81 pub struct InferCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
82 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
83
84 /// During type-checking/inference of a body, `in_progress_tables`
85 /// contains a reference to the tables being built up, which are
86 /// used for reading closure kinds/signatures as they are inferred,
87 /// and for error reporting logic to read arbitrary node types.
88 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
89
90 // Cache for projections. This cache is snapshotted along with the
91 // infcx.
92 //
93 // Public so that `traits::project` can use it.
94 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
95
96 // We instantiate UnificationTable with bounds<Ty> because the
97 // types that might instantiate a general type variable have an
98 // order, represented by its upper and lower bounds.
99 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
100
101 // Map from integral variable to the kind of integer it represents
102 int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
103
104 // Map from floating variable to the kind of float it represents
105 float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
106
107 // Tracks the set of region variables and the constraints between
108 // them. This is initially `Some(_)` but when
109 // `resolve_regions_and_report_errors` is invoked, this gets set
110 // to `None` -- further attempts to perform unification etc may
111 // fail if new region constraints would've been added.
112 region_constraints: RefCell<Option<RegionConstraintCollector<'tcx>>>,
113
114 // Once region inference is done, the values for each variable.
115 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
116
117 /// Caches the results of trait selection. This cache is used
118 /// for things that have to do with the parameters in scope.
119 pub selection_cache: traits::SelectionCache<'tcx>,
120
121 /// Caches the results of trait evaluation.
122 pub evaluation_cache: traits::EvaluationCache<'tcx>,
123
124 // the set of predicates on which errors have been reported, to
125 // avoid reporting the same error twice.
126 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
127
128 // When an error occurs, we want to avoid reporting "derived"
129 // errors that are due to this original failure. Normally, we
130 // handle this with the `err_count_on_creation` count, which
131 // basically just tracks how many errors were reported when we
132 // started type-checking a fn and checks to see if any new errors
133 // have been reported since then. Not great, but it works.
134 //
135 // However, when errors originated in other passes -- notably
136 // resolve -- this heuristic breaks down. Therefore, we have this
137 // auxiliary flag that one can set whenever one creates a
138 // type-error that is due to an error in a prior pass.
139 //
140 // Don't read this flag directly, call `is_tainted_by_errors()`
141 // and `set_tainted_by_errors()`.
142 tainted_by_errors_flag: Cell<bool>,
143
144 // Track how many errors were reported when this infcx is created.
145 // If the number of errors increases, that's also a sign (line
146 // `tained_by_errors`) to avoid reporting certain kinds of errors.
147 err_count_on_creation: usize,
148
149 // This flag is true while there is an active snapshot.
150 in_snapshot: Cell<bool>,
151
152 // A set of constraints that regionck must validate. Each
153 // constraint has the form `T:'a`, meaning "some type `T` must
154 // outlive the lifetime 'a". These constraints derive from
155 // instantiated type parameters. So if you had a struct defined
156 // like
157 //
158 // struct Foo<T:'static> { ... }
159 //
160 // then in some expression `let x = Foo { ... }` it will
161 // instantiate the type parameter `T` with a fresh type `$0`. At
162 // the same time, it will record a region obligation of
163 // `$0:'static`. This will get checked later by regionck. (We
164 // can't generally check these things right away because we have
165 // to wait until types are resolved.)
166 //
167 // These are stored in a map keyed to the id of the innermost
168 // enclosing fn body / static initializer expression. This is
169 // because the location where the obligation was incurred can be
170 // relevant with respect to which sublifetime assumptions are in
171 // place. The reason that we store under the fn-id, and not
172 // something more fine-grained, is so that it is easier for
173 // regionck to be sure that it has found *all* the region
174 // obligations (otherwise, it's easy to fail to walk to a
175 // particular node-id).
176 //
177 // Before running `resolve_regions_and_report_errors`, the creator
178 // of the inference context is expected to invoke
179 // `process_region_obligations` (defined in `self::region_obligations`)
180 // for each body-id in this map, which will process the
181 // obligations within. This is expected to be done 'late enough'
182 // that all type inference variables have been bound and so forth.
183 region_obligations: RefCell<Vec<(ast::NodeId, RegionObligation<'tcx>)>>,
184 }
185
186 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
187 /// region that each late-bound region was replaced with.
188 pub type SkolemizationMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
189
190 /// See `error_reporting` module for more details
191 #[derive(Clone, Debug)]
192 pub enum ValuePairs<'tcx> {
193 Types(ExpectedFound<Ty<'tcx>>),
194 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
195 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
196 }
197
198 /// The trace designates the path through inference that we took to
199 /// encounter an error or subtyping constraint.
200 ///
201 /// See `error_reporting` module for more details.
202 #[derive(Clone)]
203 pub struct TypeTrace<'tcx> {
204 cause: ObligationCause<'tcx>,
205 values: ValuePairs<'tcx>,
206 }
207
208 /// The origin of a `r1 <= r2` constraint.
209 ///
210 /// See `error_reporting` module for more details
211 #[derive(Clone, Debug)]
212 pub enum SubregionOrigin<'tcx> {
213 // Arose from a subtyping relation
214 Subtype(TypeTrace<'tcx>),
215
216 // Stack-allocated closures cannot outlive innermost loop
217 // or function so as to ensure we only require finite stack
218 InfStackClosure(Span),
219
220 // Invocation of closure must be within its lifetime
221 InvokeClosure(Span),
222
223 // Dereference of reference must be within its lifetime
224 DerefPointer(Span),
225
226 // Closure bound must not outlive captured free variables
227 FreeVariable(Span, ast::NodeId),
228
229 // Index into slice must be within its lifetime
230 IndexSlice(Span),
231
232 // When casting `&'a T` to an `&'b Trait` object,
233 // relating `'a` to `'b`
234 RelateObjectBound(Span),
235
236 // Some type parameter was instantiated with the given type,
237 // and that type must outlive some region.
238 RelateParamBound(Span, Ty<'tcx>),
239
240 // The given region parameter was instantiated with a region
241 // that must outlive some other region.
242 RelateRegionParamBound(Span),
243
244 // A bound placed on type parameters that states that must outlive
245 // the moment of their instantiation.
246 RelateDefaultParamBound(Span, Ty<'tcx>),
247
248 // Creating a pointer `b` to contents of another reference
249 Reborrow(Span),
250
251 // Creating a pointer `b` to contents of an upvar
252 ReborrowUpvar(Span, ty::UpvarId),
253
254 // Data with type `Ty<'tcx>` was borrowed
255 DataBorrowed(Ty<'tcx>, Span),
256
257 // (&'a &'b T) where a >= b
258 ReferenceOutlivesReferent(Ty<'tcx>, Span),
259
260 // Type or region parameters must be in scope.
261 ParameterInScope(ParameterOrigin, Span),
262
263 // The type T of an expression E must outlive the lifetime for E.
264 ExprTypeIsNotInScope(Ty<'tcx>, Span),
265
266 // A `ref b` whose region does not enclose the decl site
267 BindingTypeIsNotValidAtDecl(Span),
268
269 // Regions appearing in a method receiver must outlive method call
270 CallRcvr(Span),
271
272 // Regions appearing in a function argument must outlive func call
273 CallArg(Span),
274
275 // Region in return type of invoked fn must enclose call
276 CallReturn(Span),
277
278 // Operands must be in scope
279 Operand(Span),
280
281 // Region resulting from a `&` expr must enclose the `&` expr
282 AddrOf(Span),
283
284 // An auto-borrow that does not enclose the expr where it occurs
285 AutoBorrow(Span),
286
287 // Region constraint arriving from destructor safety
288 SafeDestructor(Span),
289
290 // Comparing the signature and requirements of an impl method against
291 // the containing trait.
292 CompareImplMethodObligation {
293 span: Span,
294 item_name: ast::Name,
295 impl_item_def_id: DefId,
296 trait_item_def_id: DefId,
297 },
298 }
299
300 /// Places that type/region parameters can appear.
301 #[derive(Clone, Copy, Debug)]
302 pub enum ParameterOrigin {
303 Path, // foo::bar
304 MethodCall, // foo.bar() <-- parameters on impl providing bar()
305 OverloadedOperator, // a + b when overloaded
306 OverloadedDeref, // *a when overloaded
307 }
308
309 /// Times when we replace late-bound regions with variables:
310 #[derive(Clone, Copy, Debug)]
311 pub enum LateBoundRegionConversionTime {
312 /// when a fn is called
313 FnCall,
314
315 /// when two higher-ranked types are compared
316 HigherRankedType,
317
318 /// when projecting an associated type
319 AssocTypeProjection(DefId),
320 }
321
322 /// Reasons to create a region inference variable
323 ///
324 /// See `error_reporting` module for more details
325 #[derive(Copy, Clone, Debug)]
326 pub enum RegionVariableOrigin {
327 // Region variables created for ill-categorized reasons,
328 // mostly indicates places in need of refactoring
329 MiscVariable(Span),
330
331 // Regions created by a `&P` or `[...]` pattern
332 PatternRegion(Span),
333
334 // Regions created by `&` operator
335 AddrOfRegion(Span),
336
337 // Regions created as part of an autoref of a method receiver
338 Autoref(Span),
339
340 // Regions created as part of an automatic coercion
341 Coercion(Span),
342
343 // Region variables created as the values for early-bound regions
344 EarlyBoundRegion(Span, ast::Name),
345
346 // Region variables created for bound regions
347 // in a function or method that is called
348 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
349
350 UpvarRegion(ty::UpvarId, Span),
351
352 BoundRegionInCoherence(ast::Name),
353
354 // This origin is used for the inference variables that we create
355 // during NLL region processing.
356 NLL(NLLRegionVariableOrigin),
357 }
358
359 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
360 pub enum NLLRegionVariableOrigin {
361 // During NLL region processing, we create variables for free
362 // regions that we encounter in the function signature and
363 // elsewhere. This origin indices we've got one of those.
364 FreeRegion,
365
366 Inferred(::mir::visit::TyContext),
367 }
368
369 #[derive(Copy, Clone, Debug)]
370 pub enum FixupError {
371 UnresolvedIntTy(IntVid),
372 UnresolvedFloatTy(FloatVid),
373 UnresolvedTy(TyVid)
374 }
375
376 /// See the `region_obligations` field for more information.
377 #[derive(Clone)]
378 pub struct RegionObligation<'tcx> {
379 pub sub_region: ty::Region<'tcx>,
380 pub sup_type: Ty<'tcx>,
381 pub cause: ObligationCause<'tcx>,
382 }
383
384 impl fmt::Display for FixupError {
385 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
386 use self::FixupError::*;
387
388 match *self {
389 UnresolvedIntTy(_) => {
390 write!(f, "cannot determine the type of this integer; \
391 add a suffix to specify the type explicitly")
392 }
393 UnresolvedFloatTy(_) => {
394 write!(f, "cannot determine the type of this number; \
395 add a suffix to specify the type explicitly")
396 }
397 UnresolvedTy(_) => write!(f, "unconstrained type")
398 }
399 }
400 }
401
402 /// Helper type of a temporary returned by tcx.infer_ctxt().
403 /// Necessary because we can't write the following bound:
404 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
405 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
406 global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
407 arena: DroplessArena,
408 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
409 }
410
411 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
412 pub fn infer_ctxt(self) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
413 InferCtxtBuilder {
414 global_tcx: self,
415 arena: DroplessArena::new(),
416 fresh_tables: None,
417
418 }
419 }
420 }
421
422 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
423 /// Used only by `rustc_typeck` during body type-checking/inference,
424 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
425 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
426 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
427 self
428 }
429
430 pub fn enter<F, R>(&'tcx mut self, f: F) -> R
431 where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
432 {
433 let InferCtxtBuilder {
434 global_tcx,
435 ref arena,
436 ref fresh_tables,
437 } = *self;
438 let in_progress_tables = fresh_tables.as_ref();
439 global_tcx.enter_local(arena, |tcx| f(InferCtxt {
440 tcx,
441 in_progress_tables,
442 projection_cache: RefCell::new(traits::ProjectionCache::new()),
443 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
444 int_unification_table: RefCell::new(UnificationTable::new()),
445 float_unification_table: RefCell::new(UnificationTable::new()),
446 region_constraints: RefCell::new(Some(RegionConstraintCollector::new())),
447 lexical_region_resolutions: RefCell::new(None),
448 selection_cache: traits::SelectionCache::new(),
449 evaluation_cache: traits::EvaluationCache::new(),
450 reported_trait_errors: RefCell::new(FxHashMap()),
451 tainted_by_errors_flag: Cell::new(false),
452 err_count_on_creation: tcx.sess.err_count(),
453 in_snapshot: Cell::new(false),
454 region_obligations: RefCell::new(vec![]),
455 }))
456 }
457 }
458
459 impl<T> ExpectedFound<T> {
460 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
461 if a_is_expected {
462 ExpectedFound {expected: a, found: b}
463 } else {
464 ExpectedFound {expected: b, found: a}
465 }
466 }
467 }
468
469 impl<'tcx, T> InferOk<'tcx, T> {
470 pub fn unit(self) -> InferOk<'tcx, ()> {
471 InferOk { value: (), obligations: self.obligations }
472 }
473 }
474
475 #[must_use = "once you start a snapshot, you should always consume it"]
476 pub struct CombinedSnapshot<'a, 'tcx:'a> {
477 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
478 type_snapshot: type_variable::Snapshot,
479 int_snapshot: unify::Snapshot<ty::IntVid>,
480 float_snapshot: unify::Snapshot<ty::FloatVid>,
481 region_constraints_snapshot: RegionSnapshot,
482 region_obligations_snapshot: usize,
483 was_in_snapshot: bool,
484 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
485 }
486
487 /// Helper trait for shortening the lifetimes inside a
488 /// value for post-type-checking normalization.
489 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
490 fn trans_normalize<'a, 'tcx>(&self,
491 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
492 param_env: ty::ParamEnv<'tcx>)
493 -> Self;
494 }
495
496 macro_rules! items { ($($item:item)+) => ($($item)+) }
497 macro_rules! impl_trans_normalize {
498 ($lt_gcx:tt, $($ty:ty),+) => {
499 items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
500 fn trans_normalize<'a, 'tcx>(&self,
501 infcx: &InferCtxt<'a, $lt_gcx, 'tcx>,
502 param_env: ty::ParamEnv<'tcx>)
503 -> Self {
504 infcx.normalize_projections_in(param_env, self)
505 }
506 })+);
507 }
508 }
509
510 impl_trans_normalize!('gcx,
511 Ty<'gcx>,
512 &'gcx ty::Const<'gcx>,
513 &'gcx Substs<'gcx>,
514 ty::FnSig<'gcx>,
515 ty::PolyFnSig<'gcx>,
516 ty::ClosureSubsts<'gcx>,
517 ty::PolyTraitRef<'gcx>,
518 ty::ExistentialTraitRef<'gcx>
519 );
520
521 impl<'gcx> TransNormalize<'gcx> for PlaceTy<'gcx> {
522 fn trans_normalize<'a, 'tcx>(&self,
523 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
524 param_env: ty::ParamEnv<'tcx>)
525 -> Self {
526 match *self {
527 PlaceTy::Ty { ty } => PlaceTy::Ty { ty: ty.trans_normalize(infcx, param_env) },
528 PlaceTy::Downcast { adt_def, substs, variant_index } => {
529 PlaceTy::Downcast {
530 adt_def,
531 substs: substs.trans_normalize(infcx, param_env),
532 variant_index,
533 }
534 }
535 }
536 }
537 }
538
539 // NOTE: Callable from trans only!
540 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
541 /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
542 /// each time we erase them in translation, we need to normalize
543 /// the contents.
544 pub fn erase_late_bound_regions_and_normalize<T>(self, value: &ty::Binder<T>)
545 -> T
546 where T: TransNormalize<'tcx>
547 {
548 assert!(!value.needs_subst());
549 let value = self.erase_late_bound_regions(value);
550 self.fully_normalize_associated_types_in(&value)
551 }
552
553 /// Fully normalizes any associated types in `value`, using an
554 /// empty environment and `Reveal::All` mode (therefore, suitable
555 /// only for monomorphized code during trans, basically).
556 pub fn fully_normalize_associated_types_in<T>(self, value: &T) -> T
557 where T: TransNormalize<'tcx>
558 {
559 debug!("fully_normalize_associated_types_in(t={:?})", value);
560
561 let param_env = ty::ParamEnv::empty(Reveal::All);
562 let value = self.erase_regions(value);
563
564 if !value.has_projections() {
565 return value;
566 }
567
568 self.infer_ctxt().enter(|infcx| {
569 value.trans_normalize(&infcx, param_env)
570 })
571 }
572
573 /// Does a best-effort to normalize any associated types in
574 /// `value`; this includes revealing specializable types, so this
575 /// should be not be used during type-checking, but only during
576 /// optimization and code generation.
577 pub fn normalize_associated_type_in_env<T>(
578 self, value: &T, env: ty::ParamEnv<'tcx>
579 ) -> T
580 where T: TransNormalize<'tcx>
581 {
582 debug!("normalize_associated_type_in_env(t={:?})", value);
583
584 let value = self.erase_regions(value);
585
586 if !value.has_projections() {
587 return value;
588 }
589
590 self.infer_ctxt().enter(|infcx| {
591 value.trans_normalize(&infcx, env.reveal_all())
592 })
593 }
594 }
595
596 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
597 fn normalize_projections_in<T>(&self, param_env: ty::ParamEnv<'tcx>, value: &T) -> T::Lifted
598 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
599 {
600 let mut selcx = traits::SelectionContext::new(self);
601 let cause = traits::ObligationCause::dummy();
602 let traits::Normalized { value: result, obligations } =
603 traits::normalize(&mut selcx, param_env, cause, value);
604
605 debug!("normalize_projections_in: result={:?} obligations={:?}",
606 result, obligations);
607
608 let mut fulfill_cx = traits::FulfillmentContext::new();
609
610 for obligation in obligations {
611 fulfill_cx.register_predicate_obligation(self, obligation);
612 }
613
614 self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
615 }
616
617 /// Finishes processes any obligations that remain in the
618 /// fulfillment context, and then returns the result with all type
619 /// variables removed and regions erased. Because this is intended
620 /// for use after type-check has completed, if any errors occur,
621 /// it will panic. It is used during normalization and other cases
622 /// where processing the obligations in `fulfill_cx` may cause
623 /// type inference variables that appear in `result` to be
624 /// unified, and hence we need to process those obligations to get
625 /// the complete picture of the type.
626 pub fn drain_fulfillment_cx_or_panic<T>(&self,
627 span: Span,
628 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
629 result: &T)
630 -> T::Lifted
631 where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
632 {
633 debug!("drain_fulfillment_cx_or_panic()");
634
635 // In principle, we only need to do this so long as `result`
636 // contains unbound type parameters. It could be a slight
637 // optimization to stop iterating early.
638 match fulfill_cx.select_all_or_error(self) {
639 Ok(()) => { }
640 Err(errors) => {
641 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
642 errors);
643 }
644 }
645
646 let result = self.resolve_type_vars_if_possible(result);
647 let result = self.tcx.erase_regions(&result);
648
649 match self.tcx.lift_to_global(&result) {
650 Some(result) => result,
651 None => {
652 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
653 }
654 }
655 }
656
657 pub fn is_in_snapshot(&self) -> bool {
658 self.in_snapshot.get()
659 }
660
661 pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
662 t.fold_with(&mut self.freshener())
663 }
664
665 pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
666 match ty.sty {
667 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
668 _ => false
669 }
670 }
671
672 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
673 freshen::TypeFreshener::new(self)
674 }
675
676 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
677 use ty::error::UnconstrainedNumeric::Neither;
678 use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
679 match ty.sty {
680 ty::TyInfer(ty::IntVar(vid)) => {
681 if self.int_unification_table.borrow_mut().has_value(vid) {
682 Neither
683 } else {
684 UnconstrainedInt
685 }
686 },
687 ty::TyInfer(ty::FloatVar(vid)) => {
688 if self.float_unification_table.borrow_mut().has_value(vid) {
689 Neither
690 } else {
691 UnconstrainedFloat
692 }
693 },
694 _ => Neither,
695 }
696 }
697
698 /// Returns a type variable's default fallback if any exists. A default
699 /// must be attached to the variable when created, if it is created
700 /// without a default, this will return None.
701 ///
702 /// This code does not apply to integral or floating point variables,
703 /// only to use declared defaults.
704 ///
705 /// See `new_ty_var_with_default` to create a type variable with a default.
706 /// See `type_variable::Default` for details about what a default entails.
707 pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
708 match ty.sty {
709 ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
710 _ => None
711 }
712 }
713
714 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
715 let mut variables = Vec::new();
716
717 let unbound_ty_vars = self.type_variables
718 .borrow_mut()
719 .unsolved_variables()
720 .into_iter()
721 .map(|t| self.tcx.mk_var(t));
722
723 let unbound_int_vars = self.int_unification_table
724 .borrow_mut()
725 .unsolved_variables()
726 .into_iter()
727 .map(|v| self.tcx.mk_int_var(v));
728
729 let unbound_float_vars = self.float_unification_table
730 .borrow_mut()
731 .unsolved_variables()
732 .into_iter()
733 .map(|v| self.tcx.mk_float_var(v));
734
735 variables.extend(unbound_ty_vars);
736 variables.extend(unbound_int_vars);
737 variables.extend(unbound_float_vars);
738
739 return variables;
740 }
741
742 fn combine_fields(&'a self, trace: TypeTrace<'tcx>, param_env: ty::ParamEnv<'tcx>)
743 -> CombineFields<'a, 'gcx, 'tcx> {
744 CombineFields {
745 infcx: self,
746 trace,
747 cause: None,
748 param_env,
749 obligations: PredicateObligations::new(),
750 }
751 }
752
753 // Clear the "currently in a snapshot" flag, invoke the closure,
754 // then restore the flag to its original value. This flag is a
755 // debugging measure designed to detect cases where we start a
756 // snapshot, create type variables, and register obligations
757 // which may involve those type variables in the fulfillment cx,
758 // potentially leaving "dangling type variables" behind.
759 // In such cases, an assertion will fail when attempting to
760 // register obligations, within a snapshot. Very useful, much
761 // better than grovelling through megabytes of RUST_LOG output.
762 //
763 // HOWEVER, in some cases the flag is unhelpful. In particular, we
764 // sometimes create a "mini-fulfilment-cx" in which we enroll
765 // obligations. As long as this fulfillment cx is fully drained
766 // before we return, this is not a problem, as there won't be any
767 // escaping obligations in the main cx. In those cases, you can
768 // use this function.
769 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
770 where F: FnOnce(&Self) -> R
771 {
772 let flag = self.in_snapshot.get();
773 self.in_snapshot.set(false);
774 let result = func(self);
775 self.in_snapshot.set(flag);
776 result
777 }
778
779 fn start_snapshot<'b>(&'b self) -> CombinedSnapshot<'b, 'tcx> {
780 debug!("start_snapshot()");
781
782 let in_snapshot = self.in_snapshot.get();
783 self.in_snapshot.set(true);
784
785 CombinedSnapshot {
786 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
787 type_snapshot: self.type_variables.borrow_mut().snapshot(),
788 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
789 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
790 region_constraints_snapshot: self.borrow_region_constraints().start_snapshot(),
791 region_obligations_snapshot: self.region_obligations.borrow().len(),
792 was_in_snapshot: in_snapshot,
793 // Borrow tables "in progress" (i.e. during typeck)
794 // to ban writes from within a snapshot to them.
795 _in_progress_tables: self.in_progress_tables.map(|tables| {
796 tables.borrow()
797 })
798 }
799 }
800
801 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
802 debug!("rollback_to(cause={})", cause);
803 let CombinedSnapshot { projection_cache_snapshot,
804 type_snapshot,
805 int_snapshot,
806 float_snapshot,
807 region_constraints_snapshot,
808 region_obligations_snapshot,
809 was_in_snapshot,
810 _in_progress_tables } = snapshot;
811
812 self.in_snapshot.set(was_in_snapshot);
813
814 self.projection_cache
815 .borrow_mut()
816 .rollback_to(projection_cache_snapshot);
817 self.type_variables
818 .borrow_mut()
819 .rollback_to(type_snapshot);
820 self.int_unification_table
821 .borrow_mut()
822 .rollback_to(int_snapshot);
823 self.float_unification_table
824 .borrow_mut()
825 .rollback_to(float_snapshot);
826 self.region_obligations
827 .borrow_mut()
828 .truncate(region_obligations_snapshot);
829 self.borrow_region_constraints()
830 .rollback_to(region_constraints_snapshot);
831 }
832
833 fn commit_from(&self, snapshot: CombinedSnapshot) {
834 debug!("commit_from()");
835 let CombinedSnapshot { projection_cache_snapshot,
836 type_snapshot,
837 int_snapshot,
838 float_snapshot,
839 region_constraints_snapshot,
840 region_obligations_snapshot: _,
841 was_in_snapshot,
842 _in_progress_tables } = snapshot;
843
844 self.in_snapshot.set(was_in_snapshot);
845
846 self.projection_cache
847 .borrow_mut()
848 .commit(projection_cache_snapshot);
849 self.type_variables
850 .borrow_mut()
851 .commit(type_snapshot);
852 self.int_unification_table
853 .borrow_mut()
854 .commit(int_snapshot);
855 self.float_unification_table
856 .borrow_mut()
857 .commit(float_snapshot);
858 self.borrow_region_constraints()
859 .commit(region_constraints_snapshot);
860 }
861
862 /// Execute `f` and commit the bindings
863 pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
864 F: FnOnce() -> R,
865 {
866 debug!("commit()");
867 let snapshot = self.start_snapshot();
868 let r = f();
869 self.commit_from(snapshot);
870 r
871 }
872
873 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
874 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
875 F: FnOnce(&CombinedSnapshot) -> Result<T, E>
876 {
877 debug!("commit_if_ok()");
878 let snapshot = self.start_snapshot();
879 let r = f(&snapshot);
880 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
881 match r {
882 Ok(_) => { self.commit_from(snapshot); }
883 Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
884 }
885 r
886 }
887
888 // Execute `f` in a snapshot, and commit the bindings it creates
889 pub fn in_snapshot<T, F>(&self, f: F) -> T where
890 F: FnOnce(&CombinedSnapshot) -> T
891 {
892 debug!("in_snapshot()");
893 let snapshot = self.start_snapshot();
894 let r = f(&snapshot);
895 self.commit_from(snapshot);
896 r
897 }
898
899 /// Execute `f` then unroll any bindings it creates
900 pub fn probe<R, F>(&self, f: F) -> R where
901 F: FnOnce(&CombinedSnapshot) -> R,
902 {
903 debug!("probe()");
904 let snapshot = self.start_snapshot();
905 let r = f(&snapshot);
906 self.rollback_to("probe", snapshot);
907 r
908 }
909
910 pub fn add_given(&self,
911 sub: ty::Region<'tcx>,
912 sup: ty::RegionVid)
913 {
914 self.borrow_region_constraints().add_given(sub, sup);
915 }
916
917 pub fn can_sub<T>(&self,
918 param_env: ty::ParamEnv<'tcx>,
919 a: T,
920 b: T)
921 -> UnitResult<'tcx>
922 where T: at::ToTrace<'tcx>
923 {
924 let origin = &ObligationCause::dummy();
925 self.probe(|_| {
926 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
927 // Ignore obligations, since we are unrolling
928 // everything anyway.
929 })
930 })
931 }
932
933 pub fn can_eq<T>(&self,
934 param_env: ty::ParamEnv<'tcx>,
935 a: T,
936 b: T)
937 -> UnitResult<'tcx>
938 where T: at::ToTrace<'tcx>
939 {
940 let origin = &ObligationCause::dummy();
941 self.probe(|_| {
942 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
943 // Ignore obligations, since we are unrolling
944 // everything anyway.
945 })
946 })
947 }
948
949 pub fn sub_regions(&self,
950 origin: SubregionOrigin<'tcx>,
951 a: ty::Region<'tcx>,
952 b: ty::Region<'tcx>) {
953 debug!("sub_regions({:?} <: {:?})", a, b);
954 self.borrow_region_constraints().make_subregion(origin, a, b);
955 }
956
957 pub fn equality_predicate(&self,
958 cause: &ObligationCause<'tcx>,
959 param_env: ty::ParamEnv<'tcx>,
960 predicate: &ty::PolyEquatePredicate<'tcx>)
961 -> InferResult<'tcx, ()>
962 {
963 self.commit_if_ok(|snapshot| {
964 let (ty::EquatePredicate(a, b), skol_map) =
965 self.skolemize_late_bound_regions(predicate, snapshot);
966 let cause_span = cause.span;
967 let eqty_ok = self.at(cause, param_env).eq(b, a)?;
968 self.leak_check(false, cause_span, &skol_map, snapshot)?;
969 self.pop_skolemized(skol_map, snapshot);
970 Ok(eqty_ok.unit())
971 })
972 }
973
974 pub fn subtype_predicate(&self,
975 cause: &ObligationCause<'tcx>,
976 param_env: ty::ParamEnv<'tcx>,
977 predicate: &ty::PolySubtypePredicate<'tcx>)
978 -> Option<InferResult<'tcx, ()>>
979 {
980 // Subtle: it's ok to skip the binder here and resolve because
981 // `shallow_resolve` just ignores anything that is not a type
982 // variable, and because type variable's can't (at present, at
983 // least) capture any of the things bound by this binder.
984 //
985 // Really, there is no *particular* reason to do this
986 // `shallow_resolve` here except as a
987 // micro-optimization. Naturally I could not
988 // resist. -nmatsakis
989 let two_unbound_type_vars = {
990 let a = self.shallow_resolve(predicate.skip_binder().a);
991 let b = self.shallow_resolve(predicate.skip_binder().b);
992 a.is_ty_var() && b.is_ty_var()
993 };
994
995 if two_unbound_type_vars {
996 // Two unbound type variables? Can't make progress.
997 return None;
998 }
999
1000 Some(self.commit_if_ok(|snapshot| {
1001 let (ty::SubtypePredicate { a_is_expected, a, b}, skol_map) =
1002 self.skolemize_late_bound_regions(predicate, snapshot);
1003
1004 let cause_span = cause.span;
1005 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1006 self.leak_check(false, cause_span, &skol_map, snapshot)?;
1007 self.pop_skolemized(skol_map, snapshot);
1008 Ok(ok.unit())
1009 }))
1010 }
1011
1012 pub fn region_outlives_predicate(&self,
1013 cause: &traits::ObligationCause<'tcx>,
1014 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1015 -> UnitResult<'tcx>
1016 {
1017 self.commit_if_ok(|snapshot| {
1018 let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1019 self.skolemize_late_bound_regions(predicate, snapshot);
1020 let origin =
1021 SubregionOrigin::from_obligation_cause(cause,
1022 || RelateRegionParamBound(cause.span));
1023 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1024 self.leak_check(false, cause.span, &skol_map, snapshot)?;
1025 Ok(self.pop_skolemized(skol_map, snapshot))
1026 })
1027 }
1028
1029 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1030 self.type_variables
1031 .borrow_mut()
1032 .new_var(diverging, origin, None)
1033 }
1034
1035 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1036 self.tcx.mk_var(self.next_ty_var_id(false, origin))
1037 }
1038
1039 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1040 self.tcx.mk_var(self.next_ty_var_id(true, origin))
1041 }
1042
1043 pub fn next_int_var_id(&self) -> IntVid {
1044 self.int_unification_table
1045 .borrow_mut()
1046 .new_key(None)
1047 }
1048
1049 pub fn next_float_var_id(&self) -> FloatVid {
1050 self.float_unification_table
1051 .borrow_mut()
1052 .new_key(None)
1053 }
1054
1055 /// Create a fresh region variable with the next available index.
1056 ///
1057 /// # Parameters
1058 ///
1059 /// - `origin`: information about why we created this variable, for use
1060 /// during diagnostics / error-reporting.
1061 pub fn next_region_var(&self, origin: RegionVariableOrigin)
1062 -> ty::Region<'tcx> {
1063 self.tcx.mk_region(ty::ReVar(self.borrow_region_constraints().new_region_var(origin)))
1064 }
1065
1066 /// Number of region variables created so far.
1067 pub fn num_region_vars(&self) -> usize {
1068 self.borrow_region_constraints().var_origins().len()
1069 }
1070
1071 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1072 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin)
1073 -> ty::Region<'tcx> {
1074 self.next_region_var(RegionVariableOrigin::NLL(origin))
1075 }
1076
1077 /// Create a region inference variable for the given
1078 /// region parameter definition.
1079 pub fn region_var_for_def(&self,
1080 span: Span,
1081 def: &ty::RegionParameterDef)
1082 -> ty::Region<'tcx> {
1083 self.next_region_var(EarlyBoundRegion(span, def.name))
1084 }
1085
1086 /// Create a type inference variable for the given
1087 /// type parameter definition. The substitutions are
1088 /// for actual parameters that may be referred to by
1089 /// the default of this type parameter, if it exists.
1090 /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1091 /// used in a path such as `Foo::<T, U>::new()` will
1092 /// use an inference variable for `C` with `[T, U]`
1093 /// as the substitutions for the default, `(T, U)`.
1094 pub fn type_var_for_def(&self,
1095 span: Span,
1096 def: &ty::TypeParameterDef,
1097 substs: &[Kind<'tcx>])
1098 -> Ty<'tcx> {
1099 let default = if def.has_default {
1100 let default = self.tcx.type_of(def.def_id);
1101 Some(type_variable::Default {
1102 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1103 origin_span: span,
1104 def_id: def.def_id
1105 })
1106 } else {
1107 None
1108 };
1109
1110
1111 let ty_var_id = self.type_variables
1112 .borrow_mut()
1113 .new_var(false,
1114 TypeVariableOrigin::TypeParameterDefinition(span, def.name),
1115 default);
1116
1117 self.tcx.mk_var(ty_var_id)
1118 }
1119
1120 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1121 /// type/region parameter to a fresh inference variable.
1122 pub fn fresh_substs_for_item(&self,
1123 span: Span,
1124 def_id: DefId)
1125 -> &'tcx Substs<'tcx> {
1126 Substs::for_item(self.tcx, def_id, |def, _| {
1127 self.region_var_for_def(span, def)
1128 }, |def, substs| {
1129 self.type_var_for_def(span, def, substs)
1130 })
1131 }
1132
1133 /// True if errors have been reported since this infcx was
1134 /// created. This is sometimes used as a heuristic to skip
1135 /// reporting errors that often occur as a result of earlier
1136 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1137 /// inference variables, regionck errors).
1138 pub fn is_tainted_by_errors(&self) -> bool {
1139 debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1140 tainted_by_errors_flag={})",
1141 self.tcx.sess.err_count(),
1142 self.err_count_on_creation,
1143 self.tainted_by_errors_flag.get());
1144
1145 if self.tcx.sess.err_count() > self.err_count_on_creation {
1146 return true; // errors reported since this infcx was made
1147 }
1148 self.tainted_by_errors_flag.get()
1149 }
1150
1151 /// Set the "tainted by errors" flag to true. We call this when we
1152 /// observe an error from a prior pass.
1153 pub fn set_tainted_by_errors(&self) {
1154 debug!("set_tainted_by_errors()");
1155 self.tainted_by_errors_flag.set(true)
1156 }
1157
1158 /// Process the region constraints and report any errors that
1159 /// result. After this, no more unification operations should be
1160 /// done -- or the compiler will panic -- but it is legal to use
1161 /// `resolve_type_vars_if_possible` as well as `fully_resolve`.
1162 pub fn resolve_regions_and_report_errors(
1163 &self,
1164 region_context: DefId,
1165 region_map: &region::ScopeTree,
1166 outlives_env: &OutlivesEnvironment<'tcx>,
1167 ) {
1168 self.resolve_regions_and_report_errors_inner(
1169 region_context,
1170 region_map,
1171 outlives_env,
1172 false,
1173 )
1174 }
1175
1176 /// Like `resolve_regions_and_report_errors`, but skips error
1177 /// reporting if NLL is enabled. This is used for fn bodies where
1178 /// the same error may later be reported by the NLL-based
1179 /// inference.
1180 pub fn resolve_regions_and_report_errors_unless_nll(
1181 &self,
1182 region_context: DefId,
1183 region_map: &region::ScopeTree,
1184 outlives_env: &OutlivesEnvironment<'tcx>,
1185 ) {
1186 self.resolve_regions_and_report_errors_inner(
1187 region_context,
1188 region_map,
1189 outlives_env,
1190 true,
1191 )
1192 }
1193
1194 fn resolve_regions_and_report_errors_inner(
1195 &self,
1196 region_context: DefId,
1197 region_map: &region::ScopeTree,
1198 outlives_env: &OutlivesEnvironment<'tcx>,
1199 will_later_be_reported_by_nll: bool,
1200 ) {
1201 assert!(self.is_tainted_by_errors() || self.region_obligations.borrow().is_empty(),
1202 "region_obligations not empty: {:#?}",
1203 self.region_obligations.borrow());
1204
1205 let region_rels = &RegionRelations::new(self.tcx,
1206 region_context,
1207 region_map,
1208 outlives_env.free_region_map());
1209 let (var_origins, data) = self.region_constraints.borrow_mut()
1210 .take()
1211 .expect("regions already resolved")
1212 .into_origins_and_data();
1213 let (lexical_region_resolutions, errors) =
1214 lexical_region_resolve::resolve(region_rels, var_origins, data);
1215
1216 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1217 assert!(old_value.is_none());
1218
1219 if !self.is_tainted_by_errors() {
1220 // As a heuristic, just skip reporting region errors
1221 // altogether if other errors have been reported while
1222 // this infcx was in use. This is totally hokey but
1223 // otherwise we have a hard time separating legit region
1224 // errors from silly ones.
1225 self.report_region_errors(region_map, &errors, will_later_be_reported_by_nll);
1226 }
1227 }
1228
1229 /// Obtains (and clears) the current set of region
1230 /// constraints. The inference context is still usable: further
1231 /// unifications will simply add new constraints.
1232 ///
1233 /// This method is not meant to be used with normal lexical region
1234 /// resolution. Rather, it is used in the NLL mode as a kind of
1235 /// interim hack: basically we run normal type-check and generate
1236 /// region constraints as normal, but then we take them and
1237 /// translate them into the form that the NLL solver
1238 /// understands. See the NLL module for mode details.
1239 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1240 assert!(self.region_obligations.borrow().is_empty(),
1241 "region_obligations not empty: {:#?}",
1242 self.region_obligations.borrow());
1243
1244 self.borrow_region_constraints().take_and_reset_data()
1245 }
1246
1247 /// Takes ownership of the list of variable regions. This implies
1248 /// that all the region constriants have already been taken, and
1249 /// hence that `resolve_regions_and_report_errors` can never be
1250 /// called. This is used only during NLL processing to "hand off" ownership
1251 /// of the set of region vairables into the NLL region context.
1252 pub fn take_region_var_origins(&self) -> VarOrigins {
1253 let (var_origins, data) = self.region_constraints.borrow_mut()
1254 .take()
1255 .expect("regions already resolved")
1256 .into_origins_and_data();
1257 assert!(data.is_empty());
1258 var_origins
1259 }
1260
1261 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1262 self.resolve_type_vars_if_possible(&t).to_string()
1263 }
1264
1265 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1266 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1267 format!("({})", tstrs.join(", "))
1268 }
1269
1270 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1271 self.resolve_type_vars_if_possible(t).to_string()
1272 }
1273
1274 pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1275 match typ.sty {
1276 ty::TyInfer(ty::TyVar(v)) => {
1277 // Not entirely obvious: if `typ` is a type variable,
1278 // it can be resolved to an int/float variable, which
1279 // can then be recursively resolved, hence the
1280 // recursion. Note though that we prevent type
1281 // variables from unifying to other type variables
1282 // directly (though they may be embedded
1283 // structurally), and we prevent cycles in any case,
1284 // so this recursion should always be of very limited
1285 // depth.
1286 self.type_variables.borrow_mut()
1287 .probe(v)
1288 .map(|t| self.shallow_resolve(t))
1289 .unwrap_or(typ)
1290 }
1291
1292 ty::TyInfer(ty::IntVar(v)) => {
1293 self.int_unification_table
1294 .borrow_mut()
1295 .probe(v)
1296 .map(|v| v.to_type(self.tcx))
1297 .unwrap_or(typ)
1298 }
1299
1300 ty::TyInfer(ty::FloatVar(v)) => {
1301 self.float_unification_table
1302 .borrow_mut()
1303 .probe(v)
1304 .map(|v| v.to_type(self.tcx))
1305 .unwrap_or(typ)
1306 }
1307
1308 _ => {
1309 typ
1310 }
1311 }
1312 }
1313
1314 pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1315 where T: TypeFoldable<'tcx>
1316 {
1317 /*!
1318 * Where possible, replaces type/int/float variables in
1319 * `value` with their final value. Note that region variables
1320 * are unaffected. If a type variable has not been unified, it
1321 * is left as is. This is an idempotent operation that does
1322 * not affect inference state in any way and so you can do it
1323 * at will.
1324 */
1325
1326 if !value.needs_infer() {
1327 return value.clone(); // avoid duplicated subst-folding
1328 }
1329 let mut r = resolve::OpportunisticTypeResolver::new(self);
1330 value.fold_with(&mut r)
1331 }
1332
1333 /// Returns true if `T` contains unresolved type variables. In the
1334 /// process of visiting `T`, this will resolve (where possible)
1335 /// type variables in `T`, but it never constructs the final,
1336 /// resolved type, so it's more efficient than
1337 /// `resolve_type_vars_if_possible()`.
1338 pub fn any_unresolved_type_vars<T>(&self, value: &T) -> bool
1339 where T: TypeFoldable<'tcx>
1340 {
1341 let mut r = resolve::UnresolvedTypeFinder::new(self);
1342 value.visit_with(&mut r)
1343 }
1344
1345 pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1346 where T: TypeFoldable<'tcx>
1347 {
1348 let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1349 value.fold_with(&mut r)
1350 }
1351
1352 pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1353 /*!
1354 * Attempts to resolve all type/region variables in
1355 * `value`. Region inference must have been run already (e.g.,
1356 * by calling `resolve_regions_and_report_errors`). If some
1357 * variable was never unified, an `Err` results.
1358 *
1359 * This method is idempotent, but it not typically not invoked
1360 * except during the writeback phase.
1361 */
1362
1363 resolve::fully_resolve(self, value)
1364 }
1365
1366 // [Note-Type-error-reporting]
1367 // An invariant is that anytime the expected or actual type is TyError (the special
1368 // error type, meaning that an error occurred when typechecking this expression),
1369 // this is a derived error. The error cascaded from another error (that was already
1370 // reported), so it's not useful to display it to the user.
1371 // The following methods implement this logic.
1372 // They check if either the actual or expected type is TyError, and don't print the error
1373 // in this case. The typechecker should only ever report type errors involving mismatched
1374 // types using one of these methods, and should not call span_err directly for such
1375 // errors.
1376
1377 pub fn type_error_struct_with_diag<M>(&self,
1378 sp: Span,
1379 mk_diag: M,
1380 actual_ty: Ty<'tcx>)
1381 -> DiagnosticBuilder<'tcx>
1382 where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1383 {
1384 let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1385 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1386
1387 // Don't report an error if actual type is TyError.
1388 if actual_ty.references_error() {
1389 return self.tcx.sess.diagnostic().struct_dummy();
1390 }
1391
1392 mk_diag(self.ty_to_string(actual_ty))
1393 }
1394
1395 pub fn report_mismatched_types(&self,
1396 cause: &ObligationCause<'tcx>,
1397 expected: Ty<'tcx>,
1398 actual: Ty<'tcx>,
1399 err: TypeError<'tcx>)
1400 -> DiagnosticBuilder<'tcx> {
1401 let trace = TypeTrace::types(cause, true, expected, actual);
1402 self.report_and_explain_type_error(trace, &err)
1403 }
1404
1405 pub fn report_conflicting_default_types(&self,
1406 span: Span,
1407 body_id: ast::NodeId,
1408 expected: type_variable::Default<'tcx>,
1409 actual: type_variable::Default<'tcx>) {
1410 let trace = TypeTrace {
1411 cause: ObligationCause::misc(span, body_id),
1412 values: Types(ExpectedFound {
1413 expected: expected.ty,
1414 found: actual.ty
1415 })
1416 };
1417
1418 self.report_and_explain_type_error(
1419 trace,
1420 &TypeError::TyParamDefaultMismatch(ExpectedFound {
1421 expected,
1422 found: actual
1423 }))
1424 .emit();
1425 }
1426
1427 pub fn replace_late_bound_regions_with_fresh_var<T>(
1428 &self,
1429 span: Span,
1430 lbrct: LateBoundRegionConversionTime,
1431 value: &ty::Binder<T>)
1432 -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1433 where T : TypeFoldable<'tcx>
1434 {
1435 self.tcx.replace_late_bound_regions(
1436 value,
1437 |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1438 }
1439
1440 /// Given a higher-ranked projection predicate like:
1441 ///
1442 /// for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1443 ///
1444 /// and a target trait-ref like:
1445 ///
1446 /// <T as Fn<&'x u32>>
1447 ///
1448 /// find a substitution `S` for the higher-ranked regions (here,
1449 /// `['a => 'x]`) such that the predicate matches the trait-ref,
1450 /// and then return the value (here, `&'a u32`) but with the
1451 /// substitution applied (hence, `&'x u32`).
1452 ///
1453 /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1454 /// details.
1455 pub fn match_poly_projection_predicate(&self,
1456 cause: ObligationCause<'tcx>,
1457 param_env: ty::ParamEnv<'tcx>,
1458 match_a: ty::PolyProjectionPredicate<'tcx>,
1459 match_b: ty::TraitRef<'tcx>)
1460 -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1461 {
1462 let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref(self.tcx), p.ty));
1463 let trace = TypeTrace {
1464 cause,
1465 values: TraitRefs(ExpectedFound::new(true, match_pair.skip_binder().0, match_b))
1466 };
1467
1468 let mut combine = self.combine_fields(trace, param_env);
1469 let result = combine.higher_ranked_match(&match_pair, &match_b, true)?;
1470 Ok(InferOk { value: result, obligations: combine.obligations })
1471 }
1472
1473 /// See `verify_generic_bound` method in `region_constraints`
1474 pub fn verify_generic_bound(&self,
1475 origin: SubregionOrigin<'tcx>,
1476 kind: GenericKind<'tcx>,
1477 a: ty::Region<'tcx>,
1478 bound: VerifyBound<'tcx>) {
1479 debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1480 kind,
1481 a,
1482 bound);
1483
1484 self.borrow_region_constraints().verify_generic_bound(origin, kind, a, bound);
1485 }
1486
1487 pub fn type_moves_by_default(&self,
1488 param_env: ty::ParamEnv<'tcx>,
1489 ty: Ty<'tcx>,
1490 span: Span)
1491 -> bool {
1492 let ty = self.resolve_type_vars_if_possible(&ty);
1493 // Even if the type may have no inference variables, during
1494 // type-checking closure types are in local tables only.
1495 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1496 if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1497 return ty.moves_by_default(self.tcx.global_tcx(), param_env, span);
1498 }
1499 }
1500
1501 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1502
1503 // this can get called from typeck (by euv), and moves_by_default
1504 // rightly refuses to work with inference variables, but
1505 // moves_by_default has a cache, which we want to use in other
1506 // cases.
1507 !traits::type_known_to_meet_bound(self, param_env, ty, copy_def_id, span)
1508 }
1509
1510 /// Obtains the latest type of the given closure; this may be a
1511 /// closure in the current function, in which case its
1512 /// `ClosureKind` may not yet be known.
1513 pub fn closure_kind(&self,
1514 closure_def_id: DefId,
1515 closure_substs: ty::ClosureSubsts<'tcx>)
1516 -> Option<ty::ClosureKind>
1517 {
1518 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx);
1519 let closure_kind_ty = self.shallow_resolve(&closure_kind_ty);
1520 closure_kind_ty.to_opt_closure_kind()
1521 }
1522
1523 /// Obtain the signature of a closure. For closures, unlike
1524 /// `tcx.fn_sig(def_id)`, this method will work during the
1525 /// type-checking of the enclosing function and return the closure
1526 /// signature in its partially inferred state.
1527 pub fn closure_sig(
1528 &self,
1529 def_id: DefId,
1530 substs: ty::ClosureSubsts<'tcx>
1531 ) -> ty::PolyFnSig<'tcx> {
1532 let closure_sig_ty = substs.closure_sig_ty(def_id, self.tcx);
1533 let closure_sig_ty = self.shallow_resolve(&closure_sig_ty);
1534 closure_sig_ty.fn_sig(self.tcx)
1535 }
1536
1537 /// Normalizes associated types in `value`, potentially returning
1538 /// new obligations that must further be processed.
1539 pub fn partially_normalize_associated_types_in<T>(&self,
1540 span: Span,
1541 body_id: ast::NodeId,
1542 param_env: ty::ParamEnv<'tcx>,
1543 value: &T)
1544 -> InferOk<'tcx, T>
1545 where T : TypeFoldable<'tcx>
1546 {
1547 debug!("partially_normalize_associated_types_in(value={:?})", value);
1548 let mut selcx = traits::SelectionContext::new(self);
1549 let cause = ObligationCause::misc(span, body_id);
1550 let traits::Normalized { value, obligations } =
1551 traits::normalize(&mut selcx, param_env, cause, value);
1552 debug!("partially_normalize_associated_types_in: result={:?} predicates={:?}",
1553 value,
1554 obligations);
1555 InferOk { value, obligations }
1556 }
1557
1558 fn borrow_region_constraints(&self) -> RefMut<'_, RegionConstraintCollector<'tcx>> {
1559 RefMut::map(
1560 self.region_constraints.borrow_mut(),
1561 |c| c.as_mut().expect("region constraints already solved"))
1562 }
1563 }
1564
1565 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1566 pub fn span(&self) -> Span {
1567 self.cause.span
1568 }
1569
1570 pub fn types(cause: &ObligationCause<'tcx>,
1571 a_is_expected: bool,
1572 a: Ty<'tcx>,
1573 b: Ty<'tcx>)
1574 -> TypeTrace<'tcx> {
1575 TypeTrace {
1576 cause: cause.clone(),
1577 values: Types(ExpectedFound::new(a_is_expected, a, b))
1578 }
1579 }
1580
1581 pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1582 TypeTrace {
1583 cause: ObligationCause::dummy(),
1584 values: Types(ExpectedFound {
1585 expected: tcx.types.err,
1586 found: tcx.types.err,
1587 })
1588 }
1589 }
1590 }
1591
1592 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1593 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1594 write!(f, "TypeTrace({:?})", self.cause)
1595 }
1596 }
1597
1598 impl<'tcx> SubregionOrigin<'tcx> {
1599 pub fn span(&self) -> Span {
1600 match *self {
1601 Subtype(ref a) => a.span(),
1602 InfStackClosure(a) => a,
1603 InvokeClosure(a) => a,
1604 DerefPointer(a) => a,
1605 FreeVariable(a, _) => a,
1606 IndexSlice(a) => a,
1607 RelateObjectBound(a) => a,
1608 RelateParamBound(a, _) => a,
1609 RelateRegionParamBound(a) => a,
1610 RelateDefaultParamBound(a, _) => a,
1611 Reborrow(a) => a,
1612 ReborrowUpvar(a, _) => a,
1613 DataBorrowed(_, a) => a,
1614 ReferenceOutlivesReferent(_, a) => a,
1615 ParameterInScope(_, a) => a,
1616 ExprTypeIsNotInScope(_, a) => a,
1617 BindingTypeIsNotValidAtDecl(a) => a,
1618 CallRcvr(a) => a,
1619 CallArg(a) => a,
1620 CallReturn(a) => a,
1621 Operand(a) => a,
1622 AddrOf(a) => a,
1623 AutoBorrow(a) => a,
1624 SafeDestructor(a) => a,
1625 CompareImplMethodObligation { span, .. } => span,
1626 }
1627 }
1628
1629 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>,
1630 default: F)
1631 -> Self
1632 where F: FnOnce() -> Self
1633 {
1634 match cause.code {
1635 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
1636 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span),
1637
1638 traits::ObligationCauseCode::CompareImplMethodObligation { item_name,
1639 impl_item_def_id,
1640 trait_item_def_id, } =>
1641 SubregionOrigin::CompareImplMethodObligation {
1642 span: cause.span,
1643 item_name,
1644 impl_item_def_id,
1645 trait_item_def_id,
1646 },
1647
1648 _ => default(),
1649 }
1650 }
1651 }
1652
1653 impl RegionVariableOrigin {
1654 pub fn span(&self) -> Span {
1655 match *self {
1656 MiscVariable(a) => a,
1657 PatternRegion(a) => a,
1658 AddrOfRegion(a) => a,
1659 Autoref(a) => a,
1660 Coercion(a) => a,
1661 EarlyBoundRegion(a, ..) => a,
1662 LateBoundRegion(a, ..) => a,
1663 BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1664 UpvarRegion(_, a) => a,
1665 NLL(..) => bug!("NLL variable used with `span`"),
1666 }
1667 }
1668 }
1669
1670 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1671 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1672 match *self {
1673 ValuePairs::Types(ref ef) => {
1674 ValuePairs::Types(ef.fold_with(folder))
1675 }
1676 ValuePairs::TraitRefs(ref ef) => {
1677 ValuePairs::TraitRefs(ef.fold_with(folder))
1678 }
1679 ValuePairs::PolyTraitRefs(ref ef) => {
1680 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1681 }
1682 }
1683 }
1684
1685 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1686 match *self {
1687 ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1688 ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1689 ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1690 }
1691 }
1692 }
1693
1694 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1695 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1696 TypeTrace {
1697 cause: self.cause.fold_with(folder),
1698 values: self.values.fold_with(folder)
1699 }
1700 }
1701
1702 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1703 self.cause.visit_with(visitor) || self.values.visit_with(visitor)
1704 }
1705 }
1706
1707 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1708 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1709 write!(f, "RegionObligation(sub_region={:?}, sup_type={:?})",
1710 self.sub_region,
1711 self.sup_type)
1712 }
1713 }
1714