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