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