1use std::cell::{Cell, RefCell};
2use std::fmt;
34pub use at::DefineOpaqueTypes;
5use free_regions::RegionRelations;
6pub use freshen::TypeFreshener;
7use lexical_region_resolve::LexicalRegionResolutions;
8pub use lexical_region_resolve::RegionResolutionError;
9pub use opaque_types::{OpaqueTypeStorage, OpaqueTypeStorageEntries, OpaqueTypeTable};
10use region_constraints::{
11GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
12};
13pub use relate::combine::PredicateEmittingRelation;
14use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
15use rustc_data_structures::snapshot_vecas sv;
16use rustc_data_structures::undo_log::{Rollback, UndoLogs};
17use rustc_data_structures::unify::{selfas ut, UnifyKey, UnifyValue};
18use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
19use rustc_hir::def_id::{DefId, LocalDefId};
20use rustc_hir::{selfas hir, HirId};
21use rustc_index::IndexVec;
22use rustc_macros::extension;
23pub use rustc_macros::{TypeFoldable, TypeVisitable};
24use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
25use rustc_middle::mir::ConstraintCategory;
26use rustc_middle::traits::select;
27use rustc_middle::traits::solve::Goal;
28use rustc_middle::ty::error::{ExpectedFound, TypeError};
29use rustc_middle::ty::{
30self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
31GenericArgsRef, GenericParamDefKind, InferConst, OpaqueTypeKey, ProvisionalHiddenType,
32PseudoCanonicalInput, Term, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable,
33TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
34};
35use rustc_span::{DUMMY_SP, Span, Symbol, bug};
36use rustc_type_ir::{CanonicalizerState, MayBeErased};
37use snapshot::undo_log::InferCtxtUndoLogs;
38use tracing::{debug, instrument};
39use ty::solve::TyOrConstInferVar;
40use type_variable::TypeVariableOrigin;
4142use crate::infer::snapshot::undo_log::UndoLog;
43use crate::infer::type_variable::{FloatVariableOrigin, TypeVariableValue};
44use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
45use crate::traits::{
46self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
47TraitEngine,
48};
4950pub mod at;
51pub mod canonical;
52mod context;
53mod free_regions;
54mod freshen;
55mod lexical_region_resolve;
56mod opaque_types;
57pub mod outlives;
58mod projection;
59pub mod region_constraints;
60pub mod relate;
61pub mod resolve;
62pub(crate) mod snapshot;
63mod solver_region_constraints;
64mod type_variable;
65mod unify_key;
6667pub use solver_region_constraints::SolverRegionConstraint;
68use solver_region_constraints::SolverRegionConstraintStorage;
6970/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
71/// around `PredicateObligations<'tcx>`, but it has one important property:
72/// because `InferOk` is marked with `#[must_use]`, if you have a method
73/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
74/// `infcx.f()?;` you'll get a warning about the obligations being discarded
75/// without use, which is probably unintentional and has been a source of bugs
76/// in the past.
77#[must_use]
78#[derive(#[automatically_derived]
impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug for InferOk<'tcx, T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "InferOk",
"value", &self.value, "obligations", &&self.obligations)
}
}Debug)]
79pub struct InferOk<'tcx, T> {
80pub value: T,
81pub obligations: PredicateObligations<'tcx>,
82}
83pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
8485pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
8687pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
88 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
89>;
9091/// This type contains all the things within [`InferCtxt`] that sit within a
92/// [`RefCell`] and are involved with taking/rolling back snapshots. Snapshot
93/// operations are hot enough that we want only one call to
94/// [`RefCell::borrow_mut`] per call to [`InferCtxt::start_snapshot`] and
95/// [`InferCtxt::rollback_to`].
96#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for InferCtxtInner<'tcx> {
#[inline]
fn clone(&self) -> InferCtxtInner<'tcx> {
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),
solver_region_constraint_storage: ::core::clone::Clone::clone(&self.solver_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)]
97pub struct InferCtxtInner<'tcx> {
98 undo_log: InferCtxtUndoLogs<'tcx>,
99100/// Cache for projections.
101 ///
102 /// This cache is snapshotted along with the infcx.
103projection_cache: traits::ProjectionCacheStorage<'tcx>,
104105/// Primary map of inference variables to the types that they currently
106 /// represent.
107 ///
108 /// We instantiate [`UnificationTable`] with `bounds<Ty>` because the types
109 /// that might instantiate a general type variable have an order,
110 /// represented by its upper and lower bounds.
111type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
112113/// Map from const parameter variable to the kind of const it represents.
114const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
115116/// Map from integral variable to the kind of integer it represents.
117int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
118119/// Map from floating variable to the kind of float it represents.
120float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
121122/// Map from floating variable to the origin span it came from, and the HirId that should be
123 /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
124 /// so can be removed once the `f32` fallback is removed.
125float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
126127/// Tracks the set of region variables and the constraints between them.
128 ///
129 /// This is initially `Some(_)` but when
130 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
131 /// -- further attempts to perform unification, etc., may fail if new
132 /// region constraints would've been added.
133region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
134135/// Used by the next solver when `-Zassumptions-on-binders` is set.
136solver_region_constraint_storage: SolverRegionConstraintStorage<'tcx>,
137138/// A set of constraints that regionck must validate.
139 ///
140 /// Each constraint has the form `T:'a`, meaning "some type `T` must
141 /// outlive the lifetime 'a". These constraints derive from
142 /// instantiated type parameters. So if you had a struct defined
143 /// like the following:
144 /// ```ignore (illustrative)
145 /// struct Foo<T: 'static> { ... }
146 /// ```
147 /// In some expression `let x = Foo { ... }`, it will
148 /// instantiate the type parameter `T` with a fresh type `$0`. At
149 /// the same time, it will record a region obligation of
150 /// `$0: 'static`. This will get checked later by regionck. (We
151 /// can't generally check these things right away because we have
152 /// to wait until types are resolved.)
153region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
154155/// The outlives bounds that we assume must hold about placeholders that
156 /// come from instantiating the binder of coroutine-witnesses. These bounds
157 /// are deduced from the well-formedness of the witness's types, and are
158 /// necessary because of the way we anonymize the regions in a coroutine,
159 /// which may cause types to no longer be considered well-formed.
160region_assumptions: Vec<ty::ArgOutlivesClause<'tcx>>,
161162/// `-Znext-solver`: Successfully proven goals during HIR typeck which
163 /// reference inference variables and get reproven in case MIR type check
164 /// fails to prove something.
165 ///
166 /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
167hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
168169/// Caches for opaque type inference.
170opaque_type_storage: OpaqueTypeStorage<'tcx>,
171}
172173impl<'tcx> InferCtxtInner<'tcx> {
174fn new() -> InferCtxtInner<'tcx> {
175InferCtxtInner {
176 undo_log: InferCtxtUndoLogs::default(),
177178 projection_cache: Default::default(),
179 type_variable_storage: Default::default(),
180 const_unification_storage: Default::default(),
181 int_unification_storage: Default::default(),
182 float_unification_storage: Default::default(),
183 float_origin_origin_storage: Default::default(),
184 region_constraint_storage: Some(Default::default()),
185 solver_region_constraint_storage: SolverRegionConstraintStorage::new(),
186 region_obligations: Default::default(),
187 region_assumptions: Default::default(),
188 hir_typeck_potentially_region_dependent_goals: Default::default(),
189 opaque_type_storage: Default::default(),
190 }
191 }
192193#[inline]
194pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
195&self.region_obligations
196 }
197198#[inline]
199pub fn region_assumptions(&self) -> &[ty::ArgOutlivesClause<'tcx>] {
200&self.region_assumptions
201 }
202203#[inline]
204pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
205self.projection_cache.with_log(&mut self.undo_log)
206 }
207208#[inline]
209fn try_type_variables_probe_ref(&self, vid: ty::TyVid) -> Option<&TypeVariableValue<'tcx>> {
210// Uses a read-only view of the unification table, this way we don't
211 // need an undo log.
212self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
213 }
214215#[inline]
216fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
217self.type_variable_storage.with_log(&mut self.undo_log)
218 }
219220#[inline]
221pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
222self.opaque_type_storage.with_log(&mut self.undo_log)
223 }
224225#[inline]
226fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
227self.int_unification_storage.with_log(&mut self.undo_log)
228 }
229230#[inline]
231fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
232self.float_unification_storage.with_log(&mut self.undo_log)
233 }
234235#[inline]
236fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
237self.const_unification_storage.with_log(&mut self.undo_log)
238 }
239240#[inline]
241pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
242self.region_constraint_storage
243 .as_mut()
244 .expect("region constraints already solved")
245 .with_log(&mut self.undo_log)
246 }
247}
248249pub struct InferCtxt<'tcx> {
250pub tcx: TyCtxt<'tcx>,
251252/// The mode of this inference context, see the struct documentation
253 /// for more details.
254typing_mode: TypingMode<'tcx>,
255256/// Whether this inference context should care about region obligations in
257 /// the root universe. Most notably, this is used during HIR typeck as region
258 /// solving is left to borrowck instead.
259 ///
260 /// This is used in the old solver to enable the generation of regions constraints.
261 /// In the new solver its only used inside the InferCtxt's `Drop` implementation:
262 /// if we're considering regions, and new opaques are registered, we panic.
263pub considering_regions: bool,
264/// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
265 /// need to make sure we don't rely on region identity in the trait solver or when
266 /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
267 /// free region with a unique inference variable. If HIR typeck ends up depending on two
268 /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
269 /// resulting in an ICE.
270 ///
271 /// The trait solver sometimes depends on regions being identical. As a concrete example
272 /// the trait solver ignores other candidates if one candidate exists without any constraints.
273 /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
274 /// occurrence of `'a` with a unique region the goal now equates these regions. See
275 /// the tests in trait-system-refactor-initiative#27 for concrete examples.
276 ///
277 /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
278 /// This is still insufficient as inference variables may *hide* region variables, so e.g.
279 /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
280 /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
281 /// stash all successfully proven goals which reference inference variables and then reprove
282 /// them after writeback.
283pub in_hir_typeck: bool,
284285/// If set, this flag causes us to skip the 'leak check' during
286 /// higher-ranked subtyping operations. This flag is a temporary one used
287 /// to manage the removal of the leak-check: for the time being, we still run the
288 /// leak-check, but we issue warnings.
289skip_leak_check: bool,
290291pub inner: RefCell<InferCtxtInner<'tcx>>,
292293/// Once region inference is done, the values for each variable.
294lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
295296/// Caches the results of trait selection. This cache is used
297 /// for things that depends on inference variables or placeholders.
298pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
299300/// Caches the results of trait evaluation. This cache is used
301 /// for things that depends on inference variables or placeholders.
302pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
303304/// The set of predicates on which errors have been reported, to
305 /// avoid reporting the same error twice.
306pub reported_trait_errors:
307RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
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<
339 ty::UniverseIndex,
340Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
341 >,
342 >,
343344 next_trait_solver: bool,
345346/// We have a `recursion_depth_exceeding_limit` FCW to mitigate breakages
347 /// caused by enabling the next solver globally. But the next solver is
348 /// already used by default in some places so we know they won't have
349 /// additional breakages. We also don't want spurious result in coherence
350 /// checking so we disable the FCW there as well.
351enable_next_solver_overflow_fcw: Cell<bool>,
352353pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
354355/// State reused by each new canonicalizer, and then cleared (but not deallocated) once the
356 /// canonicalizer is finished. A performance win, because it avoids reallocating new
357 /// vecs/hashmaps for every canonicalizer.
358pub canonicalizer_state: RefCell<CanonicalizerState<TyCtxt<'tcx>>>,
359}
360361impl<'tcx> Dropfor InferCtxt<'tcx> {
362fn drop(&mut self) {
363let mut inner = self.inner.borrow_mut();
364let opaque_type_storage = &mut inner.opaque_type_storage;
365366// No need for the drop bomb when we're in `TypingMode::PostTypeckUntilBorrowck`, and the `InferCtxt`
367 // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
368 // in relation to regions. In some places *after* typeck that aren't borrowck, we use
369 // `TypingMode::PostTypeckUntilBorrowck` to prevent defining opaque types and we simply don't care about regions.
370match self.typing_mode_raw() {
371TypingMode::Coherence372 | TypingMode::Typeck { .. }
373 | TypingMode::PostBorrowck { .. }
374 | TypingMode::Reflection375 | TypingMode::PostAnalysis376 | TypingMode::Codegen => {}
377// In erased mode, the opaque type storage is always empty
378TypingMode::ErasedNotCoherence(..) => {}
379TypingMode::PostTypeckUntilBorrowck { .. } => {
380if !self.considering_regions {
381return;
382 }
383 }
384 }
385386if !opaque_type_storage.is_empty() {
387 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:?}")));
388 }
389 }
390}
391392/// See the `error_reporting` module for more details.
393#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for ValuePairs<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ValuePairs<'tcx> {
#[inline]
fn clone(&self) -> ValuePairs<'tcx> {
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::Region<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::Term<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::AliasTerm<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::TraitRef<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::PolyFnSig<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>>;
let _:
::core::clone::AssertParamIsClone<ExpectedFound<ty::PolyExistentialProjection<'tcx>>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ValuePairs<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ValuePairs<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ValuePairs::Regions(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Regions", &__self_0),
ValuePairs::Terms(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Terms",
&__self_0),
ValuePairs::Aliases(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Aliases", &__self_0),
ValuePairs::TraitRefs(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TraitRefs", &__self_0),
ValuePairs::PolySigs(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"PolySigs", &__self_0),
ValuePairs::ExistentialTraitRef(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ExistentialTraitRef", &__self_0),
ValuePairs::ExistentialProjection(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ExistentialProjection", &__self_0),
}
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for ValuePairs<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for ValuePairs<'tcx> {
#[inline]
fn eq(&self, other: &ValuePairs<'tcx>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ValuePairs::Regions(__self_0), ValuePairs::Regions(__arg1_0))
=> __self_0 == __arg1_0,
(ValuePairs::Terms(__self_0), ValuePairs::Terms(__arg1_0)) =>
__self_0 == __arg1_0,
(ValuePairs::Aliases(__self_0), ValuePairs::Aliases(__arg1_0))
=> __self_0 == __arg1_0,
(ValuePairs::TraitRefs(__self_0),
ValuePairs::TraitRefs(__arg1_0)) => __self_0 == __arg1_0,
(ValuePairs::PolySigs(__self_0),
ValuePairs::PolySigs(__arg1_0)) => __self_0 == __arg1_0,
(ValuePairs::ExistentialTraitRef(__self_0),
ValuePairs::ExistentialTraitRef(__arg1_0)) =>
__self_0 == __arg1_0,
(ValuePairs::ExistentialProjection(__self_0),
ValuePairs::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)]
394pub enum ValuePairs<'tcx> {
395 Regions(ExpectedFound<ty::Region<'tcx>>),
396 Terms(ExpectedFound<ty::Term<'tcx>>),
397 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
398 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
399 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
400 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
401 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
402}
403404impl<'tcx> ValuePairs<'tcx> {
405pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
406if let ValuePairs::Terms(ExpectedFound { expected, found }) = self407 && let Some(expected) = expected.as_type()
408 && let Some(found) = found.as_type()
409 {
410Some((expected, found))
411 } else {
412None413 }
414 }
415}
416417/// The trace designates the path through inference that we took to
418/// encounter an error or subtyping constraint.
419///
420/// See the `error_reporting` module for more details.
421#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeTrace<'tcx> {
#[inline]
fn clone(&self) -> TypeTrace<'tcx> {
TypeTrace {
cause: ::core::clone::Clone::clone(&self.cause),
values: ::core::clone::Clone::clone(&self.values),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypeTrace<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "TypeTrace",
"cause", &self.cause, "values", &&self.values)
}
}Debug)]
422pub struct TypeTrace<'tcx> {
423pub cause: ObligationCause<'tcx>,
424pub values: ValuePairs<'tcx>,
425}
426427/// The origin of a `r1 <= r2` constraint.
428///
429/// See `error_reporting` module for more details
430#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for SubregionOrigin<'tcx> {
#[inline]
fn clone(&self) -> SubregionOrigin<'tcx> {
match self {
SubregionOrigin::Subtype(__self_0) =>
SubregionOrigin::Subtype(::core::clone::Clone::clone(__self_0)),
SubregionOrigin::RelateObjectBound(__self_0) =>
SubregionOrigin::RelateObjectBound(::core::clone::Clone::clone(__self_0)),
SubregionOrigin::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)),
SubregionOrigin::RelateRegionParamBound(__self_0, __self_1) =>
SubregionOrigin::RelateRegionParamBound(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
SubregionOrigin::Reborrow(__self_0) =>
SubregionOrigin::Reborrow(::core::clone::Clone::clone(__self_0)),
SubregionOrigin::ReferenceOutlivesReferent(__self_0, __self_1) =>
SubregionOrigin::ReferenceOutlivesReferent(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
SubregionOrigin::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),
},
SubregionOrigin::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),
},
SubregionOrigin::AscribeUserTypeProvePredicate(__self_0) =>
SubregionOrigin::AscribeUserTypeProvePredicate(::core::clone::Clone::clone(__self_0)),
SubregionOrigin::SolverRegionConstraint(__self_0) =>
SubregionOrigin::SolverRegionConstraint(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for SubregionOrigin<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
SubregionOrigin::Subtype(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Subtype", &__self_0),
SubregionOrigin::RelateObjectBound(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"RelateObjectBound", &__self_0),
SubregionOrigin::RelateParamBound(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"RelateParamBound", __self_0, __self_1, &__self_2),
SubregionOrigin::RelateRegionParamBound(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"RelateRegionParamBound", __self_0, &__self_1),
SubregionOrigin::Reborrow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Reborrow", &__self_0),
SubregionOrigin::ReferenceOutlivesReferent(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ReferenceOutlivesReferent", __self_0, &__self_1),
SubregionOrigin::CompareImplItemObligation {
span: __self_0,
impl_item_def_id: __self_1,
trait_item_def_id: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"CompareImplItemObligation", "span", __self_0,
"impl_item_def_id", __self_1, "trait_item_def_id",
&__self_2),
SubregionOrigin::CheckAssociatedTypeBounds {
parent: __self_0,
impl_item_def_id: __self_1,
trait_item_def_id: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"CheckAssociatedTypeBounds", "parent", __self_0,
"impl_item_def_id", __self_1, "trait_item_def_id",
&__self_2),
SubregionOrigin::AscribeUserTypeProvePredicate(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AscribeUserTypeProvePredicate", &__self_0),
SubregionOrigin::SolverRegionConstraint(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SolverRegionConstraint", &__self_0),
}
}
}Debug)]
431pub enum SubregionOrigin<'tcx> {
432/// Arose from a subtyping relation
433Subtype(Box<TypeTrace<'tcx>>),
434435/// When casting `&'a T` to an `&'b Trait` object,
436 /// relating `'a` to `'b`.
437RelateObjectBound(Span),
438439/// Some type parameter was instantiated with the given type,
440 /// and that type must outlive some region.
441RelateParamBound(Span, Ty<'tcx>, Option<Span>),
442443/// The given region parameter was instantiated with a region
444 /// that must outlive some other region.
445RelateRegionParamBound(Span, Option<Ty<'tcx>>),
446447/// Creating a pointer `b` to contents of another reference.
448Reborrow(Span),
449450/// (&'a &'b T) where a >= b
451ReferenceOutlivesReferent(Ty<'tcx>, Span),
452453/// Comparing the signature and requirements of an impl method against
454 /// the containing trait.
455CompareImplItemObligation {
456 span: Span,
457 impl_item_def_id: LocalDefId,
458 trait_item_def_id: DefId,
459 },
460461/// Checking that the bounds of a trait's associated type hold for a given impl.
462CheckAssociatedTypeBounds {
463 parent: Box<SubregionOrigin<'tcx>>,
464 impl_item_def_id: LocalDefId,
465 trait_item_def_id: DefId,
466 },
467468 AscribeUserTypeProvePredicate(Span),
469470// FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
471 // proper diagnostics for solver region constraints.
472SolverRegionConstraint(Span),
473}
474475// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
476#[cfg(target_pointer_width = "64")]
477const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
478479impl<'tcx> SubregionOrigin<'tcx> {
480pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
481match self {
482Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
483Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
484Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
485_ => ConstraintCategory::BoringNoLocation,
486 }
487 }
488}
489490/// Times when we replace bound regions with existentials:
491#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BoundRegionConversionTime { }
#[automatically_derived]
impl ::core::clone::Clone for BoundRegionConversionTime {
#[inline]
fn clone(&self) -> BoundRegionConversionTime {
let _: ::core::clone::AssertParamIsClone<DefId>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BoundRegionConversionTime { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for BoundRegionConversionTime {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
BoundRegionConversionTime::FnCall =>
::core::fmt::Formatter::write_str(f, "FnCall"),
BoundRegionConversionTime::HigherRankedType =>
::core::fmt::Formatter::write_str(f, "HigherRankedType"),
BoundRegionConversionTime::AssocTypeProjection(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AssocTypeProjection", &__self_0),
}
}
}Debug)]
492pub enum BoundRegionConversionTime {
493/// when a fn is called
494FnCall,
495496/// when two higher-ranked types are compared
497HigherRankedType,
498499/// when projecting an associated type
500AssocTypeProjection(DefId),
501}
502503/// Reasons to create a region inference variable.
504///
505/// See `error_reporting` module for more details.
506#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for RegionVariableOrigin<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for RegionVariableOrigin<'tcx> {
}
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for RegionVariableOrigin<'tcx> {
#[inline]
fn clone(&self) -> RegionVariableOrigin<'tcx> {
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<Symbol>;
let _: ::core::clone::AssertParamIsClone<ty::BoundRegionKind<'tcx>>;
let _: ::core::clone::AssertParamIsClone<BoundRegionConversionTime>;
let _: ::core::clone::AssertParamIsClone<ty::UpvarId>;
let _:
::core::clone::AssertParamIsClone<NllRegionVariableOrigin<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for RegionVariableOrigin<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
RegionVariableOrigin::Misc(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Misc",
&__self_0),
RegionVariableOrigin::PatternRegion(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"PatternRegion", &__self_0),
RegionVariableOrigin::BorrowRegion(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"BorrowRegion", &__self_0),
RegionVariableOrigin::Autoref(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Autoref", &__self_0),
RegionVariableOrigin::Coercion(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Coercion", &__self_0),
RegionVariableOrigin::RegionParameterDefinition(__self_0,
__self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"RegionParameterDefinition", __self_0, &__self_1),
RegionVariableOrigin::BoundRegion(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"BoundRegion", __self_0, __self_1, &__self_2),
RegionVariableOrigin::UpvarRegion(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"UpvarRegion", __self_0, &__self_1),
RegionVariableOrigin::Nll(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Nll",
&__self_0),
}
}
}Debug)]
507pub enum RegionVariableOrigin<'tcx> {
508/// Region variables created for ill-categorized reasons.
509 ///
510 /// They mostly indicate places in need of refactoring.
511Misc(Span),
512513/// Regions created by a `&P` or `[...]` pattern.
514PatternRegion(Span),
515516/// Regions created by `&` operator.
517BorrowRegion(Span),
518519/// Regions created as part of an autoref of a method receiver.
520Autoref(Span),
521522/// Regions created as part of an automatic coercion.
523Coercion(Span),
524525/// Region variables created as the values for early-bound regions.
526 ///
527 /// FIXME(@lcnr): This should also store a `DefId`, similar to
528 /// `TypeVariableOrigin`.
529RegionParameterDefinition(Span, Symbol),
530531/// Region variables created when instantiating a binder with
532 /// existential variables, e.g. when calling a function or method.
533BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
534535 UpvarRegion(ty::UpvarId, Span),
536537/// This origin is used for the inference variables that we create
538 /// during NLL region processing.
539Nll(NllRegionVariableOrigin<'tcx>),
540}
541542#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for NllRegionVariableOrigin<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for
NllRegionVariableOrigin<'tcx> {
}
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for NllRegionVariableOrigin<'tcx> {
#[inline]
fn clone(&self) -> NllRegionVariableOrigin<'tcx> {
let _: ::core::clone::AssertParamIsClone<ty::PlaceholderRegion<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Option<Symbol>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for NllRegionVariableOrigin<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
NllRegionVariableOrigin::FreeRegion =>
::core::fmt::Formatter::write_str(f, "FreeRegion"),
NllRegionVariableOrigin::Placeholder(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Placeholder", &__self_0),
NllRegionVariableOrigin::Existential { name: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Existential", "name", &__self_0),
}
}
}Debug)]
543pub enum NllRegionVariableOrigin<'tcx> {
544/// During NLL region processing, we create variables for free
545 /// regions that we encounter in the function signature and
546 /// elsewhere. This origin indices we've got one of those.
547FreeRegion,
548549/// "Universal" instantiation of a higher-ranked region (e.g.,
550 /// from a `for<'a> T` binder). Meant to represent "any region".
551Placeholder(ty::PlaceholderRegion<'tcx>),
552553 Existential {
554 name: Option<Symbol>,
555 },
556}
557558#[derive(#[automatically_derived]
impl ::core::marker::Copy for FixupError { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for FixupError { }
#[automatically_derived]
impl ::core::clone::Clone for FixupError {
#[inline]
fn clone(&self) -> FixupError {
let _: ::core::clone::AssertParamIsClone<TyOrConstInferVar>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for FixupError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "FixupError",
"unresolved", &&self.unresolved)
}
}Debug)]
559pub struct FixupError {
560 unresolved: TyOrConstInferVar,
561}
562563impl fmt::Displayfor FixupError {
564fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
565match self.unresolved {
566 TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
567f,
568"cannot determine the type of this integer; \
569 add a suffix to specify the type explicitly"
570),
571 TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
572f,
573"cannot determine the type of this number; \
574 add a suffix to specify the type explicitly"
575),
576 TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
577 TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
578 }
579 }
580}
581582/// See the `region_obligations` field for more information.
583#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeOutlivesConstraint<'tcx> {
#[inline]
fn clone(&self) -> TypeOutlivesConstraint<'tcx> {
TypeOutlivesConstraint {
sub_region: ::core::clone::Clone::clone(&self.sub_region),
sup_type: ::core::clone::Clone::clone(&self.sup_type),
origin: ::core::clone::Clone::clone(&self.origin),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypeOutlivesConstraint<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"TypeOutlivesConstraint", "sub_region", &self.sub_region,
"sup_type", &self.sup_type, "origin", &&self.origin)
}
}Debug)]
584pub struct TypeOutlivesConstraint<'tcx> {
585pub sub_region: ty::Region<'tcx>,
586pub sup_type: Ty<'tcx>,
587pub origin: SubregionOrigin<'tcx>,
588}
589590/// Used to configure inference contexts before their creation.
591pub struct InferCtxtBuilder<'tcx> {
592 tcx: TyCtxt<'tcx>,
593 considering_regions: bool,
594 in_hir_typeck: bool,
595 skip_leak_check: bool,
596/// Whether we should use the new trait solver in the local inference context,
597 /// which affects things like which solver is used in `predicate_may_hold`.
598next_trait_solver: bool,
599 enable_next_solver_overflow_fcw: bool,
600}
601602pub 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>)]603impl<'tcx> TyCtxt<'tcx> {
604fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
605InferCtxtBuilder {
606 tcx: self,
607 considering_regions: true,
608 in_hir_typeck: false,
609 skip_leak_check: false,
610 next_trait_solver: self.next_trait_solver_globally(),
611 enable_next_solver_overflow_fcw: true,
612 }
613 }
614}
615616impl<'tcx> InferCtxtBuilder<'tcx> {
617pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
618self.next_trait_solver = next_trait_solver;
619self620 }
621622pub fn enable_next_solver_overflow_fcw(
623mut self,
624 enable_next_solver_overflow_fcw: bool,
625 ) -> Self {
626self.enable_next_solver_overflow_fcw = enable_next_solver_overflow_fcw;
627self628 }
629630pub fn ignoring_regions(mut self) -> Self {
631self.considering_regions = false;
632self633 }
634635pub fn in_hir_typeck(mut self) -> Self {
636self.in_hir_typeck = true;
637self638 }
639640pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
641self.skip_leak_check = skip_leak_check;
642self643 }
644645/// Given a canonical value `C` as a starting point, create an
646 /// inference context that contains each of the bound values
647 /// within instantiated as a fresh variable. The `f` closure is
648 /// invoked with the new infcx, along with the instantiated value
649 /// `V` and a instantiation `S`. This instantiation `S` maps from
650 /// the bound values in `C` to their instantiated values in `V`
651 /// (in other words, `S(C) = V`).
652pub fn build_with_canonical<T>(
653mut self,
654 span: Span,
655 input: &CanonicalQueryInput<'tcx, T>,
656 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
657where
658T: TypeFoldable<TyCtxt<'tcx>>,
659 {
660let infcx = self.build(input.typing_mode.0);
661let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
662 (infcx, value, args)
663 }
664665pub fn build_with_typing_env(
666mut self,
667 typing_env: TypingEnv<'tcx>,
668 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
669 (self.build(typing_env.typing_mode()), typing_env.param_env)
670 }
671672pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
673let InferCtxtBuilder {
674 tcx,
675 considering_regions,
676 in_hir_typeck,
677 skip_leak_check,
678 next_trait_solver,
679 enable_next_solver_overflow_fcw,
680 } = *self;
681InferCtxt {
682tcx,
683typing_mode,
684considering_regions,
685in_hir_typeck,
686skip_leak_check,
687 inner: RefCell::new(InferCtxtInner::new()),
688 lexical_region_resolutions: RefCell::new(None),
689 selection_cache: Default::default(),
690 evaluation_cache: Default::default(),
691 reported_trait_errors: Default::default(),
692 reported_signature_mismatch: Default::default(),
693 tainted_by_errors: Cell::new(None),
694 universe: Cell::new(ty::UniverseIndex::ROOT),
695 placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
696next_trait_solver,
697 enable_next_solver_overflow_fcw: Cell::new(enable_next_solver_overflow_fcw),
698 obligation_inspector: Cell::new(None),
699 canonicalizer_state: Default::default(),
700 }
701 }
702}
703704impl<'tcx, T> InferOk<'tcx, T> {
705/// Extracts `value`, registering any obligations into `fulfill_cx`.
706pub fn into_value_registering_obligations<E: 'tcx>(
707self,
708 infcx: &InferCtxt<'tcx>,
709 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
710 ) -> T {
711let InferOk { value, obligations } = self;
712fulfill_cx.register_predicate_obligations(infcx, obligations);
713value714 }
715}
716717impl<'tcx> InferOk<'tcx, ()> {
718pub fn into_obligations(self) -> PredicateObligations<'tcx> {
719self.obligations
720 }
721}
722723impl<'tcx> InferCtxt<'tcx> {
724pub fn dcx(&self) -> DiagCtxtHandle<'_> {
725self.tcx.dcx().into_taintable(&self.tainted_by_errors)
726 }
727728pub fn next_trait_solver(&self) -> bool {
729self.next_trait_solver
730 }
731732/// This method is deliberately called `..._raw`,
733 /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
734 /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
735 /// more information.
736 ///
737 /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
738 /// works as a kind of store for for example type unification information.
739 /// `InferCtxt` is also often used outside the trait solver during typeck.
740 /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
741 /// To make sure these two uses are never confused, we want to statically encode this information.
742 ///
743 /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
744 /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
745 /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
746 /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
747 /// match on the variant and can safely ignore it.
748 ///
749 /// Prefer non-raw apis if available. e.g.,
750 /// - On the `FnCtxt`
751 /// - on the `SelectionCtxt`
752#[inline(always)]
753pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
754self.typing_mode
755 }
756757#[inline(always)]
758pub fn disable_trait_solver_fast_paths(&self) -> bool {
759self.tcx.disable_trait_solver_fast_paths()
760 }
761762/// Returns the origin of the type variable identified by `vid`.
763 ///
764 /// No attempt is made to resolve `vid` to its root variable.
765pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
766self.inner.borrow_mut().type_variables().var_origin(vid)
767 }
768769/// Returns the origin of the float type variable identified by `vid`.
770 ///
771 /// No attempt is made to resolve `vid` to its root variable.
772pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
773self.inner.borrow_mut().float_origin_origin_storage[vid]
774 }
775776/// Returns the origin of the const variable identified by `vid`
777// FIXME: We should store origins separately from the unification table
778 // so this doesn't need to be optional.
779pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
780match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
781 ConstVariableValue::Known { .. } => None,
782 ConstVariableValue::Unknown { origin, .. } => Some(origin),
783 }
784 }
785786pub fn unresolved_root_variables(&self) -> (Vec<TyVid>, Vec<ty::IntVid>, Vec<ty::FloatVid>) {
787let mut inner = self.inner.borrow_mut();
788789let ty = inner.type_variables().unresolved_root_variables();
790791let int = unresolved_root_variables_of(
792inner.int_unification_table(),
793 ty::IntVarValue::is_unknown,
794 );
795796let float = unresolved_root_variables_of(
797inner.float_unification_table(),
798 ty::FloatVarValue::is_unknown,
799 );
800801 (ty, int, float)
802 }
803804{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("sub_regions",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(804u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("vis")
}> =
::tracing::__macro_support::FieldName::new("vis");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin,
a, b, vis);
}
}
}#[instrument(skip(self), level = "debug")]805pub fn sub_regions(
806&self,
807 origin: SubregionOrigin<'tcx>,
808 a: ty::Region<'tcx>,
809 b: ty::Region<'tcx>,
810 vis: ty::VisibleForLeakCheck,
811 ) {
812self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
813 }
814815{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("equate_regions",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(815u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("vis")
}> =
::tracing::__macro_support::FieldName::new("vis");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin,
a, b, vis);
}
}
}#[instrument(skip(self), level = "debug")]816pub fn equate_regions(
817&self,
818 origin: SubregionOrigin<'tcx>,
819 a: ty::Region<'tcx>,
820 b: ty::Region<'tcx>,
821 vis: ty::VisibleForLeakCheck,
822 ) {
823self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
824 }
825826/// Processes a `Coerce` predicate from the fulfillment context.
827 /// This is NOT the preferred way to handle coercion, which is to
828 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
829 ///
830 /// This method here is actually a fallback that winds up being
831 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
832 /// and records a coercion predicate. Presently, this method is equivalent
833 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
834 /// actually requiring `a <: b`. This is of course a valid coercion,
835 /// but it's not as flexible as `FnCtxt::coerce` would be.
836 ///
837 /// (We may refactor this in the future, but there are a number of
838 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
839 /// records adjustments that are required on the HIR in order to perform
840 /// the coercion, and we don't currently have a way to manage that.)
841pub fn coerce_predicate(
842&self,
843 cause: &ObligationCause<'tcx>,
844 param_env: ty::ParamEnv<'tcx>,
845 predicate: ty::PolyCoercePredicate<'tcx>,
846 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
847let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
848 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
849a: p.a,
850 b: p.b,
851 });
852self.subtype_predicate(cause, param_env, subtype_predicate)
853 }
854855pub fn subtype_predicate(
856&self,
857 cause: &ObligationCause<'tcx>,
858 param_env: ty::ParamEnv<'tcx>,
859 predicate: ty::PolySubtypePredicate<'tcx>,
860 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
861// Check for two unresolved inference variables, in which case we can
862 // make no progress. This is partly a micro-optimization, but it's
863 // also an opportunity to "sub-unify" the variables. This isn't
864 // *necessary* to prevent cycles, because they would eventually be sub-unified
865 // anyhow during generalization, but it helps with diagnostics (we can detect
866 // earlier that they are sub-unified).
867 //
868 // Note that we can just skip the binders here because
869 // type variables can't (at present, at
870 // least) capture any of the things bound by this binder.
871 //
872 // Note that this sub here is not just for diagnostics - it has semantic
873 // effects as well.
874let r_a = self.shallow_resolve(predicate.skip_binder().a);
875let r_b = self.shallow_resolve(predicate.skip_binder().b);
876match (r_a.kind(), r_b.kind()) {
877 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
878self.sub_unify_ty_vids_raw(a_vid, b_vid);
879return Err((a_vid, b_vid));
880 }
881_ => {}
882 }
883884self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
885if a_is_expected {
886Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
887 } else {
888Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
889 }
890 })
891 }
892893/// Number of type variables created so far.
894pub fn num_ty_vars(&self) -> usize {
895self.inner.borrow_mut().type_variables().num_vars()
896 }
897898pub fn next_ty_vid(&self, span: Span) -> TyVid {
899self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
900 }
901902pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
903self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
904 }
905906pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
907let origin = TypeVariableOrigin { span, param_def_id: None };
908self.inner.borrow_mut().type_variables().new_var(universe, origin)
909 }
910911pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
912self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
913 }
914915pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
916let vid = self.next_ty_vid_with_origin(origin);
917Ty::new_var(self.tcx, vid)
918 }
919920pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
921let vid = self.next_ty_vid_in_universe(span, universe);
922Ty::new_var(self.tcx, vid)
923 }
924925pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
926self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
927 }
928929pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
930let vid = self931 .inner
932 .borrow_mut()
933 .const_unification_table()
934 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
935 .vid;
936 ty::Const::new_var(self.tcx, vid)
937 }
938939pub fn next_const_var_in_universe(
940&self,
941 span: Span,
942 universe: ty::UniverseIndex,
943 ) -> ty::Const<'tcx> {
944let origin = ConstVariableOrigin { span, param_def_id: None };
945let vid = self946 .inner
947 .borrow_mut()
948 .const_unification_table()
949 .new_key(ConstVariableValue::Unknown { origin, universe })
950 .vid;
951 ty::Const::new_var(self.tcx, vid)
952 }
953954pub fn next_int_var(&self) -> Ty<'tcx> {
955let next_int_var_id =
956self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
957Ty::new_int_var(self.tcx, next_int_var_id)
958 }
959960pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
961let mut inner = self.inner.borrow_mut();
962let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
963let origin = FloatVariableOrigin { span, lint_id };
964let span_index = inner.float_origin_origin_storage.push(origin);
965if true {
{
match (&next_float_var_id, &span_index) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(next_float_var_id, span_index);
966Ty::new_float_var(self.tcx, next_float_var_id)
967 }
968969/// Creates a fresh region variable with the next available index.
970 /// The variable will be created in the maximum universe created
971 /// thus far, allowing it to name any region created thus far.
972pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
973self.next_region_var_in_universe(origin, self.universe())
974 }
975976/// Creates a fresh region variable with the next available index
977 /// in the given universe; typically, you can use
978 /// `next_region_var` and just use the maximal universe.
979pub fn next_region_var_in_universe(
980&self,
981 origin: RegionVariableOrigin<'tcx>,
982 universe: ty::UniverseIndex,
983 ) -> ty::Region<'tcx> {
984let region_var =
985self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
986 ty::Region::new_var(self.tcx, region_var)
987 }
988989pub fn next_term_var_of_alias_kind(
990&self,
991 alias_term: ty::AliasTerm<'tcx>,
992 span: Span,
993 ) -> ty::Term<'tcx> {
994match alias_term.kind {
995 ty::AliasTermKind::ProjectionTy { .. }
996 | ty::AliasTermKind::InherentTy { .. }
997 | ty::AliasTermKind::OpaqueTy { .. }
998 | ty::AliasTermKind::FreeTy { .. } => self.next_ty_var(span).into(),
999 ty::AliasTermKind::FreeConst { .. }
1000 | ty::AliasTermKind::InherentConstSelf { .. }
1001 | ty::AliasTermKind::InherentConstImpl { .. }
1002 | ty::AliasTermKind::AnonConst { .. }
1003 | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_var(span).into(),
1004 }
1005 }
10061007/// Return the universe that the region `r` was created in. For
1008 /// most regions (e.g., `'static`, named regions from the user,
1009 /// etc) this is the root universe U0. For inference variables or
1010 /// placeholders, however, it will return the universe which they
1011 /// are associated.
1012pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1013self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1014 }
10151016/// Number of region variables created so far.
1017pub fn num_region_vars(&self) -> usize {
1018self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1019 }
10201021/// Just a convenient wrapper of `next_region_var` for using during NLL.
1022{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("next_nll_region_var",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1022u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{ self.next_region_var(RegionVariableOrigin::Nll(origin)) }
}
}#[instrument(skip(self), level = "debug")]1023pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
1024self.next_region_var(RegionVariableOrigin::Nll(origin))
1025 }
10261027/// Just a convenient wrapper of `next_region_var` for using during NLL.
1028{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("next_nll_region_var_in_universe",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1028u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("universe")
}> =
::tracing::__macro_support::FieldName::new("universe");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&universe)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin),
universe)
}
}
}#[instrument(skip(self), level = "debug")]1029pub fn next_nll_region_var_in_universe(
1030&self,
1031 origin: NllRegionVariableOrigin<'tcx>,
1032 universe: ty::UniverseIndex,
1033 ) -> ty::Region<'tcx> {
1034self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1035 }
10361037pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1038match param.kind {
1039 GenericParamDefKind::Lifetime => {
1040// Create a region inference variable for the given
1041 // region parameter definition.
1042self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1043span, param.name,
1044 ))
1045 .into()
1046 }
1047 GenericParamDefKind::Type { .. } => {
1048// Create a type inference variable for the given
1049 // type parameter definition. The generic parameters are
1050 // for actual parameters that may be referred to by
1051 // the default of this type parameter, if it exists.
1052 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1053 // used in a path such as `Foo::<T, U>::new()` will
1054 // use an inference variable for `C` with `[T, U]`
1055 // as the generic parameters for the default, `(T, U)`.
1056let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1057self.universe(),
1058TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1059 );
10601061Ty::new_var(self.tcx, ty_var_id).into()
1062 }
1063 GenericParamDefKind::Const { .. } => {
1064let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1065let const_var_id = self1066 .inner
1067 .borrow_mut()
1068 .const_unification_table()
1069 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1070 .vid;
1071 ty::Const::new_var(self.tcx, const_var_id).into()
1072 }
1073 }
1074 }
10751076/// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1077 /// each type/region parameter to a fresh inference variable.
1078pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
1079GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1080 }
10811082/// Returns `true` if errors have been reported since this infcx was
1083 /// created. This is sometimes used as a heuristic to skip
1084 /// reporting errors that often occur as a result of earlier
1085 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1086 /// inference variables, regionck errors).
1087#[must_use = "this method does not have any side effects"]
1088pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1089self.tainted_by_errors.get()
1090 }
10911092/// Set the "tainted by errors" flag to true. We call this when we
1093 /// observe an error from a prior pass.
1094pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1095{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs:1095",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1095u32),
::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)");
1096self.tainted_by_errors.set(Some(e));
1097 }
10981099pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1100let mut inner = self.inner.borrow_mut();
1101let inner = &mut *inner;
1102inner.unwrap_region_constraints().var_origin(vid)
1103 }
11041105/// Clone the list of variable regions. This is used only during NLL processing
1106 /// to put the set of region variables into the NLL region context.
1107pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1108let inner = self.inner.borrow();
1109if !!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));
1110let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1111if !storage.data.is_empty() {
{ ::core::panicking::panic_fmt(format_args!("{0:#?}", storage.data)); }
};assert!(storage.data.is_empty(), "{:#?}", storage.data);
1112// We clone instead of taking because borrowck still wants to use the
1113 // inference context after calling this for diagnostics and the new
1114 // trait solver.
1115storage.var_infos.clone()
1116 }
11171118pub fn has_opaque_types_in_storage(&self) -> bool {
1119 !self.inner.borrow().opaque_type_storage.is_empty()
1120 }
11211122{}
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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1122u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs:1122",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1122u32),
::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)]1123pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1124self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1125 }
11261127{}
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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1127u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs:1127",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1127u32),
::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)]1128pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1129self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1130 }
11311132pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1133if !self.next_trait_solver() {
1134return false;
1135 }
11361137let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1138let inner = &mut *self.inner.borrow_mut();
1139let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1140inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1141if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1142let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1143if opaque_sub_vid == ty_sub_vid {
1144return true;
1145 }
1146 }
11471148false
1149})
1150 }
11511152/// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1153 ///
1154 /// This only checks for a subtype relation, it does not require equality.
1155pub fn opaques_with_sub_unified_hidden_type(
1156&self,
1157 ty_vid: TyVid,
1158 ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1159// Avoid accidentally allowing more code to compile with the old solver.
1160if !self.next_trait_solver() {
1161return ::alloc::vec::Vec::new()vec![];
1162 }
11631164let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1165let inner = &mut *self.inner.borrow_mut();
1166// This is iffy, can't call `type_variables()` as we're already
1167 // borrowing the `opaque_type_storage` here.
1168let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1169inner1170 .opaque_type_storage
1171 .iter_opaque_types()
1172 .filter_map(|(key, hidden_ty)| {
1173if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1174let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1175if opaque_sub_vid == ty_sub_vid {
1176return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1177self.tcx,
1178key.def_id.into(),
1179key.args,
1180 ));
1181 }
1182 }
11831184None1185 })
1186 .collect()
1187 }
11881189#[inline(always)]
1190pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1191if true {
if !!self.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.next_trait_solver()")
};
};debug_assert!(!self.next_trait_solver());
1192match self.typing_mode_raw().assert_not_erased() {
1193TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1194 | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types } => {
1195id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1196 }
1197// FIXME(#132279): This function is quite weird in post-analysis
1198 // and post-borrowck analysis mode. We may need to modify its uses
1199 // to support PostBorrowck in the old solver as well.
1200TypingMode::Coherence1201 | TypingMode::Reflection1202 | TypingMode::PostBorrowck { .. }
1203 | TypingMode::PostAnalysis1204 | TypingMode::Codegen => false,
1205 }
1206 }
12071208pub fn push_hir_typeck_potentially_region_dependent_goal(
1209&self,
1210 goal: PredicateObligation<'tcx>,
1211 ) {
1212let mut inner = self.inner.borrow_mut();
1213inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1214inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1215 }
12161217pub fn take_hir_typeck_potentially_region_dependent_goals(
1218&self,
1219 ) -> Vec<PredicateObligation<'tcx>> {
1220if !!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");
1221 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1222 }
12231224pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1225self.deeply_resolve_ignoring_regions(t).to_string()
1226 }
12271228/// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1229 /// universe index of `TyVar(vid)`.
1230pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1231use self::type_variable::TypeVariableValue;
12321233match self.inner.borrow_mut().type_variables().probe(vid) {
1234 TypeVariableValue::Known { value } => Ok(value),
1235 TypeVariableValue::Unknown { universe } => Err(universe),
1236 }
1237 }
12381239/// If `vid` resolves to a type, return that type. Otherwise return the root variable id for `vid`.
1240pub fn shallow_resolve_ty_var_or_get_root(&self, vid: TyVid) -> Result<Ty<'tcx>, TyVid> {
1241let (root, value) = self.inner.borrow_mut().type_variables().probe_with_root_vid(vid);
12421243match value {
1244 TypeVariableValue::Known { value } => Ok(value),
1245 TypeVariableValue::Unknown { universe: _ } => Err(root),
1246 }
1247 }
12481249/// Resolve a type variable. Resolving means the following:
1250 ///
1251 /// - If a `Ty` is a rigid type (like, an integer, or some ADT), do nothing.
1252 /// - If a `Ty` is a type infer variable, but has been equated with an actual type,
1253 /// return that type.
1254 /// - If a `Ty` is an int or float infer variable, and has been equated with an integer
1255 /// or floating point type, return that type.
1256 /// - If a `Ty` is any kind of infer variable that has been equated, but not yet with a rigid
1257 /// type, then this set of equated variables forms an equivalence class. One of the variables
1258 /// in that equivalent class is said to be the root variable, and resolving makes sure to
1259 /// consistently return this root variable. This is beneficial for caching.
1260 /// This behavior, of returning roots, changed in <https://github.com/rust-lang/rust/pull/158447>.
1261 ///
1262 /// Otherwise, resolving simply does nothing.
1263 ///
1264 /// The "shallow" part of the name refers to the fact that types may themselves contain more
1265 /// type variables. e.g. The field types of a struct. `shallow_resolve` does not recurse into
1266 /// these nested variables. If that's what you want, use [`deeply_resolve_ignoring_regions`](Self::deeply_resolve_ignoring_regions),
1267 /// or better [`deeply_resolve_via_unification_table`](rustc_type_ir::InferCtxtLike::deeply_resolve_via_unification_table), if you can, which *does* resolve regions.
1268pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1269if let ty::Infer(v) = *ty.kind() {
1270match v {
1271 ty::TyVar(v) => {
1272// Not entirely obvious: if `typ` is a type variable,
1273 // it can be resolved to an int/float variable, which
1274 // can then be recursively resolved, hence the
1275 // recursion. Note though that we prevent type
1276 // variables from unifying to other type variables
1277 // directly (though they may be embedded
1278 // structurally), and we prevent cycles in any case,
1279 // so this recursion should always be of very limited
1280 // depth.
1281 //
1282 // Note: if these two lines are combined into one we get
1283 // dynamic borrow errors on `self.inner`.
1284let (root_vid, value) =
1285self.inner.borrow_mut().type_variables().probe_with_root_vid(v);
1286value.known().map_or_else(
1287 || if root_vid == v { ty } else { Ty::new_var(self.tcx, root_vid) },
1288 |t| self.shallow_resolve(t),
1289 )
1290 }
12911292 ty::IntVar(v) => {
1293let (root, value) =
1294self.inner.borrow_mut().int_unification_table().inlined_probe_key_value(v);
1295match value {
1296 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1297 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1298 ty::IntVarValue::Unknown => {
1299if root == v {
1300ty1301 } else {
1302Ty::new_int_var(self.tcx, root)
1303 }
1304 }
1305 }
1306 }
13071308 ty::FloatVar(v) => {
1309let (root, value) = self1310 .inner
1311 .borrow_mut()
1312 .float_unification_table()
1313 .inlined_probe_key_value(v);
1314match value {
1315 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1316 ty::FloatVarValue::Unknown => {
1317if root == v {
1318ty1319 } else {
1320Ty::new_float_var(self.tcx, root)
1321 }
1322 }
1323 }
1324 }
13251326 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1327 }
1328 } else {
1329ty1330 }
1331 }
13321333/// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1334 /// It's the same, but for consts.
1335pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1336match ct.kind() {
1337 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1338 InferConst::Var(vid) => {
1339let (root, value) = self1340 .inner
1341 .borrow_mut()
1342 .const_unification_table()
1343 .inlined_probe_key_value(vid);
1344value.known().unwrap_or_else(|| {
1345if root.vid == vid { ct } else { ty::Const::new_var(self.tcx, root.vid) }
1346 })
1347 }
1348 InferConst::Fresh(_) => ct,
1349 },
13501351 ty::ConstKind::Param(_)
1352 | ty::ConstKind::Bound(_, _)
1353 | ty::ConstKind::Placeholder(_)
1354 | ty::ConstKind::Alias(_, _)
1355 | ty::ConstKind::Value(_)
1356 | ty::ConstKind::Error(_)
1357 | ty::ConstKind::Expr(_) => ct,
1358 }
1359 }
13601361/// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1362 /// It's the same, but for terms (types or consts).
1363pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1364match term.kind() {
1365 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1366 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1367 }
1368 }
13691370pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1371self.inner.borrow_mut().type_variables().root_var(var)
1372 }
13731374/// If `ty` is an unresolved type variable, returns its root vid.
1375pub fn root_vid(&self, ty: Ty<'tcx>) -> Option<ty::TyVid> {
1376let (root, value) =
1377self.inner.borrow_mut().type_variables().inlined_probe_with_vid(ty.ty_vid()?);
1378value.is_unknown().then_some(root)
1379 }
13801381pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1382self.inner.borrow_mut().type_variables().sub_unify(a, b);
1383 }
13841385pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1386self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1387 }
13881389pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1390self.inner.borrow_mut().float_unification_table().find(var)
1391 }
13921393pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1394self.inner.borrow_mut().const_unification_table().find(var).vid
1395 }
13961397/// Resolves a const var to a rigid const, if it was constrained to one,
1398 /// or else the root const var in the unification table.
1399pub fn shallow_resolve_const_var(&self, vid: ty::ConstVid) -> ty::Const<'tcx> {
1400match self.try_resolve_const_var(vid) {
1401Ok(ct) => ct,
1402Err(_) => ty::Const::new_var(self.tcx, self.root_const_var(vid)),
1403 }
1404 }
14051406/// Resolves a type var to a rigid type, if it was constrained to one,
1407 /// or else the root type var in the unification table.
1408pub fn shallow_resolve_ty_var(&self, vid: ty::TyVid) -> Ty<'tcx> {
1409match self.try_resolve_ty_var(vid) {
1410Ok(ty) => ty,
1411Err(_) => Ty::new_var(self.tcx, self.root_var(vid)),
1412 }
1413 }
14141415/// Resolves an int var to a rigid int type, if it was constrained to one,
1416 /// or else the root int var in the unification table.
1417pub fn shallow_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1418let mut inner = self.inner.borrow_mut();
1419let value = inner.int_unification_table().probe_value(vid);
1420match value {
1421 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1422 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1423 ty::IntVarValue::Unknown => {
1424Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1425 }
1426 }
1427 }
14281429/// Resolves a float var to a rigid type, if it was constrained to one,
1430 /// or else the root float var in the unification table.
1431pub fn shallow_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1432let mut inner = self.inner.borrow_mut();
1433let value = inner.float_unification_table().probe_value(vid);
1434match value {
1435 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1436 ty::FloatVarValue::Unknown => {
1437Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1438 }
1439 }
1440 }
14411442/// If a type/const variable has not (yet) been unified, it is left as is.
1443 ///
1444 /// This is an idempotent operation that does not affect inference state in any way,
1445 /// which means it's safe to call this function at will.
1446 ///
1447 /// Region variables are unaffected.
1448pub fn deeply_resolve_ignoring_regions<T>(&self, value: T) -> T
1449where
1450T: TypeFoldable<TyCtxt<'tcx>>,
1451 {
1452if let Err(guar) = value.error_reported() {
1453self.set_tainted_by_errors(guar);
1454 }
1455if !value.has_non_region_infer() {
1456return value;
1457 }
1458let mut r = resolve::DeepResolverIgnoringRegions::new(self);
1459value.fold_with(&mut r)
1460 }
14611462/// Where possible, replaces type/const/region variables in `value` with their final value.
1463 /// If a type/const/region variable has not (yet) been unified, it is left as is.
1464 ///
1465 /// This is an idempotent operation that does not affect inference state in any way,
1466 /// which means it's safe to call this function at will.
1467pub fn deeply_resolve_via_unification_table<T>(&self, value: T) -> T
1468where
1469T: TypeFoldable<TyCtxt<'tcx>>,
1470 {
1471use rustc_middle::ty::InferCtxtLike;
1472#[allow(rustc::usage_of_type_ir_traits)]
1473InferCtxtLike::deeply_resolve_via_unification_table(self, value)
1474 }
14751476pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1477where
1478T: TypeFoldable<TyCtxt<'tcx>>,
1479 {
1480if !value.has_infer() {
1481return value; // Avoid duplicated type-folding.
1482}
1483let mut r = InferenceLiteralEraser { tcx: self.tcx };
1484value.fold_with(&mut r)
1485 }
14861487pub fn try_resolve_const_var(
1488&self,
1489 vid: ty::ConstVid,
1490 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1491match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1492 ConstVariableValue::Known { value } => Ok(value),
1493 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1494 }
1495 }
14961497/// Attempts to resolve all type/region/const variables in
1498 /// `value`. Region inference must have been run already (e.g.,
1499 /// by calling `resolve_regions_and_report_errors`). If some
1500 /// variable was never unified, an `Err` results.
1501 ///
1502 /// This method is idempotent, but it not typically not invoked
1503 /// except during the writeback phase.
1504pub fn deeply_resolve_via_region_graph<T: TypeFoldable<TyCtxt<'tcx>>>(
1505&self,
1506 value: T,
1507 ) -> FixupResult<T> {
1508match resolve::deeply_resolve_via_region_graph(self, value) {
1509Ok(value) => {
1510if value.has_non_region_infer() {
1511bug_impl(None, format_args!("`{0:?}` is not fully resolved", value),
Location::caller());bug!("`{value:?}` is not fully resolved");
1512 }
1513if value.has_infer_regions() {
1514let 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"));
1515Ok(fold_regions(self.tcx, value, |re, _| {
1516if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1517 }))
1518 } else {
1519Ok(value)
1520 }
1521 }
1522Err(e) => Err(e),
1523 }
1524 }
15251526// Instantiates the bound variables in a given binder with fresh inference
1527 // variables in the current universe.
1528 //
1529 // Use this method if you'd like to find some generic parameters of the binder's
1530 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1531 // that corresponds to your use case, consider whether or not you should
1532 // use [`InferCtxt::enter_forall`] instead.
1533pub fn instantiate_binder_with_fresh_vars<T>(
1534&self,
1535 span: Span,
1536 lbrct: BoundRegionConversionTime,
1537 value: ty::Binder<'tcx, T>,
1538 ) -> T
1539where
1540T: TypeFoldable<TyCtxt<'tcx>>,
1541 {
1542if let Some(_) = value.as_ref().no_bound_vars() {
1543return value.skip_binder();
1544 }
15451546let bound_vars = value.bound_vars();
1547let mut args = Vec::with_capacity(bound_vars.len());
15481549for bound_var_kind in bound_vars {
1550let arg: ty::GenericArg<'_> = match bound_var_kind {
1551 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1552 ty::BoundVariableKind::Region(br) => {
1553self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1554 }
1555 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1556 };
1557 args.push(arg);
1558 }
15591560struct ToFreshVars<'tcx> {
1561 args: Vec<ty::GenericArg<'tcx>>,
1562 }
15631564impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1565fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1566self.args[br.var.index()].expect_region()
1567 }
1568fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1569self.args[bt.var.index()].expect_ty()
1570 }
1571fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1572self.args[bc.var.index()].expect_const()
1573 }
1574 }
1575let delegate = ToFreshVars { args };
1576self.tcx.replace_bound_vars_uncached(value, delegate)
1577 }
15781579pub fn insert_placeholder_assumptions(
1580&self,
1581 u: ty::UniverseIndex,
1582 assumptions: Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
1583 ) {
1584if let Some(assumptions) = &assumptions {
1585if !!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!(
1586 !assumptions.type_outlives.has_escaping_bound_vars(),
1587"assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1588 assumptions.type_outlives
1589 );
1590if !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!(
1591 assumptions.region_outlives.base_edges().all(|r| !r.has_escaping_bound_vars()),
1592"assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1593 assumptions.region_outlives
1594 );
1595 }
1596self.placeholder_assumptions_for_next_solver.borrow_mut().insert(u, assumptions);
1597 }
15981599pub fn get_placeholder_assumptions(
1600&self,
1601 u: ty::UniverseIndex,
1602 ) -> Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>> {
1603self.placeholder_assumptions_for_next_solver.borrow().get(&u).unwrap().as_ref().cloned()
1604 }
16051606pub fn get_solver_region_constraint(&self) -> SolverRegionConstraint<'tcx> {
1607self.inner.borrow().solver_region_constraint_storage.get_constraint()
1608 }
16091610pub fn overwrite_solver_region_constraint(&self, constraint: SolverRegionConstraint<'tcx>) {
1611if !!constraint.has_escaping_bound_vars() {
{
::core::panicking::panic_fmt(format_args!("solver region constraint has escaping bound vars, which is indicative of a bug in how constraints are handled: {0:?}",
constraint));
}
};assert!(
1612 !constraint.has_escaping_bound_vars(),
1613"solver region constraint has escaping bound vars, which is indicative of a bug in how constraints are handled: {constraint:?}",
1614 );
1615let mut inner = self.inner.borrow_mut();
1616let old_constraint = inner.solver_region_constraint_storage.get_constraint();
1617inner.undo_log.push(UndoLog::OverwriteSolverRegionConstraint { old_constraint });
1618inner.solver_region_constraint_storage.overwrite(constraint);
1619 }
16201621/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1622pub(crate) fn verify_generic_bound(
1623&self,
1624 origin: SubregionOrigin<'tcx>,
1625 kind: GenericKind<'tcx>,
1626 a: ty::Region<'tcx>,
1627 bound: VerifyBound<'tcx>,
1628 ) {
1629{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs:1629",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1629u32),
::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);
16301631self.inner
1632 .borrow_mut()
1633 .unwrap_region_constraints()
1634 .verify_generic_bound(origin, kind, a, bound);
1635 }
16361637/// Obtains the latest type of the given closure; this may be a
1638 /// closure in the current function, in which case its
1639 /// `ClosureKind` may not yet be known.
1640pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1641let unresolved_kind_ty = match *closure_ty.kind() {
1642 ty::Closure(_, args) => args.as_closure().kind_ty(),
1643 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1644_ => bug_impl(None, format_args!("unexpected type {0}", closure_ty),
Location::caller())bug!("unexpected type {closure_ty}"),
1645 };
1646let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1647closure_kind_ty.to_opt_closure_kind()
1648 }
16491650pub fn universe(&self) -> ty::UniverseIndex {
1651self.universe.get()
1652 }
16531654/// Creates and return a fresh universe that extends all previous
1655 /// universes. Updates `self.universe` to that new universe.
1656pub fn create_next_universe(&self) -> ty::UniverseIndex {
1657let u = self.universe.get().next_universe();
1658{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs:1658",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1658u32),
::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:?}");
1659self.universe.set(u);
1660u1661 }
16621663/// We need to disable the fcw if we're already in a fcw emitting to avoid
1664 /// indefinite triggering.
1665pub fn with_disabled_next_solver_overflow_fcw<F, R>(&self, mut f: F) -> R
1666where
1667F: FnMut() -> R,
1668 {
1669let prev = self.enable_next_solver_overflow_fcw.replace(false);
1670let ret = f();
1671self.enable_next_solver_overflow_fcw.set(prev);
1672ret1673 }
16741675/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1676 /// which contains the necessary information to use the trait system without
1677 /// using canonicalization or carrying this inference context around.
1678pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1679let typing_mode = match self.typing_mode_raw() {
1680// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1681 // to handle them without proper canonicalization. This means we may cause cycle
1682 // errors and fail to reveal opaques while inside of bodies. We should rename this
1683 // function and require explicit comments on all use-sites in the future.
1684ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1685 | ty::TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ } => {
1686TypingMode::non_body_analysis()
1687 }
1688 mode @ (ty::TypingMode::Coherence1689 | ty::TypingMode::PostBorrowck { .. }
1690 | ty::TypingMode::PostAnalysis1691 | ty::TypingMode::Reflection1692 | ty::TypingMode::Codegen) => mode,
1693 ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1694 };
1695 ty::TypingEnv::new(param_env, typing_mode)
1696 }
16971698/// Similar to [`Self::canonicalize_query`], except that it returns
1699 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1700 /// `param_env` to not contain any inference variables or placeholders.
1701pub fn pseudo_canonicalize_query<V>(
1702&self,
1703 param_env: ty::ParamEnv<'tcx>,
1704 value: V,
1705 ) -> PseudoCanonicalInput<'tcx, V>
1706where
1707V: TypeVisitable<TyCtxt<'tcx>>,
1708 {
1709if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1710if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1711if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1712if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1713self.typing_env(param_env).as_query_input(value)
1714 }
17151716/// The returned function is used in a fast path. If it returns `true` the variable is
1717 /// unchanged, `false` indicates that the status is unknown.
1718#[inline]
1719pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1720// This hoists the borrow/release out of the loop body.
1721let inner = self.inner.try_borrow();
17221723move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1724 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1725use self::type_variable::TypeVariableValue;
17261727#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1728 inner.try_type_variables_probe_ref(ty_var),
1729Some(TypeVariableValue::Unknown { .. })
1730 )1731 }
1732_ => false,
1733 }
1734 }
17351736/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1737 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1738 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1739 ///
1740 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1741 /// inlined, despite being large, because it has only two call sites that
1742 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1743 /// inference variables), and it handles both `Ty` and `ty::Const` without
1744 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1745#[inline(always)]
1746pub fn ty_or_const_infer_var_changed(&self, var: TyOrConstInferVar) -> bool {
1747match var {
1748 TyOrConstInferVar::Ty(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().try_type_variables_probe_ref(vid)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1749self.inner.borrow().try_type_variables_probe_ref(vid),
1750Some(TypeVariableValue::Unknown { .. })
1751 ),
1752 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!(
1753self.inner.borrow().int_unification_storage.try_probe_value(vid),
1754Some(ty::IntVarValue::Unknown)
1755 ),
1756 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!(
1757self.inner.borrow().float_unification_storage.try_probe_value(vid),
1758Some(ty::FloatVarValue::Unknown)
1759 ),
1760 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!(
1761self.inner.borrow().const_unification_storage.try_probe_value(vid),
1762Some(ConstVariableValue::Unknown { .. })
1763 ),
1764 }
1765 }
17661767/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1768pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1769if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1770self.obligation_inspector.get().is_none(),
1771"shouldn't override a set obligation inspector"
1772);
1773self.obligation_inspector.set(Some(inspector));
1774 }
1775}
17761777/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1778/// Used only for diagnostics.
1779struct InferenceLiteralEraser<'tcx> {
1780 tcx: TyCtxt<'tcx>,
1781}
17821783impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1784fn cx(&self) -> TyCtxt<'tcx> {
1785self.tcx
1786 }
17871788fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1789match ty.kind() {
1790 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1791 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1792_ => ty.super_fold_with(self),
1793 }
1794 }
1795}
17961797impl<'tcx> TypeTrace<'tcx> {
1798pub fn span(&self) -> Span {
1799self.cause.span
1800 }
18011802pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1803TypeTrace {
1804 cause: cause.clone(),
1805 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1806 }
1807 }
18081809pub fn trait_refs(
1810 cause: &ObligationCause<'tcx>,
1811 a: ty::TraitRef<'tcx>,
1812 b: ty::TraitRef<'tcx>,
1813 ) -> TypeTrace<'tcx> {
1814TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1815 }
18161817pub fn consts(
1818 cause: &ObligationCause<'tcx>,
1819 a: ty::Const<'tcx>,
1820 b: ty::Const<'tcx>,
1821 ) -> TypeTrace<'tcx> {
1822TypeTrace {
1823 cause: cause.clone(),
1824 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1825 }
1826 }
1827}
18281829impl<'tcx> SubregionOrigin<'tcx> {
1830pub fn span(&self) -> Span {
1831match *self {
1832 SubregionOrigin::Subtype(ref a) => a.span(),
1833 SubregionOrigin::RelateObjectBound(a) => a,
1834 SubregionOrigin::RelateParamBound(a, ..) => a,
1835 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1836 SubregionOrigin::Reborrow(a) => a,
1837 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1838 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1839 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1840 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1841 SubregionOrigin::SolverRegionConstraint(a) => a,
1842 }
1843 }
18441845pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1846where
1847F: FnOnce() -> Self,
1848 {
1849match *cause.code() {
1850 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1851 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1852 }
18531854 traits::ObligationCauseCode::CompareImplItem {
1855 impl_item_def_id,
1856 trait_item_def_id,
1857 kind: _,
1858 } => SubregionOrigin::CompareImplItemObligation {
1859 span: cause.span,
1860impl_item_def_id,
1861trait_item_def_id,
1862 },
18631864 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1865 impl_item_def_id,
1866 trait_item_def_id,
1867 } => SubregionOrigin::CheckAssociatedTypeBounds {
1868impl_item_def_id,
1869trait_item_def_id,
1870 parent: Box::new(default()),
1871 },
18721873 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1874 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1875 }
18761877 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1878 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1879 }
18801881_ => default(),
1882 }
1883 }
1884}
18851886impl<'tcx> RegionVariableOrigin<'tcx> {
1887pub fn span(&self) -> Span {
1888match *self {
1889 RegionVariableOrigin::Misc(a)
1890 | RegionVariableOrigin::PatternRegion(a)
1891 | RegionVariableOrigin::BorrowRegion(a)
1892 | RegionVariableOrigin::Autoref(a)
1893 | RegionVariableOrigin::Coercion(a)
1894 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1895 | RegionVariableOrigin::BoundRegion(a, ..)
1896 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1897 RegionVariableOrigin::Nll(..) => bug_impl(None, format_args!("NLL variable used with `span`"),
Location::caller())bug!("NLL variable used with `span`"),
1898 }
1899 }
1900}
19011902impl<'tcx> InferCtxt<'tcx> {
1903/// Given a [`hir::Block`], get the span of its last expression or
1904 /// statement, peeling off any inner blocks.
1905pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1906let block = block.innermost_block();
1907if let Some(expr) = &block.expr {
1908expr.span
1909 } else if let Some(stmt) = block.stmts.last() {
1910// possibly incorrect trailing `;` in the else arm
1911stmt.span
1912 } else {
1913// empty block; point at its entirety
1914block.span
1915 }
1916 }
19171918/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1919 /// of its last expression or statement, peeling off any inner blocks.
1920pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1921match self.tcx.hir_node(hir_id) {
1922 hir::Node::Block(blk)
1923 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1924self.find_block_span(blk)
1925 }
1926 hir::Node::Expr(e) => e.span,
1927_ => DUMMY_SP,
1928 }
1929 }
1930}
19311932/// Returns unresolved root variables from `table`, according to `is_unresolved`.
1933fn unresolved_root_variables_of<V: UnifyKey>(
1934mut table: UnificationTable<'_, '_, V>,
1935 is_unresolved: impl Fn(V::Value) -> bool,
1936) -> Vec<V>
1937where
1938V: Eq,
1939 V::Value: UnifyValue,
1940for<'a> UndoLog<'a>: From<sv::UndoLog<ut::Delegate<V>>>,
1941{
1942 (0..table.len() as u32)
1943 .map(V::from_index)
1944 .filter(|&vid| {
1945// NB: as of writing this `ena` doesn't provide a non-inlined `probe_key_value`...
1946let (root, value) = table.inlined_probe_key_value(vid);
1947root == vid && is_unresolved(value)
1948 })
1949 .collect()
1950}