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