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