1use std::cell::{Cell, RefCell};
2use std::fmt;
3use std::range::RangeInclusive;
45pub use at::DefineOpaqueTypes;
6use free_regions::RegionRelations;
7pub use freshen::TypeFreshener;
8use lexical_region_resolve::LexicalRegionResolutions;
9pub use lexical_region_resolve::RegionResolutionError;
10pub use opaque_types::{OpaqueTypeStorage, OpaqueTypeStorageEntries, OpaqueTypeTable};
11use region_constraints::{
12GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
13};
14pub use relate::combine::PredicateEmittingRelation;
15use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
16use rustc_data_structures::snapshot_vecas sv;
17use rustc_data_structures::undo_log::{Rollback, UndoLogs};
18use rustc_data_structures::unify::{selfas ut, UnifyKey, UnifyValue};
19use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
20use rustc_hir::def_id::{DefId, LocalDefId};
21use rustc_hir::{selfas hir, HirId};
22use rustc_index::IndexVec;
23use rustc_macros::extension;
24pub use rustc_macros::{TypeFoldable, TypeVisitable};
25use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
26use rustc_middle::mir::ConstraintCategory;
27use rustc_middle::traits::select;
28use rustc_middle::traits::solve::Goal;
29use rustc_middle::ty::error::{ExpectedFound, TypeError};
30use rustc_middle::ty::{
31self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
32GenericArgsRef, GenericParamDefKind, InferConst, OpaqueTypeKey, ProvisionalHiddenType,
33PseudoCanonicalInput, Term, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable,
34TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
35};
36use rustc_span::{DUMMY_SP, Span, Symbol, bug};
37use rustc_type_ir::{CanonicalizerState, MayBeErased};
38use snapshot::undo_log::InferCtxtUndoLogs;
39use tracing::{debug, instrument};
40use ty::solve::TyOrConstInferVar;
41use type_variable::TypeVariableOrigin;
4243use crate::infer::snapshot::undo_log::UndoLog;
44use crate::infer::type_variable::{FloatVariableOrigin, TypeVariableValue};
45use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
46use crate::traits::{
47self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
48TraitEngine,
49};
5051pub mod at;
52pub mod canonical;
53mod context;
54mod free_regions;
55mod freshen;
56mod lexical_region_resolve;
57mod opaque_types;
58pub mod outlives;
59mod projection;
60pub mod region_constraints;
61pub mod relate;
62pub mod resolve;
63pub(crate) mod snapshot;
64mod type_variable;
65mod unify_key;
6667pub use region_constraints::SolverRegionConstraint;
6869/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
70/// around `PredicateObligations<'tcx>`, but it has one important property:
71/// because `InferOk` is marked with `#[must_use]`, if you have a method
72/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
73/// `infcx.f()?;` you'll get a warning about the obligations being discarded
74/// without use, which is probably unintentional and has been a source of bugs
75/// in the past.
76#[must_use]
77#[derive(#[automatically_derived]impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug
for InferOk<'tcx, T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "InferOk",
"value", &self.value, "obligations", &&self.obligations)
}
}Debug)]
78pub struct InferOk<'tcx, T> {
79pub value: T,
80pub obligations: PredicateObligations<'tcx>,
81}
82pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
8384pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
8586pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
87 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
88>;
8990/// This type contains all the things within [`InferCtxt`] that sit within a
91/// [`RefCell`] and are involved with taking/rolling back snapshots. Snapshot
92/// operations are hot enough that we want only one call to
93/// [`RefCell::borrow_mut`] per call to [`InferCtxt::start_snapshot`] and
94/// [`InferCtxt::rollback_to`].
95#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
InferCtxtInner<'tcx> {
#[inline]
fn clone(&self) -> Self {
InferCtxtInner {
undo_log: ::core::clone::Clone::clone(&self.undo_log),
projection_cache: ::core::clone::Clone::clone(&self.projection_cache),
type_variable_storage: ::core::clone::Clone::clone(&self.type_variable_storage),
const_unification_storage: ::core::clone::Clone::clone(&self.const_unification_storage),
int_unification_storage: ::core::clone::Clone::clone(&self.int_unification_storage),
float_unification_storage: ::core::clone::Clone::clone(&self.float_unification_storage),
float_origin_origin_storage: ::core::clone::Clone::clone(&self.float_origin_origin_storage),
region_constraint_storage: ::core::clone::Clone::clone(&self.region_constraint_storage),
region_obligations: ::core::clone::Clone::clone(&self.region_obligations),
region_assumptions: ::core::clone::Clone::clone(&self.region_assumptions),
hir_typeck_potentially_region_dependent_goals: ::core::clone::Clone::clone(&self.hir_typeck_potentially_region_dependent_goals),
opaque_type_storage: ::core::clone::Clone::clone(&self.opaque_type_storage),
}
}
}Clone)]
96pub struct InferCtxtInner<'tcx> {
97 undo_log: InferCtxtUndoLogs<'tcx>,
9899/// Cache for projections.
100 ///
101 /// This cache is snapshotted along with the infcx.
102projection_cache: traits::ProjectionCacheStorage<'tcx>,
103104/// Primary map of inference variables to the types that they currently
105 /// represent.
106 ///
107 /// We instantiate [`UnificationTable`] with `bounds<Ty>` because the types
108 /// that might instantiate a general type variable have an order,
109 /// represented by its upper and lower bounds.
110type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
111112/// Map from const parameter variable to the kind of const it represents.
113const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
114115/// Map from integral variable to the kind of integer it represents.
116int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
117118/// Map from floating variable to the kind of float it represents.
119float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
120121/// Map from floating variable to the origin span it came from, and the HirId that should be
122 /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
123 /// so can be removed once the `f32` fallback is removed.
124float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
125126/// Tracks the set of region variables and the constraints between them.
127 ///
128 /// This is initially `Some(_)` but when
129 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
130 /// -- further attempts to perform unification, etc., may fail if new
131 /// region constraints would've been added.
132region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
133134/// A set of constraints that regionck must validate.
135 ///
136 /// Each constraint has the form `T:'a`, meaning "some type `T` must
137 /// outlive the lifetime 'a". These constraints derive from
138 /// instantiated type parameters. So if you had a struct defined
139 /// like the following:
140 /// ```ignore (illustrative)
141 /// struct Foo<T: 'static> { ... }
142 /// ```
143 /// In some expression `let x = Foo { ... }`, it will
144 /// instantiate the type parameter `T` with a fresh type `$0`. At
145 /// the same time, it will record a region obligation of
146 /// `$0: 'static`. This will get checked later by regionck. (We
147 /// can't generally check these things right away because we have
148 /// to wait until types are resolved.)
149region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
150151/// The outlives bounds that we assume must hold about placeholders that
152 /// come from instantiating the binder of coroutine-witnesses. These bounds
153 /// are deduced from the well-formedness of the witness's types, and are
154 /// necessary because of the way we anonymize the regions in a coroutine,
155 /// which may cause types to no longer be considered well-formed.
156region_assumptions: Vec<ty::ArgOutlivesClause<'tcx>>,
157158/// `-Znext-solver`: Successfully proven goals during HIR typeck which
159 /// reference inference variables and get reproven in case MIR type check
160 /// fails to prove something.
161 ///
162 /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
163hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
164165/// Caches for opaque type inference.
166opaque_type_storage: OpaqueTypeStorage<'tcx>,
167}
168169impl<'tcx> InferCtxtInner<'tcx> {
170fn new() -> InferCtxtInner<'tcx> {
171InferCtxtInner {
172 undo_log: InferCtxtUndoLogs::default(),
173174 projection_cache: Default::default(),
175 type_variable_storage: Default::default(),
176 const_unification_storage: Default::default(),
177 int_unification_storage: Default::default(),
178 float_unification_storage: Default::default(),
179 float_origin_origin_storage: Default::default(),
180 region_constraint_storage: Some(Default::default()),
181 region_obligations: Default::default(),
182 region_assumptions: Default::default(),
183 hir_typeck_potentially_region_dependent_goals: Default::default(),
184 opaque_type_storage: Default::default(),
185 }
186 }
187188#[inline]
189pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
190&self.region_obligations
191 }
192193#[inline]
194pub fn region_assumptions(&self) -> &[ty::ArgOutlivesClause<'tcx>] {
195&self.region_assumptions
196 }
197198#[inline]
199pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
200self.projection_cache.with_log(&mut self.undo_log)
201 }
202203#[inline]
204fn try_type_variables_probe_ref(&self, vid: ty::TyVid) -> Option<&TypeVariableValue<'tcx>> {
205// Uses a read-only view of the unification table, this way we don't
206 // need an undo log.
207self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
208 }
209210#[inline]
211fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
212self.type_variable_storage.with_log(&mut self.undo_log)
213 }
214215#[inline]
216pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
217self.opaque_type_storage.with_log(&mut self.undo_log)
218 }
219220#[inline]
221fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
222self.int_unification_storage.with_log(&mut self.undo_log)
223 }
224225#[inline]
226fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
227self.float_unification_storage.with_log(&mut self.undo_log)
228 }
229230#[inline]
231fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
232self.const_unification_storage.with_log(&mut self.undo_log)
233 }
234235#[inline]
236pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
237self.region_constraint_storage
238 .as_mut()
239 .expect("region constraints already solved")
240 .with_log(&mut self.undo_log)
241 }
242}
243244pub struct InferCtxt<'tcx> {
245pub tcx: TyCtxt<'tcx>,
246247/// The mode of this inference context, see the struct documentation
248 /// for more details.
249typing_mode: TypingMode<'tcx>,
250251/// Whether this inference context should care about region obligations in
252 /// the root universe. Most notably, this is used during HIR typeck as region
253 /// solving is left to borrowck instead.
254 ///
255 /// This is used in the old solver to enable the generation of regions constraints.
256 /// In the new solver its only used inside the InferCtxt's `Drop` implementation:
257 /// if we're considering regions, and new opaques are registered, we panic.
258pub considering_regions: bool,
259/// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
260 /// need to make sure we don't rely on region identity in the trait solver or when
261 /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
262 /// free region with a unique inference variable. If HIR typeck ends up depending on two
263 /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
264 /// resulting in an ICE.
265 ///
266 /// The trait solver sometimes depends on regions being identical. As a concrete example
267 /// the trait solver ignores other candidates if one candidate exists without any constraints.
268 /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
269 /// occurrence of `'a` with a unique region the goal now equates these regions. See
270 /// the tests in trait-system-refactor-initiative#27 for concrete examples.
271 ///
272 /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
273 /// This is still insufficient as inference variables may *hide* region variables, so e.g.
274 /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
275 /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
276 /// stash all successfully proven goals which reference inference variables and then reprove
277 /// them after writeback.
278pub in_hir_typeck: bool,
279280/// If set, this flag causes us to skip the 'leak check' during
281 /// higher-ranked subtyping operations. This flag is a temporary one used
282 /// to manage the removal of the leak-check: for the time being, we still run the
283 /// leak-check, but we issue warnings.
284skip_leak_check: bool,
285286pub inner: RefCell<InferCtxtInner<'tcx>>,
287288/// Once region inference is done, the values for each variable.
289lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
290291/// Caches the results of trait selection. This cache is used
292 /// for things that depends on inference variables or placeholders.
293pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
294295/// Caches the results of trait evaluation. This cache is used
296 /// for things that depends on inference variables or placeholders.
297pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
298299/// The set of predicates on which errors have been reported, to
300 /// avoid reporting the same error twice.
301pub reported_trait_errors:
302RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
303304/// A set of predicates *on a specific* HIR node (the originating expression and its enclosing
305 /// statement), to avoid reporting multiple errors pointing at different sub-expressions in the
306 /// same method chain.
307pub reported_hir_errors: RefCell<FxIndexMap<HirId, FxHashSet<ty::Predicate<'tcx>>>>,
308309pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
310311/// When an error occurs, we want to avoid reporting "derived"
312 /// errors that are due to this original failure. We have this
313 /// flag that one can set whenever one creates a type-error that
314 /// is due to an error in a prior pass.
315 ///
316 /// Don't read this flag directly, call `is_tainted_by_errors()`
317 /// and `set_tainted_by_errors()`.
318tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
319320/// What is the innermost universe we have created? Starts out as
321 /// `UniverseIndex::root()` but grows from there as we enter
322 /// universal quantifiers.
323 ///
324 /// N.B., at present, we exclude the universal quantifiers on the
325 /// item we are type-checking, and just consider those names as
326 /// part of the root universe. So this would only get incremented
327 /// when we enter into a higher-ranked (`for<..>`) type or trait
328 /// bound.
329universe: Cell<ty::UniverseIndex>,
330331/// List of assumed wellformed types which we can derive implied
332 /// bounds on a `for<...>` from. Only used unstabley and by the
333 /// new solver.
334//
335 // FIXME(-Zassumptions-on-binders): This and `universe` should probably be
336 // in `InferCtxtInner` so they can participate in rollbacks and whatnot
337placeholder_assumptions_for_next_solver: RefCell<
338FxIndexMap<ty::UniverseIndex, rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
339 >,
340341 next_trait_solver: bool,
342343/// We have a `recursion_depth_exceeding_limit` FCW to mitigate breakages
344 /// caused by enabling the next solver globally. But the next solver is
345 /// already used by default in some places so we know they won't have
346 /// additional breakages. We also don't want spurious result in coherence
347 /// checking so we disable the FCW there as well.
348enable_next_solver_overflow_fcw: Cell<bool>,
349350pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
351352/// State reused by each new canonicalizer, and then cleared (but not deallocated) once the
353 /// canonicalizer is finished. A performance win, because it avoids reallocating new
354 /// vecs/hashmaps for every canonicalizer.
355pub canonicalizer_state: RefCell<CanonicalizerState<TyCtxt<'tcx>>>,
356}
357358impl<'tcx> Dropfor InferCtxt<'tcx> {
359fn drop(&mut self) {
360let mut inner = self.inner.borrow_mut();
361let opaque_type_storage = &mut inner.opaque_type_storage;
362363// No need for the drop bomb when we're in `TypingMode::PostTypeckThroughBorrowck`, and the `InferCtxt`
364 // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
365 // in relation to regions. In some places *after* typeck that aren't borrowck, we use
366 // `TypingMode::PostTypeckThroughBorrowck` to prevent defining opaque types and we simply don't care about regions.
367match self.typing_mode_raw() {
368TypingMode::Coherence369 | TypingMode::Typeck { .. }
370 | TypingMode::PostBorrowck { .. }
371 | TypingMode::Reflection372 | TypingMode::PostAnalysis373 | TypingMode::Codegen => {}
374// In erased mode, the opaque type storage is always empty
375TypingMode::ErasedNotCoherence(..) => {}
376TypingMode::PostTypeckThroughBorrowck { .. } => {
377if !self.considering_regions {
378return;
379 }
380 }
381 }
382383if !opaque_type_storage.is_empty() {
384 ty::tls::with(|tcx| tcx.dcx().delayed_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", opaque_type_storage))
})format!("{opaque_type_storage:?}")));
385 }
386 }
387}
388389/// See the `error_reporting` module for more details.
390#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for ValuePairs<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for ValuePairs<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::Region<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::Term<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::AliasTerm<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::TraitRef<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::PolyFnSig<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::PolyExistentialProjection<'tcx>>>;
*self
}
}Clone, #[automatically_derived]impl<'tcx> ::core::marker::Copy for ValuePairs<'tcx> {
}Copy, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for ValuePairs<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Regions(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Regions", &__self_0),
Self::Terms(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Terms",
&__self_0),
Self::Aliases(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Aliases", &__self_0),
Self::TraitRefs(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TraitRefs", &__self_0),
Self::PolySigs(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"PolySigs", &__self_0),
Self::ExistentialTraitRef(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ExistentialTraitRef", &__self_0),
Self::ExistentialProjection(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ExistentialProjection", &__self_0),
}
}
}Debug, #[automatically_derived]impl<'tcx> ::core::marker::StructuralPartialEq for
ValuePairs<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::cmp::PartialEq for ValuePairs<'tcx>
{
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Regions(__self_0), Self::Regions(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Terms(__self_0), Self::Terms(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Aliases(__self_0), Self::Aliases(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::TraitRefs(__self_0), Self::TraitRefs(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::PolySigs(__self_0), Self::PolySigs(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::ExistentialTraitRef(__self_0),
Self::ExistentialTraitRef(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::ExistentialProjection(__self_0),
Self::ExistentialProjection(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]impl<'tcx> ::core::cmp::Eq for ValuePairs<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ExpectedFound<ty::Region<'tcx>>>;
let _: ::core::cmp::AssertParamIsEq<ExpectedFound<ty::Term<'tcx>>>;
let _:
::core::cmp::AssertParamIsEq<ExpectedFound<ty::AliasTerm<'tcx>>>;
let _:
::core::cmp::AssertParamIsEq<ExpectedFound<ty::TraitRef<'tcx>>>;
let _:
::core::cmp::AssertParamIsEq<ExpectedFound<ty::PolyFnSig<'tcx>>>;
let _:
::core::cmp::AssertParamIsEq<ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>>;
let _:
::core::cmp::AssertParamIsEq<ExpectedFound<ty::PolyExistentialProjection<'tcx>>>;
}
}Eq, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for ValuePairs<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
ValuePairs::Regions(__binding_0) => {
ValuePairs::Regions(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::Terms(__binding_0) => {
ValuePairs::Terms(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::Aliases(__binding_0) => {
ValuePairs::Aliases(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::TraitRefs(__binding_0) => {
ValuePairs::TraitRefs(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::PolySigs(__binding_0) => {
ValuePairs::PolySigs(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::ExistentialTraitRef(__binding_0) => {
ValuePairs::ExistentialTraitRef(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::ExistentialProjection(__binding_0) => {
ValuePairs::ExistentialProjection(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
ValuePairs::Regions(__binding_0) => {
ValuePairs::Regions(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::Terms(__binding_0) => {
ValuePairs::Terms(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::Aliases(__binding_0) => {
ValuePairs::Aliases(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::TraitRefs(__binding_0) => {
ValuePairs::TraitRefs(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::PolySigs(__binding_0) => {
ValuePairs::PolySigs(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::ExistentialTraitRef(__binding_0) => {
ValuePairs::ExistentialTraitRef(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::ExistentialProjection(__binding_0) => {
ValuePairs::ExistentialProjection(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for ValuePairs<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
ValuePairs::Regions(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::Terms(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::Aliases(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::TraitRefs(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::PolySigs(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::ExistentialTraitRef(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::ExistentialProjection(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
391pub enum ValuePairs<'tcx> {
392 Regions(ExpectedFound<ty::Region<'tcx>>),
393 Terms(ExpectedFound<ty::Term<'tcx>>),
394 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
395 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
396 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
397 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
398 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
399}
400401impl<'tcx> ValuePairs<'tcx> {
402pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
403if let ValuePairs::Terms(ExpectedFound { expected, found }) = self404 && let Some(expected) = expected.as_type()
405 && let Some(found) = found.as_type()
406 {
407Some((expected, found))
408 } else {
409None410 }
411 }
412}
413414/// The trace designates the path through inference that we took to
415/// encounter an error or subtyping constraint.
416///
417/// See the `error_reporting` module for more details.
418#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for TypeTrace<'tcx> {
#[inline]
fn clone(&self) -> Self {
TypeTrace {
cause: ::core::clone::Clone::clone(&self.cause),
values: ::core::clone::Clone::clone(&self.values),
}
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for TypeTrace<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "TypeTrace",
"cause", &self.cause, "values", &&self.values)
}
}Debug)]
419pub struct TypeTrace<'tcx> {
420pub cause: ObligationCause<'tcx>,
421pub values: ValuePairs<'tcx>,
422}
423424/// The origin of a `r1 <= r2` constraint.
425///
426/// See `error_reporting` module for more details
427#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
SubregionOrigin<'tcx> {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Subtype(__self_0) =>
SubregionOrigin::Subtype(::core::clone::Clone::clone(__self_0)),
Self::RelateObjectBound(__self_0) =>
SubregionOrigin::RelateObjectBound(::core::clone::Clone::clone(__self_0)),
Self::RelateParamBound(__self_0, __self_1, __self_2) =>
SubregionOrigin::RelateParamBound(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1),
::core::clone::Clone::clone(__self_2)),
Self::RelateRegionParamBound(__self_0, __self_1) =>
SubregionOrigin::RelateRegionParamBound(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
Self::Reborrow(__self_0) =>
SubregionOrigin::Reborrow(::core::clone::Clone::clone(__self_0)),
Self::ReferenceOutlivesReferent(__self_0, __self_1) =>
SubregionOrigin::ReferenceOutlivesReferent(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
Self::CompareImplItemObligation {
span: __self_0,
impl_item_def_id: __self_1,
trait_item_def_id: __self_2 } =>
SubregionOrigin::CompareImplItemObligation {
span: ::core::clone::Clone::clone(__self_0),
impl_item_def_id: ::core::clone::Clone::clone(__self_1),
trait_item_def_id: ::core::clone::Clone::clone(__self_2),
},
Self::CheckAssociatedTypeBounds {
parent: __self_0,
impl_item_def_id: __self_1,
trait_item_def_id: __self_2 } =>
SubregionOrigin::CheckAssociatedTypeBounds {
parent: ::core::clone::Clone::clone(__self_0),
impl_item_def_id: ::core::clone::Clone::clone(__self_1),
trait_item_def_id: ::core::clone::Clone::clone(__self_2),
},
Self::AscribeUserTypeProvePredicate(__self_0, __self_1) =>
SubregionOrigin::AscribeUserTypeProvePredicate(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
Self::SolverRegionConstraint(__self_0) =>
SubregionOrigin::SolverRegionConstraint(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for
SubregionOrigin<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Subtype(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Subtype", &__self_0),
Self::RelateObjectBound(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"RelateObjectBound", &__self_0),
Self::RelateParamBound(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"RelateParamBound", __self_0, __self_1, &__self_2),
Self::RelateRegionParamBound(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"RelateRegionParamBound", __self_0, &__self_1),
Self::Reborrow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Reborrow", &__self_0),
Self::ReferenceOutlivesReferent(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ReferenceOutlivesReferent", __self_0, &__self_1),
Self::CompareImplItemObligation {
span: __self_0,
impl_item_def_id: __self_1,
trait_item_def_id: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"CompareImplItemObligation", "span", __self_0,
"impl_item_def_id", __self_1, "trait_item_def_id",
&__self_2),
Self::CheckAssociatedTypeBounds {
parent: __self_0,
impl_item_def_id: __self_1,
trait_item_def_id: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"CheckAssociatedTypeBounds", "parent", __self_0,
"impl_item_def_id", __self_1, "trait_item_def_id",
&__self_2),
Self::AscribeUserTypeProvePredicate(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"AscribeUserTypeProvePredicate", __self_0, &__self_1),
Self::SolverRegionConstraint(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SolverRegionConstraint", &__self_0),
}
}
}Debug)]
428pub enum SubregionOrigin<'tcx> {
429/// Arose from a subtyping relation
430Subtype(Box<TypeTrace<'tcx>>),
431432/// When casting `&'a T` to an `&'b Trait` object,
433 /// relating `'a` to `'b`.
434RelateObjectBound(Span),
435436/// Some type parameter was instantiated with the given type,
437 /// and that type must outlive some region.
438RelateParamBound(Span, Ty<'tcx>, Option<Span>),
439440/// The given region parameter was instantiated with a region
441 /// that must outlive some other region.
442RelateRegionParamBound(Span, Option<Ty<'tcx>>),
443444/// Creating a pointer `b` to contents of another reference.
445Reborrow(Span),
446447/// (&'a &'b T) where a >= b
448ReferenceOutlivesReferent(Ty<'tcx>, Span),
449450/// Comparing the signature and requirements of an impl method against
451 /// the containing trait.
452CompareImplItemObligation {
453 span: Span,
454 impl_item_def_id: LocalDefId,
455 trait_item_def_id: DefId,
456 },
457458/// Checking that the bounds of a trait's associated type hold for a given impl.
459CheckAssociatedTypeBounds {
460 parent: Box<SubregionOrigin<'tcx>>,
461 impl_item_def_id: LocalDefId,
462 trait_item_def_id: DefId,
463 },
464465 AscribeUserTypeProvePredicate(Span, DefId),
466467// FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
468 // proper diagnostics for solver region constraints.
469SolverRegionConstraint(Span),
470}
471472// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
473#[cfg(target_pointer_width = "64")]
474const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
475476impl<'tcx> SubregionOrigin<'tcx> {
477pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
478match self {
479Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
480Self::AscribeUserTypeProvePredicate(span, def_id) => {
481 ConstraintCategory::Predicate(*span, *def_id)
482 }
483Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
484_ => ConstraintCategory::BoringNoLocation,
485 }
486 }
487}
488489/// Times when we replace bound regions with existentials:
490#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for BoundRegionConversionTime {
}
#[automatically_derived]impl ::core::clone::Clone for
BoundRegionConversionTime {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<DefId>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for
BoundRegionConversionTime {
}Copy, #[automatically_derived]impl ::core::fmt::Debug for BoundRegionConversionTime
{
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::FnCall => ::core::fmt::Formatter::write_str(f, "FnCall"),
Self::HigherRankedType =>
::core::fmt::Formatter::write_str(f, "HigherRankedType"),
Self::AssocTypeProjection(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AssocTypeProjection", &__self_0),
}
}
}Debug)]
491pub enum BoundRegionConversionTime {
492/// when a fn is called
493FnCall,
494495/// when two higher-ranked types are compared
496HigherRankedType,
497498/// when projecting an associated type
499AssocTypeProjection(DefId),
500}
501502/// Reasons to create a region inference variable.
503///
504/// See `error_reporting` module for more details.
505#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for
RegionVariableOrigin<'tcx> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for RegionVariableOrigin<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for
RegionVariableOrigin<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<Symbol>;
let _: ::core::clone::AssertParamIsClone<ty::BoundRegionKind<'tcx>>;
let _: ::core::clone::AssertParamIsClone<BoundRegionConversionTime>;
let _: ::core::clone::AssertParamIsClone<ty::UpvarId>;
let _:
::core::clone::AssertParamIsClone<NllRegionVariableOrigin<'tcx>>;
*self
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for
RegionVariableOrigin<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Misc(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Misc",
&__self_0),
Self::PatternRegion(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"PatternRegion", &__self_0),
Self::BorrowRegion(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"BorrowRegion", &__self_0),
Self::Autoref(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Autoref", &__self_0),
Self::Coercion(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Coercion", &__self_0),
Self::RegionParameterDefinition(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"RegionParameterDefinition", __self_0, &__self_1),
Self::BoundRegion(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"BoundRegion", __self_0, __self_1, &__self_2),
Self::UpvarRegion(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"UpvarRegion", __self_0, &__self_1),
Self::Nll(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Nll",
&__self_0),
}
}
}Debug)]
506pub enum RegionVariableOrigin<'tcx> {
507/// Region variables created for ill-categorized reasons.
508 ///
509 /// They mostly indicate places in need of refactoring.
510Misc(Span),
511512/// Regions created by a `&P` or `[...]` pattern.
513PatternRegion(Span),
514515/// Regions created by `&` operator.
516BorrowRegion(Span),
517518/// Regions created as part of an autoref of a method receiver.
519Autoref(Span),
520521/// Regions created as part of an automatic coercion.
522Coercion(Span),
523524/// Region variables created as the values for early-bound regions.
525 ///
526 /// FIXME(@lcnr): This should also store a `DefId`, similar to
527 /// `TypeVariableOrigin`.
528RegionParameterDefinition(Span, Symbol),
529530/// Region variables created when instantiating a binder with
531 /// existential variables, e.g. when calling a function or method.
532BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
533534 UpvarRegion(ty::UpvarId, Span),
535536/// This origin is used for the inference variables that we create
537 /// during NLL region processing.
538Nll(NllRegionVariableOrigin<'tcx>),
539}
540541#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for
NllRegionVariableOrigin<'tcx> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for NllRegionVariableOrigin<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for
NllRegionVariableOrigin<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<ty::PlaceholderRegion<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Option<Symbol>>;
*self
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for
NllRegionVariableOrigin<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::FreeRegion =>
::core::fmt::Formatter::write_str(f, "FreeRegion"),
Self::Placeholder(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Placeholder", &__self_0),
Self::Existential { name: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Existential", "name", &__self_0),
}
}
}Debug)]
542pub enum NllRegionVariableOrigin<'tcx> {
543/// During NLL region processing, we create variables for free
544 /// regions that we encounter in the function signature and
545 /// elsewhere. This origin indices we've got one of those.
546FreeRegion,
547548/// "Universal" instantiation of a higher-ranked region (e.g.,
549 /// from a `for<'a> T` binder). Meant to represent "any region".
550Placeholder(ty::PlaceholderRegion<'tcx>),
551552 Existential {
553 name: Option<Symbol>,
554 },
555}
556557#[derive(#[automatically_derived]impl ::core::marker::Copy for FixupError { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for FixupError {
}
#[automatically_derived]impl ::core::clone::Clone for FixupError {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<TyOrConstInferVar>;
*self
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for FixupError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "FixupError",
"unresolved", &&self.unresolved)
}
}Debug)]
558pub struct FixupError {
559 unresolved: TyOrConstInferVar,
560}
561562impl fmt::Displayfor FixupError {
563fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
564match self.unresolved {
565 TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
566f,
567"cannot determine the type of this integer; \
568 add a suffix to specify the type explicitly"
569),
570 TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
571f,
572"cannot determine the type of this number; \
573 add a suffix to specify the type explicitly"
574),
575 TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
576 TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
577 }
578 }
579}
580581/// See the `region_obligations` field for more information.
582#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
TypeOutlivesConstraint<'tcx> {
#[inline]
fn clone(&self) -> Self {
TypeOutlivesConstraint {
sub_region: ::core::clone::Clone::clone(&self.sub_region),
sup_type: ::core::clone::Clone::clone(&self.sup_type),
origin: ::core::clone::Clone::clone(&self.origin),
}
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for
TypeOutlivesConstraint<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"TypeOutlivesConstraint", "sub_region", &self.sub_region,
"sup_type", &self.sup_type, "origin", &&self.origin)
}
}Debug)]
583pub struct TypeOutlivesConstraint<'tcx> {
584pub sub_region: ty::Region<'tcx>,
585pub sup_type: Ty<'tcx>,
586pub origin: SubregionOrigin<'tcx>,
587}
588589/// Used to configure inference contexts before their creation.
590pub struct InferCtxtBuilder<'tcx> {
591 tcx: TyCtxt<'tcx>,
592 considering_regions: bool,
593 in_hir_typeck: bool,
594 skip_leak_check: bool,
595/// Whether we should use the new trait solver in the local inference context,
596 /// which affects things like which solver is used in `predicate_may_hold`.
597next_trait_solver: bool,
598 enable_next_solver_overflow_fcw: bool,
599}
600601pub trait TyCtxtInferExt<'tcx> {
fn infer_ctxt(self)
-> InferCtxtBuilder<'tcx>;
}
impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
InferCtxtBuilder {
tcx: self,
considering_regions: true,
in_hir_typeck: false,
skip_leak_check: false,
next_trait_solver: self.next_trait_solver_globally(),
enable_next_solver_overflow_fcw: true,
}
}
}#[extension(pub trait TyCtxtInferExt<'tcx>)]602impl<'tcx> TyCtxt<'tcx> {
603fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
604InferCtxtBuilder {
605 tcx: self,
606 considering_regions: true,
607 in_hir_typeck: false,
608 skip_leak_check: false,
609 next_trait_solver: self.next_trait_solver_globally(),
610 enable_next_solver_overflow_fcw: true,
611 }
612 }
613}
614615impl<'tcx> InferCtxtBuilder<'tcx> {
616pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
617self.next_trait_solver = next_trait_solver;
618self619 }
620621pub fn enable_next_solver_overflow_fcw(
622mut self,
623 enable_next_solver_overflow_fcw: bool,
624 ) -> Self {
625self.enable_next_solver_overflow_fcw = enable_next_solver_overflow_fcw;
626self627 }
628629pub fn ignoring_regions(mut self) -> Self {
630self.considering_regions = false;
631self632 }
633634pub fn in_hir_typeck(mut self) -> Self {
635self.in_hir_typeck = true;
636self637 }
638639pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
640self.skip_leak_check = skip_leak_check;
641self642 }
643644/// Given a canonical value `C` as a starting point, create an
645 /// inference context that contains each of the bound values
646 /// within instantiated as a fresh variable. The `f` closure is
647 /// invoked with the new infcx, along with the instantiated value
648 /// `V` and a instantiation `S`. This instantiation `S` maps from
649 /// the bound values in `C` to their instantiated values in `V`
650 /// (in other words, `S(C) = V`).
651pub fn build_with_canonical<T>(
652mut self,
653 span: Span,
654 input: &CanonicalQueryInput<'tcx, T>,
655 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
656where
657T: TypeFoldable<TyCtxt<'tcx>>,
658 {
659let infcx = self.build(input.typing_mode.0);
660let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
661 (infcx, value, args)
662 }
663664pub fn build_with_typing_env(
665mut self,
666 typing_env: TypingEnv<'tcx>,
667 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
668 (self.build(typing_env.typing_mode()), typing_env.param_env)
669 }
670671pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
672let InferCtxtBuilder {
673 tcx,
674 considering_regions,
675 in_hir_typeck,
676 skip_leak_check,
677 next_trait_solver,
678 enable_next_solver_overflow_fcw,
679 } = *self;
680InferCtxt {
681tcx,
682typing_mode,
683considering_regions,
684in_hir_typeck,
685skip_leak_check,
686 inner: RefCell::new(InferCtxtInner::new()),
687 lexical_region_resolutions: RefCell::new(None),
688 selection_cache: Default::default(),
689 evaluation_cache: Default::default(),
690 reported_trait_errors: Default::default(),
691 reported_hir_errors: Default::default(),
692 reported_signature_mismatch: Default::default(),
693 tainted_by_errors: Cell::new(None),
694 universe: Cell::new(ty::UniverseIndex::ROOT),
695 placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
696next_trait_solver,
697 enable_next_solver_overflow_fcw: Cell::new(enable_next_solver_overflow_fcw),
698 obligation_inspector: Cell::new(None),
699 canonicalizer_state: Default::default(),
700 }
701 }
702}
703704impl<'tcx, T> InferOk<'tcx, T> {
705/// Extracts `value`, registering any obligations into `fulfill_cx`.
706pub fn into_value_registering_obligations<E: 'tcx>(
707self,
708 infcx: &InferCtxt<'tcx>,
709 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
710 ) -> T {
711let InferOk { value, obligations } = self;
712fulfill_cx.register_predicate_obligations(infcx, obligations);
713value714 }
715}
716717impl<'tcx> InferOk<'tcx, ()> {
718pub fn into_obligations(self) -> PredicateObligations<'tcx> {
719self.obligations
720 }
721}
722723impl<'tcx> InferCtxt<'tcx> {
724pub fn dcx(&self) -> DiagCtxtHandle<'_> {
725self.tcx.dcx().into_taintable(&self.tainted_by_errors)
726 }
727728pub fn next_trait_solver(&self) -> bool {
729self.next_trait_solver
730 }
731732/// This method is deliberately called `..._raw`,
733 /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
734 /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
735 /// more information.
736 ///
737 /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
738 /// works as a kind of store for for example type unification information.
739 /// `InferCtxt` is also often used outside the trait solver during typeck.
740 /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
741 /// To make sure these two uses are never confused, we want to statically encode this information.
742 ///
743 /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
744 /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
745 /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
746 /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
747 /// match on the variant and can safely ignore it.
748 ///
749 /// Prefer non-raw apis if available. e.g.,
750 /// - On the `FnCtxt`
751 /// - on the `SelectionCtxt`
752#[inline(always)]
753pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
754self.typing_mode
755 }
756757#[inline(always)]
758pub fn disable_trait_solver_fast_paths(&self) -> bool {
759self.tcx.disable_trait_solver_fast_paths()
760 }
761762/// Returns the origin of the type variable identified by `vid`.
763 ///
764 /// No attempt is made to resolve `vid` to its root variable.
765pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
766self.inner.borrow_mut().type_variables().var_origin(vid)
767 }
768769/// Returns the origin of the float type variable identified by `vid`.
770 ///
771 /// No attempt is made to resolve `vid` to its root variable.
772pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
773self.inner.borrow_mut().float_origin_origin_storage[vid]
774 }
775776/// Returns the origin of the const variable identified by `vid`
777// FIXME: We should store origins separately from the unification table
778 // so this doesn't need to be optional.
779pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
780match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
781 ConstVariableValue::Known { .. } => None,
782 ConstVariableValue::Unknown { origin, .. } => Some(origin),
783 }
784 }
785786pub fn unresolved_root_variables(&self) -> (Vec<TyVid>, Vec<ty::IntVid>, Vec<ty::FloatVid>) {
787let mut inner = self.inner.borrow_mut();
788789let ty = inner.type_variables().unresolved_root_variables();
790791let int = unresolved_root_variables_of(
792inner.int_unification_table(),
793 ty::IntVarValue::is_unknown,
794 );
795796let float = unresolved_root_variables_of(
797inner.float_unification_table(),
798 ty::FloatVarValue::is_unknown,
799 );
800801 (ty, int, float)
802 }
803804{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("sub_regions",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(804u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("vis")
}> =
::tracing::__macro_support::FieldName::new("vis");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin,
a, b, vis);
}
}
}#[instrument(skip(self), level = "debug")]805pub fn sub_regions(
806&self,
807 origin: SubregionOrigin<'tcx>,
808 a: ty::Region<'tcx>,
809 b: ty::Region<'tcx>,
810 vis: ty::VisibleForLeakCheck,
811 ) {
812self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
813 }
814815{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("equate_regions",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(815u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("vis")
}> =
::tracing::__macro_support::FieldName::new("vis");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin,
a, b, vis);
}
}
}#[instrument(skip(self), level = "debug")]816pub fn equate_regions(
817&self,
818 origin: SubregionOrigin<'tcx>,
819 a: ty::Region<'tcx>,
820 b: ty::Region<'tcx>,
821 vis: ty::VisibleForLeakCheck,
822 ) {
823self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
824 }
825826/// Processes a `Coerce` predicate from the fulfillment context.
827 /// This is NOT the preferred way to handle coercion, which is to
828 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
829 ///
830 /// This method here is actually a fallback that winds up being
831 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
832 /// and records a coercion predicate. Presently, this method is equivalent
833 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
834 /// actually requiring `a <: b`. This is of course a valid coercion,
835 /// but it's not as flexible as `FnCtxt::coerce` would be.
836 ///
837 /// (We may refactor this in the future, but there are a number of
838 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
839 /// records adjustments that are required on the HIR in order to perform
840 /// the coercion, and we don't currently have a way to manage that.)
841pub fn coerce_predicate(
842&self,
843 cause: &ObligationCause<'tcx>,
844 param_env: ty::ParamEnv<'tcx>,
845 predicate: ty::PolyCoercePredicate<'tcx>,
846 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
847let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
848 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
849a: p.a,
850 b: p.b,
851 });
852self.subtype_predicate(cause, param_env, subtype_predicate)
853 }
854855pub fn subtype_predicate(
856&self,
857 cause: &ObligationCause<'tcx>,
858 param_env: ty::ParamEnv<'tcx>,
859 predicate: ty::PolySubtypePredicate<'tcx>,
860 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
861// Check for two unresolved inference variables, in which case we can
862 // make no progress. This is partly a micro-optimization, but it's
863 // also an opportunity to "sub-unify" the variables. This isn't
864 // *necessary* to prevent cycles, because they would eventually be sub-unified
865 // anyhow during generalization, but it helps with diagnostics (we can detect
866 // earlier that they are sub-unified).
867 //
868 // Note that we can just skip the binders here because
869 // type variables can't (at present, at
870 // least) capture any of the things bound by this binder.
871 //
872 // Note that this sub here is not just for diagnostics - it has semantic
873 // effects as well.
874let r_a = self.shallow_resolve(predicate.skip_binder().a);
875let r_b = self.shallow_resolve(predicate.skip_binder().b);
876match (r_a.kind(), r_b.kind()) {
877 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
878self.sub_unify_ty_vids_raw(a_vid, b_vid);
879return Err((a_vid, b_vid));
880 }
881_ => {}
882 }
883884self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
885if a_is_expected {
886Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
887 } else {
888Ok(self.sup_raw(cause, param_env, DefineOpaqueTypes::Yes, b, a))
889 }
890 })
891 }
892893/// Number of type variables created so far.
894pub fn num_ty_vars(&self) -> usize {
895self.inner.borrow_mut().type_variables().num_vars()
896 }
897898pub fn next_ty_vid(&self, span: Span) -> TyVid {
899self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
900 }
901902pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
903self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
904 }
905906pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
907let origin = TypeVariableOrigin { span, param_def_id: None };
908self.inner.borrow_mut().type_variables().new_var(universe, origin)
909 }
910911pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
912self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
913 }
914915pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
916let vid = self.next_ty_vid_with_origin(origin);
917Ty::new_var(self.tcx, vid)
918 }
919920pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
921let vid = self.next_ty_vid_in_universe(span, universe);
922Ty::new_var(self.tcx, vid)
923 }
924925pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
926self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
927 }
928929pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
930let vid = self931 .inner
932 .borrow_mut()
933 .const_unification_table()
934 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
935 .vid;
936 ty::Const::new_var(self.tcx, vid)
937 }
938939pub fn next_const_var_in_universe(
940&self,
941 span: Span,
942 universe: ty::UniverseIndex,
943 ) -> ty::Const<'tcx> {
944let origin = ConstVariableOrigin { span, param_def_id: None };
945let vid = self946 .inner
947 .borrow_mut()
948 .const_unification_table()
949 .new_key(ConstVariableValue::Unknown { origin, universe })
950 .vid;
951 ty::Const::new_var(self.tcx, vid)
952 }
953954pub fn next_int_var(&self) -> Ty<'tcx> {
955let next_int_var_id =
956self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
957Ty::new_int_var(self.tcx, next_int_var_id)
958 }
959960pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
961let mut inner = self.inner.borrow_mut();
962let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
963let origin = FloatVariableOrigin { span, lint_id };
964let span_index = inner.float_origin_origin_storage.push(origin);
965if true {
{
match (&next_float_var_id, &span_index) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(next_float_var_id, span_index);
966Ty::new_float_var(self.tcx, next_float_var_id)
967 }
968969/// Creates a fresh region variable with the next available index.
970 /// The variable will be created in the maximum universe created
971 /// thus far, allowing it to name any region created thus far.
972pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
973self.next_region_var_in_universe(origin, self.universe())
974 }
975976/// Creates a fresh region variable with the next available index
977 /// in the given universe; typically, you can use
978 /// `next_region_var` and just use the maximal universe.
979pub fn next_region_var_in_universe(
980&self,
981 origin: RegionVariableOrigin<'tcx>,
982 universe: ty::UniverseIndex,
983 ) -> ty::Region<'tcx> {
984let region_var =
985self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
986 ty::Region::new_var(self.tcx, region_var)
987 }
988989pub fn next_term_var_of_alias_kind(
990&self,
991 alias_term: ty::AliasTerm<'tcx>,
992 span: Span,
993 ) -> ty::Term<'tcx> {
994match alias_term.kind {
995 ty::AliasTermKind::ProjectionTy { .. }
996 | ty::AliasTermKind::InherentTy { .. }
997 | ty::AliasTermKind::OpaqueTy { .. }
998 | ty::AliasTermKind::FreeTy { .. } => self.next_ty_var(span).into(),
999 ty::AliasTermKind::FreeConst { .. }
1000 | ty::AliasTermKind::InherentConstSelf { .. }
1001 | ty::AliasTermKind::InherentConstImpl { .. }
1002 | ty::AliasTermKind::AnonConst { .. }
1003 | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_var(span).into(),
1004 }
1005 }
10061007/// Return the universe that the region `r` was created in. For
1008 /// most regions (e.g., `'static`, named regions from the user,
1009 /// etc) this is the root universe U0. For inference variables or
1010 /// placeholders, however, it will return the universe which they
1011 /// are associated.
1012pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1013self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1014 }
10151016/// Number of region variables created so far.
1017pub fn num_region_vars(&self) -> usize {
1018self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1019 }
10201021/// Just a convenient wrapper of `next_region_var` for using during NLL.
1022{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("next_nll_region_var",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1022u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{ self.next_region_var(RegionVariableOrigin::Nll(origin)) }
}
}#[instrument(skip(self), level = "debug")]1023pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
1024self.next_region_var(RegionVariableOrigin::Nll(origin))
1025 }
10261027/// Just a convenient wrapper of `next_region_var` for using during NLL.
1028{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("next_nll_region_var_in_universe",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1028u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("universe")
}> =
::tracing::__macro_support::FieldName::new("universe");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&universe)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin),
universe)
}
}
}#[instrument(skip(self), level = "debug")]1029pub fn next_nll_region_var_in_universe(
1030&self,
1031 origin: NllRegionVariableOrigin<'tcx>,
1032 universe: ty::UniverseIndex,
1033 ) -> ty::Region<'tcx> {
1034self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1035 }
10361037#[inline(always)]
1038pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1039match param.kind {
1040 GenericParamDefKind::Lifetime => {
1041// Create a region inference variable for the given
1042 // region parameter definition.
1043self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1044span, param.name,
1045 ))
1046 .into()
1047 }
1048 GenericParamDefKind::Type { .. } => {
1049// Create a type inference variable for the given
1050 // type parameter definition. The generic parameters are
1051 // for actual parameters that may be referred to by
1052 // the default of this type parameter, if it exists.
1053 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1054 // used in a path such as `Foo::<T, U>::new()` will
1055 // use an inference variable for `C` with `[T, U]`
1056 // as the generic parameters for the default, `(T, U)`.
1057let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1058self.universe(),
1059TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1060 );
10611062Ty::new_var(self.tcx, ty_var_id).into()
1063 }
1064 GenericParamDefKind::Const { .. } => {
1065let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1066let const_var_id = self1067 .inner
1068 .borrow_mut()
1069 .const_unification_table()
1070 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1071 .vid;
1072 ty::Const::new_var(self.tcx, const_var_id).into()
1073 }
1074 }
1075 }
10761077/// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1078 /// each type/region parameter to a fresh inference variable.
1079pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
1080GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1081 }
10821083/// Returns `true` if errors have been reported since this infcx was
1084 /// created. This is sometimes used as a heuristic to skip
1085 /// reporting errors that often occur as a result of earlier
1086 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1087 /// inference variables, regionck errors).
1088#[must_use = "this method does not have any side effects"]
1089pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1090self.tainted_by_errors.get()
1091 }
10921093/// Set the "tainted by errors" flag to true. We call this when we
1094 /// observe an error from a prior pass.
1095pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1096{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs:1096",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1096u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("set_tainted_by_errors(ErrorGuaranteed)")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("set_tainted_by_errors(ErrorGuaranteed)");
1097self.tainted_by_errors.set(Some(e));
1098 }
10991100pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1101let mut inner = self.inner.borrow_mut();
1102let inner = &mut *inner;
1103inner.unwrap_region_constraints().var_origin(vid)
1104 }
11051106/// Clone the list of variable regions. This is used only during NLL processing
1107 /// to put the set of region variables into the NLL region context.
1108pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1109let inner = self.inner.borrow();
1110if !!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log) {
::core::panicking::panic("assertion failed: !UndoLogs::<UndoLog<\'_>>::in_snapshot(&inner.undo_log)")
};assert!(!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log));
1111let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1112// FIXME(-Zassumptions-on-binders): Handle solver_data
1113if !storage.legacy_data.is_empty() {
{
::core::panicking::panic_fmt(format_args!("{0:#?}",
storage.legacy_data));
}
};assert!(storage.legacy_data.is_empty(), "{:#?}", storage.legacy_data);
1114// We clone instead of taking because borrowck still wants to use the
1115 // inference context after calling this for diagnostics and the new
1116 // trait solver.
1117storage.var_infos.clone()
1118 }
11191120pub fn has_opaque_types_in_storage(&self) -> bool {
1121 !self.inner.borrow().opaque_type_storage.is_empty()
1122 }
11231124{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() || { false }
{
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("take_opaque_types",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1124u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> =
loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs:1124",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1124u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]1125pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1126self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1127 }
11281129{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() || { false }
{
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("clone_opaque_types",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1129u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> =
loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs:1129",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1129u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]1130pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1131self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1132 }
11331134pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1135if !self.next_trait_solver() {
1136return false;
1137 }
11381139let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1140let inner = &mut *self.inner.borrow_mut();
1141let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1142inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1143if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1144let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1145if opaque_sub_vid == ty_sub_vid {
1146return true;
1147 }
1148 }
11491150false
1151})
1152 }
11531154/// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1155 ///
1156 /// This only checks for a subtype relation, it does not require equality.
1157pub fn opaques_with_sub_unified_hidden_type(
1158&self,
1159 ty_vid: TyVid,
1160 ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1161// Avoid accidentally allowing more code to compile with the old solver.
1162if !self.next_trait_solver() {
1163return ::alloc::vec::Vec::new()vec![];
1164 }
11651166let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1167let inner = &mut *self.inner.borrow_mut();
1168// This is iffy, can't call `type_variables()` as we're already
1169 // borrowing the `opaque_type_storage` here.
1170let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1171inner1172 .opaque_type_storage
1173 .iter_opaque_types()
1174 .filter_map(|(key, hidden_ty)| {
1175if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1176let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1177if opaque_sub_vid == ty_sub_vid {
1178return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1179self.tcx,
1180key.def_id.into(),
1181key.args,
1182 ));
1183 }
1184 }
11851186None1187 })
1188 .collect()
1189 }
11901191#[inline(always)]
1192pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1193if true {
if !!self.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.next_trait_solver()")
};
};debug_assert!(!self.next_trait_solver());
1194match self.typing_mode_raw().assert_not_erased() {
1195TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1196 | TypingMode::PostTypeckThroughBorrowck { defining_opaque_types } => {
1197id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1198 }
1199// FIXME(#132279): This function is quite weird in post-analysis
1200 // and post-borrowck analysis mode. We may need to modify its uses
1201 // to support PostBorrowck in the old solver as well.
1202TypingMode::Coherence1203 | TypingMode::Reflection1204 | TypingMode::PostBorrowck { .. }
1205 | TypingMode::PostAnalysis1206 | TypingMode::Codegen => false,
1207 }
1208 }
12091210pub fn push_hir_typeck_potentially_region_dependent_goal(
1211&self,
1212 goal: PredicateObligation<'tcx>,
1213 ) {
1214let mut inner = self.inner.borrow_mut();
1215inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1216inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1217 }
12181219pub fn take_hir_typeck_potentially_region_dependent_goals(
1220&self,
1221 ) -> Vec<PredicateObligation<'tcx>> {
1222if !!self.in_snapshot() {
{
::core::panicking::panic_fmt(format_args!("cannot take goals in a snapshot"));
}
};assert!(!self.in_snapshot(), "cannot take goals in a snapshot");
1223 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1224 }
12251226pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1227self.deeply_resolve_ignoring_regions(t).to_string()
1228 }
12291230/// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1231 /// universe index of `TyVar(vid)`.
1232pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1233use self::type_variable::TypeVariableValue;
12341235match self.inner.borrow_mut().type_variables().probe(vid) {
1236 TypeVariableValue::Known { value } => Ok(value),
1237 TypeVariableValue::Unknown { universe } => Err(universe),
1238 }
1239 }
12401241/// If `vid` resolves to a type, return that type. Otherwise return the root variable id for `vid`.
1242pub fn shallow_resolve_ty_var_or_get_root(&self, vid: TyVid) -> Result<Ty<'tcx>, TyVid> {
1243let (root, value) = self.inner.borrow_mut().type_variables().probe_with_root_vid(vid);
12441245match value {
1246 TypeVariableValue::Known { value } => Ok(value),
1247 TypeVariableValue::Unknown { universe: _ } => Err(root),
1248 }
1249 }
12501251/// Resolve a type variable. Resolving means the following:
1252 ///
1253 /// - If a `Ty` is a rigid type (like, an integer, or some ADT), do nothing.
1254 /// - If a `Ty` is a type infer variable, but has been equated with an actual type,
1255 /// return that type.
1256 /// - If a `Ty` is an int or float infer variable, and has been equated with an integer
1257 /// or floating point type, return that type.
1258 /// - If a `Ty` is any kind of infer variable that has been equated, but not yet with a rigid
1259 /// type, then this set of equated variables forms an equivalence class. One of the variables
1260 /// in that equivalent class is said to be the root variable, and resolving makes sure to
1261 /// consistently return this root variable. This is beneficial for caching.
1262 /// This behavior, of returning roots, changed in <https://github.com/rust-lang/rust/pull/158447>.
1263 ///
1264 /// Otherwise, resolving simply does nothing.
1265 ///
1266 /// The "shallow" part of the name refers to the fact that types may themselves contain more
1267 /// type variables. e.g. The field types of a struct. `shallow_resolve` does not recurse into
1268 /// these nested variables. If that's what you want, use [`deeply_resolve_ignoring_regions`](Self::deeply_resolve_ignoring_regions),
1269 /// or better [`deeply_resolve_via_unification_table`](rustc_type_ir::InferCtxtLike::deeply_resolve_via_unification_table), if you can, which *does* resolve regions.
1270pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1271if let ty::Infer(v) = *ty.kind() {
1272match v {
1273 ty::TyVar(v) => {
1274// Not entirely obvious: if `typ` is a type variable,
1275 // it can be resolved to an int/float variable, which
1276 // can then be recursively resolved, hence the
1277 // recursion. Note though that we prevent type
1278 // variables from unifying to other type variables
1279 // directly (though they may be embedded
1280 // structurally), and we prevent cycles in any case,
1281 // so this recursion should always be of very limited
1282 // depth.
1283 //
1284 // Note: if these two lines are combined into one we get
1285 // dynamic borrow errors on `self.inner`.
1286let (root_vid, value) =
1287self.inner.borrow_mut().type_variables().probe_with_root_vid(v);
1288value.known().map_or_else(
1289 || if root_vid == v { ty } else { Ty::new_var(self.tcx, root_vid) },
1290 |t| self.shallow_resolve(t),
1291 )
1292 }
12931294 ty::IntVar(v) => {
1295let (root, value) =
1296self.inner.borrow_mut().int_unification_table().inlined_probe_key_value(v);
1297match value {
1298 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1299 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1300 ty::IntVarValue::Unknown => {
1301if root == v {
1302ty1303 } else {
1304Ty::new_int_var(self.tcx, root)
1305 }
1306 }
1307 }
1308 }
13091310 ty::FloatVar(v) => {
1311let (root, value) = self1312 .inner
1313 .borrow_mut()
1314 .float_unification_table()
1315 .inlined_probe_key_value(v);
1316match value {
1317 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1318 ty::FloatVarValue::Unknown => {
1319if root == v {
1320ty1321 } else {
1322Ty::new_float_var(self.tcx, root)
1323 }
1324 }
1325 }
1326 }
13271328 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1329 }
1330 } else {
1331ty1332 }
1333 }
13341335/// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1336 /// It's the same, but for consts.
1337pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1338match ct.kind() {
1339 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1340 InferConst::Var(vid) => {
1341let (root, value) = self1342 .inner
1343 .borrow_mut()
1344 .const_unification_table()
1345 .inlined_probe_key_value(vid);
1346value.known().unwrap_or_else(|| {
1347if root.vid == vid { ct } else { ty::Const::new_var(self.tcx, root.vid) }
1348 })
1349 }
1350 InferConst::Fresh(_) => ct,
1351 },
13521353 ty::ConstKind::Param(_)
1354 | ty::ConstKind::Bound(_, _)
1355 | ty::ConstKind::Placeholder(_)
1356 | ty::ConstKind::Alias(_, _)
1357 | ty::ConstKind::Value(_)
1358 | ty::ConstKind::Error(_)
1359 | ty::ConstKind::Expr(_) => ct,
1360 }
1361 }
13621363/// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1364 /// It's the same, but for terms (types or consts).
1365pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1366match term.kind() {
1367 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1368 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1369 }
1370 }
13711372pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1373self.inner.borrow_mut().type_variables().root_var(var)
1374 }
13751376/// If `ty` is an unresolved type variable, returns its root vid.
1377pub fn root_vid(&self, ty: Ty<'tcx>) -> Option<ty::TyVid> {
1378let (root, value) =
1379self.inner.borrow_mut().type_variables().inlined_probe_with_vid(ty.ty_vid()?);
1380value.is_unknown().then_some(root)
1381 }
13821383pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1384self.inner.borrow_mut().type_variables().sub_unify(a, b);
1385 }
13861387pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1388self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1389 }
13901391pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1392self.inner.borrow_mut().float_unification_table().find(var)
1393 }
13941395pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1396self.inner.borrow_mut().const_unification_table().find(var).vid
1397 }
13981399/// Resolves a const var to a rigid const, if it was constrained to one,
1400 /// or else the root const var in the unification table.
1401pub fn shallow_resolve_const_var(&self, vid: ty::ConstVid) -> ty::Const<'tcx> {
1402match self.try_resolve_const_var(vid) {
1403Ok(ct) => ct,
1404Err(_) => ty::Const::new_var(self.tcx, self.root_const_var(vid)),
1405 }
1406 }
14071408/// Resolves a type var to a rigid type, if it was constrained to one,
1409 /// or else the root type var in the unification table.
1410pub fn shallow_resolve_ty_var(&self, vid: ty::TyVid) -> Ty<'tcx> {
1411match self.try_resolve_ty_var(vid) {
1412Ok(ty) => ty,
1413Err(_) => Ty::new_var(self.tcx, self.root_var(vid)),
1414 }
1415 }
14161417/// Resolves an int var to a rigid int type, if it was constrained to one,
1418 /// or else the root int var in the unification table.
1419pub fn shallow_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1420let mut inner = self.inner.borrow_mut();
1421let value = inner.int_unification_table().probe_value(vid);
1422match value {
1423 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1424 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1425 ty::IntVarValue::Unknown => {
1426Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1427 }
1428 }
1429 }
14301431/// Resolves a float var to a rigid type, if it was constrained to one,
1432 /// or else the root float var in the unification table.
1433pub fn shallow_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1434let mut inner = self.inner.borrow_mut();
1435let value = inner.float_unification_table().probe_value(vid);
1436match value {
1437 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1438 ty::FloatVarValue::Unknown => {
1439Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1440 }
1441 }
1442 }
14431444/// If a type/const variable has not (yet) been unified, it is left as is.
1445 ///
1446 /// This is an idempotent operation that does not affect inference state in any way,
1447 /// which means it's safe to call this function at will.
1448 ///
1449 /// Region variables are unaffected.
1450pub fn deeply_resolve_ignoring_regions<T>(&self, value: T) -> T
1451where
1452T: TypeFoldable<TyCtxt<'tcx>>,
1453 {
1454if let Err(guar) = value.error_reported() {
1455self.set_tainted_by_errors(guar);
1456 }
1457if !value.has_non_region_infer() {
1458return value;
1459 }
1460let mut r = resolve::DeepResolverIgnoringRegions::new(self);
1461value.fold_with(&mut r)
1462 }
14631464/// Where possible, replaces type/const/region variables in `value` with their final value.
1465 /// If a type/const/region variable has not (yet) been unified, it is left as is.
1466 ///
1467 /// This is an idempotent operation that does not affect inference state in any way,
1468 /// which means it's safe to call this function at will.
1469pub fn deeply_resolve_via_unification_table<T>(&self, value: T) -> T
1470where
1471T: TypeFoldable<TyCtxt<'tcx>>,
1472 {
1473use rustc_middle::ty::InferCtxtLike;
1474#[allow(rustc::usage_of_type_ir_traits)]
1475InferCtxtLike::deeply_resolve_via_unification_table(self, value)
1476 }
14771478pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1479where
1480T: TypeFoldable<TyCtxt<'tcx>>,
1481 {
1482if !value.has_infer() {
1483return value; // Avoid duplicated type-folding.
1484}
1485let mut r = InferenceLiteralEraser { tcx: self.tcx };
1486value.fold_with(&mut r)
1487 }
14881489pub fn try_resolve_const_var(
1490&self,
1491 vid: ty::ConstVid,
1492 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1493match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1494 ConstVariableValue::Known { value } => Ok(value),
1495 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1496 }
1497 }
14981499/// Attempts to resolve all type/region/const variables in
1500 /// `value`. Region inference must have been run already (e.g.,
1501 /// by calling `resolve_regions_and_report_errors`). If some
1502 /// variable was never unified, an `Err` results.
1503 ///
1504 /// This method is idempotent, but it not typically not invoked
1505 /// except during the writeback phase.
1506pub fn deeply_resolve_via_region_graph<T: TypeFoldable<TyCtxt<'tcx>>>(
1507&self,
1508 value: T,
1509 ) -> FixupResult<T> {
1510match resolve::deeply_resolve_via_region_graph(self, value) {
1511Ok(value) => {
1512if value.has_non_region_infer() {
1513::rustc_span::macros::bug_impl(None,
format_args!("`{0:?}` is not fully resolved", value), Location::caller());bug!("`{value:?}` is not fully resolved");
1514 }
1515if value.has_infer_regions() {
1516let guar = self.dcx().delayed_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0:?}` is not fully resolved",
value))
})format!("`{value:?}` is not fully resolved"));
1517Ok(fold_regions(self.tcx, value, |re, _| {
1518if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1519 }))
1520 } else {
1521Ok(value)
1522 }
1523 }
1524Err(e) => Err(e),
1525 }
1526 }
15271528// Instantiates the bound variables in a given binder with fresh inference
1529 // variables in the current universe.
1530 //
1531 // Use this method if you'd like to find some generic parameters of the binder's
1532 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1533 // that corresponds to your use case, consider whether or not you should
1534 // use [`InferCtxt::enter_forall`] instead.
1535pub fn instantiate_binder_with_fresh_vars<T>(
1536&self,
1537 span: Span,
1538 lbrct: BoundRegionConversionTime,
1539 value: ty::Binder<'tcx, T>,
1540 ) -> T
1541where
1542T: TypeFoldable<TyCtxt<'tcx>>,
1543 {
1544if let Some(_) = value.as_ref().no_bound_vars() {
1545return value.skip_binder();
1546 }
15471548let bound_vars = value.bound_vars();
1549let mut args = Vec::with_capacity(bound_vars.len());
15501551for bound_var_kind in bound_vars {
1552let arg: ty::GenericArg<'_> = match bound_var_kind {
1553 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1554 ty::BoundVariableKind::Region(br) => {
1555self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1556 }
1557 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1558 };
1559 args.push(arg);
1560 }
15611562struct ToFreshVars<'tcx> {
1563 args: Vec<ty::GenericArg<'tcx>>,
1564 }
15651566impl<'tcx> BoundVarReplacerDelegate<TyCtxt<'tcx>> for ToFreshVars<'tcx> {
1567fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1568self.args[br.var.index()].expect_region()
1569 }
1570fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1571self.args[bt.var.index()].expect_ty()
1572 }
1573fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1574self.args[bc.var.index()].expect_const()
1575 }
1576 }
1577let delegate = ToFreshVars { args };
1578self.tcx.replace_bound_vars_uncached(value, delegate)
1579 }
15801581pub fn insert_placeholder_assumptions(
1582&self,
1583 u: ty::UniverseIndex,
1584 assumptions: rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>,
1585 ) {
1586if !!assumptions.type_outlives.has_escaping_bound_vars() {
{
::core::panicking::panic_fmt(format_args!("assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {0:?}",
assumptions.type_outlives));
}
};assert!(
1587 !assumptions.type_outlives.has_escaping_bound_vars(),
1588"assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1589 assumptions.type_outlives
1590 );
1591if !assumptions.region_outlives.base_edges().all(|r|
!r.has_escaping_bound_vars()) {
{
::core::panicking::panic_fmt(format_args!("assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {0:?}",
assumptions.region_outlives));
}
};assert!(
1592 assumptions.region_outlives.base_edges().all(|r| !r.has_escaping_bound_vars()),
1593"assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1594 assumptions.region_outlives
1595 );
1596self.placeholder_assumptions_for_next_solver.borrow_mut().insert(u, assumptions);
1597 }
15981599pub fn get_placeholder_assumptions(
1600&self,
1601 u: ty::UniverseIndex,
1602 ) -> rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>> {
1603self.placeholder_assumptions_for_next_solver.borrow().get(&u).unwrap().clone()
1604 }
16051606pub fn has_placeholder_assumptions(&self, range: RangeInclusive<ty::UniverseIndex>) -> bool {
1607let assumptions = self.placeholder_assumptions_for_next_solver.borrow();
1608// Walk around that `Step` trait is nightly only.
1609(range.start.index()..=range.last.index())
1610 .map(ty::UniverseIndex::from_usize)
1611 .all(|u| assumptions.get(&u).is_some())
1612 }
16131614pub fn get_solver_region_constraint(&self) -> SolverRegionConstraint<'tcx> {
1615self.inner.borrow().region_constraint_storage.as_ref().unwrap().solver_data.get_constraint()
1616 }
16171618pub fn overwrite_solver_region_constraint(&self, constraint: SolverRegionConstraint<'tcx>) {
1619self.inner.borrow_mut().unwrap_region_constraints().overwrite_solver_constraint(constraint);
1620 }
16211622/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1623pub(crate) fn verify_generic_bound(
1624&self,
1625 origin: SubregionOrigin<'tcx>,
1626 kind: GenericKind<'tcx>,
1627 a: ty::Region<'tcx>,
1628 bound: VerifyBound<'tcx>,
1629 ) {
1630{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs:1630",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1630u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("verify_generic_bound({0:?}, {1:?} <: {2:?})",
kind, a, bound) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
16311632self.inner
1633 .borrow_mut()
1634 .unwrap_region_constraints()
1635 .verify_generic_bound(origin, kind, a, bound);
1636 }
16371638/// Obtains the latest type of the given closure; this may be a
1639 /// closure in the current function, in which case its
1640 /// `ClosureKind` may not yet be known.
1641pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1642let unresolved_kind_ty = match *closure_ty.kind() {
1643 ty::Closure(_, args) => args.as_closure().kind_ty(),
1644 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1645_ => ::rustc_span::macros::bug_impl(None,
format_args!("unexpected type {0}", closure_ty), Location::caller())bug!("unexpected type {closure_ty}"),
1646 };
1647let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1648closure_kind_ty.to_opt_closure_kind()
1649 }
16501651pub fn universe(&self) -> ty::UniverseIndex {
1652self.universe.get()
1653 }
16541655/// Creates and return a fresh universe that extends all previous
1656 /// universes. Updates `self.universe` to that new universe.
1657pub fn create_next_universe(&self) -> ty::UniverseIndex {
1658let u = self.universe.get().next_universe();
1659{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs:1659",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1659u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("create_next_universe {0:?}",
u) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("create_next_universe {u:?}");
1660self.universe.set(u);
1661u1662 }
16631664/// We need to disable the fcw if we're already in a fcw emitting to avoid
1665 /// indefinite triggering.
1666pub fn with_disabled_next_solver_overflow_fcw<F, R>(&self, mut f: F) -> R
1667where
1668F: FnMut() -> R,
1669 {
1670let prev = self.enable_next_solver_overflow_fcw.replace(false);
1671let ret = f();
1672self.enable_next_solver_overflow_fcw.set(prev);
1673ret1674 }
16751676/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1677 /// which contains the necessary information to use the trait system without
1678 /// using canonicalization or carrying this inference context around.
1679pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1680let typing_mode = match self.typing_mode_raw() {
1681// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1682 // to handle them without proper canonicalization. This means we may cause cycle
1683 // errors and fail to reveal opaques while inside of bodies. We should rename this
1684 // function and require explicit comments on all use-sites in the future.
1685ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1686 | ty::TypingMode::PostTypeckThroughBorrowck { defining_opaque_types: _ } => {
1687TypingMode::non_body_analysis()
1688 }
1689 mode @ (ty::TypingMode::Coherence1690 | ty::TypingMode::PostBorrowck { .. }
1691 | ty::TypingMode::PostAnalysis1692 | ty::TypingMode::Reflection1693 | ty::TypingMode::Codegen) => mode,
1694 ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::unreachable_default_msg()unreachable!(),
1695 };
1696 ty::TypingEnv::new(param_env, typing_mode)
1697 }
16981699/// Similar to [`Self::canonicalize_query`], except that it returns
1700 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1701 /// `param_env` to not contain any inference variables or placeholders.
1702pub fn pseudo_canonicalize_query<V>(
1703&self,
1704 param_env: ty::ParamEnv<'tcx>,
1705 value: V,
1706 ) -> PseudoCanonicalInput<'tcx, V>
1707where
1708V: TypeVisitable<TyCtxt<'tcx>>,
1709 {
1710if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1711if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1712if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1713if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1714self.typing_env(param_env).as_query_input(value)
1715 }
17161717/// The returned function is used in a fast path. If it returns `true` the variable is
1718 /// unchanged, `false` indicates that the status is unknown.
1719#[inline]
1720pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1721// This hoists the borrow/release out of the loop body.
1722let inner = self.inner.try_borrow();
17231724move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1725 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1726use self::type_variable::TypeVariableValue;
17271728#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1729 inner.try_type_variables_probe_ref(ty_var),
1730Some(TypeVariableValue::Unknown { .. })
1731 )1732 }
1733_ => false,
1734 }
1735 }
17361737/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1738 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1739 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1740 ///
1741 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1742 /// inlined, despite being large, because it has only two call sites that
1743 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1744 /// inference variables), and it handles both `Ty` and `ty::Const` without
1745 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1746#[inline(always)]
1747pub fn ty_or_const_infer_var_changed(&self, var: TyOrConstInferVar) -> bool {
1748match var {
1749 TyOrConstInferVar::Ty(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().try_type_variables_probe_ref(vid)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1750self.inner.borrow().try_type_variables_probe_ref(vid),
1751Some(TypeVariableValue::Unknown { .. })
1752 ),
1753 TyOrConstInferVar::TyInt(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().int_unification_storage.try_probe_value(vid)
{
Some(ty::IntVarValue::Unknown) => true,
_ => false,
}matches!(
1754self.inner.borrow().int_unification_storage.try_probe_value(vid),
1755Some(ty::IntVarValue::Unknown)
1756 ),
1757 TyOrConstInferVar::TyFloat(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().float_unification_storage.try_probe_value(vid)
{
Some(ty::FloatVarValue::Unknown) => true,
_ => false,
}matches!(
1758self.inner.borrow().float_unification_storage.try_probe_value(vid),
1759Some(ty::FloatVarValue::Unknown)
1760 ),
1761 TyOrConstInferVar::Const(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().const_unification_storage.try_probe_value(vid)
{
Some(ConstVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1762self.inner.borrow().const_unification_storage.try_probe_value(vid),
1763Some(ConstVariableValue::Unknown { .. })
1764 ),
1765 }
1766 }
17671768/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1769pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1770if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1771self.obligation_inspector.get().is_none(),
1772"shouldn't override a set obligation inspector"
1773);
1774self.obligation_inspector.set(Some(inspector));
1775 }
1776}
17771778/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1779/// Used only for diagnostics.
1780struct InferenceLiteralEraser<'tcx> {
1781 tcx: TyCtxt<'tcx>,
1782}
17831784impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1785fn cx(&self) -> TyCtxt<'tcx> {
1786self.tcx
1787 }
17881789fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1790match ty.kind() {
1791 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1792 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1793_ => ty.super_fold_with(self),
1794 }
1795 }
1796}
17971798impl<'tcx> TypeTrace<'tcx> {
1799pub fn span(&self) -> Span {
1800self.cause.span
1801 }
18021803pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1804TypeTrace {
1805 cause: cause.clone(),
1806 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1807 }
1808 }
18091810pub fn trait_refs(
1811 cause: &ObligationCause<'tcx>,
1812 a: ty::TraitRef<'tcx>,
1813 b: ty::TraitRef<'tcx>,
1814 ) -> TypeTrace<'tcx> {
1815TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1816 }
18171818pub fn consts(
1819 cause: &ObligationCause<'tcx>,
1820 a: ty::Const<'tcx>,
1821 b: ty::Const<'tcx>,
1822 ) -> TypeTrace<'tcx> {
1823TypeTrace {
1824 cause: cause.clone(),
1825 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1826 }
1827 }
1828}
18291830impl<'tcx> SubregionOrigin<'tcx> {
1831pub fn span(&self) -> Span {
1832match *self {
1833 SubregionOrigin::Subtype(ref a) => a.span(),
1834 SubregionOrigin::RelateObjectBound(a) => a,
1835 SubregionOrigin::RelateParamBound(a, ..) => a,
1836 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1837 SubregionOrigin::Reborrow(a) => a,
1838 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1839 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1840 SubregionOrigin::AscribeUserTypeProvePredicate(span, _) => span,
1841 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1842 SubregionOrigin::SolverRegionConstraint(a) => a,
1843 }
1844 }
18451846pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1847where
1848F: FnOnce() -> Self,
1849 {
1850match *cause.code() {
1851 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1852 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1853 }
18541855 traits::ObligationCauseCode::CompareImplItem {
1856 impl_item_def_id,
1857 trait_item_def_id,
1858 kind: _,
1859 } => SubregionOrigin::CompareImplItemObligation {
1860 span: cause.span,
1861impl_item_def_id,
1862trait_item_def_id,
1863 },
18641865 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1866 impl_item_def_id,
1867 trait_item_def_id,
1868 } => SubregionOrigin::CheckAssociatedTypeBounds {
1869impl_item_def_id,
1870trait_item_def_id,
1871 parent: Box::new(default()),
1872 },
18731874 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span, def_id) => {
1875 SubregionOrigin::AscribeUserTypeProvePredicate(span, def_id)
1876 }
18771878 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1879 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1880 }
18811882_ => default(),
1883 }
1884 }
1885}
18861887impl<'tcx> RegionVariableOrigin<'tcx> {
1888pub fn span(&self) -> Span {
1889match *self {
1890 RegionVariableOrigin::Misc(a)
1891 | RegionVariableOrigin::PatternRegion(a)
1892 | RegionVariableOrigin::BorrowRegion(a)
1893 | RegionVariableOrigin::Autoref(a)
1894 | RegionVariableOrigin::Coercion(a)
1895 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1896 | RegionVariableOrigin::BoundRegion(a, ..)
1897 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1898 RegionVariableOrigin::Nll(..) => ::rustc_span::macros::bug_impl(None,
format_args!("NLL variable used with `span`"), Location::caller())bug!("NLL variable used with `span`"),
1899 }
1900 }
1901}
19021903impl<'tcx> InferCtxt<'tcx> {
1904/// Given a [`hir::Block`], get the span of its last expression or
1905 /// statement, peeling off any inner blocks.
1906pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1907let block = block.innermost_block();
1908if let Some(expr) = &block.expr {
1909expr.span
1910 } else if let Some(stmt) = block.stmts.last() {
1911// possibly incorrect trailing `;` in the else arm
1912stmt.span
1913 } else {
1914// empty block; point at its entirety
1915block.span
1916 }
1917 }
19181919/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1920 /// of its last expression or statement, peeling off any inner blocks.
1921pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1922match self.tcx.hir_node(hir_id) {
1923 hir::Node::Block(blk)
1924 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1925self.find_block_span(blk)
1926 }
1927 hir::Node::Expr(e) => e.span,
1928_ => DUMMY_SP,
1929 }
1930 }
1931}
19321933/// Returns unresolved root variables from `table`, according to `is_unresolved`.
1934fn unresolved_root_variables_of<V: UnifyKey>(
1935mut table: UnificationTable<'_, '_, V>,
1936 is_unresolved: impl Fn(V::Value) -> bool,
1937) -> Vec<V>
1938where
1939V: Eq,
1940 V::Value: UnifyValue,
1941for<'a> UndoLog<'a>: From<sv::UndoLog<ut::Delegate<V>>>,
1942{
1943 (0..table.len() as u32)
1944 .map(V::from_index)
1945 .filter(|&vid| {
1946// NB: as of writing this `ena` doesn't provide a non-inlined `probe_key_value`...
1947let (root, value) = table.inlined_probe_key_value(vid);
1948root == vid && is_unresolved(value)
1949 })
1950 .collect()
1951}