1use std::cell::{Cell, RefCell};
2use std::fmt;
34pub use at::DefineOpaqueTypes;
5use free_regions::RegionRelations;
6pub use freshen::TypeFreshener;
7use lexical_region_resolve::LexicalRegionResolutions;
8pub use lexical_region_resolve::RegionResolutionError;
9pub use opaque_types::{OpaqueTypeStorage, OpaqueTypeStorageEntries, OpaqueTypeTable};
10use region_constraints::{
11GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
12};
13pub use relate::combine::PredicateEmittingRelation;
14use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
15use rustc_data_structures::snapshot_vecas sv;
16use rustc_data_structures::undo_log::{Rollback, UndoLogs};
17use rustc_data_structures::unify::{selfas ut, UnifyKey, UnifyValue};
18use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
19use rustc_hir::def_id::{DefId, LocalDefId};
20use rustc_hir::{selfas hir, HirId};
21use rustc_index::IndexVec;
22use rustc_macros::extension;
23pub use rustc_macros::{TypeFoldable, TypeVisitable};
24use rustc_middle::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, OpaqueTypeKey, ProvisionalHiddenType,
33PseudoCanonicalInput, RegionExt, Term, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder,
34TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
35};
36use rustc_span::{DUMMY_SP, Span, Symbol};
37use rustc_type_ir::{CanonicalizerState, MayBeErased};
38use snapshot::undo_log::InferCtxtUndoLogs;
39use tracing::{debug, instrument};
40use ty::solve::TyOrConstInferVar;
41use type_variable::TypeVariableOrigin;
4243use crate::infer::snapshot::undo_log::UndoLog;
44use crate::infer::type_variable::{FloatVariableOrigin, TypeVariableValue};
45use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
46use crate::traits::{
47self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
48TraitEngine,
49};
5051pub mod at;
52pub mod canonical;
53mod context;
54mod free_regions;
55mod freshen;
56mod lexical_region_resolve;
57mod opaque_types;
58pub mod outlives;
59mod projection;
60pub mod region_constraints;
61pub mod relate;
62pub mod resolve;
63pub(crate) mod snapshot;
64mod type_variable;
65mod unify_key;
6667/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
68/// around `PredicateObligations<'tcx>`, but it has one important property:
69/// because `InferOk` is marked with `#[must_use]`, if you have a method
70/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
71/// `infcx.f()?;` you'll get a warning about the obligations being discarded
72/// without use, which is probably unintentional and has been a source of bugs
73/// in the past.
74#[must_use]
75#[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)]
76pub struct InferOk<'tcx, T> {
77pub value: T,
78pub obligations: PredicateObligations<'tcx>,
79}
80pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
8182pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
8384pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
85 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
86>;
8788/// This type contains all the things within `InferCtxt` that sit within a
89/// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
90/// operations are hot enough that we want only one call to `borrow_mut` per
91/// call to `start_snapshot` and `rollback_to`.
92#[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)]
93pub struct InferCtxtInner<'tcx> {
94 undo_log: InferCtxtUndoLogs<'tcx>,
9596/// Cache for projections.
97 ///
98 /// This cache is snapshotted along with the infcx.
99projection_cache: traits::ProjectionCacheStorage<'tcx>,
100101/// We instantiate `UnificationTable` with `bounds<Ty>` because the types
102 /// that might instantiate a general type variable have an order,
103 /// represented by its upper and lower bounds.
104type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
105106/// Map from const parameter variable to the kind of const it represents.
107const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
108109/// Map from integral variable to the kind of integer it represents.
110int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
111112/// Map from floating variable to the kind of float it represents.
113float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
114115/// Map from floating variable to the origin span it came from, and the HirId that should be
116 /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
117 /// so can be removed once the `f32` fallback is removed.
118float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
119120/// Tracks the set of region variables and the constraints between them.
121 ///
122 /// This is initially `Some(_)` but when
123 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
124 /// -- further attempts to perform unification, etc., may fail if new
125 /// region constraints would've been added.
126region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
127128/// Used by the next solver when `-Zassumptions-on-binders` is set.
129solver_region_constraint_storage: SolverRegionConstraintStorage<'tcx>,
130131/// A set of constraints that regionck must validate.
132 ///
133 /// Each constraint has the form `T:'a`, meaning "some type `T` must
134 /// outlive the lifetime 'a". These constraints derive from
135 /// instantiated type parameters. So if you had a struct defined
136 /// like the following:
137 /// ```ignore (illustrative)
138 /// struct Foo<T: 'static> { ... }
139 /// ```
140 /// In some expression `let x = Foo { ... }`, it will
141 /// instantiate the type parameter `T` with a fresh type `$0`. At
142 /// the same time, it will record a region obligation of
143 /// `$0: 'static`. This will get checked later by regionck. (We
144 /// can't generally check these things right away because we have
145 /// to wait until types are resolved.)
146region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
147148/// The outlives bounds that we assume must hold about placeholders that
149 /// come from instantiating the binder of coroutine-witnesses. These bounds
150 /// are deduced from the well-formedness of the witness's types, and are
151 /// necessary because of the way we anonymize the regions in a coroutine,
152 /// which may cause types to no longer be considered well-formed.
153region_assumptions: Vec<ty::ArgOutlivesClause<'tcx>>,
154155/// `-Znext-solver`: Successfully proven goals during HIR typeck which
156 /// reference inference variables and get reproven in case MIR type check
157 /// fails to prove something.
158 ///
159 /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
160hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
161162/// Caches for opaque type inference.
163opaque_type_storage: OpaqueTypeStorage<'tcx>,
164}
165166impl<'tcx> InferCtxtInner<'tcx> {
167fn new() -> InferCtxtInner<'tcx> {
168InferCtxtInner {
169 undo_log: InferCtxtUndoLogs::default(),
170171 projection_cache: Default::default(),
172 type_variable_storage: Default::default(),
173 const_unification_storage: Default::default(),
174 int_unification_storage: Default::default(),
175 float_unification_storage: Default::default(),
176 float_origin_origin_storage: Default::default(),
177 region_constraint_storage: Some(Default::default()),
178 solver_region_constraint_storage: SolverRegionConstraintStorage::new(),
179 region_obligations: Default::default(),
180 region_assumptions: Default::default(),
181 hir_typeck_potentially_region_dependent_goals: Default::default(),
182 opaque_type_storage: Default::default(),
183 }
184 }
185186#[inline]
187pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
188&self.region_obligations
189 }
190191#[inline]
192pub fn region_assumptions(&self) -> &[ty::ArgOutlivesClause<'tcx>] {
193&self.region_assumptions
194 }
195196#[inline]
197pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
198self.projection_cache.with_log(&mut self.undo_log)
199 }
200201#[inline]
202fn try_type_variables_probe_ref(&self, vid: ty::TyVid) -> Option<&TypeVariableValue<'tcx>> {
203// Uses a read-only view of the unification table, this way we don't
204 // need an undo log.
205self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
206 }
207208#[inline]
209fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
210self.type_variable_storage.with_log(&mut self.undo_log)
211 }
212213#[inline]
214pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
215self.opaque_type_storage.with_log(&mut self.undo_log)
216 }
217218#[inline]
219fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
220self.int_unification_storage.with_log(&mut self.undo_log)
221 }
222223#[inline]
224fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
225self.float_unification_storage.with_log(&mut self.undo_log)
226 }
227228#[inline]
229fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
230self.const_unification_storage.with_log(&mut self.undo_log)
231 }
232233#[inline]
234pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
235self.region_constraint_storage
236 .as_mut()
237 .expect("region constraints already solved")
238 .with_log(&mut self.undo_log)
239 }
240}
241242pub struct InferCtxt<'tcx> {
243pub tcx: TyCtxt<'tcx>,
244245/// The mode of this inference context, see the struct documentation
246 /// for more details.
247typing_mode: TypingMode<'tcx>,
248249/// Whether this inference context should care about region obligations in
250 /// the root universe. Most notably, this is used during HIR typeck as region
251 /// solving is left to borrowck instead.
252 ///
253 /// This is used in the old solver to enable the generation of regions constraints.
254 /// In the new solver its only used inside the InferCtxt's `Drop` implementation:
255 /// if we're considering regions, and new opaques are registered, we panic.
256pub considering_regions: bool,
257/// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
258 /// need to make sure we don't rely on region identity in the trait solver or when
259 /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
260 /// free region with a unique inference variable. If HIR typeck ends up depending on two
261 /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
262 /// resulting in an ICE.
263 ///
264 /// The trait solver sometimes depends on regions being identical. As a concrete example
265 /// the trait solver ignores other candidates if one candidate exists without any constraints.
266 /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
267 /// occurrence of `'a` with a unique region the goal now equates these regions. See
268 /// the tests in trait-system-refactor-initiative#27 for concrete examples.
269 ///
270 /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
271 /// This is still insufficient as inference variables may *hide* region variables, so e.g.
272 /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
273 /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
274 /// stash all successfully proven goals which reference inference variables and then reprove
275 /// them after writeback.
276pub in_hir_typeck: bool,
277278/// If set, this flag causes us to skip the 'leak check' during
279 /// higher-ranked subtyping operations. This flag is a temporary one used
280 /// to manage the removal of the leak-check: for the time being, we still run the
281 /// leak-check, but we issue warnings.
282skip_leak_check: bool,
283284pub inner: RefCell<InferCtxtInner<'tcx>>,
285286/// Once region inference is done, the values for each variable.
287lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
288289/// Caches the results of trait selection. This cache is used
290 /// for things that depends on inference variables or placeholders.
291pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
292293/// Caches the results of trait evaluation. This cache is used
294 /// for things that depends on inference variables or placeholders.
295pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
296297/// The set of predicates on which errors have been reported, to
298 /// avoid reporting the same error twice.
299pub reported_trait_errors:
300RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
301302pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
303304/// When an error occurs, we want to avoid reporting "derived"
305 /// errors that are due to this original failure. We have this
306 /// flag that one can set whenever one creates a type-error that
307 /// is due to an error in a prior pass.
308 ///
309 /// Don't read this flag directly, call `is_tainted_by_errors()`
310 /// and `set_tainted_by_errors()`.
311tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
312313/// What is the innermost universe we have created? Starts out as
314 /// `UniverseIndex::root()` but grows from there as we enter
315 /// universal quantifiers.
316 ///
317 /// N.B., at present, we exclude the universal quantifiers on the
318 /// item we are type-checking, and just consider those names as
319 /// part of the root universe. So this would only get incremented
320 /// when we enter into a higher-ranked (`for<..>`) type or trait
321 /// bound.
322universe: Cell<ty::UniverseIndex>,
323324/// List of assumed wellformed types which we can derive implied
325 /// bounds on a `for<...>` from. Only used unstabley and by the
326 /// new solver.
327//
328 // FIXME(-Zassumptions-on-binders): This and `universe` should probably be
329 // in `InferCtxtInner` so they can participate in rollbacks and whatnot
330placeholder_assumptions_for_next_solver: RefCell<
331FxIndexMap<
332 ty::UniverseIndex,
333Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
334 >,
335 >,
336337 next_trait_solver: bool,
338339/// We have a `recursion_depth_exceeding_limit` FCW to mitigate breakages
340 /// caused by enabling the next solver globally. But the next solver is
341 /// already used by default in some places so we know they won't have
342 /// additional breakages. We also don't want spurious result in coherence
343 /// checking so we disable the FCW there as well.
344enable_next_solver_overflow_fcw: bool,
345346pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
347348/// State reused by each new canonicalizer, and then cleared (but not deallocated) once the
349 /// canonicalizer is finished. A performance win, because it avoids reallocating new
350 /// vecs/hashmaps for every canonicalizer.
351pub canonicalizer_state: RefCell<CanonicalizerState<TyCtxt<'tcx>>>,
352}
353354impl<'tcx> Dropfor InferCtxt<'tcx> {
355fn drop(&mut self) {
356let mut inner = self.inner.borrow_mut();
357let opaque_type_storage = &mut inner.opaque_type_storage;
358359// No need for the drop bomb when we're in `TypingMode::PostTypeckUntilBorrowck`, and the `InferCtxt`
360 // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
361 // in relation to regions. In some places *after* typeck that aren't borrowck, we use
362 // `TypingMode::PostTypeckUntilBorrowck` to prevent defining opaque types and we simply don't care about regions.
363match self.typing_mode_raw() {
364TypingMode::Coherence365 | TypingMode::Typeck { .. }
366 | TypingMode::PostBorrowck { .. }
367 | TypingMode::Reflection368 | TypingMode::PostAnalysis369 | TypingMode::Codegen => {}
370// In erased mode, the opaque type storage is always empty
371TypingMode::ErasedNotCoherence(..) => {}
372TypingMode::PostTypeckUntilBorrowck { .. } => {
373if !self.considering_regions {
374return;
375 }
376 }
377 }
378379if !opaque_type_storage.is_empty() {
380 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:?}")));
381 }
382 }
383}
384385/// See the `error_reporting` module for more details.
386#[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)]
387pub enum ValuePairs<'tcx> {
388 Regions(ExpectedFound<ty::Region<'tcx>>),
389 Terms(ExpectedFound<ty::Term<'tcx>>),
390 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
391 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
392 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
393 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
394 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
395}
396397impl<'tcx> ValuePairs<'tcx> {
398pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
399if let ValuePairs::Terms(ExpectedFound { expected, found }) = self400 && let Some(expected) = expected.as_type()
401 && let Some(found) = found.as_type()
402 {
403Some((expected, found))
404 } else {
405None406 }
407 }
408}
409410/// The trace designates the path through inference that we took to
411/// encounter an error or subtyping constraint.
412///
413/// See the `error_reporting` module for more details.
414#[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)]
415pub struct TypeTrace<'tcx> {
416pub cause: ObligationCause<'tcx>,
417pub values: ValuePairs<'tcx>,
418}
419420/// The origin of a `r1 <= r2` constraint.
421///
422/// See `error_reporting` module for more details
423#[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)]
424pub enum SubregionOrigin<'tcx> {
425/// Arose from a subtyping relation
426Subtype(Box<TypeTrace<'tcx>>),
427428/// When casting `&'a T` to an `&'b Trait` object,
429 /// relating `'a` to `'b`.
430RelateObjectBound(Span),
431432/// Some type parameter was instantiated with the given type,
433 /// and that type must outlive some region.
434RelateParamBound(Span, Ty<'tcx>, Option<Span>),
435436/// The given region parameter was instantiated with a region
437 /// that must outlive some other region.
438RelateRegionParamBound(Span, Option<Ty<'tcx>>),
439440/// Creating a pointer `b` to contents of another reference.
441Reborrow(Span),
442443/// (&'a &'b T) where a >= b
444ReferenceOutlivesReferent(Ty<'tcx>, Span),
445446/// Comparing the signature and requirements of an impl method against
447 /// the containing trait.
448CompareImplItemObligation {
449 span: Span,
450 impl_item_def_id: LocalDefId,
451 trait_item_def_id: DefId,
452 },
453454/// Checking that the bounds of a trait's associated type hold for a given impl.
455CheckAssociatedTypeBounds {
456 parent: Box<SubregionOrigin<'tcx>>,
457 impl_item_def_id: LocalDefId,
458 trait_item_def_id: DefId,
459 },
460461 AscribeUserTypeProvePredicate(Span),
462463// FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
464 // proper diagnostics for solver region constraints.
465SolverRegionConstraint(Span),
466}
467468// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
469#[cfg(target_pointer_width = "64")]
470const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
471472impl<'tcx> SubregionOrigin<'tcx> {
473pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
474match self {
475Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
476Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
477Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
478_ => ConstraintCategory::BoringNoLocation,
479 }
480 }
481}
482483/// Times when we replace bound regions with existentials:
484#[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)]
485pub enum BoundRegionConversionTime {
486/// when a fn is called
487FnCall,
488489/// when two higher-ranked types are compared
490HigherRankedType,
491492/// when projecting an associated type
493AssocTypeProjection(DefId),
494}
495496/// Reasons to create a region inference variable.
497///
498/// See `error_reporting` module for more details.
499#[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)]
500pub enum RegionVariableOrigin<'tcx> {
501/// Region variables created for ill-categorized reasons.
502 ///
503 /// They mostly indicate places in need of refactoring.
504Misc(Span),
505506/// Regions created by a `&P` or `[...]` pattern.
507PatternRegion(Span),
508509/// Regions created by `&` operator.
510BorrowRegion(Span),
511512/// Regions created as part of an autoref of a method receiver.
513Autoref(Span),
514515/// Regions created as part of an automatic coercion.
516Coercion(Span),
517518/// Region variables created as the values for early-bound regions.
519 ///
520 /// FIXME(@lcnr): This should also store a `DefId`, similar to
521 /// `TypeVariableOrigin`.
522RegionParameterDefinition(Span, Symbol),
523524/// Region variables created when instantiating a binder with
525 /// existential variables, e.g. when calling a function or method.
526BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
527528 UpvarRegion(ty::UpvarId, Span),
529530/// This origin is used for the inference variables that we create
531 /// during NLL region processing.
532Nll(NllRegionVariableOrigin<'tcx>),
533}
534535#[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)]
536pub enum NllRegionVariableOrigin<'tcx> {
537/// During NLL region processing, we create variables for free
538 /// regions that we encounter in the function signature and
539 /// elsewhere. This origin indices we've got one of those.
540FreeRegion,
541542/// "Universal" instantiation of a higher-ranked region (e.g.,
543 /// from a `for<'a> T` binder). Meant to represent "any region".
544Placeholder(ty::PlaceholderRegion<'tcx>),
545546 Existential {
547 name: Option<Symbol>,
548 },
549}
550551#[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)]
552pub struct FixupError {
553 unresolved: TyOrConstInferVar,
554}
555556impl fmt::Displayfor FixupError {
557fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
558match self.unresolved {
559 TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
560f,
561"cannot determine the type of this integer; \
562 add a suffix to specify the type explicitly"
563),
564 TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
565f,
566"cannot determine the type of this number; \
567 add a suffix to specify the type explicitly"
568),
569 TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
570 TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
571 }
572 }
573}
574575/// See the `region_obligations` field for more information.
576#[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)]
577pub struct TypeOutlivesConstraint<'tcx> {
578pub sub_region: ty::Region<'tcx>,
579pub sup_type: Ty<'tcx>,
580pub origin: SubregionOrigin<'tcx>,
581}
582583/// Used to configure inference contexts before their creation.
584pub struct InferCtxtBuilder<'tcx> {
585 tcx: TyCtxt<'tcx>,
586 considering_regions: bool,
587 in_hir_typeck: bool,
588 skip_leak_check: bool,
589/// Whether we should use the new trait solver in the local inference context,
590 /// which affects things like which solver is used in `predicate_may_hold`.
591next_trait_solver: bool,
592 enable_next_solver_overflow_fcw: bool,
593}
594595impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
InferCtxtBuilder {
tcx: self,
considering_regions: true,
in_hir_typeck: false,
skip_leak_check: false,
next_trait_solver: self.next_trait_solver_globally(),
enable_next_solver_overflow_fcw: true,
}
}
}#[extension(pub trait TyCtxtInferExt<'tcx>)]596impl<'tcx> TyCtxt<'tcx> {
597fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
598InferCtxtBuilder {
599 tcx: self,
600 considering_regions: true,
601 in_hir_typeck: false,
602 skip_leak_check: false,
603 next_trait_solver: self.next_trait_solver_globally(),
604 enable_next_solver_overflow_fcw: true,
605 }
606 }
607}
608609impl<'tcx> InferCtxtBuilder<'tcx> {
610pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
611self.next_trait_solver = next_trait_solver;
612self613 }
614615pub fn enable_next_solver_overflow_fcw(
616mut self,
617 enable_next_solver_overflow_fcw: bool,
618 ) -> Self {
619self.enable_next_solver_overflow_fcw = enable_next_solver_overflow_fcw;
620self621 }
622623pub fn ignoring_regions(mut self) -> Self {
624self.considering_regions = false;
625self626 }
627628pub fn in_hir_typeck(mut self) -> Self {
629self.in_hir_typeck = true;
630self631 }
632633pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
634self.skip_leak_check = skip_leak_check;
635self636 }
637638/// Given a canonical value `C` as a starting point, create an
639 /// inference context that contains each of the bound values
640 /// within instantiated as a fresh variable. The `f` closure is
641 /// invoked with the new infcx, along with the instantiated value
642 /// `V` and a instantiation `S`. This instantiation `S` maps from
643 /// the bound values in `C` to their instantiated values in `V`
644 /// (in other words, `S(C) = V`).
645pub fn build_with_canonical<T>(
646mut self,
647 span: Span,
648 input: &CanonicalQueryInput<'tcx, T>,
649 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
650where
651T: TypeFoldable<TyCtxt<'tcx>>,
652 {
653let infcx = self.build(input.typing_mode.0);
654let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
655 (infcx, value, args)
656 }
657658pub fn build_with_typing_env(
659mut self,
660 typing_env: TypingEnv<'tcx>,
661 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
662 (self.build(typing_env.typing_mode()), typing_env.param_env)
663 }
664665pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
666let InferCtxtBuilder {
667 tcx,
668 considering_regions,
669 in_hir_typeck,
670 skip_leak_check,
671 next_trait_solver,
672 enable_next_solver_overflow_fcw,
673 } = *self;
674InferCtxt {
675tcx,
676typing_mode,
677considering_regions,
678in_hir_typeck,
679skip_leak_check,
680 inner: RefCell::new(InferCtxtInner::new()),
681 lexical_region_resolutions: RefCell::new(None),
682 selection_cache: Default::default(),
683 evaluation_cache: Default::default(),
684 reported_trait_errors: Default::default(),
685 reported_signature_mismatch: Default::default(),
686 tainted_by_errors: Cell::new(None),
687 universe: Cell::new(ty::UniverseIndex::ROOT),
688 placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
689next_trait_solver,
690enable_next_solver_overflow_fcw,
691 obligation_inspector: Cell::new(None),
692 canonicalizer_state: Default::default(),
693 }
694 }
695}
696697impl<'tcx, T> InferOk<'tcx, T> {
698/// Extracts `value`, registering any obligations into `fulfill_cx`.
699pub fn into_value_registering_obligations<E: 'tcx>(
700self,
701 infcx: &InferCtxt<'tcx>,
702 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
703 ) -> T {
704let InferOk { value, obligations } = self;
705fulfill_cx.register_predicate_obligations(infcx, obligations);
706value707 }
708}
709710impl<'tcx> InferOk<'tcx, ()> {
711pub fn into_obligations(self) -> PredicateObligations<'tcx> {
712self.obligations
713 }
714}
715716impl<'tcx> InferCtxt<'tcx> {
717pub fn dcx(&self) -> DiagCtxtHandle<'_> {
718self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
719 }
720721pub fn next_trait_solver(&self) -> bool {
722self.next_trait_solver
723 }
724725/// This method is deliberately called `..._raw`,
726 /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
727 /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
728 /// more information.
729 ///
730 /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
731 /// works as a kind of store for for example type unification information.
732 /// `InferCtxt` is also often used outside the trait solver during typeck.
733 /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
734 /// To make sure these two uses are never confused, we want to statically encode this information.
735 ///
736 /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
737 /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
738 /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
739 /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
740 /// match on the variant and can safely ignore it.
741 ///
742 /// Prefer non-raw apis if available. e.g.,
743 /// - On the `FnCtxt`
744 /// - on the `SelectionCtxt`
745#[inline(always)]
746pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
747self.typing_mode
748 }
749750#[inline(always)]
751pub fn disable_trait_solver_fast_paths(&self) -> bool {
752self.tcx.disable_trait_solver_fast_paths()
753 }
754755/// Returns the origin of the type variable identified by `vid`.
756 ///
757 /// No attempt is made to resolve `vid` to its root variable.
758pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
759self.inner.borrow_mut().type_variables().var_origin(vid)
760 }
761762/// Returns the origin of the float type variable identified by `vid`.
763 ///
764 /// No attempt is made to resolve `vid` to its root variable.
765pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
766self.inner.borrow_mut().float_origin_origin_storage[vid]
767 }
768769/// Returns the origin of the const variable identified by `vid`
770// FIXME: We should store origins separately from the unification table
771 // so this doesn't need to be optional.
772pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
773match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
774 ConstVariableValue::Known { .. } => None,
775 ConstVariableValue::Unknown { origin, .. } => Some(origin),
776 }
777 }
778779pub fn unresolved_root_variables(&self) -> (Vec<TyVid>, Vec<ty::IntVid>, Vec<ty::FloatVid>) {
780let mut inner = self.inner.borrow_mut();
781782let ty = inner.type_variables().unresolved_root_variables();
783784let int = unresolved_root_variables_of(
785inner.int_unification_table(),
786 ty::IntVarValue::is_unknown,
787 );
788789let float = unresolved_root_variables_of(
790inner.float_unification_table(),
791 ty::FloatVarValue::is_unknown,
792 );
793794 (ty, int, float)
795 }
796797#[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(797u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("vis")
}> =
::tracing::__macro_support::FieldName::new("vis");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin,
a, b, vis);
}
}
}#[instrument(skip(self), level = "debug")]798pub fn sub_regions(
799&self,
800 origin: SubregionOrigin<'tcx>,
801 a: ty::Region<'tcx>,
802 b: ty::Region<'tcx>,
803 vis: ty::VisibleForLeakCheck,
804 ) {
805self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
806 }
807808#[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(808u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("vis")
}> =
::tracing::__macro_support::FieldName::new("vis");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin,
a, b, vis);
}
}
}#[instrument(skip(self), level = "debug")]809pub fn equate_regions(
810&self,
811 origin: SubregionOrigin<'tcx>,
812 a: ty::Region<'tcx>,
813 b: ty::Region<'tcx>,
814 vis: ty::VisibleForLeakCheck,
815 ) {
816self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
817 }
818819/// Processes a `Coerce` predicate from the fulfillment context.
820 /// This is NOT the preferred way to handle coercion, which is to
821 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
822 ///
823 /// This method here is actually a fallback that winds up being
824 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
825 /// and records a coercion predicate. Presently, this method is equivalent
826 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
827 /// actually requiring `a <: b`. This is of course a valid coercion,
828 /// but it's not as flexible as `FnCtxt::coerce` would be.
829 ///
830 /// (We may refactor this in the future, but there are a number of
831 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
832 /// records adjustments that are required on the HIR in order to perform
833 /// the coercion, and we don't currently have a way to manage that.)
834pub fn coerce_predicate(
835&self,
836 cause: &ObligationCause<'tcx>,
837 param_env: ty::ParamEnv<'tcx>,
838 predicate: ty::PolyCoercePredicate<'tcx>,
839 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
840let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
841 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
842a: p.a,
843 b: p.b,
844 });
845self.subtype_predicate(cause, param_env, subtype_predicate)
846 }
847848pub fn subtype_predicate(
849&self,
850 cause: &ObligationCause<'tcx>,
851 param_env: ty::ParamEnv<'tcx>,
852 predicate: ty::PolySubtypePredicate<'tcx>,
853 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
854// Check for two unresolved inference variables, in which case we can
855 // make no progress. This is partly a micro-optimization, but it's
856 // also an opportunity to "sub-unify" the variables. This isn't
857 // *necessary* to prevent cycles, because they would eventually be sub-unified
858 // anyhow during generalization, but it helps with diagnostics (we can detect
859 // earlier that they are sub-unified).
860 //
861 // Note that we can just skip the binders here because
862 // type variables can't (at present, at
863 // least) capture any of the things bound by this binder.
864 //
865 // Note that this sub here is not just for diagnostics - it has semantic
866 // effects as well.
867let r_a = self.shallow_resolve(predicate.skip_binder().a);
868let r_b = self.shallow_resolve(predicate.skip_binder().b);
869match (r_a.kind(), r_b.kind()) {
870 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
871self.sub_unify_ty_vids_raw(a_vid, b_vid);
872return Err((a_vid, b_vid));
873 }
874_ => {}
875 }
876877self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
878if a_is_expected {
879Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
880 } else {
881Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
882 }
883 })
884 }
885886/// Number of type variables created so far.
887pub fn num_ty_vars(&self) -> usize {
888self.inner.borrow_mut().type_variables().num_vars()
889 }
890891pub fn next_ty_vid(&self, span: Span) -> TyVid {
892self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
893 }
894895pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
896self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
897 }
898899pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
900let origin = TypeVariableOrigin { span, param_def_id: None };
901self.inner.borrow_mut().type_variables().new_var(universe, origin)
902 }
903904pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
905self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
906 }
907908pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
909let vid = self.next_ty_vid_with_origin(origin);
910Ty::new_var(self.tcx, vid)
911 }
912913pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
914let vid = self.next_ty_vid_in_universe(span, universe);
915Ty::new_var(self.tcx, vid)
916 }
917918pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
919self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
920 }
921922pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
923let vid = self924 .inner
925 .borrow_mut()
926 .const_unification_table()
927 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
928 .vid;
929 ty::Const::new_var(self.tcx, vid)
930 }
931932pub fn next_const_var_in_universe(
933&self,
934 span: Span,
935 universe: ty::UniverseIndex,
936 ) -> ty::Const<'tcx> {
937let origin = ConstVariableOrigin { span, param_def_id: None };
938let vid = self939 .inner
940 .borrow_mut()
941 .const_unification_table()
942 .new_key(ConstVariableValue::Unknown { origin, universe })
943 .vid;
944 ty::Const::new_var(self.tcx, vid)
945 }
946947pub fn next_int_var(&self) -> Ty<'tcx> {
948let next_int_var_id =
949self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
950Ty::new_int_var(self.tcx, next_int_var_id)
951 }
952953pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
954let mut inner = self.inner.borrow_mut();
955let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
956let origin = FloatVariableOrigin { span, lint_id };
957let span_index = inner.float_origin_origin_storage.push(origin);
958if 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);
959Ty::new_float_var(self.tcx, next_float_var_id)
960 }
961962/// Creates a fresh region variable with the next available index.
963 /// The variable will be created in the maximum universe created
964 /// thus far, allowing it to name any region created thus far.
965pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
966self.next_region_var_in_universe(origin, self.universe())
967 }
968969/// Creates a fresh region variable with the next available index
970 /// in the given universe; typically, you can use
971 /// `next_region_var` and just use the maximal universe.
972pub fn next_region_var_in_universe(
973&self,
974 origin: RegionVariableOrigin<'tcx>,
975 universe: ty::UniverseIndex,
976 ) -> ty::Region<'tcx> {
977let region_var =
978self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
979 ty::Region::new_var(self.tcx, region_var)
980 }
981982pub fn next_term_var_of_alias_kind(
983&self,
984 alias_term: ty::AliasTerm<'tcx>,
985 span: Span,
986 ) -> ty::Term<'tcx> {
987match alias_term.kind {
988 ty::AliasTermKind::ProjectionTy { .. }
989 | ty::AliasTermKind::InherentTy { .. }
990 | ty::AliasTermKind::OpaqueTy { .. }
991 | ty::AliasTermKind::FreeTy { .. } => self.next_ty_var(span).into(),
992 ty::AliasTermKind::FreeConst { .. }
993 | ty::AliasTermKind::InherentConst { .. }
994 | ty::AliasTermKind::AnonConst { .. }
995 | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_var(span).into(),
996 }
997 }
998999/// Return the universe that the region `r` was created in. For
1000 /// most regions (e.g., `'static`, named regions from the user,
1001 /// etc) this is the root universe U0. For inference variables or
1002 /// placeholders, however, it will return the universe which they
1003 /// are associated.
1004pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1005self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1006 }
10071008/// Number of region variables created so far.
1009pub fn num_region_vars(&self) -> usize {
1010self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1011 }
10121013/// Just a convenient wrapper of `next_region_var` for using during NLL.
1014#[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(1014u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{ self.next_region_var(RegionVariableOrigin::Nll(origin)) }
}
}#[instrument(skip(self), level = "debug")]1015pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
1016self.next_region_var(RegionVariableOrigin::Nll(origin))
1017 }
10181019/// Just a convenient wrapper of `next_region_var` for using during NLL.
1020#[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(1020u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("universe")
}> =
::tracing::__macro_support::FieldName::new("universe");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&universe)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin),
universe)
}
}
}#[instrument(skip(self), level = "debug")]1021pub fn next_nll_region_var_in_universe(
1022&self,
1023 origin: NllRegionVariableOrigin<'tcx>,
1024 universe: ty::UniverseIndex,
1025 ) -> ty::Region<'tcx> {
1026self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1027 }
10281029pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1030match param.kind {
1031 GenericParamDefKind::Lifetime => {
1032// Create a region inference variable for the given
1033 // region parameter definition.
1034self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1035span, param.name,
1036 ))
1037 .into()
1038 }
1039 GenericParamDefKind::Type { .. } => {
1040// Create a type inference variable for the given
1041 // type parameter definition. The generic parameters are
1042 // for actual parameters that may be referred to by
1043 // the default of this type parameter, if it exists.
1044 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1045 // used in a path such as `Foo::<T, U>::new()` will
1046 // use an inference variable for `C` with `[T, U]`
1047 // as the generic parameters for the default, `(T, U)`.
1048let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1049self.universe(),
1050TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1051 );
10521053Ty::new_var(self.tcx, ty_var_id).into()
1054 }
1055 GenericParamDefKind::Const { .. } => {
1056let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1057let const_var_id = self1058 .inner
1059 .borrow_mut()
1060 .const_unification_table()
1061 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1062 .vid;
1063 ty::Const::new_var(self.tcx, const_var_id).into()
1064 }
1065 }
1066 }
10671068/// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1069 /// each type/region parameter to a fresh inference variable.
1070pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
1071GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1072 }
10731074/// Returns `true` if errors have been reported since this infcx was
1075 /// created. This is sometimes used as a heuristic to skip
1076 /// reporting errors that often occur as a result of earlier
1077 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1078 /// inference variables, regionck errors).
1079#[must_use = "this method does not have any side effects"]
1080pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1081self.tainted_by_errors.get()
1082 }
10831084/// Set the "tainted by errors" flag to true. We call this when we
1085 /// observe an error from a prior pass.
1086pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1087{
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:1087",
"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(1087u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("set_tainted_by_errors(ErrorGuaranteed)")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("set_tainted_by_errors(ErrorGuaranteed)");
1088self.tainted_by_errors.set(Some(e));
1089 }
10901091pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1092let mut inner = self.inner.borrow_mut();
1093let inner = &mut *inner;
1094inner.unwrap_region_constraints().var_origin(vid)
1095 }
10961097/// Clone the list of variable regions. This is used only during NLL processing
1098 /// to put the set of region variables into the NLL region context.
1099pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1100let inner = self.inner.borrow();
1101if !!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));
1102let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1103if !storage.data.is_empty() {
{ ::core::panicking::panic_fmt(format_args!("{0:#?}", storage.data)); }
};assert!(storage.data.is_empty(), "{:#?}", storage.data);
1104// We clone instead of taking because borrowck still wants to use the
1105 // inference context after calling this for diagnostics and the new
1106 // trait solver.
1107storage.var_infos.clone()
1108 }
11091110pub fn has_opaque_types_in_storage(&self) -> bool {
1111 !self.inner.borrow().opaque_type_storage.is_empty()
1112 }
11131114x;#[instrument(level = "debug", skip(self), ret)]1115pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1116self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1117 }
11181119x;#[instrument(level = "debug", skip(self), ret)]1120pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1121self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1122 }
11231124pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1125if !self.next_trait_solver() {
1126return false;
1127 }
11281129let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1130let inner = &mut *self.inner.borrow_mut();
1131let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1132inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1133if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1134let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1135if opaque_sub_vid == ty_sub_vid {
1136return true;
1137 }
1138 }
11391140false
1141})
1142 }
11431144/// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1145 ///
1146 /// This only checks for a subtype relation, it does not require equality.
1147pub fn opaques_with_sub_unified_hidden_type(
1148&self,
1149 ty_vid: TyVid,
1150 ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1151// Avoid accidentally allowing more code to compile with the old solver.
1152if !self.next_trait_solver() {
1153return ::alloc::vec::Vec::new()vec![];
1154 }
11551156let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1157let inner = &mut *self.inner.borrow_mut();
1158// This is iffy, can't call `type_variables()` as we're already
1159 // borrowing the `opaque_type_storage` here.
1160let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1161inner1162 .opaque_type_storage
1163 .iter_opaque_types()
1164 .filter_map(|(key, hidden_ty)| {
1165if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1166let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1167if opaque_sub_vid == ty_sub_vid {
1168return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1169self.tcx,
1170key.def_id.into(),
1171key.args,
1172 ));
1173 }
1174 }
11751176None1177 })
1178 .collect()
1179 }
11801181#[inline(always)]
1182pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1183if true {
if !!self.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.next_trait_solver()")
};
};debug_assert!(!self.next_trait_solver());
1184match self.typing_mode_raw().assert_not_erased() {
1185TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1186 | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types } => {
1187id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1188 }
1189// FIXME(#132279): This function is quite weird in post-analysis
1190 // and post-borrowck analysis mode. We may need to modify its uses
1191 // to support PostBorrowck in the old solver as well.
1192TypingMode::Coherence1193 | TypingMode::Reflection1194 | TypingMode::PostBorrowck { .. }
1195 | TypingMode::PostAnalysis1196 | TypingMode::Codegen => false,
1197 }
1198 }
11991200pub fn push_hir_typeck_potentially_region_dependent_goal(
1201&self,
1202 goal: PredicateObligation<'tcx>,
1203 ) {
1204let mut inner = self.inner.borrow_mut();
1205inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1206inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1207 }
12081209pub fn take_hir_typeck_potentially_region_dependent_goals(
1210&self,
1211 ) -> Vec<PredicateObligation<'tcx>> {
1212if !!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");
1213 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1214 }
12151216pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1217self.resolve_vars_if_possible(t).to_string()
1218 }
12191220/// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1221 /// universe index of `TyVar(vid)`.
1222pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1223use self::type_variable::TypeVariableValue;
12241225match self.inner.borrow_mut().type_variables().probe(vid) {
1226 TypeVariableValue::Known { value } => Ok(value),
1227 TypeVariableValue::Unknown { universe } => Err(universe),
1228 }
1229 }
12301231/// If `vid` resolves to a type, return that type. Otherwise return the root variable id for `vid`.
1232pub fn shallow_resolve_ty_var_or_get_root(&self, vid: TyVid) -> Result<Ty<'tcx>, TyVid> {
1233let (root, value) = self.inner.borrow_mut().type_variables().probe_with_root_vid(vid);
12341235match value {
1236 TypeVariableValue::Known { value } => Ok(value),
1237 TypeVariableValue::Unknown { universe: _ } => Err(root),
1238 }
1239 }
12401241pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1242if let ty::Infer(v) = *ty.kind() {
1243match v {
1244 ty::TyVar(v) => {
1245// Not entirely obvious: if `typ` is a type variable,
1246 // it can be resolved to an int/float variable, which
1247 // can then be recursively resolved, hence the
1248 // recursion. Note though that we prevent type
1249 // variables from unifying to other type variables
1250 // directly (though they may be embedded
1251 // structurally), and we prevent cycles in any case,
1252 // so this recursion should always be of very limited
1253 // depth.
1254 //
1255 // Note: if these two lines are combined into one we get
1256 // dynamic borrow errors on `self.inner`.
1257let (root_vid, value) =
1258self.inner.borrow_mut().type_variables().probe_with_root_vid(v);
1259value.known().map_or_else(
1260 || if root_vid == v { ty } else { Ty::new_var(self.tcx, root_vid) },
1261 |t| self.shallow_resolve(t),
1262 )
1263 }
12641265 ty::IntVar(v) => {
1266let (root, value) =
1267self.inner.borrow_mut().int_unification_table().inlined_probe_key_value(v);
1268match value {
1269 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1270 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1271 ty::IntVarValue::Unknown => {
1272if root == v {
1273ty1274 } else {
1275Ty::new_int_var(self.tcx, root)
1276 }
1277 }
1278 }
1279 }
12801281 ty::FloatVar(v) => {
1282let (root, value) = self1283 .inner
1284 .borrow_mut()
1285 .float_unification_table()
1286 .inlined_probe_key_value(v);
1287match value {
1288 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1289 ty::FloatVarValue::Unknown => {
1290if root == v {
1291ty1292 } else {
1293Ty::new_float_var(self.tcx, root)
1294 }
1295 }
1296 }
1297 }
12981299 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1300 }
1301 } else {
1302ty1303 }
1304 }
13051306pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1307match ct.kind() {
1308 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1309 InferConst::Var(vid) => {
1310let (root, value) = self1311 .inner
1312 .borrow_mut()
1313 .const_unification_table()
1314 .inlined_probe_key_value(vid);
1315value.known().unwrap_or_else(|| {
1316if root.vid == vid { ct } else { ty::Const::new_var(self.tcx, root.vid) }
1317 })
1318 }
1319 InferConst::Fresh(_) => ct,
1320 },
13211322 ty::ConstKind::Param(_)
1323 | ty::ConstKind::Bound(_, _)
1324 | ty::ConstKind::Placeholder(_)
1325 | ty::ConstKind::Alias(_, _)
1326 | ty::ConstKind::Value(_)
1327 | ty::ConstKind::Error(_)
1328 | ty::ConstKind::Expr(_) => ct,
1329 }
1330 }
13311332pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1333match term.kind() {
1334 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1335 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1336 }
1337 }
13381339pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1340self.inner.borrow_mut().type_variables().root_var(var)
1341 }
13421343/// If `ty` is an unresolved type variable, returns its root vid.
1344pub fn root_vid(&self, ty: Ty<'tcx>) -> Option<ty::TyVid> {
1345let (root, value) =
1346self.inner.borrow_mut().type_variables().inlined_probe_with_vid(ty.ty_vid()?);
1347value.is_unknown().then_some(root)
1348 }
13491350pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1351self.inner.borrow_mut().type_variables().sub_unify(a, b);
1352 }
13531354pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1355self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1356 }
13571358pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1359self.inner.borrow_mut().float_unification_table().find(var)
1360 }
13611362pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1363self.inner.borrow_mut().const_unification_table().find(var).vid
1364 }
13651366/// Resolves an int var to a rigid int type, if it was constrained to one,
1367 /// or else the root int var in the unification table.
1368pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1369let mut inner = self.inner.borrow_mut();
1370let value = inner.int_unification_table().probe_value(vid);
1371match value {
1372 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1373 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1374 ty::IntVarValue::Unknown => {
1375Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1376 }
1377 }
1378 }
13791380/// Resolves a float var to a rigid int type, if it was constrained to one,
1381 /// or else the root float var in the unification table.
1382pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1383let mut inner = self.inner.borrow_mut();
1384let value = inner.float_unification_table().probe_value(vid);
1385match value {
1386 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1387 ty::FloatVarValue::Unknown => {
1388Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1389 }
1390 }
1391 }
13921393/// Where possible, replaces type/const variables in
1394 /// `value` with their final value. Note that region variables
1395 /// are unaffected. If a type/const variable has not been unified, it
1396 /// is left as is. This is an idempotent operation that does
1397 /// not affect inference state in any way and so you can do it
1398 /// at will.
1399pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1400where
1401T: TypeFoldable<TyCtxt<'tcx>>,
1402 {
1403if let Err(guar) = value.error_reported() {
1404self.set_tainted_by_errors(guar);
1405 }
1406if !value.has_non_region_infer() {
1407return value;
1408 }
1409let mut r = resolve::OpportunisticVarResolver::new(self);
1410value.fold_with(&mut r)
1411 }
14121413pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1414where
1415T: TypeFoldable<TyCtxt<'tcx>>,
1416 {
1417if !value.has_infer() {
1418return value; // Avoid duplicated type-folding.
1419}
1420let mut r = InferenceLiteralEraser { tcx: self.tcx };
1421value.fold_with(&mut r)
1422 }
14231424pub fn try_resolve_const_var(
1425&self,
1426 vid: ty::ConstVid,
1427 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1428match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1429 ConstVariableValue::Known { value } => Ok(value),
1430 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1431 }
1432 }
14331434/// Attempts to resolve all type/region/const variables in
1435 /// `value`. Region inference must have been run already (e.g.,
1436 /// by calling `resolve_regions_and_report_errors`). If some
1437 /// variable was never unified, an `Err` results.
1438 ///
1439 /// This method is idempotent, but it not typically not invoked
1440 /// except during the writeback phase.
1441pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1442match resolve::fully_resolve(self, value) {
1443Ok(value) => {
1444if value.has_non_region_infer() {
1445::rustc_middle::util::bug::bug_fmt(format_args!("`{0:?}` is not fully resolved",
value));bug!("`{value:?}` is not fully resolved");
1446 }
1447if value.has_infer_regions() {
1448let 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"));
1449Ok(fold_regions(self.tcx, value, |re, _| {
1450if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1451 }))
1452 } else {
1453Ok(value)
1454 }
1455 }
1456Err(e) => Err(e),
1457 }
1458 }
14591460// Instantiates the bound variables in a given binder with fresh inference
1461 // variables in the current universe.
1462 //
1463 // Use this method if you'd like to find some generic parameters of the binder's
1464 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1465 // that corresponds to your use case, consider whether or not you should
1466 // use [`InferCtxt::enter_forall`] instead.
1467pub fn instantiate_binder_with_fresh_vars<T>(
1468&self,
1469 span: Span,
1470 lbrct: BoundRegionConversionTime,
1471 value: ty::Binder<'tcx, T>,
1472 ) -> T
1473where
1474T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1475 {
1476if let Some(inner) = value.no_bound_vars() {
1477return inner;
1478 }
14791480let bound_vars = value.bound_vars();
1481let mut args = Vec::with_capacity(bound_vars.len());
14821483for bound_var_kind in bound_vars {
1484let arg: ty::GenericArg<'_> = match bound_var_kind {
1485 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1486 ty::BoundVariableKind::Region(br) => {
1487self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1488 }
1489 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1490 };
1491 args.push(arg);
1492 }
14931494struct ToFreshVars<'tcx> {
1495 args: Vec<ty::GenericArg<'tcx>>,
1496 }
14971498impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1499fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1500self.args[br.var.index()].expect_region()
1501 }
1502fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1503self.args[bt.var.index()].expect_ty()
1504 }
1505fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1506self.args[bc.var.index()].expect_const()
1507 }
1508 }
1509let delegate = ToFreshVars { args };
1510self.tcx.replace_bound_vars_uncached(value, delegate)
1511 }
15121513/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1514pub(crate) fn verify_generic_bound(
1515&self,
1516 origin: SubregionOrigin<'tcx>,
1517 kind: GenericKind<'tcx>,
1518 a: ty::Region<'tcx>,
1519 bound: VerifyBound<'tcx>,
1520 ) {
1521{
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:1521",
"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(1521u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("verify_generic_bound({0:?}, {1:?} <: {2:?})",
kind, a, bound) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
15221523self.inner
1524 .borrow_mut()
1525 .unwrap_region_constraints()
1526 .verify_generic_bound(origin, kind, a, bound);
1527 }
15281529/// Obtains the latest type of the given closure; this may be a
1530 /// closure in the current function, in which case its
1531 /// `ClosureKind` may not yet be known.
1532pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1533let unresolved_kind_ty = match *closure_ty.kind() {
1534 ty::Closure(_, args) => args.as_closure().kind_ty(),
1535 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1536_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0}",
closure_ty))bug!("unexpected type {closure_ty}"),
1537 };
1538let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1539closure_kind_ty.to_opt_closure_kind()
1540 }
15411542pub fn universe(&self) -> ty::UniverseIndex {
1543self.universe.get()
1544 }
15451546/// Creates and return a fresh universe that extends all previous
1547 /// universes. Updates `self.universe` to that new universe.
1548pub fn create_next_universe(&self) -> ty::UniverseIndex {
1549let u = self.universe.get().next_universe();
1550{
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:1550",
"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(1550u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("create_next_universe {0:?}",
u) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("create_next_universe {u:?}");
1551self.universe.set(u);
1552u1553 }
15541555/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1556 /// which contains the necessary information to use the trait system without
1557 /// using canonicalization or carrying this inference context around.
1558pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1559let typing_mode = match self.typing_mode_raw() {
1560// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1561 // to handle them without proper canonicalization. This means we may cause cycle
1562 // errors and fail to reveal opaques while inside of bodies. We should rename this
1563 // function and require explicit comments on all use-sites in the future.
1564ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1565 | ty::TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ } => {
1566TypingMode::non_body_analysis()
1567 }
1568 mode @ (ty::TypingMode::Coherence1569 | ty::TypingMode::PostBorrowck { .. }
1570 | ty::TypingMode::PostAnalysis1571 | ty::TypingMode::Reflection1572 | ty::TypingMode::Codegen) => mode,
1573 ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1574 };
1575 ty::TypingEnv::new(param_env, typing_mode)
1576 }
15771578/// Similar to [`Self::canonicalize_query`], except that it returns
1579 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1580 /// `param_env` to not contain any inference variables or placeholders.
1581pub fn pseudo_canonicalize_query<V>(
1582&self,
1583 param_env: ty::ParamEnv<'tcx>,
1584 value: V,
1585 ) -> PseudoCanonicalInput<'tcx, V>
1586where
1587V: TypeVisitable<TyCtxt<'tcx>>,
1588 {
1589if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1590if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1591if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1592if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1593self.typing_env(param_env).as_query_input(value)
1594 }
15951596/// The returned function is used in a fast path. If it returns `true` the variable is
1597 /// unchanged, `false` indicates that the status is unknown.
1598#[inline]
1599pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1600// This hoists the borrow/release out of the loop body.
1601let inner = self.inner.try_borrow();
16021603move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1604 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1605use self::type_variable::TypeVariableValue;
16061607#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1608 inner.try_type_variables_probe_ref(ty_var),
1609Some(TypeVariableValue::Unknown { .. })
1610 )1611 }
1612_ => false,
1613 }
1614 }
16151616/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1617 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1618 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1619 ///
1620 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1621 /// inlined, despite being large, because it has only two call sites that
1622 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1623 /// inference variables), and it handles both `Ty` and `ty::Const` without
1624 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1625#[inline(always)]
1626pub fn ty_or_const_infer_var_changed(&self, var: TyOrConstInferVar) -> bool {
1627match var {
1628 TyOrConstInferVar::Ty(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().try_type_variables_probe_ref(vid)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1629self.inner.borrow().try_type_variables_probe_ref(vid),
1630Some(TypeVariableValue::Unknown { .. })
1631 ),
1632 TyOrConstInferVar::TyInt(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().int_unification_storage.try_probe_value(vid)
{
Some(ty::IntVarValue::Unknown) => true,
_ => false,
}matches!(
1633self.inner.borrow().int_unification_storage.try_probe_value(vid),
1634Some(ty::IntVarValue::Unknown)
1635 ),
1636 TyOrConstInferVar::TyFloat(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().float_unification_storage.try_probe_value(vid)
{
Some(ty::FloatVarValue::Unknown) => true,
_ => false,
}matches!(
1637self.inner.borrow().float_unification_storage.try_probe_value(vid),
1638Some(ty::FloatVarValue::Unknown)
1639 ),
1640 TyOrConstInferVar::Const(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().const_unification_storage.try_probe_value(vid)
{
Some(ConstVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1641self.inner.borrow().const_unification_storage.try_probe_value(vid),
1642Some(ConstVariableValue::Unknown { .. })
1643 ),
1644 }
1645 }
16461647/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1648pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1649if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1650self.obligation_inspector.get().is_none(),
1651"shouldn't override a set obligation inspector"
1652);
1653self.obligation_inspector.set(Some(inspector));
1654 }
1655}
16561657/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1658/// Used only for diagnostics.
1659struct InferenceLiteralEraser<'tcx> {
1660 tcx: TyCtxt<'tcx>,
1661}
16621663impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1664fn cx(&self) -> TyCtxt<'tcx> {
1665self.tcx
1666 }
16671668fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1669match ty.kind() {
1670 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1671 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1672_ => ty.super_fold_with(self),
1673 }
1674 }
1675}
16761677impl<'tcx> TypeTrace<'tcx> {
1678pub fn span(&self) -> Span {
1679self.cause.span
1680 }
16811682pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1683TypeTrace {
1684 cause: cause.clone(),
1685 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1686 }
1687 }
16881689pub fn trait_refs(
1690 cause: &ObligationCause<'tcx>,
1691 a: ty::TraitRef<'tcx>,
1692 b: ty::TraitRef<'tcx>,
1693 ) -> TypeTrace<'tcx> {
1694TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1695 }
16961697pub fn consts(
1698 cause: &ObligationCause<'tcx>,
1699 a: ty::Const<'tcx>,
1700 b: ty::Const<'tcx>,
1701 ) -> TypeTrace<'tcx> {
1702TypeTrace {
1703 cause: cause.clone(),
1704 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1705 }
1706 }
1707}
17081709impl<'tcx> SubregionOrigin<'tcx> {
1710pub fn span(&self) -> Span {
1711match *self {
1712 SubregionOrigin::Subtype(ref a) => a.span(),
1713 SubregionOrigin::RelateObjectBound(a) => a,
1714 SubregionOrigin::RelateParamBound(a, ..) => a,
1715 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1716 SubregionOrigin::Reborrow(a) => a,
1717 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1718 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1719 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1720 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1721 SubregionOrigin::SolverRegionConstraint(a) => a,
1722 }
1723 }
17241725pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1726where
1727F: FnOnce() -> Self,
1728 {
1729match *cause.code() {
1730 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1731 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1732 }
17331734 traits::ObligationCauseCode::CompareImplItem {
1735 impl_item_def_id,
1736 trait_item_def_id,
1737 kind: _,
1738 } => SubregionOrigin::CompareImplItemObligation {
1739 span: cause.span,
1740impl_item_def_id,
1741trait_item_def_id,
1742 },
17431744 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1745 impl_item_def_id,
1746 trait_item_def_id,
1747 } => SubregionOrigin::CheckAssociatedTypeBounds {
1748impl_item_def_id,
1749trait_item_def_id,
1750 parent: Box::new(default()),
1751 },
17521753 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1754 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1755 }
17561757 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1758 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1759 }
17601761_ => default(),
1762 }
1763 }
1764}
17651766impl<'tcx> RegionVariableOrigin<'tcx> {
1767pub fn span(&self) -> Span {
1768match *self {
1769 RegionVariableOrigin::Misc(a)
1770 | RegionVariableOrigin::PatternRegion(a)
1771 | RegionVariableOrigin::BorrowRegion(a)
1772 | RegionVariableOrigin::Autoref(a)
1773 | RegionVariableOrigin::Coercion(a)
1774 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1775 | RegionVariableOrigin::BoundRegion(a, ..)
1776 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1777 RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable used with `span`"))bug!("NLL variable used with `span`"),
1778 }
1779 }
1780}
17811782impl<'tcx> InferCtxt<'tcx> {
1783/// Given a [`hir::Block`], get the span of its last expression or
1784 /// statement, peeling off any inner blocks.
1785pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1786let block = block.innermost_block();
1787if let Some(expr) = &block.expr {
1788expr.span
1789 } else if let Some(stmt) = block.stmts.last() {
1790// possibly incorrect trailing `;` in the else arm
1791stmt.span
1792 } else {
1793// empty block; point at its entirety
1794block.span
1795 }
1796 }
17971798/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1799 /// of its last expression or statement, peeling off any inner blocks.
1800pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1801match self.tcx.hir_node(hir_id) {
1802 hir::Node::Block(blk)
1803 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1804self.find_block_span(blk)
1805 }
1806 hir::Node::Expr(e) => e.span,
1807_ => DUMMY_SP,
1808 }
1809 }
1810}
18111812type SolverRegionConstraint<'tcx> =
1813 rustc_type_ir::region_constraint::RegionConstraint<TyCtxt<'tcx>>;
18141815#[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)]
1816struct SolverRegionConstraintStorage<'tcx>(SolverRegionConstraint<'tcx>);
18171818impl<'tcx> SolverRegionConstraintStorage<'tcx> {
1819fn new() -> Self {
1820SolverRegionConstraintStorage(SolverRegionConstraint::And(Box::new([])))
1821 }
18221823fn get_constraint(&self) -> SolverRegionConstraint<'tcx> {
1824self.0.clone()
1825 }
18261827fn is_and(&self) -> bool {
1828self.0.is_and()
1829 }
18301831fn pop(&mut self, previous_was_and: bool) -> Option<SolverRegionConstraint<'tcx>> {
1832match &mut self.0 {
1833SolverRegionConstraint::And(and) => {
1834let mut and = core::mem::take(and).into_iter().collect::<Vec<_>>();
1835let popped = and.pop()?;
1836if previous_was_and {
1837self.0 = SolverRegionConstraint::And(and.into_boxed_slice());
1838 } else {
1839{
match (&and.len(), &1) {
(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);
}
}
}
};assert_eq!(and.len(), 1);
1840self.0 = and.pop().unwrap();
1841 }
1842Some(popped)
1843 }
1844_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1845 }
1846 }
18471848#[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(1848u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self")
}> =
::tracing::__macro_support::FieldName::new("self");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("constraint")
}> =
::tracing::__macro_support::FieldName::new("constraint");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
match core::mem::replace(&mut self.0,
SolverRegionConstraint::new_true()) {
SolverRegionConstraint::And(and) => {
let and =
and.into_iter().chain([constraint]).collect::<Vec<_>>().into_boxed_slice();
self.0 = SolverRegionConstraint::And(and);
}
previous => {
self.0 =
SolverRegionConstraint::And(Box::new([previous,
constraint]));
}
}
}
}
}#[instrument(level = "debug")]1849fn push(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1850match core::mem::replace(&mut self.0, SolverRegionConstraint::new_true()) {
1851 SolverRegionConstraint::And(and) => {
1852let and =
1853 and.into_iter().chain([constraint]).collect::<Vec<_>>().into_boxed_slice();
1854self.0 = SolverRegionConstraint::And(and);
1855 }
1856 previous => {
1857self.0 = SolverRegionConstraint::And(Box::new([previous, constraint]));
1858 }
1859 }
1860 }
18611862#[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(1862u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("constraint")
}> =
::tracing::__macro_support::FieldName::new("constraint");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{ self.0 = constraint; }
}
}#[instrument(level = "debug", skip(self))]1863fn overwrite_solver_region_constraint(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1864self.0 = constraint;
1865 }
1866}
18671868/// Returns unresolved root variables from `table`, according to `is_unresolved`.
1869fn unresolved_root_variables_of<V: UnifyKey>(
1870mut table: UnificationTable<'_, '_, V>,
1871 is_unresolved: impl Fn(V::Value) -> bool,
1872) -> Vec<V>
1873where
1874V: Eq,
1875 V::Value: UnifyValue,
1876for<'a> UndoLog<'a>: From<sv::UndoLog<ut::Delegate<V>>>,
1877{
1878 (0..table.len() as u32)
1879 .map(V::from_index)
1880 .filter(|&vid| {
1881// NB: as of writing this `ena` doesn't provide a non-inlined `probe_key_value`...
1882let (root, value) = table.inlined_probe_key_value(vid);
1883root == vid && is_unresolved(value)
1884 })
1885 .collect()
1886}