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,
32GenericParamDefKind, InferConst, OpaqueTypeKey, ProvisionalHiddenType, PseudoCanonicalInput,
33Term, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
34TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
35};
36use rustc_span::{DUMMY_SP, Span, Symbol, bug};
37use rustc_type_ir::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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"InferOk value obligations", &self.value, &&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]
#[rustc_trivial_field_reads]
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>>>,
351}
352353impl<'tcx> Dropfor InferCtxt<'tcx> {
354fn drop(&mut self) {
355let mut inner = self.inner.borrow_mut();
356let opaque_type_storage = &mut inner.opaque_type_storage;
357358// No need for the drop bomb when we're in `TypingMode::PostTypeckThroughBorrowck`, and the `InferCtxt`
359 // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
360 // in relation to regions. In some places *after* typeck that aren't borrowck, we use
361 // `TypingMode::PostTypeckThroughBorrowck` to prevent defining opaque types and we simply don't care about regions.
362match self.typing_mode_raw() {
363TypingMode::Coherence364 | TypingMode::Typeck { .. }
365 | TypingMode::PostBorrowck { .. }
366 | TypingMode::Reflection367 | TypingMode::PostAnalysis368 | TypingMode::Codegen => {}
369// In erased mode, the opaque type storage is always empty
370TypingMode::ErasedNotCoherence(..) => {}
371TypingMode::PostTypeckThroughBorrowck { .. } => {
372if !self.considering_regions {
373return;
374 }
375 }
376 }
377378if !opaque_type_storage.is_empty() {
379 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:?}")));
380 }
381 }
382}
383384/// See the `error_reporting` module for more details.
385#[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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Regions(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Regions", &__self_0),
Self::Terms(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Terms",
&__self_0),
Self::Aliases(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Aliases", &__self_0),
Self::TraitRefs(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"TraitRefs", &__self_0),
Self::PolySigs(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"PolySigs", &__self_0),
Self::ExistentialTraitRef(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ExistentialTraitRef", &__self_0),
Self::ExistentialProjection(__self_0) =>
::core::fmt::Formatter::debug_struct_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)]
386pub enum ValuePairs<'tcx> {
387 Regions(ExpectedFound<ty::Region<'tcx>>),
388 Terms(ExpectedFound<ty::Term<'tcx>>),
389 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
390 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
391 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
392 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
393 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
394}
395396impl<'tcx> ValuePairs<'tcx> {
397pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
398if let ValuePairs::Terms(ExpectedFound { expected, found }) = self399 && let Some(expected) = expected.as_type()
400 && let Some(found) = found.as_type()
401 {
402Some((expected, found))
403 } else {
404None405 }
406 }
407}
408409/// The trace designates the path through inference that we took to
410/// encounter an error or subtyping constraint.
411///
412/// See the `error_reporting` module for more details.
413#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for TypeTrace<'tcx> {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"TypeTrace cause values", &self.cause, &&self.values)
}
}Debug)]
414pub struct TypeTrace<'tcx> {
415pub cause: ObligationCause<'tcx>,
416pub values: ValuePairs<'tcx>,
417}
418419/// The origin of a `r1 <= r2` constraint.
420///
421/// See `error_reporting` module for more details
422#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
SubregionOrigin<'tcx> {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Subtype(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Subtype", &__self_0),
Self::RelateObjectBound(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"RelateObjectBound", &__self_0),
Self::RelateParamBound(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"RelateParamBound", __self_0, __self_1, &__self_2),
Self::RelateRegionParamBound(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"RelateRegionParamBound", __self_0, &__self_1),
Self::Reborrow(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Reborrow", &__self_0),
Self::ReferenceOutlivesReferent(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_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 impl_item_def_id trait_item_def_id",
__self_0, __self_1, &__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 impl_item_def_id trait_item_def_id",
__self_0, __self_1, &__self_2),
Self::AscribeUserTypeProvePredicate(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"AscribeUserTypeProvePredicate", __self_0, &__self_1),
Self::SolverRegionConstraint(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"SolverRegionConstraint", &__self_0),
}
}
}Debug)]
423pub enum SubregionOrigin<'tcx> {
424/// Arose from a subtyping relation
425Subtype(Box<TypeTrace<'tcx>>),
426427/// When casting `&'a T` to an `&'b Trait` object,
428 /// relating `'a` to `'b`.
429RelateObjectBound(Span),
430431/// Some type parameter was instantiated with the given type,
432 /// and that type must outlive some region.
433RelateParamBound(Span, Ty<'tcx>, Option<Span>),
434435/// The given region parameter was instantiated with a region
436 /// that must outlive some other region.
437RelateRegionParamBound(Span, Option<Ty<'tcx>>),
438439/// Creating a pointer `b` to contents of another reference.
440Reborrow(Span),
441442/// (&'a &'b T) where a >= b
443ReferenceOutlivesReferent(Ty<'tcx>, Span),
444445/// Comparing the signature and requirements of an impl method against
446 /// the containing trait.
447CompareImplItemObligation {
448 span: Span,
449 impl_item_def_id: LocalDefId,
450 trait_item_def_id: DefId,
451 },
452453/// Checking that the bounds of a trait's associated type hold for a given impl.
454CheckAssociatedTypeBounds {
455 parent: Box<SubregionOrigin<'tcx>>,
456 impl_item_def_id: LocalDefId,
457 trait_item_def_id: DefId,
458 },
459460 AscribeUserTypeProvePredicate(Span, DefId),
461462// FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
463 // proper diagnostics for solver region constraints.
464SolverRegionConstraint(Span),
465}
466467// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
468#[cfg(target_pointer_width = "64")]
469const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
470471impl<'tcx> SubregionOrigin<'tcx> {
472pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
473match self {
474Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
475Self::AscribeUserTypeProvePredicate(span, def_id) => {
476 ConstraintCategory::Predicate(*span, *def_id)
477 }
478Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
479_ => ConstraintCategory::BoringNoLocation,
480 }
481 }
482}
483484/// Times when we replace bound regions with existentials:
485#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for BoundRegionConversionTime {
}
#[automatically_derived]impl ::core::clone::Clone for
BoundRegionConversionTime {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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_struct_field1_finish(f,
"AssocTypeProjection", &__self_0),
}
}
}Debug)]
486pub enum BoundRegionConversionTime {
487/// when a fn is called
488FnCall,
489490/// when two higher-ranked types are compared
491HigherRankedType,
492493/// when projecting an associated type
494AssocTypeProjection(DefId),
495}
496497/// Reasons to create a region inference variable.
498///
499/// See `error_reporting` module for more details.
500#[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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Misc(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Misc",
&__self_0),
Self::PatternRegion(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"PatternRegion", &__self_0),
Self::BorrowRegion(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"BorrowRegion", &__self_0),
Self::Autoref(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Autoref", &__self_0),
Self::Coercion(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Coercion", &__self_0),
Self::RegionParameterDefinition(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"RegionParameterDefinition", __self_0, &__self_1),
Self::BoundRegion(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"BoundRegion", __self_0, __self_1, &__self_2),
Self::UpvarRegion(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"UpvarRegion", __self_0, &__self_1),
Self::Nll(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Nll",
&__self_0),
}
}
}Debug)]
501pub enum RegionVariableOrigin<'tcx> {
502/// Region variables created for ill-categorized reasons.
503 ///
504 /// They mostly indicate places in need of refactoring.
505Misc(Span),
506507/// Regions created by a `&P` or `[...]` pattern.
508PatternRegion(Span),
509510/// Regions created by `&` operator.
511BorrowRegion(Span),
512513/// Regions created as part of an autoref of a method receiver.
514Autoref(Span),
515516/// Regions created as part of an automatic coercion.
517Coercion(Span),
518519/// Region variables created as the values for early-bound regions.
520 ///
521 /// FIXME(@lcnr): This should also store a `DefId`, similar to
522 /// `TypeVariableOrigin`.
523RegionParameterDefinition(Span, Symbol),
524525/// Region variables created when instantiating a binder with
526 /// existential variables, e.g. when calling a function or method.
527BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
528529 UpvarRegion(ty::UpvarId, Span),
530531/// This origin is used for the inference variables that we create
532 /// during NLL region processing.
533Nll(NllRegionVariableOrigin<'tcx>),
534}
535536#[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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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_struct_field1_finish(f,
"Placeholder", &__self_0),
Self::Existential { name: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Existential name", &__self_0),
}
}
}Debug)]
537pub enum NllRegionVariableOrigin<'tcx> {
538/// During NLL region processing, we create variables for free
539 /// regions that we encounter in the function signature and
540 /// elsewhere. This origin indices we've got one of those.
541FreeRegion,
542543/// "Universal" instantiation of a higher-ranked region (e.g.,
544 /// from a `for<'a> T` binder). Meant to represent "any region".
545Placeholder(ty::PlaceholderRegion<'tcx>),
546547 Existential {
548 name: Option<Symbol>,
549 },
550}
551552#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<TyOrConstInferVar>;
*self
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for FixupError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"FixupError unresolved", &&self.unresolved)
}
}Debug)]
553pub struct FixupError {
554 unresolved: TyOrConstInferVar,
555}
556557impl fmt::Displayfor FixupError {
558fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559match self.unresolved {
560 TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
561f,
562"cannot determine the type of this integer; \
563 add a suffix to specify the type explicitly"
564),
565 TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
566f,
567"cannot determine the type of this number; \
568 add a suffix to specify the type explicitly"
569),
570 TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
571 TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
572 }
573 }
574}
575576/// See the `region_obligations` field for more information.
577#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
TypeOutlivesConstraint<'tcx> {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"TypeOutlivesConstraint sub_region sup_type origin",
&self.sub_region, &self.sup_type, &&self.origin)
}
}Debug)]
578pub struct TypeOutlivesConstraint<'tcx> {
579pub sub_region: ty::Region<'tcx>,
580pub sup_type: Ty<'tcx>,
581pub origin: SubregionOrigin<'tcx>,
582}
583584/// Used to configure inference contexts before their creation.
585pub struct InferCtxtBuilder<'tcx> {
586 tcx: TyCtxt<'tcx>,
587 considering_regions: bool,
588 in_hir_typeck: bool,
589 skip_leak_check: bool,
590/// Whether we should use the new trait solver in the local inference context,
591 /// which affects things like which solver is used in `predicate_may_hold`.
592next_trait_solver: bool,
593 enable_next_solver_overflow_fcw: bool,
594}
595596pub 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>)]597impl<'tcx> TyCtxt<'tcx> {
598fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
599InferCtxtBuilder {
600 tcx: self,
601 considering_regions: true,
602 in_hir_typeck: false,
603 skip_leak_check: false,
604 next_trait_solver: self.next_trait_solver_globally(),
605 enable_next_solver_overflow_fcw: true,
606 }
607 }
608}
609610impl<'tcx> InferCtxtBuilder<'tcx> {
611pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
612self.next_trait_solver = next_trait_solver;
613self614 }
615616pub fn enable_next_solver_overflow_fcw(
617mut self,
618 enable_next_solver_overflow_fcw: bool,
619 ) -> Self {
620self.enable_next_solver_overflow_fcw = enable_next_solver_overflow_fcw;
621self622 }
623624pub fn ignoring_regions(mut self) -> Self {
625self.considering_regions = false;
626self627 }
628629pub fn in_hir_typeck(mut self) -> Self {
630self.in_hir_typeck = true;
631self632 }
633634pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
635self.skip_leak_check = skip_leak_check;
636self637 }
638639/// Given a canonical value `C` as a starting point, create an
640 /// inference context that contains each of the bound values
641 /// within instantiated as a fresh variable. The `f` closure is
642 /// invoked with the new infcx, along with the instantiated value
643 /// `V` and a instantiation `S`. This instantiation `S` maps from
644 /// the bound values in `C` to their instantiated values in `V`
645 /// (in other words, `S(C) = V`).
646pub fn build_with_canonical<T>(
647mut self,
648 span: Span,
649 input: &CanonicalQueryInput<'tcx, T>,
650 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
651where
652T: TypeFoldable<TyCtxt<'tcx>>,
653 {
654let infcx = self.build(input.typing_mode.0);
655let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
656 (infcx, value, args)
657 }
658659pub fn build_with_typing_env(
660mut self,
661 typing_env: TypingEnv<'tcx>,
662 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
663 (self.build(typing_env.typing_mode()), typing_env.param_env)
664 }
665666pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
667let InferCtxtBuilder {
668 tcx,
669 considering_regions,
670 in_hir_typeck,
671 skip_leak_check,
672 next_trait_solver,
673 enable_next_solver_overflow_fcw,
674 } = *self;
675InferCtxt {
676tcx,
677typing_mode,
678considering_regions,
679in_hir_typeck,
680skip_leak_check,
681 inner: RefCell::new(InferCtxtInner::new()),
682 lexical_region_resolutions: RefCell::new(None),
683 selection_cache: Default::default(),
684 evaluation_cache: Default::default(),
685 reported_trait_errors: Default::default(),
686 reported_hir_errors: Default::default(),
687 reported_signature_mismatch: Default::default(),
688 tainted_by_errors: Cell::new(None),
689 universe: Cell::new(ty::UniverseIndex::ROOT),
690 placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
691next_trait_solver,
692 enable_next_solver_overflow_fcw: Cell::new(enable_next_solver_overflow_fcw),
693 obligation_inspector: Cell::new(None),
694 }
695 }
696}
697698impl<'tcx, T> InferOk<'tcx, T> {
699/// Extracts `value`, registering any obligations into `fulfill_cx`.
700pub fn into_value_registering_obligations<E: 'tcx>(
701self,
702 infcx: &InferCtxt<'tcx>,
703 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
704 ) -> T {
705let InferOk { value, obligations } = self;
706fulfill_cx.register_predicate_obligations(infcx, obligations);
707value708 }
709}
710711impl<'tcx> InferOk<'tcx, ()> {
712pub fn into_obligations(self) -> PredicateObligations<'tcx> {
713self.obligations
714 }
715}
716717impl<'tcx> InferCtxt<'tcx> {
718pub fn dcx(&self) -> DiagCtxtHandle<'_> {
719self.tcx.dcx().into_taintable(&self.tainted_by_errors)
720 }
721722pub fn next_trait_solver(&self) -> bool {
723self.next_trait_solver
724 }
725726/// This method is deliberately called `..._raw`,
727 /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
728 /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
729 /// more information.
730 ///
731 /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
732 /// works as a kind of store for for example type unification information.
733 /// `InferCtxt` is also often used outside the trait solver during typeck.
734 /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
735 /// To make sure these two uses are never confused, we want to statically encode this information.
736 ///
737 /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
738 /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
739 /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
740 /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
741 /// match on the variant and can safely ignore it.
742 ///
743 /// Prefer non-raw apis if available. e.g.,
744 /// - On the `FnCtxt`
745 /// - on the `SelectionCtxt`
746#[inline(always)]
747pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
748self.typing_mode
749 }
750751#[inline(always)]
752pub fn disable_trait_solver_fast_paths(&self) -> bool {
753self.tcx.disable_trait_solver_fast_paths()
754 }
755756/// Returns the origin of the type variable identified by `vid`.
757 ///
758 /// No attempt is made to resolve `vid` to its root variable.
759pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
760self.inner.borrow_mut().type_variables().var_origin(vid)
761 }
762763/// Returns the origin of the float type variable identified by `vid`.
764 ///
765 /// No attempt is made to resolve `vid` to its root variable.
766pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
767self.inner.borrow_mut().float_origin_origin_storage[vid]
768 }
769770/// Returns the origin of the const variable identified by `vid`
771// FIXME: We should store origins separately from the unification table
772 // so this doesn't need to be optional.
773pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
774match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
775 ConstVariableValue::Known { .. } => None,
776 ConstVariableValue::Unknown { origin, .. } => Some(origin),
777 }
778 }
779780pub fn unresolved_root_variables(&self) -> (Vec<TyVid>, Vec<ty::IntVid>, Vec<ty::FloatVid>) {
781let mut inner = self.inner.borrow_mut();
782783let ty = inner.type_variables().unresolved_root_variables();
784785let int = unresolved_root_variables_of(
786inner.int_unification_table(),
787 ty::IntVarValue::is_unknown,
788 );
789790let float = unresolved_root_variables_of(
791inner.float_unification_table(),
792 ty::FloatVarValue::is_unknown,
793 );
794795 (ty, int, float)
796 }
797798{}
#[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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(798u32),
::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")]799pub fn sub_regions(
800&self,
801 origin: SubregionOrigin<'tcx>,
802 a: ty::Region<'tcx>,
803 b: ty::Region<'tcx>,
804 vis: ty::VisibleForLeakCheck,
805 ) {
806self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
807 }
808809{}
#[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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(809u32),
::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")]810pub fn equate_regions(
811&self,
812 origin: SubregionOrigin<'tcx>,
813 a: ty::Region<'tcx>,
814 b: ty::Region<'tcx>,
815 vis: ty::VisibleForLeakCheck,
816 ) {
817self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
818 }
819820/// Processes a `Coerce` predicate from the fulfillment context.
821 /// This is NOT the preferred way to handle coercion, which is to
822 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
823 ///
824 /// This method here is actually a fallback that winds up being
825 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
826 /// and records a coercion predicate. Presently, this method is equivalent
827 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
828 /// actually requiring `a <: b`. This is of course a valid coercion,
829 /// but it's not as flexible as `FnCtxt::coerce` would be.
830 ///
831 /// (We may refactor this in the future, but there are a number of
832 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
833 /// records adjustments that are required on the HIR in order to perform
834 /// the coercion, and we don't currently have a way to manage that.)
835pub fn coerce_predicate(
836&self,
837 cause: &ObligationCause<'tcx>,
838 param_env: ty::ParamEnv<'tcx>,
839 predicate: ty::PolyCoercePredicate<'tcx>,
840 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
841let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
842 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
843a: p.a,
844 b: p.b,
845 });
846self.subtype_predicate(cause, param_env, subtype_predicate)
847 }
848849pub fn subtype_predicate(
850&self,
851 cause: &ObligationCause<'tcx>,
852 param_env: ty::ParamEnv<'tcx>,
853 predicate: ty::PolySubtypePredicate<'tcx>,
854 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
855// Check for two unresolved inference variables, in which case we can
856 // make no progress. This is partly a micro-optimization, but it's
857 // also an opportunity to "sub-unify" the variables. This isn't
858 // *necessary* to prevent cycles, because they would eventually be sub-unified
859 // anyhow during generalization, but it helps with diagnostics (we can detect
860 // earlier that they are sub-unified).
861 //
862 // Note that we can just skip the binders here because
863 // type variables can't (at present, at
864 // least) capture any of the things bound by this binder.
865 //
866 // Note that this sub here is not just for diagnostics - it has semantic
867 // effects as well.
868let r_a = self.shallow_resolve(predicate.skip_binder().a);
869let r_b = self.shallow_resolve(predicate.skip_binder().b);
870match (r_a.kind(), r_b.kind()) {
871 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
872self.sub_unify_ty_vids_raw(a_vid, b_vid);
873return Err((a_vid, b_vid));
874 }
875_ => {}
876 }
877878self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
879if a_is_expected {
880Ok(self.sub_raw(cause, param_env, DefineOpaqueTypes::Yes, a, b))
881 } else {
882Ok(self.sup_raw(cause, param_env, DefineOpaqueTypes::Yes, b, a))
883 }
884 })
885 }
886887/// Number of type variables created so far.
888pub fn num_ty_vars(&self) -> usize {
889self.inner.borrow_mut().type_variables().num_vars()
890 }
891892pub fn next_ty_vid(&self, span: Span) -> TyVid {
893self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
894 }
895896pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
897self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
898 }
899900pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
901let origin = TypeVariableOrigin { span, param_def_id: None };
902self.inner.borrow_mut().type_variables().new_var(universe, origin)
903 }
904905pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
906self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
907 }
908909pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
910let vid = self.next_ty_vid_with_origin(origin);
911Ty::new_var(self.tcx, vid)
912 }
913914pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
915let vid = self.next_ty_vid_in_universe(span, universe);
916Ty::new_var(self.tcx, vid)
917 }
918919pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
920self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
921 }
922923pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
924let vid = self925 .inner
926 .borrow_mut()
927 .const_unification_table()
928 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
929 .vid;
930 ty::Const::new_var(self.tcx, vid)
931 }
932933pub fn next_const_var_in_universe(
934&self,
935 span: Span,
936 universe: ty::UniverseIndex,
937 ) -> ty::Const<'tcx> {
938let origin = ConstVariableOrigin { span, param_def_id: None };
939let vid = self940 .inner
941 .borrow_mut()
942 .const_unification_table()
943 .new_key(ConstVariableValue::Unknown { origin, universe })
944 .vid;
945 ty::Const::new_var(self.tcx, vid)
946 }
947948pub fn next_int_var(&self) -> Ty<'tcx> {
949let next_int_var_id =
950self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
951Ty::new_int_var(self.tcx, next_int_var_id)
952 }
953954pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
955let mut inner = self.inner.borrow_mut();
956let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
957let origin = FloatVariableOrigin { span, lint_id };
958let span_index = inner.float_origin_origin_storage.push(origin);
959if 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);
960Ty::new_float_var(self.tcx, next_float_var_id)
961 }
962963/// Creates a fresh region variable with the next available index.
964 /// The variable will be created in the maximum universe created
965 /// thus far, allowing it to name any region created thus far.
966pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
967self.next_region_var_in_universe(origin, self.universe())
968 }
969970/// Creates a fresh region variable with the next available index
971 /// in the given universe; typically, you can use
972 /// `next_region_var` and just use the maximal universe.
973pub fn next_region_var_in_universe(
974&self,
975 origin: RegionVariableOrigin<'tcx>,
976 universe: ty::UniverseIndex,
977 ) -> ty::Region<'tcx> {
978let region_var =
979self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
980 ty::Region::new_var(self.tcx, region_var)
981 }
982983pub fn next_term_var_of_alias_kind(
984&self,
985 alias_term: ty::AliasTerm<'tcx>,
986 span: Span,
987 ) -> ty::Term<'tcx> {
988match alias_term.kind {
989 ty::AliasTermKind::ProjectionTy { .. }
990 | ty::AliasTermKind::InherentTy { .. }
991 | ty::AliasTermKind::OpaqueTy { .. }
992 | ty::AliasTermKind::FreeTy { .. } => self.next_ty_var(span).into(),
993 ty::AliasTermKind::FreeConst { .. }
994 | ty::AliasTermKind::InherentConstSelf { .. }
995 | ty::AliasTermKind::InherentConstImpl { .. }
996 | ty::AliasTermKind::AnonConst { .. }
997 | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_var(span).into(),
998 }
999 }
10001001/// Return the universe that the region `r` was created in. For
1002 /// most regions (e.g., `'static`, named regions from the user,
1003 /// etc) this is the root universe U0. For inference variables or
1004 /// placeholders, however, it will return the universe which they
1005 /// are associated.
1006pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1007self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1008 }
10091010/// Number of region variables created so far.
1011pub fn num_region_vars(&self) -> usize {
1012self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1013 }
10141015/// Just a convenient wrapper of `next_region_var` for using during NLL.
1016{}
#[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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1016u32),
::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")]1017pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
1018self.next_region_var(RegionVariableOrigin::Nll(origin))
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_in_universe",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/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()
},
{
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")]1023pub fn next_nll_region_var_in_universe(
1024&self,
1025 origin: NllRegionVariableOrigin<'tcx>,
1026 universe: ty::UniverseIndex,
1027 ) -> ty::Region<'tcx> {
1028self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1029 }
10301031#[inline(always)]
1032pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1033match param.kind {
1034 GenericParamDefKind::Lifetime => {
1035// Create a region inference variable for the given
1036 // region parameter definition.
1037self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1038span, param.name,
1039 ))
1040 .into()
1041 }
1042 GenericParamDefKind::Type { .. } => {
1043// Create a type inference variable for the given
1044 // type parameter definition. The generic parameters are
1045 // for actual parameters that may be referred to by
1046 // the default of this type parameter, if it exists.
1047 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1048 // used in a path such as `Foo::<T, U>::new()` will
1049 // use an inference variable for `C` with `[T, U]`
1050 // as the generic parameters for the default, `(T, U)`.
1051let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1052self.universe(),
1053TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1054 );
10551056Ty::new_var(self.tcx, ty_var_id).into()
1057 }
1058 GenericParamDefKind::Const { .. } => {
1059let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1060let const_var_id = self1061 .inner
1062 .borrow_mut()
1063 .const_unification_table()
1064 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1065 .vid;
1066 ty::Const::new_var(self.tcx, const_var_id).into()
1067 }
1068 }
1069 }
10701071/// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1072 /// each type/region parameter to a fresh inference variable.
1073pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgs<'tcx> {
1074GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1075 }
10761077/// Returns `true` if errors have been reported since this infcx was
1078 /// created. This is sometimes used as a heuristic to skip
1079 /// reporting errors that often occur as a result of earlier
1080 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1081 /// inference variables, regionck errors).
1082#[must_use = "this method does not have any side effects"]
1083pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1084self.tainted_by_errors.get()
1085 }
10861087/// Set the "tainted by errors" flag to true. We call this when we
1088 /// observe an error from a prior pass.
1089pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1090{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs:1090",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1090u32),
::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)");
1091self.tainted_by_errors.set(Some(e));
1092 }
10931094pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1095let mut inner = self.inner.borrow_mut();
1096let inner = &mut *inner;
1097inner.unwrap_region_constraints().var_origin(vid)
1098 }
10991100/// Clone the list of variable regions. This is used only during NLL processing
1101 /// to put the set of region variables into the NLL region context.
1102pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1103let inner = self.inner.borrow();
1104if !!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));
1105let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1106// FIXME(-Zassumptions-on-binders): Handle solver_data
1107if !storage.legacy_data.is_empty() {
{
::core::panicking::panic_fmt(format_args!("{0:#?}",
storage.legacy_data));
}
};assert!(storage.legacy_data.is_empty(), "{:#?}", storage.legacy_data);
1108// We clone instead of taking because borrowck still wants to use the
1109 // inference context after calling this for diagnostics and the new
1110 // trait solver.
1111storage.var_infos.clone()
1112 }
11131114pub fn has_opaque_types_in_storage(&self) -> bool {
1115 !self.inner.borrow().opaque_type_storage.is_empty()
1116 }
11171118{}
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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1118u32),
::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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs:1118",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1118u32),
::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)]1119pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1120self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1121 }
11221123{}
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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1123u32),
::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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs:1123",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1123u32),
::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)]1124pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1125self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1126 }
11271128pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1129if !self.next_trait_solver() {
1130return false;
1131 }
11321133let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1134let inner = &mut *self.inner.borrow_mut();
1135let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1136inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1137if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1138let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1139if opaque_sub_vid == ty_sub_vid {
1140return true;
1141 }
1142 }
11431144false
1145})
1146 }
11471148/// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1149 ///
1150 /// This only checks for a subtype relation, it does not require equality.
1151pub fn opaques_with_sub_unified_hidden_type(
1152&self,
1153 ty_vid: TyVid,
1154 ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1155// Avoid accidentally allowing more code to compile with the old solver.
1156if !self.next_trait_solver() {
1157return ::alloc::vec::Vec::new()vec![];
1158 }
11591160let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1161let inner = &mut *self.inner.borrow_mut();
1162// This is iffy, can't call `type_variables()` as we're already
1163 // borrowing the `opaque_type_storage` here.
1164let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1165inner1166 .opaque_type_storage
1167 .iter_opaque_types()
1168 .filter_map(|(key, hidden_ty)| {
1169if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1170let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1171if opaque_sub_vid == ty_sub_vid {
1172return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1173self.tcx,
1174key.def_id.into(),
1175key.args,
1176 ));
1177 }
1178 }
11791180None1181 })
1182 .collect()
1183 }
11841185#[inline(always)]
1186pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1187if true {
if !!self.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.next_trait_solver()")
};
};debug_assert!(!self.next_trait_solver());
1188match self.typing_mode_raw().assert_not_erased() {
1189TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1190 | TypingMode::PostTypeckThroughBorrowck { defining_opaque_types } => {
1191id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1192 }
1193// FIXME(#132279): This function is quite weird in post-analysis
1194 // and post-borrowck analysis mode. We may need to modify its uses
1195 // to support PostBorrowck in the old solver as well.
1196TypingMode::Coherence1197 | TypingMode::Reflection1198 | TypingMode::PostBorrowck { .. }
1199 | TypingMode::PostAnalysis1200 | TypingMode::Codegen => false,
1201 }
1202 }
12031204pub fn push_hir_typeck_potentially_region_dependent_goal(
1205&self,
1206 goal: PredicateObligation<'tcx>,
1207 ) {
1208let mut inner = self.inner.borrow_mut();
1209inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1210inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1211 }
12121213pub fn take_hir_typeck_potentially_region_dependent_goals(
1214&self,
1215 ) -> Vec<PredicateObligation<'tcx>> {
1216if !!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");
1217 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1218 }
12191220pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1221self.deeply_resolve_ignoring_regions(t).to_string()
1222 }
12231224/// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1225 /// universe index of `TyVar(vid)`.
1226pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1227use self::type_variable::TypeVariableValue;
12281229match self.inner.borrow_mut().type_variables().probe(vid) {
1230 TypeVariableValue::Known { value } => Ok(value),
1231 TypeVariableValue::Unknown { universe } => Err(universe),
1232 }
1233 }
12341235/// If `vid` resolves to a type, return that type. Otherwise return the root variable id for `vid`.
1236pub fn shallow_resolve_ty_var_or_get_root(&self, vid: TyVid) -> Result<Ty<'tcx>, TyVid> {
1237let (root, value) = self.inner.borrow_mut().type_variables().probe_with_root_vid(vid);
12381239match value {
1240 TypeVariableValue::Known { value } => Ok(value),
1241 TypeVariableValue::Unknown { universe: _ } => Err(root),
1242 }
1243 }
12441245/// Resolve a type variable. Resolving means the following:
1246 ///
1247 /// - If a `Ty` is a rigid type (like, an integer, or some ADT), do nothing.
1248 /// - If a `Ty` is a type infer variable, but has been equated with an actual type,
1249 /// return that type.
1250 /// - If a `Ty` is an int or float infer variable, and has been equated with an integer
1251 /// or floating point type, return that type.
1252 /// - If a `Ty` is any kind of infer variable that has been equated, but not yet with a rigid
1253 /// type, then this set of equated variables forms an equivalence class. One of the variables
1254 /// in that equivalent class is said to be the root variable, and resolving makes sure to
1255 /// consistently return this root variable. This is beneficial for caching.
1256 /// This behavior, of returning roots, changed in <https://github.com/rust-lang/rust/pull/158447>.
1257 ///
1258 /// Otherwise, resolving simply does nothing.
1259 ///
1260 /// The "shallow" part of the name refers to the fact that types may themselves contain more
1261 /// type variables. e.g. The field types of a struct. `shallow_resolve` does not recurse into
1262 /// these nested variables. If that's what you want, use [`deeply_resolve_ignoring_regions`](Self::deeply_resolve_ignoring_regions),
1263 /// or better [`deeply_resolve_via_unification_table`](rustc_type_ir::InferCtxtLike::deeply_resolve_via_unification_table), if you can, which *does* resolve regions.
1264pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1265if let ty::Infer(v) = *ty.kind() {
1266match v {
1267 ty::TyVar(v) => {
1268// Not entirely obvious: if `typ` is a type variable,
1269 // it can be resolved to an int/float variable, which
1270 // can then be recursively resolved, hence the
1271 // recursion. Note though that we prevent type
1272 // variables from unifying to other type variables
1273 // directly (though they may be embedded
1274 // structurally), and we prevent cycles in any case,
1275 // so this recursion should always be of very limited
1276 // depth.
1277 //
1278 // Note: if these two lines are combined into one we get
1279 // dynamic borrow errors on `self.inner`.
1280let (root_vid, value) =
1281self.inner.borrow_mut().type_variables().probe_with_root_vid(v);
1282value.known().map_or_else(
1283 || if root_vid == v { ty } else { Ty::new_var(self.tcx, root_vid) },
1284 |t| self.shallow_resolve(t),
1285 )
1286 }
12871288 ty::IntVar(v) => {
1289let (root, value) =
1290self.inner.borrow_mut().int_unification_table().inlined_probe_key_value(v);
1291match value {
1292 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1293 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1294 ty::IntVarValue::Unknown => {
1295if root == v {
1296ty1297 } else {
1298Ty::new_int_var(self.tcx, root)
1299 }
1300 }
1301 }
1302 }
13031304 ty::FloatVar(v) => {
1305let (root, value) = self1306 .inner
1307 .borrow_mut()
1308 .float_unification_table()
1309 .inlined_probe_key_value(v);
1310match value {
1311 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1312 ty::FloatVarValue::Unknown => {
1313if root == v {
1314ty1315 } else {
1316Ty::new_float_var(self.tcx, root)
1317 }
1318 }
1319 }
1320 }
13211322 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1323 }
1324 } else {
1325ty1326 }
1327 }
13281329/// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1330 /// It's the same, but for consts.
1331pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1332match ct.kind() {
1333 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1334 InferConst::Var(vid) => {
1335let (root, value) = self1336 .inner
1337 .borrow_mut()
1338 .const_unification_table()
1339 .inlined_probe_key_value(vid);
1340value.known().unwrap_or_else(|| {
1341if root.vid == vid { ct } else { ty::Const::new_var(self.tcx, root.vid) }
1342 })
1343 }
1344 InferConst::Fresh(_) => ct,
1345 },
13461347 ty::ConstKind::Param(_)
1348 | ty::ConstKind::Bound(_, _)
1349 | ty::ConstKind::Placeholder(_)
1350 | ty::ConstKind::Alias(_, _)
1351 | ty::ConstKind::Value(_)
1352 | ty::ConstKind::Error(_)
1353 | ty::ConstKind::Expr(_) => ct,
1354 }
1355 }
13561357/// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1358 /// It's the same, but for terms (types or consts).
1359pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1360match term.kind() {
1361 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1362 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1363 }
1364 }
13651366pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1367self.inner.borrow_mut().type_variables().root_var(var)
1368 }
13691370/// If `ty` is an unresolved type variable, returns its root vid.
1371pub fn root_vid(&self, ty: Ty<'tcx>) -> Option<ty::TyVid> {
1372let (root, value) =
1373self.inner.borrow_mut().type_variables().inlined_probe_with_vid(ty.ty_vid()?);
1374value.is_unknown().then_some(root)
1375 }
13761377pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1378self.inner.borrow_mut().type_variables().sub_unify(a, b);
1379 }
13801381pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1382self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1383 }
13841385pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1386self.inner.borrow_mut().float_unification_table().find(var)
1387 }
13881389pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1390self.inner.borrow_mut().const_unification_table().find(var).vid
1391 }
13921393/// Resolves a const var to a rigid const, if it was constrained to one,
1394 /// or else the root const var in the unification table.
1395pub fn shallow_resolve_const_var(&self, vid: ty::ConstVid) -> ty::Const<'tcx> {
1396match self.try_resolve_const_var(vid) {
1397Ok(ct) => ct,
1398Err(_) => ty::Const::new_var(self.tcx, self.root_const_var(vid)),
1399 }
1400 }
14011402/// Resolves a type var to a rigid type, if it was constrained to one,
1403 /// or else the root type var in the unification table.
1404pub fn shallow_resolve_ty_var(&self, vid: ty::TyVid) -> Ty<'tcx> {
1405match self.try_resolve_ty_var(vid) {
1406Ok(ty) => ty,
1407Err(_) => Ty::new_var(self.tcx, self.root_var(vid)),
1408 }
1409 }
14101411/// Resolves an int var to a rigid int type, if it was constrained to one,
1412 /// or else the root int var in the unification table.
1413pub fn shallow_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1414let mut inner = self.inner.borrow_mut();
1415let value = inner.int_unification_table().probe_value(vid);
1416match value {
1417 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1418 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1419 ty::IntVarValue::Unknown => {
1420Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1421 }
1422 }
1423 }
14241425/// Resolves a float var to a rigid type, if it was constrained to one,
1426 /// or else the root float var in the unification table.
1427pub fn shallow_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1428let mut inner = self.inner.borrow_mut();
1429let value = inner.float_unification_table().probe_value(vid);
1430match value {
1431 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1432 ty::FloatVarValue::Unknown => {
1433Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1434 }
1435 }
1436 }
14371438/// If a type/const variable has not (yet) been unified, it is left as is.
1439 ///
1440 /// This is an idempotent operation that does not affect inference state in any way,
1441 /// which means it's safe to call this function at will.
1442 ///
1443 /// Region variables are unaffected.
1444pub fn deeply_resolve_ignoring_regions<T>(&self, value: T) -> T
1445where
1446T: TypeFoldable<TyCtxt<'tcx>>,
1447 {
1448if let Err(guar) = value.error_reported() {
1449self.set_tainted_by_errors(guar);
1450 }
1451if !value.has_non_region_infer() {
1452return value;
1453 }
1454let mut r = resolve::DeepResolverIgnoringRegions::new(self);
1455value.fold_with(&mut r)
1456 }
14571458/// Where possible, replaces type/const/region variables in `value` with their final value.
1459 /// If a type/const/region variable has not (yet) been unified, it is left as is.
1460 ///
1461 /// This is an idempotent operation that does not affect inference state in any way,
1462 /// which means it's safe to call this function at will.
1463pub fn deeply_resolve_via_unification_table<T>(&self, value: T) -> T
1464where
1465T: TypeFoldable<TyCtxt<'tcx>>,
1466 {
1467use rustc_middle::ty::InferCtxtLike;
1468#[allow(rustc::usage_of_type_ir_traits)]
1469InferCtxtLike::deeply_resolve_via_unification_table(self, value)
1470 }
14711472pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1473where
1474T: TypeFoldable<TyCtxt<'tcx>>,
1475 {
1476if !value.has_infer() {
1477return value; // Avoid duplicated type-folding.
1478}
1479let mut r = InferenceLiteralEraser { tcx: self.tcx };
1480value.fold_with(&mut r)
1481 }
14821483pub fn try_resolve_const_var(
1484&self,
1485 vid: ty::ConstVid,
1486 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1487match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1488 ConstVariableValue::Known { value } => Ok(value),
1489 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1490 }
1491 }
14921493/// Attempts to resolve all type/region/const variables in
1494 /// `value`. Region inference must have been run already (e.g.,
1495 /// by calling `resolve_regions_and_report_errors`). If some
1496 /// variable was never unified, an `Err` results.
1497 ///
1498 /// This method is idempotent, but it not typically not invoked
1499 /// except during the writeback phase.
1500pub fn deeply_resolve_via_region_graph<T: TypeFoldable<TyCtxt<'tcx>>>(
1501&self,
1502 value: T,
1503 ) -> FixupResult<T> {
1504match resolve::deeply_resolve_via_region_graph(self, value) {
1505Ok(value) => {
1506if value.has_non_region_infer() {
1507::rustc_span::macros::bug_impl(None,
format_args!("`{0:?}` is not fully resolved", value), Location::caller());bug!("`{value:?}` is not fully resolved");
1508 }
1509if value.has_infer_regions() {
1510let 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"));
1511Ok(fold_regions(self.tcx, value, |re, _| {
1512if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1513 }))
1514 } else {
1515Ok(value)
1516 }
1517 }
1518Err(e) => Err(e),
1519 }
1520 }
15211522// Instantiates the bound variables in a given binder with fresh inference
1523 // variables in the current universe.
1524 //
1525 // Use this method if you'd like to find some generic parameters of the binder's
1526 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1527 // that corresponds to your use case, consider whether or not you should
1528 // use [`InferCtxt::enter_forall`] instead.
1529pub fn instantiate_binder_with_fresh_vars<T>(
1530&self,
1531 span: Span,
1532 lbrct: BoundRegionConversionTime,
1533 value: ty::Binder<'tcx, T>,
1534 ) -> T
1535where
1536T: TypeFoldable<TyCtxt<'tcx>>,
1537 {
1538if let Some(_) = value.as_ref().no_bound_vars() {
1539return value.skip_binder();
1540 }
15411542let bound_vars = value.bound_vars();
1543let mut args = Vec::with_capacity(bound_vars.len());
15441545for bound_var_kind in bound_vars {
1546let arg: ty::GenericArg<'_> = match bound_var_kind {
1547 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1548 ty::BoundVariableKind::Region(br) => {
1549self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1550 }
1551 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1552 };
1553 args.push(arg);
1554 }
15551556struct ToFreshVars<'tcx> {
1557 args: Vec<ty::GenericArg<'tcx>>,
1558 }
15591560impl<'tcx> BoundVarReplacerDelegate<TyCtxt<'tcx>> for ToFreshVars<'tcx> {
1561fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1562self.args[br.var.index()].expect_region()
1563 }
1564fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1565self.args[bt.var.index()].expect_ty()
1566 }
1567fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1568self.args[bc.var.index()].expect_const()
1569 }
1570 }
1571let delegate = ToFreshVars { args };
1572self.tcx.replace_bound_vars_uncached(value, delegate)
1573 }
15741575pub fn insert_placeholder_assumptions(
1576&self,
1577 u: ty::UniverseIndex,
1578 assumptions: rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>,
1579 ) {
1580if !!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!(
1581 !assumptions.type_outlives.has_escaping_bound_vars(),
1582"assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1583 assumptions.type_outlives
1584 );
1585if !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!(
1586 assumptions.region_outlives.base_edges().all(|r| !r.has_escaping_bound_vars()),
1587"assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1588 assumptions.region_outlives
1589 );
1590self.placeholder_assumptions_for_next_solver.borrow_mut().insert(u, assumptions);
1591 }
15921593pub fn get_placeholder_assumptions(
1594&self,
1595 u: ty::UniverseIndex,
1596 ) -> rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>> {
1597self.placeholder_assumptions_for_next_solver.borrow().get(&u).unwrap().clone()
1598 }
15991600pub fn has_placeholder_assumptions(&self, range: RangeInclusive<ty::UniverseIndex>) -> bool {
1601let assumptions = self.placeholder_assumptions_for_next_solver.borrow();
1602// Walk around that `Step` trait is nightly only.
1603(range.start.index()..=range.last.index())
1604 .map(ty::UniverseIndex::from_usize)
1605 .all(|u| assumptions.get(&u).is_some())
1606 }
16071608pub fn get_solver_region_constraint(&self) -> SolverRegionConstraint<'tcx> {
1609self.inner.borrow().region_constraint_storage.as_ref().unwrap().solver_data.get_constraint()
1610 }
16111612pub fn overwrite_solver_region_constraint(&self, constraint: SolverRegionConstraint<'tcx>) {
1613self.inner.borrow_mut().unwrap_region_constraints().overwrite_solver_constraint(constraint);
1614 }
16151616/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1617pub(crate) fn verify_generic_bound(
1618&self,
1619 origin: SubregionOrigin<'tcx>,
1620 kind: GenericKind<'tcx>,
1621 a: ty::Region<'tcx>,
1622 bound: VerifyBound<'tcx>,
1623 ) {
1624{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs:1624",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1624u32),
::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);
16251626self.inner
1627 .borrow_mut()
1628 .unwrap_region_constraints()
1629 .verify_generic_bound(origin, kind, a, bound);
1630 }
16311632/// Obtains the latest type of the given closure; this may be a
1633 /// closure in the current function, in which case its
1634 /// `ClosureKind` may not yet be known.
1635pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1636let unresolved_kind_ty = match *closure_ty.kind() {
1637 ty::Closure(_, args) => args.as_closure().kind_ty(),
1638 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1639_ => ::rustc_span::macros::bug_impl(None,
format_args!("unexpected type {0}", closure_ty), Location::caller())bug!("unexpected type {closure_ty}"),
1640 };
1641let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1642closure_kind_ty.to_opt_closure_kind()
1643 }
16441645pub fn universe(&self) -> ty::UniverseIndex {
1646self.universe.get()
1647 }
16481649/// Creates and return a fresh universe that extends all previous
1650 /// universes. Updates `self.universe` to that new universe.
1651pub fn create_next_universe(&self) -> ty::UniverseIndex {
1652let u = self.universe.get().next_universe();
1653{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs:1653",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1653u32),
::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:?}");
1654self.universe.set(u);
1655u1656 }
16571658/// We need to disable the fcw if we're already in a fcw emitting to avoid
1659 /// indefinite triggering.
1660pub fn with_disabled_next_solver_overflow_fcw<F, R>(&self, mut f: F) -> R
1661where
1662F: FnMut() -> R,
1663 {
1664let prev = self.enable_next_solver_overflow_fcw.replace(false);
1665let ret = f();
1666self.enable_next_solver_overflow_fcw.set(prev);
1667ret1668 }
16691670/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1671 /// which contains the necessary information to use the trait system without
1672 /// using canonicalization or carrying this inference context around.
1673pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1674let typing_mode = match self.typing_mode_raw() {
1675// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1676 // to handle them without proper canonicalization. This means we may cause cycle
1677 // errors and fail to reveal opaques while inside of bodies. We should rename this
1678 // function and require explicit comments on all use-sites in the future.
1679ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1680 | ty::TypingMode::PostTypeckThroughBorrowck { defining_opaque_types: _ } => {
1681TypingMode::non_body_analysis()
1682 }
1683 mode @ (ty::TypingMode::Coherence1684 | ty::TypingMode::PostBorrowck { .. }
1685 | ty::TypingMode::PostAnalysis1686 | ty::TypingMode::Reflection1687 | ty::TypingMode::Codegen) => mode,
1688 ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::unreachable_default_msg()unreachable!(),
1689 };
1690 ty::TypingEnv::new(param_env, typing_mode)
1691 }
16921693/// Similar to [`Self::canonicalize_query`], except that it returns
1694 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1695 /// `param_env` to not contain any inference variables or placeholders.
1696pub fn pseudo_canonicalize_query<V>(
1697&self,
1698 param_env: ty::ParamEnv<'tcx>,
1699 value: V,
1700 ) -> PseudoCanonicalInput<'tcx, V>
1701where
1702V: TypeVisitable<TyCtxt<'tcx>>,
1703 {
1704if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1705if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1706if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1707if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1708self.typing_env(param_env).as_query_input(value)
1709 }
17101711/// The returned function is used in a fast path. If it returns `true` the variable is
1712 /// unchanged, `false` indicates that the status is unknown.
1713#[inline]
1714pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1715// This hoists the borrow/release out of the loop body.
1716let inner = self.inner.try_borrow();
17171718move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1719 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1720use self::type_variable::TypeVariableValue;
17211722#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1723 inner.try_type_variables_probe_ref(ty_var),
1724Some(TypeVariableValue::Unknown { .. })
1725 )1726 }
1727_ => false,
1728 }
1729 }
17301731/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1732 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1733 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1734 ///
1735 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1736 /// inlined, despite being large, because it has only two call sites that
1737 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1738 /// inference variables), and it handles both `Ty` and `ty::Const` without
1739 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1740#[inline(always)]
1741pub fn ty_or_const_infer_var_changed(&self, var: TyOrConstInferVar) -> bool {
1742match var {
1743 TyOrConstInferVar::Ty(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().try_type_variables_probe_ref(vid)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1744self.inner.borrow().try_type_variables_probe_ref(vid),
1745Some(TypeVariableValue::Unknown { .. })
1746 ),
1747 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!(
1748self.inner.borrow().int_unification_storage.try_probe_value(vid),
1749Some(ty::IntVarValue::Unknown)
1750 ),
1751 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!(
1752self.inner.borrow().float_unification_storage.try_probe_value(vid),
1753Some(ty::FloatVarValue::Unknown)
1754 ),
1755 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!(
1756self.inner.borrow().const_unification_storage.try_probe_value(vid),
1757Some(ConstVariableValue::Unknown { .. })
1758 ),
1759 }
1760 }
17611762/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1763pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1764if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1765self.obligation_inspector.get().is_none(),
1766"shouldn't override a set obligation inspector"
1767);
1768self.obligation_inspector.set(Some(inspector));
1769 }
1770}
17711772/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1773/// Used only for diagnostics.
1774struct InferenceLiteralEraser<'tcx> {
1775 tcx: TyCtxt<'tcx>,
1776}
17771778impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1779fn cx(&self) -> TyCtxt<'tcx> {
1780self.tcx
1781 }
17821783fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1784match ty.kind() {
1785 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1786 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1787_ => ty.super_fold_with(self),
1788 }
1789 }
1790}
17911792impl<'tcx> TypeTrace<'tcx> {
1793pub fn span(&self) -> Span {
1794self.cause.span
1795 }
17961797pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1798TypeTrace {
1799 cause: cause.clone(),
1800 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1801 }
1802 }
18031804pub fn trait_refs(
1805 cause: &ObligationCause<'tcx>,
1806 a: ty::TraitRef<'tcx>,
1807 b: ty::TraitRef<'tcx>,
1808 ) -> TypeTrace<'tcx> {
1809TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1810 }
18111812pub fn consts(
1813 cause: &ObligationCause<'tcx>,
1814 a: ty::Const<'tcx>,
1815 b: ty::Const<'tcx>,
1816 ) -> TypeTrace<'tcx> {
1817TypeTrace {
1818 cause: cause.clone(),
1819 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1820 }
1821 }
1822}
18231824impl<'tcx> SubregionOrigin<'tcx> {
1825pub fn span(&self) -> Span {
1826match *self {
1827 SubregionOrigin::Subtype(ref a) => a.span(),
1828 SubregionOrigin::RelateObjectBound(a) => a,
1829 SubregionOrigin::RelateParamBound(a, ..) => a,
1830 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1831 SubregionOrigin::Reborrow(a) => a,
1832 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1833 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1834 SubregionOrigin::AscribeUserTypeProvePredicate(span, _) => span,
1835 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1836 SubregionOrigin::SolverRegionConstraint(a) => a,
1837 }
1838 }
18391840pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1841where
1842F: FnOnce() -> Self,
1843 {
1844match *cause.code() {
1845 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1846 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1847 }
18481849 traits::ObligationCauseCode::CompareImplItem {
1850 impl_item_def_id,
1851 trait_item_def_id,
1852 kind: _,
1853 } => SubregionOrigin::CompareImplItemObligation {
1854 span: cause.span,
1855impl_item_def_id,
1856trait_item_def_id,
1857 },
18581859 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1860 impl_item_def_id,
1861 trait_item_def_id,
1862 } => SubregionOrigin::CheckAssociatedTypeBounds {
1863impl_item_def_id,
1864trait_item_def_id,
1865 parent: Box::new(default()),
1866 },
18671868 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span, def_id) => {
1869 SubregionOrigin::AscribeUserTypeProvePredicate(span, def_id)
1870 }
18711872 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1873 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1874 }
18751876_ => default(),
1877 }
1878 }
1879}
18801881impl<'tcx> RegionVariableOrigin<'tcx> {
1882pub fn span(&self) -> Span {
1883match *self {
1884 RegionVariableOrigin::Misc(a)
1885 | RegionVariableOrigin::PatternRegion(a)
1886 | RegionVariableOrigin::BorrowRegion(a)
1887 | RegionVariableOrigin::Autoref(a)
1888 | RegionVariableOrigin::Coercion(a)
1889 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1890 | RegionVariableOrigin::BoundRegion(a, ..)
1891 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1892 RegionVariableOrigin::Nll(..) => ::rustc_span::macros::bug_impl(None,
format_args!("NLL variable used with `span`"), Location::caller())bug!("NLL variable used with `span`"),
1893 }
1894 }
1895}
18961897impl<'tcx> InferCtxt<'tcx> {
1898/// Given a [`hir::Block`], get the span of its last expression or
1899 /// statement, peeling off any inner blocks.
1900pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1901let block = block.innermost_block();
1902if let Some(expr) = &block.expr {
1903expr.span
1904 } else if let Some(stmt) = block.stmts.last() {
1905// possibly incorrect trailing `;` in the else arm
1906stmt.span
1907 } else {
1908// empty block; point at its entirety
1909block.span
1910 }
1911 }
19121913/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1914 /// of its last expression or statement, peeling off any inner blocks.
1915pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1916match self.tcx.hir_node(hir_id) {
1917 hir::Node::Block(blk)
1918 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1919self.find_block_span(blk)
1920 }
1921 hir::Node::Expr(e) => e.span,
1922_ => DUMMY_SP,
1923 }
1924 }
1925}
19261927/// Returns unresolved root variables from `table`, according to `is_unresolved`.
1928fn unresolved_root_variables_of<V: UnifyKey>(
1929mut table: UnificationTable<'_, '_, V>,
1930 is_unresolved: impl Fn(V::Value) -> bool,
1931) -> Vec<V>
1932where
1933V: Eq,
1934 V::Value: UnifyValue,
1935for<'a> UndoLog<'a>: From<sv::UndoLog<ut::Delegate<V>>>,
1936{
1937 (0..table.len() as u32)
1938 .map(V::from_index)
1939 .filter(|&vid| {
1940// NB: as of writing this `ena` doesn't provide a non-inlined `probe_key_value`...
1941let (root, value) = table.inlined_probe_key_value(vid);
1942root == vid && is_unresolved(value)
1943 })
1944 .collect()
1945}