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