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