]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/mod.rs
Rollup merge of #97992 - m-ou-se:stabilize-scoped-threads, r=joshtriplett
[rust.git] / compiler / rustc_infer / src / infer / mod.rs
1 pub use self::freshen::TypeFreshener;
2 pub use self::lexical_region_resolve::RegionResolutionError;
3 pub use self::LateBoundRegionConversionTime::*;
4 pub use self::RegionVariableOrigin::*;
5 pub use self::SubregionOrigin::*;
6 pub use self::ValuePairs::*;
7
8 use self::opaque_types::OpaqueTypeStorage;
9 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
10
11 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
12
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_data_structures::sync::Lrc;
15 use rustc_data_structures::undo_log::Rollback;
16 use rustc_data_structures::unify as ut;
17 use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed};
18 use rustc_hir as hir;
19 use rustc_hir::def_id::{DefId, LocalDefId};
20 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
21 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
22 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
23 use rustc_middle::mir::interpret::{ErrorHandled, EvalToConstValueResult};
24 use rustc_middle::traits::select;
25 use rustc_middle::ty::error::{ExpectedFound, TypeError};
26 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
27 use rustc_middle::ty::relate::RelateResult;
28 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
29 pub use rustc_middle::ty::IntVarValue;
30 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
31 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
32 use rustc_span::symbol::Symbol;
33 use rustc_span::Span;
34
35 use std::cell::{Cell, Ref, RefCell};
36 use std::fmt;
37
38 use self::combine::CombineFields;
39 use self::free_regions::RegionRelations;
40 use self::lexical_region_resolve::LexicalRegionResolutions;
41 use self::outlives::env::OutlivesEnvironment;
42 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
43 use self::region_constraints::{
44     RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
45 };
46 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
47
48 pub mod at;
49 pub mod canonical;
50 mod combine;
51 mod equate;
52 pub mod error_reporting;
53 pub mod free_regions;
54 mod freshen;
55 mod fudge;
56 mod glb;
57 mod higher_ranked;
58 pub mod lattice;
59 mod lexical_region_resolve;
60 mod lub;
61 pub mod nll_relate;
62 pub mod opaque_types;
63 pub mod outlives;
64 mod projection;
65 pub mod region_constraints;
66 pub mod resolve;
67 mod sub;
68 pub mod type_variable;
69 mod undo_log;
70
71 #[must_use]
72 #[derive(Debug)]
73 pub struct InferOk<'tcx, T> {
74     pub value: T,
75     pub obligations: PredicateObligations<'tcx>,
76 }
77 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
78
79 pub type Bound<T> = Option<T>;
80 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
81 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
82
83 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
84     ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
85 >;
86
87 /// How we should handle region solving.
88 ///
89 /// This is used so that the region values inferred by HIR region solving are
90 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
91 /// typeck will also do.
92 #[derive(Copy, Clone, Debug, Default)]
93 pub enum RegionckMode {
94     /// The default mode: report region errors, don't erase regions.
95     #[default]
96     Solve,
97     /// Erase the results of region after solving.
98     Erase,
99 }
100
101 /// This type contains all the things within `InferCtxt` that sit within a
102 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
103 /// operations are hot enough that we want only one call to `borrow_mut` per
104 /// call to `start_snapshot` and `rollback_to`.
105 #[derive(Clone)]
106 pub struct InferCtxtInner<'tcx> {
107     /// Cache for projections. This cache is snapshotted along with the infcx.
108     ///
109     /// Public so that `traits::project` can use it.
110     pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
111
112     /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
113     /// that might instantiate a general type variable have an order,
114     /// represented by its upper and lower bounds.
115     type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
116
117     /// Map from const parameter variable to the kind of const it represents.
118     const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
119
120     /// Map from integral variable to the kind of integer it represents.
121     int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
122
123     /// Map from floating variable to the kind of float it represents.
124     float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
125
126     /// Tracks the set of region variables and the constraints between them.
127     /// This is initially `Some(_)` but when
128     /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
129     /// -- further attempts to perform unification, etc., may fail if new
130     /// region constraints would've been added.
131     region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
132
133     /// A set of constraints that regionck must validate. Each
134     /// constraint has the form `T:'a`, meaning "some type `T` must
135     /// outlive the lifetime 'a". These constraints derive from
136     /// instantiated type parameters. So if you had a struct defined
137     /// like
138     /// ```ignore (illustrative)
139     ///     struct Foo<T:'static> { ... }
140     /// ```
141     /// then in some expression `let x = Foo { ... }` it will
142     /// instantiate the type parameter `T` with a fresh type `$0`. At
143     /// the same time, it will record a region obligation of
144     /// `$0:'static`. This will get checked later by regionck. (We
145     /// can't generally check these things right away because we have
146     /// to wait until types are resolved.)
147     ///
148     /// These are stored in a map keyed to the id of the innermost
149     /// enclosing fn body / static initializer expression. This is
150     /// because the location where the obligation was incurred can be
151     /// relevant with respect to which sublifetime assumptions are in
152     /// place. The reason that we store under the fn-id, and not
153     /// something more fine-grained, is so that it is easier for
154     /// regionck to be sure that it has found *all* the region
155     /// obligations (otherwise, it's easy to fail to walk to a
156     /// particular node-id).
157     ///
158     /// Before running `resolve_regions_and_report_errors`, the creator
159     /// of the inference context is expected to invoke
160     /// [`InferCtxt::process_registered_region_obligations`]
161     /// for each body-id in this map, which will process the
162     /// obligations within. This is expected to be done 'late enough'
163     /// that all type inference variables have been bound and so forth.
164     region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
165
166     undo_log: InferCtxtUndoLogs<'tcx>,
167
168     /// Caches for opaque type inference.
169     pub opaque_type_storage: OpaqueTypeStorage<'tcx>,
170 }
171
172 impl<'tcx> InferCtxtInner<'tcx> {
173     fn new() -> InferCtxtInner<'tcx> {
174         InferCtxtInner {
175             projection_cache: Default::default(),
176             type_variable_storage: type_variable::TypeVariableStorage::new(),
177             undo_log: InferCtxtUndoLogs::default(),
178             const_unification_storage: ut::UnificationTableStorage::new(),
179             int_unification_storage: ut::UnificationTableStorage::new(),
180             float_unification_storage: ut::UnificationTableStorage::new(),
181             region_constraint_storage: Some(RegionConstraintStorage::new()),
182             region_obligations: vec![],
183             opaque_type_storage: Default::default(),
184         }
185     }
186
187     #[inline]
188     pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
189         &self.region_obligations
190     }
191
192     #[inline]
193     pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
194         self.projection_cache.with_log(&mut self.undo_log)
195     }
196
197     #[inline]
198     fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
199         self.type_variable_storage.with_log(&mut self.undo_log)
200     }
201
202     #[inline]
203     pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
204         self.opaque_type_storage.with_log(&mut self.undo_log)
205     }
206
207     #[inline]
208     fn int_unification_table(
209         &mut self,
210     ) -> ut::UnificationTable<
211         ut::InPlace<
212             ty::IntVid,
213             &mut ut::UnificationStorage<ty::IntVid>,
214             &mut InferCtxtUndoLogs<'tcx>,
215         >,
216     > {
217         self.int_unification_storage.with_log(&mut self.undo_log)
218     }
219
220     #[inline]
221     fn float_unification_table(
222         &mut self,
223     ) -> ut::UnificationTable<
224         ut::InPlace<
225             ty::FloatVid,
226             &mut ut::UnificationStorage<ty::FloatVid>,
227             &mut InferCtxtUndoLogs<'tcx>,
228         >,
229     > {
230         self.float_unification_storage.with_log(&mut self.undo_log)
231     }
232
233     #[inline]
234     fn const_unification_table(
235         &mut self,
236     ) -> ut::UnificationTable<
237         ut::InPlace<
238             ty::ConstVid<'tcx>,
239             &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
240             &mut InferCtxtUndoLogs<'tcx>,
241         >,
242     > {
243         self.const_unification_storage.with_log(&mut self.undo_log)
244     }
245
246     #[inline]
247     pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
248         self.region_constraint_storage
249             .as_mut()
250             .expect("region constraints already solved")
251             .with_log(&mut self.undo_log)
252     }
253 }
254
255 pub struct InferCtxt<'a, 'tcx> {
256     pub tcx: TyCtxt<'tcx>,
257
258     /// The `DefId` of the item in whose context we are performing inference or typeck.
259     /// It is used to check whether an opaque type use is a defining use.
260     ///
261     /// If it is `None`, we can't resolve opaque types here and need to bubble up
262     /// the obligation. This frequently happens for
263     /// short lived InferCtxt within queries. The opaque type obligations are forwarded
264     /// to the outside until the end up in an `InferCtxt` for typeck or borrowck.
265     pub defining_use_anchor: Option<LocalDefId>,
266
267     /// During type-checking/inference of a body, `in_progress_typeck_results`
268     /// contains a reference to the typeck results being built up, which are
269     /// used for reading closure kinds/signatures as they are inferred,
270     /// and for error reporting logic to read arbitrary node types.
271     pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
272
273     pub inner: RefCell<InferCtxtInner<'tcx>>,
274
275     /// If set, this flag causes us to skip the 'leak check' during
276     /// higher-ranked subtyping operations. This flag is a temporary one used
277     /// to manage the removal of the leak-check: for the time being, we still run the
278     /// leak-check, but we issue warnings. This flag can only be set to true
279     /// when entering a snapshot.
280     skip_leak_check: Cell<bool>,
281
282     /// Once region inference is done, the values for each variable.
283     lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
284
285     /// Caches the results of trait selection. This cache is used
286     /// for things that have to do with the parameters in scope.
287     pub selection_cache: select::SelectionCache<'tcx>,
288
289     /// Caches the results of trait evaluation.
290     pub evaluation_cache: select::EvaluationCache<'tcx>,
291
292     /// the set of predicates on which errors have been reported, to
293     /// avoid reporting the same error twice.
294     pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
295
296     pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
297
298     /// When an error occurs, we want to avoid reporting "derived"
299     /// errors that are due to this original failure. Normally, we
300     /// handle this with the `err_count_on_creation` count, which
301     /// basically just tracks how many errors were reported when we
302     /// started type-checking a fn and checks to see if any new errors
303     /// have been reported since then. Not great, but it works.
304     ///
305     /// However, when errors originated in other passes -- notably
306     /// resolve -- this heuristic breaks down. Therefore, we have this
307     /// auxiliary flag that one can set whenever one creates a
308     /// type-error that is due to an error in a prior pass.
309     ///
310     /// Don't read this flag directly, call `is_tainted_by_errors()`
311     /// and `set_tainted_by_errors()`.
312     tainted_by_errors_flag: Cell<bool>,
313
314     /// Track how many errors were reported when this infcx is created.
315     /// If the number of errors increases, that's also a sign (line
316     /// `tainted_by_errors`) to avoid reporting certain kinds of errors.
317     // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
318     err_count_on_creation: usize,
319
320     /// This flag is true while there is an active snapshot.
321     in_snapshot: Cell<bool>,
322
323     /// What is the innermost universe we have created? Starts out as
324     /// `UniverseIndex::root()` but grows from there as we enter
325     /// universal quantifiers.
326     ///
327     /// N.B., at present, we exclude the universal quantifiers on the
328     /// item we are type-checking, and just consider those names as
329     /// part of the root universe. So this would only get incremented
330     /// when we enter into a higher-ranked (`for<..>`) type or trait
331     /// bound.
332     universe: Cell<ty::UniverseIndex>,
333 }
334
335 /// See the `error_reporting` module for more details.
336 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
337 pub enum ValuePairs<'tcx> {
338     Regions(ExpectedFound<ty::Region<'tcx>>),
339     Terms(ExpectedFound<ty::Term<'tcx>>),
340     TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
341     PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
342 }
343
344 impl<'tcx> ValuePairs<'tcx> {
345     pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
346         if let ValuePairs::Terms(ExpectedFound {
347             expected: ty::Term::Ty(expected),
348             found: ty::Term::Ty(found),
349         }) = self
350         {
351             Some((*expected, *found))
352         } else {
353             None
354         }
355     }
356 }
357
358 /// The trace designates the path through inference that we took to
359 /// encounter an error or subtyping constraint.
360 ///
361 /// See the `error_reporting` module for more details.
362 #[derive(Clone, Debug)]
363 pub struct TypeTrace<'tcx> {
364     pub cause: ObligationCause<'tcx>,
365     pub values: ValuePairs<'tcx>,
366 }
367
368 /// The origin of a `r1 <= r2` constraint.
369 ///
370 /// See `error_reporting` module for more details
371 #[derive(Clone, Debug)]
372 pub enum SubregionOrigin<'tcx> {
373     /// Arose from a subtyping relation
374     Subtype(Box<TypeTrace<'tcx>>),
375
376     /// When casting `&'a T` to an `&'b Trait` object,
377     /// relating `'a` to `'b`
378     RelateObjectBound(Span),
379
380     /// Some type parameter was instantiated with the given type,
381     /// and that type must outlive some region.
382     RelateParamBound(Span, Ty<'tcx>, Option<Span>),
383
384     /// The given region parameter was instantiated with a region
385     /// that must outlive some other region.
386     RelateRegionParamBound(Span),
387
388     /// Creating a pointer `b` to contents of another reference
389     Reborrow(Span),
390
391     /// Creating a pointer `b` to contents of an upvar
392     ReborrowUpvar(Span, ty::UpvarId),
393
394     /// Data with type `Ty<'tcx>` was borrowed
395     DataBorrowed(Ty<'tcx>, Span),
396
397     /// (&'a &'b T) where a >= b
398     ReferenceOutlivesReferent(Ty<'tcx>, Span),
399
400     /// Comparing the signature and requirements of an impl method against
401     /// the containing trait.
402     CompareImplMethodObligation {
403         span: Span,
404         impl_item_def_id: LocalDefId,
405         trait_item_def_id: DefId,
406     },
407
408     /// Comparing the signature and requirements of an impl associated type
409     /// against the containing trait
410     CompareImplTypeObligation { span: Span, impl_item_def_id: LocalDefId, trait_item_def_id: DefId },
411
412     /// Checking that the bounds of a trait's associated type hold for a given impl
413     CheckAssociatedTypeBounds {
414         parent: Box<SubregionOrigin<'tcx>>,
415         impl_item_def_id: LocalDefId,
416         trait_item_def_id: DefId,
417     },
418 }
419
420 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
421 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
422 static_assert_size!(SubregionOrigin<'_>, 32);
423
424 /// Times when we replace late-bound regions with variables:
425 #[derive(Clone, Copy, Debug)]
426 pub enum LateBoundRegionConversionTime {
427     /// when a fn is called
428     FnCall,
429
430     /// when two higher-ranked types are compared
431     HigherRankedType,
432
433     /// when projecting an associated type
434     AssocTypeProjection(DefId),
435 }
436
437 /// Reasons to create a region inference variable
438 ///
439 /// See `error_reporting` module for more details
440 #[derive(Copy, Clone, Debug)]
441 pub enum RegionVariableOrigin {
442     /// Region variables created for ill-categorized reasons,
443     /// mostly indicates places in need of refactoring
444     MiscVariable(Span),
445
446     /// Regions created by a `&P` or `[...]` pattern
447     PatternRegion(Span),
448
449     /// Regions created by `&` operator
450     AddrOfRegion(Span),
451
452     /// Regions created as part of an autoref of a method receiver
453     Autoref(Span),
454
455     /// Regions created as part of an automatic coercion
456     Coercion(Span),
457
458     /// Region variables created as the values for early-bound regions
459     EarlyBoundRegion(Span, Symbol),
460
461     /// Region variables created for bound regions
462     /// in a function or method that is called
463     LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
464
465     UpvarRegion(ty::UpvarId, Span),
466
467     /// This origin is used for the inference variables that we create
468     /// during NLL region processing.
469     Nll(NllRegionVariableOrigin),
470 }
471
472 #[derive(Copy, Clone, Debug)]
473 pub enum NllRegionVariableOrigin {
474     /// During NLL region processing, we create variables for free
475     /// regions that we encounter in the function signature and
476     /// elsewhere. This origin indices we've got one of those.
477     FreeRegion,
478
479     /// "Universal" instantiation of a higher-ranked region (e.g.,
480     /// from a `for<'a> T` binder). Meant to represent "any region".
481     Placeholder(ty::PlaceholderRegion),
482
483     /// The variable we create to represent `'empty(U0)`.
484     RootEmptyRegion,
485
486     Existential {
487         /// If this is true, then this variable was created to represent a lifetime
488         /// bound in a `for` binder. For example, it might have been created to
489         /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
490         /// Such variables are created when we are trying to figure out if there
491         /// is any valid instantiation of `'a` that could fit into some scenario.
492         ///
493         /// This is used to inform error reporting: in the case that we are trying to
494         /// determine whether there is any valid instantiation of a `'a` variable that meets
495         /// some constraint C, we want to blame the "source" of that `for` type,
496         /// rather than blaming the source of the constraint C.
497         from_forall: bool,
498     },
499 }
500
501 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
502 #[derive(Copy, Clone, Debug)]
503 pub enum FixupError<'tcx> {
504     UnresolvedIntTy(IntVid),
505     UnresolvedFloatTy(FloatVid),
506     UnresolvedTy(TyVid),
507     UnresolvedConst(ConstVid<'tcx>),
508 }
509
510 /// See the `region_obligations` field for more information.
511 #[derive(Clone)]
512 pub struct RegionObligation<'tcx> {
513     pub sub_region: ty::Region<'tcx>,
514     pub sup_type: Ty<'tcx>,
515     pub origin: SubregionOrigin<'tcx>,
516 }
517
518 impl<'tcx> fmt::Display for FixupError<'tcx> {
519     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520         use self::FixupError::*;
521
522         match *self {
523             UnresolvedIntTy(_) => write!(
524                 f,
525                 "cannot determine the type of this integer; \
526                  add a suffix to specify the type explicitly"
527             ),
528             UnresolvedFloatTy(_) => write!(
529                 f,
530                 "cannot determine the type of this number; \
531                  add a suffix to specify the type explicitly"
532             ),
533             UnresolvedTy(_) => write!(f, "unconstrained type"),
534             UnresolvedConst(_) => write!(f, "unconstrained const value"),
535         }
536     }
537 }
538
539 /// A temporary returned by `tcx.infer_ctxt()`. This is necessary
540 /// for multiple `InferCtxt` to share the same `in_progress_typeck_results`
541 /// without using `Rc` or something similar.
542 pub struct InferCtxtBuilder<'tcx> {
543     tcx: TyCtxt<'tcx>,
544     fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
545     defining_use_anchor: Option<LocalDefId>,
546 }
547
548 pub trait TyCtxtInferExt<'tcx> {
549     fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
550 }
551
552 impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
553     fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
554         InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None }
555     }
556 }
557
558 impl<'tcx> InferCtxtBuilder<'tcx> {
559     /// Used only by `rustc_typeck` during body type-checking/inference,
560     /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
561     /// Will also change the scope for opaque type defining use checks to the given owner.
562     pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
563         self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
564         self.with_opaque_type_inference(table_owner)
565     }
566
567     /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
568     /// you need to call this function. Otherwise the opaque type will be treated opaquely.
569     ///
570     /// It is only meant to be called in two places, for typeck
571     /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used
572     /// in mir borrowck.
573     pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self {
574         self.defining_use_anchor = Some(defining_use_anchor);
575         self
576     }
577
578     /// Given a canonical value `C` as a starting point, create an
579     /// inference context that contains each of the bound values
580     /// within instantiated as a fresh variable. The `f` closure is
581     /// invoked with the new infcx, along with the instantiated value
582     /// `V` and a substitution `S`. This substitution `S` maps from
583     /// the bound values in `C` to their instantiated values in `V`
584     /// (in other words, `S(C) = V`).
585     pub fn enter_with_canonical<T, R>(
586         &mut self,
587         span: Span,
588         canonical: &Canonical<'tcx, T>,
589         f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
590     ) -> R
591     where
592         T: TypeFoldable<'tcx>,
593     {
594         self.enter(|infcx| {
595             let (value, subst) =
596                 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
597             f(infcx, value, subst)
598         })
599     }
600
601     pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
602         let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self;
603         let in_progress_typeck_results = fresh_typeck_results.as_ref();
604         f(InferCtxt {
605             tcx,
606             defining_use_anchor,
607             in_progress_typeck_results,
608             inner: RefCell::new(InferCtxtInner::new()),
609             lexical_region_resolutions: RefCell::new(None),
610             selection_cache: Default::default(),
611             evaluation_cache: Default::default(),
612             reported_trait_errors: Default::default(),
613             reported_closure_mismatch: Default::default(),
614             tainted_by_errors_flag: Cell::new(false),
615             err_count_on_creation: tcx.sess.err_count(),
616             in_snapshot: Cell::new(false),
617             skip_leak_check: Cell::new(false),
618             universe: Cell::new(ty::UniverseIndex::ROOT),
619         })
620     }
621 }
622
623 impl<'tcx, T> InferOk<'tcx, T> {
624     pub fn unit(self) -> InferOk<'tcx, ()> {
625         InferOk { value: (), obligations: self.obligations }
626     }
627
628     /// Extracts `value`, registering any obligations into `fulfill_cx`.
629     pub fn into_value_registering_obligations(
630         self,
631         infcx: &InferCtxt<'_, 'tcx>,
632         fulfill_cx: &mut dyn TraitEngine<'tcx>,
633     ) -> T {
634         let InferOk { value, obligations } = self;
635         for obligation in obligations {
636             fulfill_cx.register_predicate_obligation(infcx, obligation);
637         }
638         value
639     }
640 }
641
642 impl<'tcx> InferOk<'tcx, ()> {
643     pub fn into_obligations(self) -> PredicateObligations<'tcx> {
644         self.obligations
645     }
646 }
647
648 #[must_use = "once you start a snapshot, you should always consume it"]
649 pub struct CombinedSnapshot<'a, 'tcx> {
650     undo_snapshot: Snapshot<'tcx>,
651     region_constraints_snapshot: RegionSnapshot,
652     universe: ty::UniverseIndex,
653     was_in_snapshot: bool,
654     _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
655 }
656
657 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
658     /// calls `tcx.try_unify_abstract_consts` after
659     /// canonicalizing the consts.
660     #[instrument(skip(self), level = "debug")]
661     pub fn try_unify_abstract_consts(
662         &self,
663         a: ty::Unevaluated<'tcx, ()>,
664         b: ty::Unevaluated<'tcx, ()>,
665         param_env: ty::ParamEnv<'tcx>,
666     ) -> bool {
667         // Reject any attempt to unify two unevaluated constants that contain inference
668         // variables, since inference variables in queries lead to ICEs.
669         if a.substs.has_infer_types_or_consts()
670             || b.substs.has_infer_types_or_consts()
671             || param_env.has_infer_types_or_consts()
672         {
673             debug!("a or b or param_env contain infer vars in its substs -> cannot unify");
674             return false;
675         }
676
677         let param_env_and = param_env.and((a, b));
678         let erased = self.tcx.erase_regions(param_env_and);
679         debug!("after erase_regions: {:?}", erased);
680
681         self.tcx.try_unify_abstract_consts(erased)
682     }
683
684     pub fn is_in_snapshot(&self) -> bool {
685         self.in_snapshot.get()
686     }
687
688     pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
689         t.fold_with(&mut self.freshener())
690     }
691
692     /// Returns the origin of the type variable identified by `vid`, or `None`
693     /// if this is not a type variable.
694     ///
695     /// No attempt is made to resolve `ty`.
696     pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
697         match *ty.kind() {
698             ty::Infer(ty::TyVar(vid)) => {
699                 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
700             }
701             _ => None,
702         }
703     }
704
705     pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
706         freshen::TypeFreshener::new(self, false)
707     }
708
709     /// Like `freshener`, but does not replace `'static` regions.
710     pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
711         freshen::TypeFreshener::new(self, true)
712     }
713
714     pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
715         let mut inner = self.inner.borrow_mut();
716         let mut vars: Vec<Ty<'_>> = inner
717             .type_variables()
718             .unsolved_variables()
719             .into_iter()
720             .map(|t| self.tcx.mk_ty_var(t))
721             .collect();
722         vars.extend(
723             (0..inner.int_unification_table().len())
724                 .map(|i| ty::IntVid { index: i as u32 })
725                 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
726                 .map(|v| self.tcx.mk_int_var(v)),
727         );
728         vars.extend(
729             (0..inner.float_unification_table().len())
730                 .map(|i| ty::FloatVid { index: i as u32 })
731                 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
732                 .map(|v| self.tcx.mk_float_var(v)),
733         );
734         vars
735     }
736
737     fn combine_fields(
738         &'a self,
739         trace: TypeTrace<'tcx>,
740         param_env: ty::ParamEnv<'tcx>,
741         define_opaque_types: bool,
742     ) -> CombineFields<'a, 'tcx> {
743         CombineFields {
744             infcx: self,
745             trace,
746             cause: None,
747             param_env,
748             obligations: PredicateObligations::new(),
749             define_opaque_types,
750         }
751     }
752
753     /// Clear the "currently in a snapshot" flag, invoke the closure,
754     /// then restore the flag to its original value. This flag is a
755     /// debugging measure designed to detect cases where we start a
756     /// snapshot, create type variables, and register obligations
757     /// which may involve those type variables in the fulfillment cx,
758     /// potentially leaving "dangling type variables" behind.
759     /// In such cases, an assertion will fail when attempting to
760     /// register obligations, within a snapshot. Very useful, much
761     /// better than grovelling through megabytes of `RUSTC_LOG` output.
762     ///
763     /// HOWEVER, in some cases the flag is unhelpful. In particular, we
764     /// sometimes create a "mini-fulfilment-cx" in which we enroll
765     /// obligations. As long as this fulfillment cx is fully drained
766     /// before we return, this is not a problem, as there won't be any
767     /// escaping obligations in the main cx. In those cases, you can
768     /// use this function.
769     pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
770     where
771         F: FnOnce(&Self) -> R,
772     {
773         let flag = self.in_snapshot.replace(false);
774         let result = func(self);
775         self.in_snapshot.set(flag);
776         result
777     }
778
779     fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
780         debug!("start_snapshot()");
781
782         let in_snapshot = self.in_snapshot.replace(true);
783
784         let mut inner = self.inner.borrow_mut();
785
786         CombinedSnapshot {
787             undo_snapshot: inner.undo_log.start_snapshot(),
788             region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
789             universe: self.universe(),
790             was_in_snapshot: in_snapshot,
791             // Borrow typeck results "in progress" (i.e., during typeck)
792             // to ban writes from within a snapshot to them.
793             _in_progress_typeck_results: self
794                 .in_progress_typeck_results
795                 .map(|typeck_results| typeck_results.borrow()),
796         }
797     }
798
799     #[instrument(skip(self, snapshot), level = "debug")]
800     fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
801         let CombinedSnapshot {
802             undo_snapshot,
803             region_constraints_snapshot,
804             universe,
805             was_in_snapshot,
806             _in_progress_typeck_results,
807         } = snapshot;
808
809         self.in_snapshot.set(was_in_snapshot);
810         self.universe.set(universe);
811
812         let mut inner = self.inner.borrow_mut();
813         inner.rollback_to(undo_snapshot);
814         inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
815     }
816
817     #[instrument(skip(self, snapshot), level = "debug")]
818     fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
819         let CombinedSnapshot {
820             undo_snapshot,
821             region_constraints_snapshot: _,
822             universe: _,
823             was_in_snapshot,
824             _in_progress_typeck_results,
825         } = snapshot;
826
827         self.in_snapshot.set(was_in_snapshot);
828
829         self.inner.borrow_mut().commit(undo_snapshot);
830     }
831
832     /// Executes `f` and commit the bindings.
833     #[instrument(skip(self, f), level = "debug")]
834     pub fn commit_unconditionally<R, F>(&self, f: F) -> R
835     where
836         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
837     {
838         let snapshot = self.start_snapshot();
839         let r = f(&snapshot);
840         self.commit_from(snapshot);
841         r
842     }
843
844     /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
845     #[instrument(skip(self, f), level = "debug")]
846     pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
847     where
848         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
849     {
850         let snapshot = self.start_snapshot();
851         let r = f(&snapshot);
852         debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
853         match r {
854             Ok(_) => {
855                 self.commit_from(snapshot);
856             }
857             Err(_) => {
858                 self.rollback_to("commit_if_ok -- error", snapshot);
859             }
860         }
861         r
862     }
863
864     /// Execute `f` then unroll any bindings it creates.
865     #[instrument(skip(self, f), level = "debug")]
866     pub fn probe<R, F>(&self, f: F) -> R
867     where
868         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
869     {
870         let snapshot = self.start_snapshot();
871         let r = f(&snapshot);
872         self.rollback_to("probe", snapshot);
873         r
874     }
875
876     /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
877     #[instrument(skip(self, f), level = "debug")]
878     pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
879     where
880         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
881     {
882         let snapshot = self.start_snapshot();
883         let was_skip_leak_check = self.skip_leak_check.get();
884         if should_skip {
885             self.skip_leak_check.set(true);
886         }
887         let r = f(&snapshot);
888         self.rollback_to("probe", snapshot);
889         self.skip_leak_check.set(was_skip_leak_check);
890         r
891     }
892
893     /// Scan the constraints produced since `snapshot` began and returns:
894     ///
895     /// - `None` -- if none of them involve "region outlives" constraints
896     /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
897     /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
898     pub fn region_constraints_added_in_snapshot(
899         &self,
900         snapshot: &CombinedSnapshot<'a, 'tcx>,
901     ) -> Option<bool> {
902         self.inner
903             .borrow_mut()
904             .unwrap_region_constraints()
905             .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
906     }
907
908     pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
909         self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
910     }
911
912     pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
913     where
914         T: at::ToTrace<'tcx>,
915     {
916         let origin = &ObligationCause::dummy();
917         self.probe(|_| {
918             self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
919                 // Ignore obligations, since we are unrolling
920                 // everything anyway.
921             })
922         })
923     }
924
925     pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
926     where
927         T: at::ToTrace<'tcx>,
928     {
929         let origin = &ObligationCause::dummy();
930         self.probe(|_| {
931             self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
932                 // Ignore obligations, since we are unrolling
933                 // everything anyway.
934             })
935         })
936     }
937
938     #[instrument(skip(self), level = "debug")]
939     pub fn sub_regions(
940         &self,
941         origin: SubregionOrigin<'tcx>,
942         a: ty::Region<'tcx>,
943         b: ty::Region<'tcx>,
944     ) {
945         self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
946     }
947
948     /// Require that the region `r` be equal to one of the regions in
949     /// the set `regions`.
950     #[instrument(skip(self), level = "debug")]
951     pub fn member_constraint(
952         &self,
953         opaque_type_def_id: DefId,
954         definition_span: Span,
955         hidden_ty: Ty<'tcx>,
956         region: ty::Region<'tcx>,
957         in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
958     ) {
959         self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
960             opaque_type_def_id,
961             definition_span,
962             hidden_ty,
963             region,
964             in_regions,
965         );
966     }
967
968     /// Processes a `Coerce` predicate from the fulfillment context.
969     /// This is NOT the preferred way to handle coercion, which is to
970     /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
971     ///
972     /// This method here is actually a fallback that winds up being
973     /// invoked when `FnCtxt::coerce` encounters unresolved type variables
974     /// and records a coercion predicate. Presently, this method is equivalent
975     /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
976     /// actually requiring `a <: b`. This is of course a valid coercion,
977     /// but it's not as flexible as `FnCtxt::coerce` would be.
978     ///
979     /// (We may refactor this in the future, but there are a number of
980     /// practical obstacles. Among other things, `FnCtxt::coerce` presently
981     /// records adjustments that are required on the HIR in order to perform
982     /// the coercion, and we don't currently have a way to manage that.)
983     pub fn coerce_predicate(
984         &self,
985         cause: &ObligationCause<'tcx>,
986         param_env: ty::ParamEnv<'tcx>,
987         predicate: ty::PolyCoercePredicate<'tcx>,
988     ) -> Option<InferResult<'tcx, ()>> {
989         let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
990             a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
991             a: p.a,
992             b: p.b,
993         });
994         self.subtype_predicate(cause, param_env, subtype_predicate)
995     }
996
997     pub fn subtype_predicate(
998         &self,
999         cause: &ObligationCause<'tcx>,
1000         param_env: ty::ParamEnv<'tcx>,
1001         predicate: ty::PolySubtypePredicate<'tcx>,
1002     ) -> Option<InferResult<'tcx, ()>> {
1003         // Check for two unresolved inference variables, in which case we can
1004         // make no progress. This is partly a micro-optimization, but it's
1005         // also an opportunity to "sub-unify" the variables. This isn't
1006         // *necessary* to prevent cycles, because they would eventually be sub-unified
1007         // anyhow during generalization, but it helps with diagnostics (we can detect
1008         // earlier that they are sub-unified).
1009         //
1010         // Note that we can just skip the binders here because
1011         // type variables can't (at present, at
1012         // least) capture any of the things bound by this binder.
1013         //
1014         // Note that this sub here is not just for diagnostics - it has semantic
1015         // effects as well.
1016         let r_a = self.shallow_resolve(predicate.skip_binder().a);
1017         let r_b = self.shallow_resolve(predicate.skip_binder().b);
1018         match (r_a.kind(), r_b.kind()) {
1019             (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
1020                 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
1021                 return None;
1022             }
1023             _ => {}
1024         }
1025
1026         Some(self.commit_if_ok(|_snapshot| {
1027             let ty::SubtypePredicate { a_is_expected, a, b } =
1028                 self.replace_bound_vars_with_placeholders(predicate);
1029
1030             let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1031
1032             Ok(ok.unit())
1033         }))
1034     }
1035
1036     pub fn region_outlives_predicate(
1037         &self,
1038         cause: &traits::ObligationCause<'tcx>,
1039         predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1040     ) -> UnitResult<'tcx> {
1041         self.commit_if_ok(|_snapshot| {
1042             let ty::OutlivesPredicate(r_a, r_b) =
1043                 self.replace_bound_vars_with_placeholders(predicate);
1044             let origin = SubregionOrigin::from_obligation_cause(cause, || {
1045                 RelateRegionParamBound(cause.span)
1046             });
1047             self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1048             Ok(())
1049         })
1050     }
1051
1052     /// Number of type variables created so far.
1053     pub fn num_ty_vars(&self) -> usize {
1054         self.inner.borrow_mut().type_variables().num_vars()
1055     }
1056
1057     pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1058         self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1059     }
1060
1061     pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1062         self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1063     }
1064
1065     pub fn next_ty_var_id_in_universe(
1066         &self,
1067         origin: TypeVariableOrigin,
1068         universe: ty::UniverseIndex,
1069     ) -> TyVid {
1070         self.inner.borrow_mut().type_variables().new_var(universe, origin)
1071     }
1072
1073     pub fn next_ty_var_in_universe(
1074         &self,
1075         origin: TypeVariableOrigin,
1076         universe: ty::UniverseIndex,
1077     ) -> Ty<'tcx> {
1078         let vid = self.next_ty_var_id_in_universe(origin, universe);
1079         self.tcx.mk_ty_var(vid)
1080     }
1081
1082     pub fn next_const_var(&self, ty: Ty<'tcx>, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
1083         self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1084     }
1085
1086     pub fn next_const_var_in_universe(
1087         &self,
1088         ty: Ty<'tcx>,
1089         origin: ConstVariableOrigin,
1090         universe: ty::UniverseIndex,
1091     ) -> ty::Const<'tcx> {
1092         let vid = self
1093             .inner
1094             .borrow_mut()
1095             .const_unification_table()
1096             .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1097         self.tcx.mk_const_var(vid, ty)
1098     }
1099
1100     pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1101         self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1102             origin,
1103             val: ConstVariableValue::Unknown { universe: self.universe() },
1104         })
1105     }
1106
1107     fn next_int_var_id(&self) -> IntVid {
1108         self.inner.borrow_mut().int_unification_table().new_key(None)
1109     }
1110
1111     pub fn next_int_var(&self) -> Ty<'tcx> {
1112         self.tcx.mk_int_var(self.next_int_var_id())
1113     }
1114
1115     fn next_float_var_id(&self) -> FloatVid {
1116         self.inner.borrow_mut().float_unification_table().new_key(None)
1117     }
1118
1119     pub fn next_float_var(&self) -> Ty<'tcx> {
1120         self.tcx.mk_float_var(self.next_float_var_id())
1121     }
1122
1123     /// Creates a fresh region variable with the next available index.
1124     /// The variable will be created in the maximum universe created
1125     /// thus far, allowing it to name any region created thus far.
1126     pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1127         self.next_region_var_in_universe(origin, self.universe())
1128     }
1129
1130     /// Creates a fresh region variable with the next available index
1131     /// in the given universe; typically, you can use
1132     /// `next_region_var` and just use the maximal universe.
1133     pub fn next_region_var_in_universe(
1134         &self,
1135         origin: RegionVariableOrigin,
1136         universe: ty::UniverseIndex,
1137     ) -> ty::Region<'tcx> {
1138         let region_var =
1139             self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1140         self.tcx.mk_region(ty::ReVar(region_var))
1141     }
1142
1143     /// Return the universe that the region `r` was created in.  For
1144     /// most regions (e.g., `'static`, named regions from the user,
1145     /// etc) this is the root universe U0. For inference variables or
1146     /// placeholders, however, it will return the universe which which
1147     /// they are associated.
1148     pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1149         self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1150     }
1151
1152     /// Number of region variables created so far.
1153     pub fn num_region_vars(&self) -> usize {
1154         self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1155     }
1156
1157     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1158     pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1159         self.next_region_var(RegionVariableOrigin::Nll(origin))
1160     }
1161
1162     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1163     pub fn next_nll_region_var_in_universe(
1164         &self,
1165         origin: NllRegionVariableOrigin,
1166         universe: ty::UniverseIndex,
1167     ) -> ty::Region<'tcx> {
1168         self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1169     }
1170
1171     pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1172         match param.kind {
1173             GenericParamDefKind::Lifetime => {
1174                 // Create a region inference variable for the given
1175                 // region parameter definition.
1176                 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1177             }
1178             GenericParamDefKind::Type { .. } => {
1179                 // Create a type inference variable for the given
1180                 // type parameter definition. The substitutions are
1181                 // for actual parameters that may be referred to by
1182                 // the default of this type parameter, if it exists.
1183                 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1184                 // used in a path such as `Foo::<T, U>::new()` will
1185                 // use an inference variable for `C` with `[T, U]`
1186                 // as the substitutions for the default, `(T, U)`.
1187                 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1188                     self.universe(),
1189                     TypeVariableOrigin {
1190                         kind: TypeVariableOriginKind::TypeParameterDefinition(
1191                             param.name,
1192                             Some(param.def_id),
1193                         ),
1194                         span,
1195                     },
1196                 );
1197
1198                 self.tcx.mk_ty_var(ty_var_id).into()
1199             }
1200             GenericParamDefKind::Const { .. } => {
1201                 let origin = ConstVariableOrigin {
1202                     kind: ConstVariableOriginKind::ConstParameterDefinition(
1203                         param.name,
1204                         param.def_id,
1205                     ),
1206                     span,
1207                 };
1208                 let const_var_id =
1209                     self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1210                         origin,
1211                         val: ConstVariableValue::Unknown { universe: self.universe() },
1212                     });
1213                 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1214             }
1215         }
1216     }
1217
1218     /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1219     /// type/region parameter to a fresh inference variable.
1220     pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1221         InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1222     }
1223
1224     /// Returns `true` if errors have been reported since this infcx was
1225     /// created. This is sometimes used as a heuristic to skip
1226     /// reporting errors that often occur as a result of earlier
1227     /// errors, but where it's hard to be 100% sure (e.g., unresolved
1228     /// inference variables, regionck errors).
1229     pub fn is_tainted_by_errors(&self) -> bool {
1230         debug!(
1231             "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1232              tainted_by_errors_flag={})",
1233             self.tcx.sess.err_count(),
1234             self.err_count_on_creation,
1235             self.tainted_by_errors_flag.get()
1236         );
1237
1238         if self.tcx.sess.err_count() > self.err_count_on_creation {
1239             return true; // errors reported since this infcx was made
1240         }
1241         self.tainted_by_errors_flag.get()
1242     }
1243
1244     /// Set the "tainted by errors" flag to true. We call this when we
1245     /// observe an error from a prior pass.
1246     pub fn set_tainted_by_errors(&self) {
1247         debug!("set_tainted_by_errors()");
1248         self.tainted_by_errors_flag.set(true)
1249     }
1250
1251     /// Process the region constraints and return any any errors that
1252     /// result. After this, no more unification operations should be
1253     /// done -- or the compiler will panic -- but it is legal to use
1254     /// `resolve_vars_if_possible` as well as `fully_resolve`.
1255     pub fn resolve_regions(
1256         &self,
1257         region_context: DefId,
1258         outlives_env: &OutlivesEnvironment<'tcx>,
1259         mode: RegionckMode,
1260     ) -> Vec<RegionResolutionError<'tcx>> {
1261         let (var_infos, data) = {
1262             let mut inner = self.inner.borrow_mut();
1263             let inner = &mut *inner;
1264             assert!(
1265                 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1266                 "region_obligations not empty: {:#?}",
1267                 inner.region_obligations
1268             );
1269             inner
1270                 .region_constraint_storage
1271                 .take()
1272                 .expect("regions already resolved")
1273                 .with_log(&mut inner.undo_log)
1274                 .into_infos_and_data()
1275         };
1276
1277         let region_rels =
1278             &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1279
1280         let (lexical_region_resolutions, errors) =
1281             lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1282
1283         let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1284         assert!(old_value.is_none());
1285
1286         errors
1287     }
1288
1289     /// Process the region constraints and report any errors that
1290     /// result. After this, no more unification operations should be
1291     /// done -- or the compiler will panic -- but it is legal to use
1292     /// `resolve_vars_if_possible` as well as `fully_resolve`.
1293     pub fn resolve_regions_and_report_errors(
1294         &self,
1295         region_context: DefId,
1296         outlives_env: &OutlivesEnvironment<'tcx>,
1297         mode: RegionckMode,
1298     ) {
1299         let errors = self.resolve_regions(region_context, outlives_env, mode);
1300
1301         if !self.is_tainted_by_errors() {
1302             // As a heuristic, just skip reporting region errors
1303             // altogether if other errors have been reported while
1304             // this infcx was in use.  This is totally hokey but
1305             // otherwise we have a hard time separating legit region
1306             // errors from silly ones.
1307             self.report_region_errors(&errors);
1308         }
1309     }
1310
1311     /// Obtains (and clears) the current set of region
1312     /// constraints. The inference context is still usable: further
1313     /// unifications will simply add new constraints.
1314     ///
1315     /// This method is not meant to be used with normal lexical region
1316     /// resolution. Rather, it is used in the NLL mode as a kind of
1317     /// interim hack: basically we run normal type-check and generate
1318     /// region constraints as normal, but then we take them and
1319     /// translate them into the form that the NLL solver
1320     /// understands. See the NLL module for mode details.
1321     pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1322         assert!(
1323             self.inner.borrow().region_obligations.is_empty(),
1324             "region_obligations not empty: {:#?}",
1325             self.inner.borrow().region_obligations
1326         );
1327
1328         self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1329     }
1330
1331     /// Gives temporary access to the region constraint data.
1332     pub fn with_region_constraints<R>(
1333         &self,
1334         op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1335     ) -> R {
1336         let mut inner = self.inner.borrow_mut();
1337         op(inner.unwrap_region_constraints().data())
1338     }
1339
1340     pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1341         let mut inner = self.inner.borrow_mut();
1342         let inner = &mut *inner;
1343         inner
1344             .region_constraint_storage
1345             .as_mut()
1346             .expect("regions already resolved")
1347             .with_log(&mut inner.undo_log)
1348             .var_origin(vid)
1349     }
1350
1351     /// Takes ownership of the list of variable regions. This implies
1352     /// that all the region constraints have already been taken, and
1353     /// hence that `resolve_regions_and_report_errors` can never be
1354     /// called. This is used only during NLL processing to "hand off" ownership
1355     /// of the set of region variables into the NLL region context.
1356     pub fn take_region_var_origins(&self) -> VarInfos {
1357         let mut inner = self.inner.borrow_mut();
1358         let (var_infos, data) = inner
1359             .region_constraint_storage
1360             .take()
1361             .expect("regions already resolved")
1362             .with_log(&mut inner.undo_log)
1363             .into_infos_and_data();
1364         assert!(data.is_empty());
1365         var_infos
1366     }
1367
1368     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1369         self.resolve_vars_if_possible(t).to_string()
1370     }
1371
1372     /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1373     /// universe index of `TyVar(vid)`.
1374     pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1375         use self::type_variable::TypeVariableValue;
1376
1377         match self.inner.borrow_mut().type_variables().probe(vid) {
1378             TypeVariableValue::Known { value } => Ok(value),
1379             TypeVariableValue::Unknown { universe } => Err(universe),
1380         }
1381     }
1382
1383     /// Resolve any type variables found in `value` -- but only one
1384     /// level.  So, if the variable `?X` is bound to some type
1385     /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1386     /// itself be bound to a type).
1387     ///
1388     /// Useful when you only need to inspect the outermost level of
1389     /// the type and don't care about nested types (or perhaps you
1390     /// will be resolving them as well, e.g. in a loop).
1391     pub fn shallow_resolve<T>(&self, value: T) -> T
1392     where
1393         T: TypeFoldable<'tcx>,
1394     {
1395         value.fold_with(&mut ShallowResolver { infcx: self })
1396     }
1397
1398     pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1399         self.inner.borrow_mut().type_variables().root_var(var)
1400     }
1401
1402     /// Where possible, replaces type/const variables in
1403     /// `value` with their final value. Note that region variables
1404     /// are unaffected. If a type/const variable has not been unified, it
1405     /// is left as is. This is an idempotent operation that does
1406     /// not affect inference state in any way and so you can do it
1407     /// at will.
1408     pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1409     where
1410         T: TypeFoldable<'tcx>,
1411     {
1412         if !value.needs_infer() {
1413             return value; // Avoid duplicated subst-folding.
1414         }
1415         let mut r = resolve::OpportunisticVarResolver::new(self);
1416         value.fold_with(&mut r)
1417     }
1418
1419     pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1420     where
1421         T: TypeFoldable<'tcx>,
1422     {
1423         if !value.needs_infer() {
1424             return value; // Avoid duplicated subst-folding.
1425         }
1426         let mut r = InferenceLiteralEraser { tcx: self.tcx };
1427         value.fold_with(&mut r)
1428     }
1429
1430     /// Returns the first unresolved variable contained in `T`. In the
1431     /// process of visiting `T`, this will resolve (where possible)
1432     /// type variables in `T`, but it never constructs the final,
1433     /// resolved type, so it's more efficient than
1434     /// `resolve_vars_if_possible()`.
1435     pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1436     where
1437         T: TypeFoldable<'tcx>,
1438     {
1439         value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1440     }
1441
1442     pub fn probe_const_var(
1443         &self,
1444         vid: ty::ConstVid<'tcx>,
1445     ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1446         match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1447             ConstVariableValue::Known { value } => Ok(value),
1448             ConstVariableValue::Unknown { universe } => Err(universe),
1449         }
1450     }
1451
1452     pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1453         /*!
1454          * Attempts to resolve all type/region/const variables in
1455          * `value`. Region inference must have been run already (e.g.,
1456          * by calling `resolve_regions_and_report_errors`). If some
1457          * variable was never unified, an `Err` results.
1458          *
1459          * This method is idempotent, but it not typically not invoked
1460          * except during the writeback phase.
1461          */
1462
1463         resolve::fully_resolve(self, value)
1464     }
1465
1466     // [Note-Type-error-reporting]
1467     // An invariant is that anytime the expected or actual type is Error (the special
1468     // error type, meaning that an error occurred when typechecking this expression),
1469     // this is a derived error. The error cascaded from another error (that was already
1470     // reported), so it's not useful to display it to the user.
1471     // The following methods implement this logic.
1472     // They check if either the actual or expected type is Error, and don't print the error
1473     // in this case. The typechecker should only ever report type errors involving mismatched
1474     // types using one of these methods, and should not call span_err directly for such
1475     // errors.
1476
1477     pub fn type_error_struct_with_diag<M>(
1478         &self,
1479         sp: Span,
1480         mk_diag: M,
1481         actual_ty: Ty<'tcx>,
1482     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>
1483     where
1484         M: FnOnce(String) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1485     {
1486         let actual_ty = self.resolve_vars_if_possible(actual_ty);
1487         debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1488
1489         let mut err = mk_diag(self.ty_to_string(actual_ty));
1490
1491         // Don't report an error if actual type is `Error`.
1492         if actual_ty.references_error() {
1493             err.downgrade_to_delayed_bug();
1494         }
1495
1496         err
1497     }
1498
1499     pub fn report_mismatched_types(
1500         &self,
1501         cause: &ObligationCause<'tcx>,
1502         expected: Ty<'tcx>,
1503         actual: Ty<'tcx>,
1504         err: TypeError<'tcx>,
1505     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1506         let trace = TypeTrace::types(cause, true, expected, actual);
1507         self.report_and_explain_type_error(trace, &err)
1508     }
1509
1510     pub fn report_mismatched_consts(
1511         &self,
1512         cause: &ObligationCause<'tcx>,
1513         expected: ty::Const<'tcx>,
1514         actual: ty::Const<'tcx>,
1515         err: TypeError<'tcx>,
1516     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1517         let trace = TypeTrace::consts(cause, true, expected, actual);
1518         self.report_and_explain_type_error(trace, &err)
1519     }
1520
1521     pub fn replace_bound_vars_with_fresh_vars<T>(
1522         &self,
1523         span: Span,
1524         lbrct: LateBoundRegionConversionTime,
1525         value: ty::Binder<'tcx, T>,
1526     ) -> T
1527     where
1528         T: TypeFoldable<'tcx> + Copy,
1529     {
1530         if let Some(inner) = value.no_bound_vars() {
1531             return inner;
1532         }
1533
1534         let mut region_map = FxHashMap::default();
1535         let fld_r = |br: ty::BoundRegion| {
1536             *region_map
1537                 .entry(br)
1538                 .or_insert_with(|| self.next_region_var(LateBoundRegion(span, br.kind, lbrct)))
1539         };
1540
1541         let mut ty_map = FxHashMap::default();
1542         let fld_t = |bt: ty::BoundTy| {
1543             *ty_map.entry(bt).or_insert_with(|| {
1544                 self.next_ty_var(TypeVariableOrigin {
1545                     kind: TypeVariableOriginKind::MiscVariable,
1546                     span,
1547                 })
1548             })
1549         };
1550         let mut ct_map = FxHashMap::default();
1551         let fld_c = |bc: ty::BoundVar, ty| {
1552             *ct_map.entry(bc).or_insert_with(|| {
1553                 self.next_const_var(
1554                     ty,
1555                     ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1556                 )
1557             })
1558         };
1559         self.tcx.replace_bound_vars_uncached(value, fld_r, fld_t, fld_c)
1560     }
1561
1562     /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1563     pub fn verify_generic_bound(
1564         &self,
1565         origin: SubregionOrigin<'tcx>,
1566         kind: GenericKind<'tcx>,
1567         a: ty::Region<'tcx>,
1568         bound: VerifyBound<'tcx>,
1569     ) {
1570         debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1571
1572         self.inner
1573             .borrow_mut()
1574             .unwrap_region_constraints()
1575             .verify_generic_bound(origin, kind, a, bound);
1576     }
1577
1578     /// Obtains the latest type of the given closure; this may be a
1579     /// closure in the current function, in which case its
1580     /// `ClosureKind` may not yet be known.
1581     pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1582         let closure_kind_ty = closure_substs.as_closure().kind_ty();
1583         let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1584         closure_kind_ty.to_opt_closure_kind()
1585     }
1586
1587     /// Clears the selection, evaluation, and projection caches. This is useful when
1588     /// repeatedly attempting to select an `Obligation` while changing only
1589     /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1590     pub fn clear_caches(&self) {
1591         self.selection_cache.clear();
1592         self.evaluation_cache.clear();
1593         self.inner.borrow_mut().projection_cache().clear();
1594     }
1595
1596     pub fn universe(&self) -> ty::UniverseIndex {
1597         self.universe.get()
1598     }
1599
1600     /// Creates and return a fresh universe that extends all previous
1601     /// universes. Updates `self.universe` to that new universe.
1602     pub fn create_next_universe(&self) -> ty::UniverseIndex {
1603         let u = self.universe.get().next_universe();
1604         self.universe.set(u);
1605         u
1606     }
1607
1608     /// Resolves and evaluates a constant.
1609     ///
1610     /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1611     /// substitutions and environment are used to resolve the constant. Alternatively if the
1612     /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1613     /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1614     /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1615     /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1616     /// returned.
1617     ///
1618     /// This handles inferences variables within both `param_env` and `substs` by
1619     /// performing the operation on their respective canonical forms.
1620     #[instrument(skip(self), level = "debug")]
1621     pub fn const_eval_resolve(
1622         &self,
1623         param_env: ty::ParamEnv<'tcx>,
1624         unevaluated: ty::Unevaluated<'tcx>,
1625         span: Option<Span>,
1626     ) -> EvalToConstValueResult<'tcx> {
1627         let substs = self.resolve_vars_if_possible(unevaluated.substs);
1628         debug!(?substs);
1629
1630         // Postpone the evaluation of constants whose substs depend on inference
1631         // variables
1632         if substs.has_infer_types_or_consts() {
1633             debug!("substs have infer types or consts: {:?}", substs);
1634             return Err(ErrorHandled::TooGeneric);
1635         }
1636
1637         let param_env_erased = self.tcx.erase_regions(param_env);
1638         let substs_erased = self.tcx.erase_regions(substs);
1639         debug!(?param_env_erased);
1640         debug!(?substs_erased);
1641
1642         let unevaluated = ty::Unevaluated {
1643             def: unevaluated.def,
1644             substs: substs_erased,
1645             promoted: unevaluated.promoted,
1646         };
1647
1648         // The return value is the evaluated value which doesn't contain any reference to inference
1649         // variables, thus we don't need to substitute back the original values.
1650         self.tcx.const_eval_resolve(param_env_erased, unevaluated, span)
1651     }
1652
1653     /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1654     ///   * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1655     ///   * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1656     ///
1657     /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1658     /// inlined, despite being large, because it has only two call sites that
1659     /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1660     /// inference variables), and it handles both `Ty` and `ty::Const` without
1661     /// having to resort to storing full `GenericArg`s in `stalled_on`.
1662     #[inline(always)]
1663     pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1664         match infer_var {
1665             TyOrConstInferVar::Ty(v) => {
1666                 use self::type_variable::TypeVariableValue;
1667
1668                 // If `inlined_probe` returns a `Known` value, it never equals
1669                 // `ty::Infer(ty::TyVar(v))`.
1670                 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1671                     TypeVariableValue::Unknown { .. } => false,
1672                     TypeVariableValue::Known { .. } => true,
1673                 }
1674             }
1675
1676             TyOrConstInferVar::TyInt(v) => {
1677                 // If `inlined_probe_value` returns a value it's always a
1678                 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1679                 // `ty::Infer(_)`.
1680                 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1681             }
1682
1683             TyOrConstInferVar::TyFloat(v) => {
1684                 // If `probe_value` returns a value it's always a
1685                 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1686                 //
1687                 // Not `inlined_probe_value(v)` because this call site is colder.
1688                 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1689             }
1690
1691             TyOrConstInferVar::Const(v) => {
1692                 // If `probe_value` returns a `Known` value, it never equals
1693                 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1694                 //
1695                 // Not `inlined_probe_value(v)` because this call site is colder.
1696                 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1697                     ConstVariableValue::Unknown { .. } => false,
1698                     ConstVariableValue::Known { .. } => true,
1699                 }
1700             }
1701         }
1702     }
1703 }
1704
1705 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1706 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1707 #[derive(Copy, Clone, Debug)]
1708 pub enum TyOrConstInferVar<'tcx> {
1709     /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1710     Ty(TyVid),
1711     /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1712     TyInt(IntVid),
1713     /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1714     TyFloat(FloatVid),
1715
1716     /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1717     Const(ConstVid<'tcx>),
1718 }
1719
1720 impl<'tcx> TyOrConstInferVar<'tcx> {
1721     /// Tries to extract an inference variable from a type or a constant, returns `None`
1722     /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1723     /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1724     pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1725         match arg.unpack() {
1726             GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1727             GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1728             GenericArgKind::Lifetime(_) => None,
1729         }
1730     }
1731
1732     /// Tries to extract an inference variable from a type, returns `None`
1733     /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1734     pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1735         match *ty.kind() {
1736             ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1737             ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1738             ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1739             _ => None,
1740         }
1741     }
1742
1743     /// Tries to extract an inference variable from a constant, returns `None`
1744     /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1745     pub fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1746         match ct.val() {
1747             ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1748             _ => None,
1749         }
1750     }
1751 }
1752
1753 /// Replace `{integer}` with `i32` and `{float}` with `f64`.
1754 /// Used only for diagnostics.
1755 struct InferenceLiteralEraser<'tcx> {
1756     tcx: TyCtxt<'tcx>,
1757 }
1758
1759 impl<'tcx> TypeFolder<'tcx> for InferenceLiteralEraser<'tcx> {
1760     fn tcx(&self) -> TyCtxt<'tcx> {
1761         self.tcx
1762     }
1763
1764     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1765         match ty.kind() {
1766             ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1767             ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1768             _ => ty.super_fold_with(self),
1769         }
1770     }
1771 }
1772
1773 struct ShallowResolver<'a, 'tcx> {
1774     infcx: &'a InferCtxt<'a, 'tcx>,
1775 }
1776
1777 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1778     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1779         self.infcx.tcx
1780     }
1781
1782     /// If `ty` is a type variable of some kind, resolve it one level
1783     /// (but do not resolve types found in the result). If `typ` is
1784     /// not a type variable, just return it unmodified.
1785     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1786         match *ty.kind() {
1787             ty::Infer(ty::TyVar(v)) => {
1788                 // Not entirely obvious: if `typ` is a type variable,
1789                 // it can be resolved to an int/float variable, which
1790                 // can then be recursively resolved, hence the
1791                 // recursion. Note though that we prevent type
1792                 // variables from unifying to other type variables
1793                 // directly (though they may be embedded
1794                 // structurally), and we prevent cycles in any case,
1795                 // so this recursion should always be of very limited
1796                 // depth.
1797                 //
1798                 // Note: if these two lines are combined into one we get
1799                 // dynamic borrow errors on `self.inner`.
1800                 let known = self.infcx.inner.borrow_mut().type_variables().probe(v).known();
1801                 known.map_or(ty, |t| self.fold_ty(t))
1802             }
1803
1804             ty::Infer(ty::IntVar(v)) => self
1805                 .infcx
1806                 .inner
1807                 .borrow_mut()
1808                 .int_unification_table()
1809                 .probe_value(v)
1810                 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1811
1812             ty::Infer(ty::FloatVar(v)) => self
1813                 .infcx
1814                 .inner
1815                 .borrow_mut()
1816                 .float_unification_table()
1817                 .probe_value(v)
1818                 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1819
1820             _ => ty,
1821         }
1822     }
1823
1824     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1825         if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.val() {
1826             self.infcx
1827                 .inner
1828                 .borrow_mut()
1829                 .const_unification_table()
1830                 .probe_value(vid)
1831                 .val
1832                 .known()
1833                 .unwrap_or(ct)
1834         } else {
1835             ct
1836         }
1837     }
1838 }
1839
1840 impl<'tcx> TypeTrace<'tcx> {
1841     pub fn span(&self) -> Span {
1842         self.cause.span
1843     }
1844
1845     pub fn types(
1846         cause: &ObligationCause<'tcx>,
1847         a_is_expected: bool,
1848         a: Ty<'tcx>,
1849         b: Ty<'tcx>,
1850     ) -> TypeTrace<'tcx> {
1851         TypeTrace {
1852             cause: cause.clone(),
1853             values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1854         }
1855     }
1856
1857     pub fn consts(
1858         cause: &ObligationCause<'tcx>,
1859         a_is_expected: bool,
1860         a: ty::Const<'tcx>,
1861         b: ty::Const<'tcx>,
1862     ) -> TypeTrace<'tcx> {
1863         TypeTrace {
1864             cause: cause.clone(),
1865             values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1866         }
1867     }
1868 }
1869
1870 impl<'tcx> SubregionOrigin<'tcx> {
1871     pub fn span(&self) -> Span {
1872         match *self {
1873             Subtype(ref a) => a.span(),
1874             RelateObjectBound(a) => a,
1875             RelateParamBound(a, ..) => a,
1876             RelateRegionParamBound(a) => a,
1877             Reborrow(a) => a,
1878             ReborrowUpvar(a, _) => a,
1879             DataBorrowed(_, a) => a,
1880             ReferenceOutlivesReferent(_, a) => a,
1881             CompareImplMethodObligation { span, .. } => span,
1882             CompareImplTypeObligation { span, .. } => span,
1883             CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1884         }
1885     }
1886
1887     pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1888     where
1889         F: FnOnce() -> Self,
1890     {
1891         match *cause.code() {
1892             traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1893                 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1894             }
1895
1896             traits::ObligationCauseCode::CompareImplMethodObligation {
1897                 impl_item_def_id,
1898                 trait_item_def_id,
1899             } => SubregionOrigin::CompareImplMethodObligation {
1900                 span: cause.span,
1901                 impl_item_def_id,
1902                 trait_item_def_id,
1903             },
1904
1905             traits::ObligationCauseCode::CompareImplTypeObligation {
1906                 impl_item_def_id,
1907                 trait_item_def_id,
1908             } => SubregionOrigin::CompareImplTypeObligation {
1909                 span: cause.span,
1910                 impl_item_def_id,
1911                 trait_item_def_id,
1912             },
1913
1914             traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1915                 impl_item_def_id,
1916                 trait_item_def_id,
1917             } => SubregionOrigin::CheckAssociatedTypeBounds {
1918                 impl_item_def_id,
1919                 trait_item_def_id,
1920                 parent: Box::new(default()),
1921             },
1922
1923             _ => default(),
1924         }
1925     }
1926 }
1927
1928 impl RegionVariableOrigin {
1929     pub fn span(&self) -> Span {
1930         match *self {
1931             MiscVariable(a)
1932             | PatternRegion(a)
1933             | AddrOfRegion(a)
1934             | Autoref(a)
1935             | Coercion(a)
1936             | EarlyBoundRegion(a, ..)
1937             | LateBoundRegion(a, ..)
1938             | UpvarRegion(_, a) => a,
1939             Nll(..) => bug!("NLL variable used with `span`"),
1940         }
1941     }
1942 }
1943
1944 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1945     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1946         write!(
1947             f,
1948             "RegionObligation(sub_region={:?}, sup_type={:?})",
1949             self.sub_region, self.sup_type
1950         )
1951     }
1952 }