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