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::StructurallyRelateAliases;
14pub use relate::combine::PredicateEmittingRelation;
15use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
16use rustc_data_structures::undo_log::{Rollback, UndoLogs};
17use rustc_data_structures::unifyas ut;
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::bug;
25use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
26use rustc_middle::mir::ConstraintCategory;
27use rustc_middle::traits::select;
28use rustc_middle::traits::solve::Goal;
29use rustc_middle::ty::error::{ExpectedFound, TypeError};
30use rustc_middle::ty::{
31self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
32GenericArgsRef, GenericParamDefKind, InferConst, IntVid, OpaqueTypeKey, ProvisionalHiddenType,
33PseudoCanonicalInput, Term, TermKind, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder,
34TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
35};
36use rustc_span::{DUMMY_SP, Span, Symbol};
37use rustc_type_ir::MayBeErased;
38use snapshot::undo_log::InferCtxtUndoLogs;
39use tracing::{debug, instrument};
40use type_variable::TypeVariableOrigin;
4142use crate::infer::snapshot::undo_log::UndoLog;
43use crate::infer::type_variable::FloatVariableOrigin;
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 type_variable;
64mod unify_key;
6566/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
67/// around `PredicateObligations<'tcx>`, but it has one important property:
68/// because `InferOk` is marked with `#[must_use]`, if you have a method
69/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
70/// `infcx.f()?;` you'll get a warning about the obligations being discarded
71/// without use, which is probably unintentional and has been a source of bugs
72/// in the past.
73#[must_use]
74#[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)]
75pub struct InferOk<'tcx, T> {
76pub value: T,
77pub obligations: PredicateObligations<'tcx>,
78}
79pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
8081pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
8283pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
84 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
85>;
8687/// This type contains all the things within `InferCtxt` that sit within a
88/// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
89/// operations are hot enough that we want only one call to `borrow_mut` per
90/// call to `start_snapshot` and `rollback_to`.
91#[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)]
92pub struct InferCtxtInner<'tcx> {
93 undo_log: InferCtxtUndoLogs<'tcx>,
9495/// Cache for projections.
96 ///
97 /// This cache is snapshotted along with the infcx.
98projection_cache: traits::ProjectionCacheStorage<'tcx>,
99100/// We instantiate `UnificationTable` with `bounds<Ty>` because the types
101 /// that might instantiate a general type variable have an order,
102 /// represented by its upper and lower bounds.
103type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
104105/// Map from const parameter variable to the kind of const it represents.
106const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
107108/// Map from integral variable to the kind of integer it represents.
109int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
110111/// Map from floating variable to the kind of float it represents.
112float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
113114/// Map from floating variable to the origin span it came from, and the HirId that should be
115 /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
116 /// so can be removed once the `f32` fallback is removed.
117float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
118119/// Tracks the set of region variables and the constraints between them.
120 ///
121 /// This is initially `Some(_)` but when
122 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
123 /// -- further attempts to perform unification, etc., may fail if new
124 /// region constraints would've been added.
125region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
126127/// Used by the next solver when `-Zassumptions-on-binders` is set.
128solver_region_constraint_storage: SolverRegionConstraintStorage<'tcx>,
129130/// A set of constraints that regionck must validate.
131 ///
132 /// Each constraint has the form `T:'a`, meaning "some type `T` must
133 /// outlive the lifetime 'a". These constraints derive from
134 /// instantiated type parameters. So if you had a struct defined
135 /// like the following:
136 /// ```ignore (illustrative)
137 /// struct Foo<T: 'static> { ... }
138 /// ```
139 /// In some expression `let x = Foo { ... }`, it will
140 /// instantiate the type parameter `T` with a fresh type `$0`. At
141 /// the same time, it will record a region obligation of
142 /// `$0: 'static`. This will get checked later by regionck. (We
143 /// can't generally check these things right away because we have
144 /// to wait until types are resolved.)
145region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
146147/// The outlives bounds that we assume must hold about placeholders that
148 /// come from instantiating the binder of coroutine-witnesses. These bounds
149 /// are deduced from the well-formedness of the witness's types, and are
150 /// necessary because of the way we anonymize the regions in a coroutine,
151 /// which may cause types to no longer be considered well-formed.
152region_assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
153154/// `-Znext-solver`: Successfully proven goals during HIR typeck which
155 /// reference inference variables and get reproven in case MIR type check
156 /// fails to prove something.
157 ///
158 /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
159hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
160161/// Caches for opaque type inference.
162opaque_type_storage: OpaqueTypeStorage<'tcx>,
163}
164165impl<'tcx> InferCtxtInner<'tcx> {
166fn new() -> InferCtxtInner<'tcx> {
167InferCtxtInner {
168 undo_log: InferCtxtUndoLogs::default(),
169170 projection_cache: Default::default(),
171 type_variable_storage: Default::default(),
172 const_unification_storage: Default::default(),
173 int_unification_storage: Default::default(),
174 float_unification_storage: Default::default(),
175 float_origin_origin_storage: Default::default(),
176 region_constraint_storage: Some(Default::default()),
177 solver_region_constraint_storage: SolverRegionConstraintStorage::new(),
178 region_obligations: Default::default(),
179 region_assumptions: Default::default(),
180 hir_typeck_potentially_region_dependent_goals: Default::default(),
181 opaque_type_storage: Default::default(),
182 }
183 }
184185#[inline]
186pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
187&self.region_obligations
188 }
189190#[inline]
191pub fn region_assumptions(&self) -> &[ty::ArgOutlivesPredicate<'tcx>] {
192&self.region_assumptions
193 }
194195#[inline]
196pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
197self.projection_cache.with_log(&mut self.undo_log)
198 }
199200#[inline]
201fn try_type_variables_probe_ref(
202&self,
203 vid: ty::TyVid,
204 ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
205// Uses a read-only view of the unification table, this way we don't
206 // need an undo log.
207self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
208 }
209210#[inline]
211fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
212self.type_variable_storage.with_log(&mut self.undo_log)
213 }
214215#[inline]
216pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
217self.opaque_type_storage.with_log(&mut self.undo_log)
218 }
219220#[inline]
221fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
222self.int_unification_storage.with_log(&mut self.undo_log)
223 }
224225#[inline]
226fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
227self.float_unification_storage.with_log(&mut self.undo_log)
228 }
229230#[inline]
231fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
232self.const_unification_storage.with_log(&mut self.undo_log)
233 }
234235#[inline]
236pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
237self.region_constraint_storage
238 .as_mut()
239 .expect("region constraints already solved")
240 .with_log(&mut self.undo_log)
241 }
242}
243244pub struct InferCtxt<'tcx> {
245pub tcx: TyCtxt<'tcx>,
246247/// The mode of this inference context, see the struct documentation
248 /// for more details.
249typing_mode: TypingMode<'tcx>,
250251/// Whether this inference context should care about region obligations in
252 /// the root universe. Most notably, this is used during HIR typeck as region
253 /// solving is left to borrowck instead.
254 ///
255 /// This is used in the old solver to enable the generation of regions constraints.
256 /// In the new solver its only used inside the InferCtxt's `Drop` implementation:
257 /// if we're considering regions, and new opaques are registered, we panic.
258pub considering_regions: bool,
259/// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
260 /// need to make sure we don't rely on region identity in the trait solver or when
261 /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
262 /// free region with a unique inference variable. If HIR typeck ends up depending on two
263 /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
264 /// resulting in an ICE.
265 ///
266 /// The trait solver sometimes depends on regions being identical. As a concrete example
267 /// the trait solver ignores other candidates if one candidate exists without any constraints.
268 /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
269 /// occurrence of `'a` with a unique region the goal now equates these regions. See
270 /// the tests in trait-system-refactor-initiative#27 for concrete examples.
271 ///
272 /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
273 /// This is still insufficient as inference variables may *hide* region variables, so e.g.
274 /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
275 /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
276 /// stash all successfully proven goals which reference inference variables and then reprove
277 /// them after writeback.
278pub in_hir_typeck: bool,
279280/// If set, this flag causes us to skip the 'leak check' during
281 /// higher-ranked subtyping operations. This flag is a temporary one used
282 /// to manage the removal of the leak-check: for the time being, we still run the
283 /// leak-check, but we issue warnings.
284skip_leak_check: bool,
285286pub inner: RefCell<InferCtxtInner<'tcx>>,
287288/// Once region inference is done, the values for each variable.
289lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
290291/// Caches the results of trait selection. This cache is used
292 /// for things that depends on inference variables or placeholders.
293pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
294295/// Caches the results of trait evaluation. This cache is used
296 /// for things that depends on inference variables or placeholders.
297pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
298299/// The set of predicates on which errors have been reported, to
300 /// avoid reporting the same error twice.
301pub reported_trait_errors:
302RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
303304pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
305306/// When an error occurs, we want to avoid reporting "derived"
307 /// errors that are due to this original failure. We have this
308 /// flag that one can set whenever one creates a type-error that
309 /// is due to an error in a prior pass.
310 ///
311 /// Don't read this flag directly, call `is_tainted_by_errors()`
312 /// and `set_tainted_by_errors()`.
313tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
314315/// What is the innermost universe we have created? Starts out as
316 /// `UniverseIndex::root()` but grows from there as we enter
317 /// universal quantifiers.
318 ///
319 /// N.B., at present, we exclude the universal quantifiers on the
320 /// item we are type-checking, and just consider those names as
321 /// part of the root universe. So this would only get incremented
322 /// when we enter into a higher-ranked (`for<..>`) type or trait
323 /// bound.
324universe: Cell<ty::UniverseIndex>,
325326/// List of assumed wellformed types which we can derive implied
327 /// bounds on a `for<...>` from. Only used unstabley and by the
328 /// new solver.
329//
330 // FIXME(-Zassumptions-on-binders): This and `universe` should probably be
331 // in `InferCtxtInner` so they can participate in rollbacks and whatnot
332placeholder_assumptions_for_next_solver: RefCell<
333FxIndexMap<
334 ty::UniverseIndex,
335Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
336 >,
337 >,
338339 next_trait_solver: bool,
340341pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
342}
343344impl<'tcx> Dropfor InferCtxt<'tcx> {
345fn drop(&mut self) {
346let mut inner = self.inner.borrow_mut();
347let opaque_type_storage = &mut inner.opaque_type_storage;
348349// No need for the drop bomb when we're in `TypingMode::PostTypeckUntilBorrowck`, and the `InferCtxt`
350 // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
351 // in relation to regions. In some places *after* typeck that aren't borrowck, like in lints we use
352 // `TypingMode::PostTypeckUntilBorrowck` to prevent defining opaque types and we simply don't care about regions.
353match self.typing_mode_raw() {
354TypingMode::Coherence355 | TypingMode::Typeck { .. }
356 | TypingMode::PostBorrowck { .. }
357 | TypingMode::PostAnalysis358 | TypingMode::Codegen => {}
359// In erased mode, the opaque type storage is always empty
360TypingMode::ErasedNotCoherence(..) => {}
361TypingMode::PostTypeckUntilBorrowck { .. } => {
362if !self.considering_regions {
363return;
364 }
365 }
366 }
367368if !opaque_type_storage.is_empty() {
369 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:?}")));
370 }
371 }
372}
373374/// See the `error_reporting` module for more details.
375#[derive(#[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::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)]
376pub enum ValuePairs<'tcx> {
377 Regions(ExpectedFound<ty::Region<'tcx>>),
378 Terms(ExpectedFound<ty::Term<'tcx>>),
379 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
380 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
381 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
382 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
383 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
384}
385386impl<'tcx> ValuePairs<'tcx> {
387pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
388if let ValuePairs::Terms(ExpectedFound { expected, found }) = self389 && let Some(expected) = expected.as_type()
390 && let Some(found) = found.as_type()
391 {
392Some((expected, found))
393 } else {
394None395 }
396 }
397}
398399/// The trace designates the path through inference that we took to
400/// encounter an error or subtyping constraint.
401///
402/// See the `error_reporting` module for more details.
403#[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)]
404pub struct TypeTrace<'tcx> {
405pub cause: ObligationCause<'tcx>,
406pub values: ValuePairs<'tcx>,
407}
408409/// The origin of a `r1 <= r2` constraint.
410///
411/// See `error_reporting` module for more details
412#[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)]
413pub enum SubregionOrigin<'tcx> {
414/// Arose from a subtyping relation
415Subtype(Box<TypeTrace<'tcx>>),
416417/// When casting `&'a T` to an `&'b Trait` object,
418 /// relating `'a` to `'b`.
419RelateObjectBound(Span),
420421/// Some type parameter was instantiated with the given type,
422 /// and that type must outlive some region.
423RelateParamBound(Span, Ty<'tcx>, Option<Span>),
424425/// The given region parameter was instantiated with a region
426 /// that must outlive some other region.
427RelateRegionParamBound(Span, Option<Ty<'tcx>>),
428429/// Creating a pointer `b` to contents of another reference.
430Reborrow(Span),
431432/// (&'a &'b T) where a >= b
433ReferenceOutlivesReferent(Ty<'tcx>, Span),
434435/// Comparing the signature and requirements of an impl method against
436 /// the containing trait.
437CompareImplItemObligation {
438 span: Span,
439 impl_item_def_id: LocalDefId,
440 trait_item_def_id: DefId,
441 },
442443/// Checking that the bounds of a trait's associated type hold for a given impl.
444CheckAssociatedTypeBounds {
445 parent: Box<SubregionOrigin<'tcx>>,
446 impl_item_def_id: LocalDefId,
447 trait_item_def_id: DefId,
448 },
449450 AscribeUserTypeProvePredicate(Span),
451452// FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
453 // proper diagnostics for solver region constraints.
454SolverRegionConstraint(Span),
455}
456457// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
458#[cfg(target_pointer_width = "64")]
459const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
460461impl<'tcx> SubregionOrigin<'tcx> {
462pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
463match self {
464Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
465Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
466Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
467_ => ConstraintCategory::BoringNoLocation,
468 }
469 }
470}
471472/// Times when we replace bound regions with existentials:
473#[derive(#[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)]
474pub enum BoundRegionConversionTime {
475/// when a fn is called
476FnCall,
477478/// when two higher-ranked types are compared
479HigherRankedType,
480481/// when projecting an associated type
482AssocTypeProjection(DefId),
483}
484485/// Reasons to create a region inference variable.
486///
487/// See `error_reporting` module for more details.
488#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for RegionVariableOrigin<'tcx> { }Copy, #[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)]
489pub enum RegionVariableOrigin<'tcx> {
490/// Region variables created for ill-categorized reasons.
491 ///
492 /// They mostly indicate places in need of refactoring.
493Misc(Span),
494495/// Regions created by a `&P` or `[...]` pattern.
496PatternRegion(Span),
497498/// Regions created by `&` operator.
499BorrowRegion(Span),
500501/// Regions created as part of an autoref of a method receiver.
502Autoref(Span),
503504/// Regions created as part of an automatic coercion.
505Coercion(Span),
506507/// Region variables created as the values for early-bound regions.
508 ///
509 /// FIXME(@lcnr): This should also store a `DefId`, similar to
510 /// `TypeVariableOrigin`.
511RegionParameterDefinition(Span, Symbol),
512513/// Region variables created when instantiating a binder with
514 /// existential variables, e.g. when calling a function or method.
515BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
516517 UpvarRegion(ty::UpvarId, Span),
518519/// This origin is used for the inference variables that we create
520 /// during NLL region processing.
521Nll(NllRegionVariableOrigin<'tcx>),
522}
523524#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for NllRegionVariableOrigin<'tcx> { }Copy, #[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)]
525pub enum NllRegionVariableOrigin<'tcx> {
526/// During NLL region processing, we create variables for free
527 /// regions that we encounter in the function signature and
528 /// elsewhere. This origin indices we've got one of those.
529FreeRegion,
530531/// "Universal" instantiation of a higher-ranked region (e.g.,
532 /// from a `for<'a> T` binder). Meant to represent "any region".
533Placeholder(ty::PlaceholderRegion<'tcx>),
534535 Existential {
536 name: Option<Symbol>,
537 },
538}
539540#[derive(#[automatically_derived]
impl ::core::marker::Copy for FixupError { }Copy, #[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)]
541pub struct FixupError {
542 unresolved: TyOrConstInferVar,
543}
544545impl fmt::Displayfor FixupError {
546fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
547match self.unresolved {
548 TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
549f,
550"cannot determine the type of this integer; \
551 add a suffix to specify the type explicitly"
552),
553 TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
554f,
555"cannot determine the type of this number; \
556 add a suffix to specify the type explicitly"
557),
558 TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
559 TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
560 }
561 }
562}
563564/// See the `region_obligations` field for more information.
565#[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)]
566pub struct TypeOutlivesConstraint<'tcx> {
567pub sub_region: ty::Region<'tcx>,
568pub sup_type: Ty<'tcx>,
569pub origin: SubregionOrigin<'tcx>,
570}
571572/// Used to configure inference contexts before their creation.
573pub struct InferCtxtBuilder<'tcx> {
574 tcx: TyCtxt<'tcx>,
575 considering_regions: bool,
576 in_hir_typeck: bool,
577 skip_leak_check: bool,
578/// Whether we should use the new trait solver in the local inference context,
579 /// which affects things like which solver is used in `predicate_may_hold`.
580next_trait_solver: bool,
581}
582583impl<'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(),
}
}
}#[extension(pub trait TyCtxtInferExt<'tcx>)]584impl<'tcx> TyCtxt<'tcx> {
585fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
586InferCtxtBuilder {
587 tcx: self,
588 considering_regions: true,
589 in_hir_typeck: false,
590 skip_leak_check: false,
591 next_trait_solver: self.next_trait_solver_globally(),
592 }
593 }
594}
595596impl<'tcx> InferCtxtBuilder<'tcx> {
597pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
598self.next_trait_solver = next_trait_solver;
599self600 }
601602pub fn ignoring_regions(mut self) -> Self {
603self.considering_regions = false;
604self605 }
606607pub fn in_hir_typeck(mut self) -> Self {
608self.in_hir_typeck = true;
609self610 }
611612pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
613self.skip_leak_check = skip_leak_check;
614self615 }
616617/// Given a canonical value `C` as a starting point, create an
618 /// inference context that contains each of the bound values
619 /// within instantiated as a fresh variable. The `f` closure is
620 /// invoked with the new infcx, along with the instantiated value
621 /// `V` and a instantiation `S`. This instantiation `S` maps from
622 /// the bound values in `C` to their instantiated values in `V`
623 /// (in other words, `S(C) = V`).
624pub fn build_with_canonical<T>(
625mut self,
626 span: Span,
627 input: &CanonicalQueryInput<'tcx, T>,
628 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
629where
630T: TypeFoldable<TyCtxt<'tcx>>,
631 {
632let infcx = self.build(input.typing_mode.0);
633let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
634 (infcx, value, args)
635 }
636637pub fn build_with_typing_env(
638mut self,
639 typing_env: TypingEnv<'tcx>,
640 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
641 (self.build(typing_env.typing_mode()), typing_env.param_env)
642 }
643644pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
645let InferCtxtBuilder {
646 tcx,
647 considering_regions,
648 in_hir_typeck,
649 skip_leak_check,
650 next_trait_solver,
651 } = *self;
652InferCtxt {
653tcx,
654typing_mode,
655considering_regions,
656in_hir_typeck,
657skip_leak_check,
658 inner: RefCell::new(InferCtxtInner::new()),
659 lexical_region_resolutions: RefCell::new(None),
660 selection_cache: Default::default(),
661 evaluation_cache: Default::default(),
662 reported_trait_errors: Default::default(),
663 reported_signature_mismatch: Default::default(),
664 tainted_by_errors: Cell::new(None),
665 universe: Cell::new(ty::UniverseIndex::ROOT),
666 placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
667next_trait_solver,
668 obligation_inspector: Cell::new(None),
669 }
670 }
671}
672673impl<'tcx, T> InferOk<'tcx, T> {
674/// Extracts `value`, registering any obligations into `fulfill_cx`.
675pub fn into_value_registering_obligations<E: 'tcx>(
676self,
677 infcx: &InferCtxt<'tcx>,
678 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
679 ) -> T {
680let InferOk { value, obligations } = self;
681fulfill_cx.register_predicate_obligations(infcx, obligations);
682value683 }
684}
685686impl<'tcx> InferOk<'tcx, ()> {
687pub fn into_obligations(self) -> PredicateObligations<'tcx> {
688self.obligations
689 }
690}
691692impl<'tcx> InferCtxt<'tcx> {
693pub fn dcx(&self) -> DiagCtxtHandle<'_> {
694self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
695 }
696697pub fn next_trait_solver(&self) -> bool {
698self.next_trait_solver
699 }
700701/// This method is deliberately called `..._raw`,
702 /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
703 /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
704 /// more information.
705 ///
706 /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
707 /// works as a kind of store for for example type unification information.
708 /// `InferCtxt` is also often used outside the trait solver during typeck.
709 /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
710 /// To make sure these two uses are never confused, we want to statically encode this information.
711 ///
712 /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
713 /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
714 /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
715 /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
716 /// match on the variant and can safely ignore it.
717 ///
718 /// Prefer non-raw apis if available. e.g.,
719 /// - On the `FnCtxt`
720 /// - on the `SelectionCtxt`
721#[inline(always)]
722pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
723self.typing_mode
724 }
725726#[inline(always)]
727pub fn disable_trait_solver_fast_paths(&self) -> bool {
728self.tcx.disable_trait_solver_fast_paths()
729 }
730731/// Returns the origin of the type variable identified by `vid`.
732 ///
733 /// No attempt is made to resolve `vid` to its root variable.
734pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
735self.inner.borrow_mut().type_variables().var_origin(vid)
736 }
737738/// Returns the origin of the float type variable identified by `vid`.
739 ///
740 /// No attempt is made to resolve `vid` to its root variable.
741pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
742self.inner.borrow_mut().float_origin_origin_storage[vid]
743 }
744745/// Returns the origin of the const variable identified by `vid`
746// FIXME: We should store origins separately from the unification table
747 // so this doesn't need to be optional.
748pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
749match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
750 ConstVariableValue::Known { .. } => None,
751 ConstVariableValue::Unknown { origin, .. } => Some(origin),
752 }
753 }
754755pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
756let mut inner = self.inner.borrow_mut();
757let mut vars: Vec<Ty<'_>> = inner758 .type_variables()
759 .unresolved_variables()
760 .into_iter()
761 .map(|t| Ty::new_var(self.tcx, t))
762 .collect();
763vars.extend(
764 (0..inner.int_unification_table().len())
765 .map(|i| ty::IntVid::from_usize(i))
766 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
767 .map(|v| Ty::new_int_var(self.tcx, v)),
768 );
769vars.extend(
770 (0..inner.float_unification_table().len())
771 .map(|i| ty::FloatVid::from_usize(i))
772 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
773 .map(|v| Ty::new_float_var(self.tcx, v)),
774 );
775vars776 }
777778#[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("compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(778u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["origin", "a", "b",
"vis"], ::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
as &dyn 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")]779pub fn sub_regions(
780&self,
781 origin: SubregionOrigin<'tcx>,
782 a: ty::Region<'tcx>,
783 b: ty::Region<'tcx>,
784 vis: ty::VisibleForLeakCheck,
785 ) {
786self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
787 }
788789#[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("compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(789u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["origin", "a", "b",
"vis"], ::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
as &dyn 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")]790pub fn equate_regions(
791&self,
792 origin: SubregionOrigin<'tcx>,
793 a: ty::Region<'tcx>,
794 b: ty::Region<'tcx>,
795 vis: ty::VisibleForLeakCheck,
796 ) {
797self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
798 }
799800/// Processes a `Coerce` predicate from the fulfillment context.
801 /// This is NOT the preferred way to handle coercion, which is to
802 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
803 ///
804 /// This method here is actually a fallback that winds up being
805 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
806 /// and records a coercion predicate. Presently, this method is equivalent
807 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
808 /// actually requiring `a <: b`. This is of course a valid coercion,
809 /// but it's not as flexible as `FnCtxt::coerce` would be.
810 ///
811 /// (We may refactor this in the future, but there are a number of
812 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
813 /// records adjustments that are required on the HIR in order to perform
814 /// the coercion, and we don't currently have a way to manage that.)
815pub fn coerce_predicate(
816&self,
817 cause: &ObligationCause<'tcx>,
818 param_env: ty::ParamEnv<'tcx>,
819 predicate: ty::PolyCoercePredicate<'tcx>,
820 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
821let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
822 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
823a: p.a,
824 b: p.b,
825 });
826self.subtype_predicate(cause, param_env, subtype_predicate)
827 }
828829pub fn subtype_predicate(
830&self,
831 cause: &ObligationCause<'tcx>,
832 param_env: ty::ParamEnv<'tcx>,
833 predicate: ty::PolySubtypePredicate<'tcx>,
834 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
835// Check for two unresolved inference variables, in which case we can
836 // make no progress. This is partly a micro-optimization, but it's
837 // also an opportunity to "sub-unify" the variables. This isn't
838 // *necessary* to prevent cycles, because they would eventually be sub-unified
839 // anyhow during generalization, but it helps with diagnostics (we can detect
840 // earlier that they are sub-unified).
841 //
842 // Note that we can just skip the binders here because
843 // type variables can't (at present, at
844 // least) capture any of the things bound by this binder.
845 //
846 // Note that this sub here is not just for diagnostics - it has semantic
847 // effects as well.
848let r_a = self.shallow_resolve(predicate.skip_binder().a);
849let r_b = self.shallow_resolve(predicate.skip_binder().b);
850match (r_a.kind(), r_b.kind()) {
851 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
852self.sub_unify_ty_vids_raw(a_vid, b_vid);
853return Err((a_vid, b_vid));
854 }
855_ => {}
856 }
857858self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
859if a_is_expected {
860Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
861 } else {
862Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
863 }
864 })
865 }
866867/// Number of type variables created so far.
868pub fn num_ty_vars(&self) -> usize {
869self.inner.borrow_mut().type_variables().num_vars()
870 }
871872pub fn next_ty_vid(&self, span: Span) -> TyVid {
873self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
874 }
875876pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
877self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
878 }
879880pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
881let origin = TypeVariableOrigin { span, param_def_id: None };
882self.inner.borrow_mut().type_variables().new_var(universe, origin)
883 }
884885pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
886self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
887 }
888889pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
890let vid = self.next_ty_vid_with_origin(origin);
891Ty::new_var(self.tcx, vid)
892 }
893894pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
895let vid = self.next_ty_vid_in_universe(span, universe);
896Ty::new_var(self.tcx, vid)
897 }
898899pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
900self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
901 }
902903pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
904let vid = self905 .inner
906 .borrow_mut()
907 .const_unification_table()
908 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
909 .vid;
910 ty::Const::new_var(self.tcx, vid)
911 }
912913pub fn next_const_var_in_universe(
914&self,
915 span: Span,
916 universe: ty::UniverseIndex,
917 ) -> ty::Const<'tcx> {
918let origin = ConstVariableOrigin { span, param_def_id: None };
919let vid = self920 .inner
921 .borrow_mut()
922 .const_unification_table()
923 .new_key(ConstVariableValue::Unknown { origin, universe })
924 .vid;
925 ty::Const::new_var(self.tcx, vid)
926 }
927928pub fn next_int_var(&self) -> Ty<'tcx> {
929let next_int_var_id =
930self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
931Ty::new_int_var(self.tcx, next_int_var_id)
932 }
933934pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
935let mut inner = self.inner.borrow_mut();
936let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
937let origin = FloatVariableOrigin { span, lint_id };
938let span_index = inner.float_origin_origin_storage.push(origin);
939if 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);
940Ty::new_float_var(self.tcx, next_float_var_id)
941 }
942943/// Creates a fresh region variable with the next available index.
944 /// The variable will be created in the maximum universe created
945 /// thus far, allowing it to name any region created thus far.
946pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
947self.next_region_var_in_universe(origin, self.universe())
948 }
949950/// Creates a fresh region variable with the next available index
951 /// in the given universe; typically, you can use
952 /// `next_region_var` and just use the maximal universe.
953pub fn next_region_var_in_universe(
954&self,
955 origin: RegionVariableOrigin<'tcx>,
956 universe: ty::UniverseIndex,
957 ) -> ty::Region<'tcx> {
958let region_var =
959self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
960 ty::Region::new_var(self.tcx, region_var)
961 }
962963pub fn next_term_var_of_alias_kind(
964&self,
965 alias_term: ty::AliasTerm<'tcx>,
966 span: Span,
967 ) -> ty::Term<'tcx> {
968match alias_term.kind {
969 ty::AliasTermKind::ProjectionTy { .. }
970 | ty::AliasTermKind::InherentTy { .. }
971 | ty::AliasTermKind::OpaqueTy { .. }
972 | ty::AliasTermKind::FreeTy { .. } => self.next_ty_var(span).into(),
973 ty::AliasTermKind::FreeConst { .. }
974 | ty::AliasTermKind::InherentConst { .. }
975 | ty::AliasTermKind::AnonConst { .. }
976 | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_var(span).into(),
977 }
978 }
979980/// Return the universe that the region `r` was created in. For
981 /// most regions (e.g., `'static`, named regions from the user,
982 /// etc) this is the root universe U0. For inference variables or
983 /// placeholders, however, it will return the universe which they
984 /// are associated.
985pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
986self.inner.borrow_mut().unwrap_region_constraints().universe(r)
987 }
988989/// Number of region variables created so far.
990pub fn num_region_vars(&self) -> usize {
991self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
992 }
993994/// Just a convenient wrapper of `next_region_var` for using during NLL.
995#[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("compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(995u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["origin"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn 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")]996pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
997self.next_region_var(RegionVariableOrigin::Nll(origin))
998 }
9991000/// Just a convenient wrapper of `next_region_var` for using during NLL.
1001#[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("compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1001u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["origin",
"universe"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&universe)
as &dyn 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")]1002pub fn next_nll_region_var_in_universe(
1003&self,
1004 origin: NllRegionVariableOrigin<'tcx>,
1005 universe: ty::UniverseIndex,
1006 ) -> ty::Region<'tcx> {
1007self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1008 }
10091010pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1011match param.kind {
1012 GenericParamDefKind::Lifetime => {
1013// Create a region inference variable for the given
1014 // region parameter definition.
1015self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1016span, param.name,
1017 ))
1018 .into()
1019 }
1020 GenericParamDefKind::Type { .. } => {
1021// Create a type inference variable for the given
1022 // type parameter definition. The generic parameters are
1023 // for actual parameters that may be referred to by
1024 // the default of this type parameter, if it exists.
1025 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1026 // used in a path such as `Foo::<T, U>::new()` will
1027 // use an inference variable for `C` with `[T, U]`
1028 // as the generic parameters for the default, `(T, U)`.
1029let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1030self.universe(),
1031TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1032 );
10331034Ty::new_var(self.tcx, ty_var_id).into()
1035 }
1036 GenericParamDefKind::Const { .. } => {
1037let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1038let const_var_id = self1039 .inner
1040 .borrow_mut()
1041 .const_unification_table()
1042 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1043 .vid;
1044 ty::Const::new_var(self.tcx, const_var_id).into()
1045 }
1046 }
1047 }
10481049/// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1050 /// each type/region parameter to a fresh inference variable.
1051pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
1052GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1053 }
10541055/// Returns `true` if errors have been reported since this infcx was
1056 /// created. This is sometimes used as a heuristic to skip
1057 /// reporting errors that often occur as a result of earlier
1058 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1059 /// inference variables, regionck errors).
1060#[must_use = "this method does not have any side effects"]
1061pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1062self.tainted_by_errors.get()
1063 }
10641065/// Set the "tainted by errors" flag to true. We call this when we
1066 /// observe an error from a prior pass.
1067pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1068{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/mod.rs:1068",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1068u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("set_tainted_by_errors(ErrorGuaranteed)")
as &dyn Value))])
});
} else { ; }
};debug!("set_tainted_by_errors(ErrorGuaranteed)");
1069self.tainted_by_errors.set(Some(e));
1070 }
10711072pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1073let mut inner = self.inner.borrow_mut();
1074let inner = &mut *inner;
1075inner.unwrap_region_constraints().var_origin(vid)
1076 }
10771078/// Clone the list of variable regions. This is used only during NLL processing
1079 /// to put the set of region variables into the NLL region context.
1080pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1081let inner = self.inner.borrow();
1082if !!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));
1083let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1084if !storage.data.is_empty() {
{ ::core::panicking::panic_fmt(format_args!("{0:#?}", storage.data)); }
};assert!(storage.data.is_empty(), "{:#?}", storage.data);
1085// We clone instead of taking because borrowck still wants to use the
1086 // inference context after calling this for diagnostics and the new
1087 // trait solver.
1088storage.var_infos.clone()
1089 }
10901091pub fn has_opaque_types_in_storage(&self) -> bool {
1092 !self.inner.borrow().opaque_type_storage.is_empty()
1093 }
10941095x;#[instrument(level = "debug", skip(self), ret)]1096pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1097self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1098 }
10991100x;#[instrument(level = "debug", skip(self), ret)]1101pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1102self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1103 }
11041105pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1106if !self.next_trait_solver() {
1107return false;
1108 }
11091110let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1111let inner = &mut *self.inner.borrow_mut();
1112let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1113inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1114if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1115let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1116if opaque_sub_vid == ty_sub_vid {
1117return true;
1118 }
1119 }
11201121false
1122})
1123 }
11241125/// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1126 ///
1127 /// This only checks for a subtype relation, it does not require equality.
1128pub fn opaques_with_sub_unified_hidden_type(
1129&self,
1130 ty_vid: TyVid,
1131 ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1132// Avoid accidentally allowing more code to compile with the old solver.
1133if !self.next_trait_solver() {
1134return ::alloc::vec::Vec::new()vec![];
1135 }
11361137let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1138let inner = &mut *self.inner.borrow_mut();
1139// This is iffy, can't call `type_variables()` as we're already
1140 // borrowing the `opaque_type_storage` here.
1141let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1142inner1143 .opaque_type_storage
1144 .iter_opaque_types()
1145 .filter_map(|(key, hidden_ty)| {
1146if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1147let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1148if opaque_sub_vid == ty_sub_vid {
1149return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1150self.tcx,
1151key.def_id.into(),
1152key.args,
1153 ));
1154 }
1155 }
11561157None1158 })
1159 .collect()
1160 }
11611162#[inline(always)]
1163pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1164if true {
if !!self.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.next_trait_solver()")
};
};debug_assert!(!self.next_trait_solver());
1165match self.typing_mode_raw().assert_not_erased() {
1166TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1167 | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types } => {
1168id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1169 }
1170// FIXME(#132279): This function is quite weird in post-analysis
1171 // and post-borrowck analysis mode. We may need to modify its uses
1172 // to support PostBorrowck in the old solver as well.
1173TypingMode::Coherence1174 | TypingMode::PostBorrowck { .. }
1175 | TypingMode::PostAnalysis1176 | TypingMode::Codegen => false,
1177 }
1178 }
11791180pub fn push_hir_typeck_potentially_region_dependent_goal(
1181&self,
1182 goal: PredicateObligation<'tcx>,
1183 ) {
1184let mut inner = self.inner.borrow_mut();
1185inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1186inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1187 }
11881189pub fn take_hir_typeck_potentially_region_dependent_goals(
1190&self,
1191 ) -> Vec<PredicateObligation<'tcx>> {
1192if !!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");
1193 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1194 }
11951196pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1197self.resolve_vars_if_possible(t).to_string()
1198 }
11991200/// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1201 /// universe index of `TyVar(vid)`.
1202pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1203use self::type_variable::TypeVariableValue;
12041205match self.inner.borrow_mut().type_variables().probe(vid) {
1206 TypeVariableValue::Known { value } => Ok(value),
1207 TypeVariableValue::Unknown { universe } => Err(universe),
1208 }
1209 }
12101211pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1212if let ty::Infer(v) = *ty.kind() {
1213match v {
1214 ty::TyVar(v) => {
1215// Not entirely obvious: if `typ` is a type variable,
1216 // it can be resolved to an int/float variable, which
1217 // can then be recursively resolved, hence the
1218 // recursion. Note though that we prevent type
1219 // variables from unifying to other type variables
1220 // directly (though they may be embedded
1221 // structurally), and we prevent cycles in any case,
1222 // so this recursion should always be of very limited
1223 // depth.
1224 //
1225 // Note: if these two lines are combined into one we get
1226 // dynamic borrow errors on `self.inner`.
1227let known = self.inner.borrow_mut().type_variables().probe(v).known();
1228known.map_or(ty, |t| self.shallow_resolve(t))
1229 }
12301231 ty::IntVar(v) => {
1232match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1233 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1234 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1235 ty::IntVarValue::Unknown => ty,
1236 }
1237 }
12381239 ty::FloatVar(v) => {
1240match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1241 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1242 ty::FloatVarValue::Unknown => ty,
1243 }
1244 }
12451246 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1247 }
1248 } else {
1249ty1250 }
1251 }
12521253pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1254match ct.kind() {
1255 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1256 InferConst::Var(vid) => self1257 .inner
1258 .borrow_mut()
1259 .const_unification_table()
1260 .probe_value(vid)
1261 .known()
1262 .unwrap_or(ct),
1263 InferConst::Fresh(_) => ct,
1264 },
12651266 ty::ConstKind::Param(_)
1267 | ty::ConstKind::Bound(_, _)
1268 | ty::ConstKind::Placeholder(_)
1269 | ty::ConstKind::Unevaluated(_, _)
1270 | ty::ConstKind::Value(_)
1271 | ty::ConstKind::Error(_)
1272 | ty::ConstKind::Expr(_) => ct,
1273 }
1274 }
12751276pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1277match term.kind() {
1278 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1279 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1280 }
1281 }
12821283pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1284self.inner.borrow_mut().type_variables().root_var(var)
1285 }
12861287pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1288self.inner.borrow_mut().type_variables().sub_unify(a, b);
1289 }
12901291pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1292self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1293 }
12941295pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1296self.inner.borrow_mut().float_unification_table().find(var)
1297 }
12981299pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1300self.inner.borrow_mut().const_unification_table().find(var).vid
1301 }
13021303/// Resolves an int var to a rigid int type, if it was constrained to one,
1304 /// or else the root int var in the unification table.
1305pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1306let mut inner = self.inner.borrow_mut();
1307let value = inner.int_unification_table().probe_value(vid);
1308match value {
1309 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1310 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1311 ty::IntVarValue::Unknown => {
1312Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1313 }
1314 }
1315 }
13161317/// Resolves a float var to a rigid int type, if it was constrained to one,
1318 /// or else the root float var in the unification table.
1319pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1320let mut inner = self.inner.borrow_mut();
1321let value = inner.float_unification_table().probe_value(vid);
1322match value {
1323 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1324 ty::FloatVarValue::Unknown => {
1325Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1326 }
1327 }
1328 }
13291330/// Where possible, replaces type/const variables in
1331 /// `value` with their final value. Note that region variables
1332 /// are unaffected. If a type/const variable has not been unified, it
1333 /// is left as is. This is an idempotent operation that does
1334 /// not affect inference state in any way and so you can do it
1335 /// at will.
1336pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1337where
1338T: TypeFoldable<TyCtxt<'tcx>>,
1339 {
1340if let Err(guar) = value.error_reported() {
1341self.set_tainted_by_errors(guar);
1342 }
1343if !value.has_non_region_infer() {
1344return value;
1345 }
1346let mut r = resolve::OpportunisticVarResolver::new(self);
1347value.fold_with(&mut r)
1348 }
13491350pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1351where
1352T: TypeFoldable<TyCtxt<'tcx>>,
1353 {
1354if !value.has_infer() {
1355return value; // Avoid duplicated type-folding.
1356}
1357let mut r = InferenceLiteralEraser { tcx: self.tcx };
1358value.fold_with(&mut r)
1359 }
13601361pub fn try_resolve_const_var(
1362&self,
1363 vid: ty::ConstVid,
1364 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1365match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1366 ConstVariableValue::Known { value } => Ok(value),
1367 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1368 }
1369 }
13701371/// Attempts to resolve all type/region/const variables in
1372 /// `value`. Region inference must have been run already (e.g.,
1373 /// by calling `resolve_regions_and_report_errors`). If some
1374 /// variable was never unified, an `Err` results.
1375 ///
1376 /// This method is idempotent, but it not typically not invoked
1377 /// except during the writeback phase.
1378pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1379match resolve::fully_resolve(self, value) {
1380Ok(value) => {
1381if value.has_non_region_infer() {
1382::rustc_middle::util::bug::bug_fmt(format_args!("`{0:?}` is not fully resolved",
value));bug!("`{value:?}` is not fully resolved");
1383 }
1384if value.has_infer_regions() {
1385let 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"));
1386Ok(fold_regions(self.tcx, value, |re, _| {
1387if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1388 }))
1389 } else {
1390Ok(value)
1391 }
1392 }
1393Err(e) => Err(e),
1394 }
1395 }
13961397// Instantiates the bound variables in a given binder with fresh inference
1398 // variables in the current universe.
1399 //
1400 // Use this method if you'd like to find some generic parameters of the binder's
1401 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1402 // that corresponds to your use case, consider whether or not you should
1403 // use [`InferCtxt::enter_forall`] instead.
1404pub fn instantiate_binder_with_fresh_vars<T>(
1405&self,
1406 span: Span,
1407 lbrct: BoundRegionConversionTime,
1408 value: ty::Binder<'tcx, T>,
1409 ) -> T
1410where
1411T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1412 {
1413if let Some(inner) = value.no_bound_vars() {
1414return inner;
1415 }
14161417let bound_vars = value.bound_vars();
1418let mut args = Vec::with_capacity(bound_vars.len());
14191420for bound_var_kind in bound_vars {
1421let arg: ty::GenericArg<'_> = match bound_var_kind {
1422 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1423 ty::BoundVariableKind::Region(br) => {
1424self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1425 }
1426 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1427 };
1428 args.push(arg);
1429 }
14301431struct ToFreshVars<'tcx> {
1432 args: Vec<ty::GenericArg<'tcx>>,
1433 }
14341435impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1436fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1437self.args[br.var.index()].expect_region()
1438 }
1439fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1440self.args[bt.var.index()].expect_ty()
1441 }
1442fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1443self.args[bc.var.index()].expect_const()
1444 }
1445 }
1446let delegate = ToFreshVars { args };
1447self.tcx.replace_bound_vars_uncached(value, delegate)
1448 }
14491450/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1451pub(crate) fn verify_generic_bound(
1452&self,
1453 origin: SubregionOrigin<'tcx>,
1454 kind: GenericKind<'tcx>,
1455 a: ty::Region<'tcx>,
1456 bound: VerifyBound<'tcx>,
1457 ) {
1458{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/mod.rs:1458",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1458u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("verify_generic_bound({0:?}, {1:?} <: {2:?})",
kind, a, bound) as &dyn Value))])
});
} else { ; }
};debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
14591460self.inner
1461 .borrow_mut()
1462 .unwrap_region_constraints()
1463 .verify_generic_bound(origin, kind, a, bound);
1464 }
14651466/// Obtains the latest type of the given closure; this may be a
1467 /// closure in the current function, in which case its
1468 /// `ClosureKind` may not yet be known.
1469pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1470let unresolved_kind_ty = match *closure_ty.kind() {
1471 ty::Closure(_, args) => args.as_closure().kind_ty(),
1472 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1473_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0}",
closure_ty))bug!("unexpected type {closure_ty}"),
1474 };
1475let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1476closure_kind_ty.to_opt_closure_kind()
1477 }
14781479pub fn universe(&self) -> ty::UniverseIndex {
1480self.universe.get()
1481 }
14821483/// Creates and return a fresh universe that extends all previous
1484 /// universes. Updates `self.universe` to that new universe.
1485pub fn create_next_universe(&self) -> ty::UniverseIndex {
1486let u = self.universe.get().next_universe();
1487{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/mod.rs:1487",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1487u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("create_next_universe {0:?}",
u) as &dyn Value))])
});
} else { ; }
};debug!("create_next_universe {u:?}");
1488self.universe.set(u);
1489u1490 }
14911492/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1493 /// which contains the necessary information to use the trait system without
1494 /// using canonicalization or carrying this inference context around.
1495pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1496let typing_mode = match self.typing_mode_raw() {
1497// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1498 // to handle them without proper canonicalization. This means we may cause cycle
1499 // errors and fail to reveal opaques while inside of bodies. We should rename this
1500 // function and require explicit comments on all use-sites in the future.
1501ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1502 | ty::TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ } => {
1503TypingMode::non_body_analysis()
1504 }
1505 mode @ (ty::TypingMode::Coherence1506 | ty::TypingMode::PostBorrowck { .. }
1507 | ty::TypingMode::PostAnalysis1508 | ty::TypingMode::Codegen) => mode,
1509 ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1510 };
1511 ty::TypingEnv::new(param_env, typing_mode)
1512 }
15131514/// Similar to [`Self::canonicalize_query`], except that it returns
1515 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1516 /// `param_env` to not contain any inference variables or placeholders.
1517pub fn pseudo_canonicalize_query<V>(
1518&self,
1519 param_env: ty::ParamEnv<'tcx>,
1520 value: V,
1521 ) -> PseudoCanonicalInput<'tcx, V>
1522where
1523V: TypeVisitable<TyCtxt<'tcx>>,
1524 {
1525if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1526if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1527if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1528if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1529self.typing_env(param_env).as_query_input(value)
1530 }
15311532/// The returned function is used in a fast path. If it returns `true` the variable is
1533 /// unchanged, `false` indicates that the status is unknown.
1534#[inline]
1535pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1536// This hoists the borrow/release out of the loop body.
1537let inner = self.inner.try_borrow();
15381539move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1540 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1541use self::type_variable::TypeVariableValue;
15421543#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1544 inner.try_type_variables_probe_ref(ty_var),
1545Some(TypeVariableValue::Unknown { .. })
1546 )1547 }
1548_ => false,
1549 }
1550 }
15511552/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1553 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1554 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1555 ///
1556 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1557 /// inlined, despite being large, because it has only two call sites that
1558 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1559 /// inference variables), and it handles both `Ty` and `ty::Const` without
1560 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1561#[inline(always)]
1562pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1563match infer_var {
1564 TyOrConstInferVar::Ty(v) => {
1565use self::type_variable::TypeVariableValue;
15661567// If `inlined_probe` returns a `Known` value, it never equals
1568 // `ty::Infer(ty::TyVar(v))`.
1569match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1570 TypeVariableValue::Unknown { .. } => false,
1571 TypeVariableValue::Known { .. } => true,
1572 }
1573 }
15741575 TyOrConstInferVar::TyInt(v) => {
1576// If `inlined_probe_value` returns a value it's always a
1577 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1578 // `ty::Infer(_)`.
1579self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1580 }
15811582 TyOrConstInferVar::TyFloat(v) => {
1583// If `probe_value` returns a value it's always a
1584 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1585 //
1586 // Not `inlined_probe_value(v)` because this call site is colder.
1587self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1588 }
15891590 TyOrConstInferVar::Const(v) => {
1591// If `probe_value` returns a `Known` value, it never equals
1592 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1593 //
1594 // Not `inlined_probe_value(v)` because this call site is colder.
1595match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1596 ConstVariableValue::Unknown { .. } => false,
1597 ConstVariableValue::Known { .. } => true,
1598 }
1599 }
1600 }
1601 }
16021603/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1604pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1605if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1606self.obligation_inspector.get().is_none(),
1607"shouldn't override a set obligation inspector"
1608);
1609self.obligation_inspector.set(Some(inspector));
1610 }
1611}
16121613/// Helper for [InferCtxt::ty_or_const_infer_var_changed] (see comment on that), currently
1614/// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1615#[derive(#[automatically_derived]
impl ::core::marker::Copy for TyOrConstInferVar { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TyOrConstInferVar {
#[inline]
fn clone(&self) -> TyOrConstInferVar {
let _: ::core::clone::AssertParamIsClone<TyVid>;
let _: ::core::clone::AssertParamIsClone<IntVid>;
let _: ::core::clone::AssertParamIsClone<FloatVid>;
let _: ::core::clone::AssertParamIsClone<ConstVid>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for TyOrConstInferVar {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TyOrConstInferVar::Ty(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ty",
&__self_0),
TyOrConstInferVar::TyInt(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "TyInt",
&__self_0),
TyOrConstInferVar::TyFloat(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TyFloat", &__self_0),
TyOrConstInferVar::Const(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Const",
&__self_0),
}
}
}Debug)]
1616pub enum TyOrConstInferVar {
1617/// Equivalent to `ty::Infer(ty::TyVar(_))`.
1618Ty(TyVid),
1619/// Equivalent to `ty::Infer(ty::IntVar(_))`.
1620TyInt(IntVid),
1621/// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1622TyFloat(FloatVid),
16231624/// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1625Const(ConstVid),
1626}
16271628impl<'tcx> TyOrConstInferVar {
1629/// Tries to extract an inference variable from a type or a constant, returns `None`
1630 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1631 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1632pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1633match arg.kind() {
1634GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1635GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1636GenericArgKind::Lifetime(_) => None,
1637 }
1638 }
16391640/// Tries to extract an inference variable from a type or a constant, returns `None`
1641 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1642 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1643pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1644match term.kind() {
1645TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1646TermKind::Const(ct) => Self::maybe_from_const(ct),
1647 }
1648 }
16491650/// Tries to extract an inference variable from a type, returns `None`
1651 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1652fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1653match *ty.kind() {
1654 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1655 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1656 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1657_ => None,
1658 }
1659 }
16601661/// Tries to extract an inference variable from a constant, returns `None`
1662 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1663fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1664match ct.kind() {
1665 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1666_ => None,
1667 }
1668 }
1669}
16701671/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1672/// Used only for diagnostics.
1673struct InferenceLiteralEraser<'tcx> {
1674 tcx: TyCtxt<'tcx>,
1675}
16761677impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1678fn cx(&self) -> TyCtxt<'tcx> {
1679self.tcx
1680 }
16811682fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1683match ty.kind() {
1684 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1685 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1686_ => ty.super_fold_with(self),
1687 }
1688 }
1689}
16901691impl<'tcx> TypeTrace<'tcx> {
1692pub fn span(&self) -> Span {
1693self.cause.span
1694 }
16951696pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1697TypeTrace {
1698 cause: cause.clone(),
1699 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1700 }
1701 }
17021703pub fn trait_refs(
1704 cause: &ObligationCause<'tcx>,
1705 a: ty::TraitRef<'tcx>,
1706 b: ty::TraitRef<'tcx>,
1707 ) -> TypeTrace<'tcx> {
1708TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1709 }
17101711pub fn consts(
1712 cause: &ObligationCause<'tcx>,
1713 a: ty::Const<'tcx>,
1714 b: ty::Const<'tcx>,
1715 ) -> TypeTrace<'tcx> {
1716TypeTrace {
1717 cause: cause.clone(),
1718 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1719 }
1720 }
1721}
17221723impl<'tcx> SubregionOrigin<'tcx> {
1724pub fn span(&self) -> Span {
1725match *self {
1726 SubregionOrigin::Subtype(ref a) => a.span(),
1727 SubregionOrigin::RelateObjectBound(a) => a,
1728 SubregionOrigin::RelateParamBound(a, ..) => a,
1729 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1730 SubregionOrigin::Reborrow(a) => a,
1731 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1732 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1733 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1734 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1735 SubregionOrigin::SolverRegionConstraint(a) => a,
1736 }
1737 }
17381739pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1740where
1741F: FnOnce() -> Self,
1742 {
1743match *cause.code() {
1744 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1745 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1746 }
17471748 traits::ObligationCauseCode::CompareImplItem {
1749 impl_item_def_id,
1750 trait_item_def_id,
1751 kind: _,
1752 } => SubregionOrigin::CompareImplItemObligation {
1753 span: cause.span,
1754impl_item_def_id,
1755trait_item_def_id,
1756 },
17571758 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1759 impl_item_def_id,
1760 trait_item_def_id,
1761 } => SubregionOrigin::CheckAssociatedTypeBounds {
1762impl_item_def_id,
1763trait_item_def_id,
1764 parent: Box::new(default()),
1765 },
17661767 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1768 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1769 }
17701771 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1772 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1773 }
17741775_ => default(),
1776 }
1777 }
1778}
17791780impl<'tcx> RegionVariableOrigin<'tcx> {
1781pub fn span(&self) -> Span {
1782match *self {
1783 RegionVariableOrigin::Misc(a)
1784 | RegionVariableOrigin::PatternRegion(a)
1785 | RegionVariableOrigin::BorrowRegion(a)
1786 | RegionVariableOrigin::Autoref(a)
1787 | RegionVariableOrigin::Coercion(a)
1788 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1789 | RegionVariableOrigin::BoundRegion(a, ..)
1790 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1791 RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable used with `span`"))bug!("NLL variable used with `span`"),
1792 }
1793 }
1794}
17951796impl<'tcx> InferCtxt<'tcx> {
1797/// Given a [`hir::Block`], get the span of its last expression or
1798 /// statement, peeling off any inner blocks.
1799pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1800let block = block.innermost_block();
1801if let Some(expr) = &block.expr {
1802expr.span
1803 } else if let Some(stmt) = block.stmts.last() {
1804// possibly incorrect trailing `;` in the else arm
1805stmt.span
1806 } else {
1807// empty block; point at its entirety
1808block.span
1809 }
1810 }
18111812/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1813 /// of its last expression or statement, peeling off any inner blocks.
1814pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1815match self.tcx.hir_node(hir_id) {
1816 hir::Node::Block(blk)
1817 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1818self.find_block_span(blk)
1819 }
1820 hir::Node::Expr(e) => e.span,
1821_ => DUMMY_SP,
1822 }
1823 }
1824}
18251826type SolverRegionConstraint<'tcx> =
1827 rustc_type_ir::region_constraint::RegionConstraint<TyCtxt<'tcx>>;
18281829#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for SolverRegionConstraintStorage<'tcx> {
#[inline]
fn clone(&self) -> SolverRegionConstraintStorage<'tcx> {
SolverRegionConstraintStorage(::core::clone::Clone::clone(&self.0))
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for SolverRegionConstraintStorage<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SolverRegionConstraintStorage", &&self.0)
}
}Debug)]
1830struct SolverRegionConstraintStorage<'tcx>(SolverRegionConstraint<'tcx>);
18311832impl<'tcx> SolverRegionConstraintStorage<'tcx> {
1833fn new() -> Self {
1834SolverRegionConstraintStorage(SolverRegionConstraint::And(Box::new([])))
1835 }
18361837fn get_constraint(&self) -> SolverRegionConstraint<'tcx> {
1838self.0.clone()
1839 }
18401841fn pop(&mut self) -> Option<SolverRegionConstraint<'tcx>> {
1842match &mut self.0 {
1843SolverRegionConstraint::And(and) => {
1844let mut and = core::mem::take(and).into_iter().collect::<Vec<_>>();
1845let popped = and.pop()?;
1846self.0 = SolverRegionConstraint::And(and.into_boxed_slice());
1847Some(popped)
1848 }
1849_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1850 }
1851 }
18521853#[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("push",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1853u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["self",
"constraint"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint)
as &dyn 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;
}
{
match &mut self.0 {
SolverRegionConstraint::And(and) => {
let and =
core::mem::take(and).into_iter().chain([constraint]).collect::<Vec<_>>().into_boxed_slice();
self.0 = SolverRegionConstraint::And(and);
}
_ =>
::core::panicking::panic("internal error: entered unreachable code"),
}
}
}
}#[instrument(level = "debug")]1854fn push(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1855match &mut self.0 {
1856 SolverRegionConstraint::And(and) => {
1857let and = core::mem::take(and)
1858 .into_iter()
1859 .chain([constraint])
1860 .collect::<Vec<_>>()
1861 .into_boxed_slice();
1862self.0 = SolverRegionConstraint::And(and);
1863 }
1864_ => unreachable!(),
1865 }
1866 }
18671868#[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("overwrite_solver_region_constraint",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1868u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["constraint"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint)
as &dyn 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;
}
{
if !constraint.is_and() {
self.0 =
SolverRegionConstraint::And(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[constraint])).into_boxed_slice())
} else { self.0 = constraint; }
}
}
}#[instrument(level = "debug", skip(self))]1869fn overwrite_solver_region_constraint(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1870if !constraint.is_and() {
1871self.0 = SolverRegionConstraint::And(vec![constraint].into_boxed_slice())
1872 } else {
1873self.0 = constraint;
1874 }
1875 }
1876}