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