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::undo_log::{Rollback, UndoLogs};
16use rustc_data_structures::unifyas ut;
17use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
18use rustc_hir::def_id::{DefId, LocalDefId};
19use rustc_hir::{selfas hir, HirId};
20use rustc_index::IndexVec;
21use rustc_macros::extension;
22pub use rustc_macros::{TypeFoldable, TypeVisitable};
23use rustc_middle::bug;
24use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
25use rustc_middle::mir::ConstraintCategory;
26use rustc_middle::traits::select;
27use rustc_middle::traits::solve::Goal;
28use rustc_middle::ty::error::{ExpectedFound, TypeError};
29use rustc_middle::ty::{
30self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
31GenericArgsRef, GenericParamDefKind, InferConst, IntVid, OpaqueTypeKey, ProvisionalHiddenType,
32PseudoCanonicalInput, RegionExt, Term, TermKind, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder,
33TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
34};
35use rustc_span::{DUMMY_SP, Span, Symbol};
36use rustc_type_ir::MayBeErased;
37use snapshot::undo_log::InferCtxtUndoLogs;
38use tracing::{debug, instrument};
39use type_variable::TypeVariableOrigin;
4041use crate::infer::snapshot::undo_log::UndoLog;
42use crate::infer::type_variable::FloatVariableOrigin;
43use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
44use crate::traits::{
45self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
46TraitEngine,
47};
4849pub mod at;
50pub mod canonical;
51mod context;
52mod free_regions;
53mod freshen;
54mod lexical_region_resolve;
55mod opaque_types;
56pub mod outlives;
57mod projection;
58pub mod region_constraints;
59pub mod relate;
60pub mod resolve;
61pub(crate) mod snapshot;
62mod type_variable;
63mod unify_key;
6465/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
66/// around `PredicateObligations<'tcx>`, but it has one important property:
67/// because `InferOk` is marked with `#[must_use]`, if you have a method
68/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
69/// `infcx.f()?;` you'll get a warning about the obligations being discarded
70/// without use, which is probably unintentional and has been a source of bugs
71/// in the past.
72#[must_use]
73#[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)]
74pub struct InferOk<'tcx, T> {
75pub value: T,
76pub obligations: PredicateObligations<'tcx>,
77}
78pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
7980pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
8182pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
83 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
84>;
8586/// This type contains all the things within `InferCtxt` that sit within a
87/// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
88/// operations are hot enough that we want only one call to `borrow_mut` per
89/// call to `start_snapshot` and `rollback_to`.
90#[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)]
91pub struct InferCtxtInner<'tcx> {
92 undo_log: InferCtxtUndoLogs<'tcx>,
9394/// Cache for projections.
95 ///
96 /// This cache is snapshotted along with the infcx.
97projection_cache: traits::ProjectionCacheStorage<'tcx>,
9899/// We instantiate `UnificationTable` with `bounds<Ty>` because the types
100 /// that might instantiate a general type variable have an order,
101 /// represented by its upper and lower bounds.
102type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
103104/// Map from const parameter variable to the kind of const it represents.
105const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
106107/// Map from integral variable to the kind of integer it represents.
108int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
109110/// Map from floating variable to the kind of float it represents.
111float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
112113/// Map from floating variable to the origin span it came from, and the HirId that should be
114 /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
115 /// so can be removed once the `f32` fallback is removed.
116float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
117118/// Tracks the set of region variables and the constraints between them.
119 ///
120 /// This is initially `Some(_)` but when
121 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
122 /// -- further attempts to perform unification, etc., may fail if new
123 /// region constraints would've been added.
124region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
125126/// Used by the next solver when `-Zassumptions-on-binders` is set.
127solver_region_constraint_storage: SolverRegionConstraintStorage<'tcx>,
128129/// A set of constraints that regionck must validate.
130 ///
131 /// Each constraint has the form `T:'a`, meaning "some type `T` must
132 /// outlive the lifetime 'a". These constraints derive from
133 /// instantiated type parameters. So if you had a struct defined
134 /// like the following:
135 /// ```ignore (illustrative)
136 /// struct Foo<T: 'static> { ... }
137 /// ```
138 /// In some expression `let x = Foo { ... }`, it will
139 /// instantiate the type parameter `T` with a fresh type `$0`. At
140 /// the same time, it will record a region obligation of
141 /// `$0: 'static`. This will get checked later by regionck. (We
142 /// can't generally check these things right away because we have
143 /// to wait until types are resolved.)
144region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
145146/// The outlives bounds that we assume must hold about placeholders that
147 /// come from instantiating the binder of coroutine-witnesses. These bounds
148 /// are deduced from the well-formedness of the witness's types, and are
149 /// necessary because of the way we anonymize the regions in a coroutine,
150 /// which may cause types to no longer be considered well-formed.
151region_assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
152153/// `-Znext-solver`: Successfully proven goals during HIR typeck which
154 /// reference inference variables and get reproven in case MIR type check
155 /// fails to prove something.
156 ///
157 /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
158hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
159160/// Caches for opaque type inference.
161opaque_type_storage: OpaqueTypeStorage<'tcx>,
162}
163164impl<'tcx> InferCtxtInner<'tcx> {
165fn new() -> InferCtxtInner<'tcx> {
166InferCtxtInner {
167 undo_log: InferCtxtUndoLogs::default(),
168169 projection_cache: Default::default(),
170 type_variable_storage: Default::default(),
171 const_unification_storage: Default::default(),
172 int_unification_storage: Default::default(),
173 float_unification_storage: Default::default(),
174 float_origin_origin_storage: Default::default(),
175 region_constraint_storage: Some(Default::default()),
176 solver_region_constraint_storage: SolverRegionConstraintStorage::new(),
177 region_obligations: Default::default(),
178 region_assumptions: Default::default(),
179 hir_typeck_potentially_region_dependent_goals: Default::default(),
180 opaque_type_storage: Default::default(),
181 }
182 }
183184#[inline]
185pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
186&self.region_obligations
187 }
188189#[inline]
190pub fn region_assumptions(&self) -> &[ty::ArgOutlivesPredicate<'tcx>] {
191&self.region_assumptions
192 }
193194#[inline]
195pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
196self.projection_cache.with_log(&mut self.undo_log)
197 }
198199#[inline]
200fn try_type_variables_probe_ref(
201&self,
202 vid: ty::TyVid,
203 ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
204// Uses a read-only view of the unification table, this way we don't
205 // need an undo log.
206self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
207 }
208209#[inline]
210fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
211self.type_variable_storage.with_log(&mut self.undo_log)
212 }
213214#[inline]
215pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
216self.opaque_type_storage.with_log(&mut self.undo_log)
217 }
218219#[inline]
220fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
221self.int_unification_storage.with_log(&mut self.undo_log)
222 }
223224#[inline]
225fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
226self.float_unification_storage.with_log(&mut self.undo_log)
227 }
228229#[inline]
230fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
231self.const_unification_storage.with_log(&mut self.undo_log)
232 }
233234#[inline]
235pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
236self.region_constraint_storage
237 .as_mut()
238 .expect("region constraints already solved")
239 .with_log(&mut self.undo_log)
240 }
241}
242243pub struct InferCtxt<'tcx> {
244pub tcx: TyCtxt<'tcx>,
245246/// The mode of this inference context, see the struct documentation
247 /// for more details.
248typing_mode: TypingMode<'tcx>,
249250/// Whether this inference context should care about region obligations in
251 /// the root universe. Most notably, this is used during HIR typeck as region
252 /// solving is left to borrowck instead.
253 ///
254 /// This is used in the old solver to enable the generation of regions constraints.
255 /// In the new solver its only used inside the InferCtxt's `Drop` implementation:
256 /// if we're considering regions, and new opaques are registered, we panic.
257pub considering_regions: bool,
258/// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
259 /// need to make sure we don't rely on region identity in the trait solver or when
260 /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
261 /// free region with a unique inference variable. If HIR typeck ends up depending on two
262 /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
263 /// resulting in an ICE.
264 ///
265 /// The trait solver sometimes depends on regions being identical. As a concrete example
266 /// the trait solver ignores other candidates if one candidate exists without any constraints.
267 /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
268 /// occurrence of `'a` with a unique region the goal now equates these regions. See
269 /// the tests in trait-system-refactor-initiative#27 for concrete examples.
270 ///
271 /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
272 /// This is still insufficient as inference variables may *hide* region variables, so e.g.
273 /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
274 /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
275 /// stash all successfully proven goals which reference inference variables and then reprove
276 /// them after writeback.
277pub in_hir_typeck: bool,
278279/// If set, this flag causes us to skip the 'leak check' during
280 /// higher-ranked subtyping operations. This flag is a temporary one used
281 /// to manage the removal of the leak-check: for the time being, we still run the
282 /// leak-check, but we issue warnings.
283skip_leak_check: bool,
284285pub inner: RefCell<InferCtxtInner<'tcx>>,
286287/// Once region inference is done, the values for each variable.
288lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
289290/// Caches the results of trait selection. This cache is used
291 /// for things that depends on inference variables or placeholders.
292pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
293294/// Caches the results of trait evaluation. This cache is used
295 /// for things that depends on inference variables or placeholders.
296pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
297298/// The set of predicates on which errors have been reported, to
299 /// avoid reporting the same error twice.
300pub reported_trait_errors:
301RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
302303pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
304305/// When an error occurs, we want to avoid reporting "derived"
306 /// errors that are due to this original failure. We have this
307 /// flag that one can set whenever one creates a type-error that
308 /// is due to an error in a prior pass.
309 ///
310 /// Don't read this flag directly, call `is_tainted_by_errors()`
311 /// and `set_tainted_by_errors()`.
312tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
313314/// What is the innermost universe we have created? Starts out as
315 /// `UniverseIndex::root()` but grows from there as we enter
316 /// universal quantifiers.
317 ///
318 /// N.B., at present, we exclude the universal quantifiers on the
319 /// item we are type-checking, and just consider those names as
320 /// part of the root universe. So this would only get incremented
321 /// when we enter into a higher-ranked (`for<..>`) type or trait
322 /// bound.
323universe: Cell<ty::UniverseIndex>,
324325/// List of assumed wellformed types which we can derive implied
326 /// bounds on a `for<...>` from. Only used unstabley and by the
327 /// new solver.
328//
329 // FIXME(-Zassumptions-on-binders): This and `universe` should probably be
330 // in `InferCtxtInner` so they can participate in rollbacks and whatnot
331placeholder_assumptions_for_next_solver: RefCell<
332FxIndexMap<
333 ty::UniverseIndex,
334Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
335 >,
336 >,
337338 next_trait_solver: bool,
339340/// We have a `recursion_depth_exceeding_limit` FCW to mitigate breakages
341 /// caused by enabling the next solver globally. But the next solver is
342 /// already used by default in some places so we know they won't have
343 /// additional breakages. We also don't want spurious result in coherence
344 /// checking so we disable the FCW there as well.
345enable_next_solver_overflow_fcw: bool,
346347pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
348}
349350impl<'tcx> Dropfor InferCtxt<'tcx> {
351fn drop(&mut self) {
352let mut inner = self.inner.borrow_mut();
353let opaque_type_storage = &mut inner.opaque_type_storage;
354355// No need for the drop bomb when we're in `TypingMode::PostTypeckUntilBorrowck`, and the `InferCtxt`
356 // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
357 // in relation to regions. In some places *after* typeck that aren't borrowck, we use
358 // `TypingMode::PostTypeckUntilBorrowck` to prevent defining opaque types and we simply don't care about regions.
359match self.typing_mode_raw() {
360TypingMode::Coherence361 | TypingMode::Typeck { .. }
362 | TypingMode::PostBorrowck { .. }
363 | TypingMode::Reflection364 | TypingMode::PostAnalysis365 | TypingMode::Codegen => {}
366// In erased mode, the opaque type storage is always empty
367TypingMode::ErasedNotCoherence(..) => {}
368TypingMode::PostTypeckUntilBorrowck { .. } => {
369if !self.considering_regions {
370return;
371 }
372 }
373 }
374375if !opaque_type_storage.is_empty() {
376 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:?}")));
377 }
378 }
379}
380381/// See the `error_reporting` module for more details.
382#[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)]
383pub enum ValuePairs<'tcx> {
384 Regions(ExpectedFound<ty::Region<'tcx>>),
385 Terms(ExpectedFound<ty::Term<'tcx>>),
386 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
387 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
388 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
389 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
390 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
391}
392393impl<'tcx> ValuePairs<'tcx> {
394pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
395if let ValuePairs::Terms(ExpectedFound { expected, found }) = self396 && let Some(expected) = expected.as_type()
397 && let Some(found) = found.as_type()
398 {
399Some((expected, found))
400 } else {
401None402 }
403 }
404}
405406/// The trace designates the path through inference that we took to
407/// encounter an error or subtyping constraint.
408///
409/// See the `error_reporting` module for more details.
410#[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)]
411pub struct TypeTrace<'tcx> {
412pub cause: ObligationCause<'tcx>,
413pub values: ValuePairs<'tcx>,
414}
415416/// The origin of a `r1 <= r2` constraint.
417///
418/// See `error_reporting` module for more details
419#[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)]
420pub enum SubregionOrigin<'tcx> {
421/// Arose from a subtyping relation
422Subtype(Box<TypeTrace<'tcx>>),
423424/// When casting `&'a T` to an `&'b Trait` object,
425 /// relating `'a` to `'b`.
426RelateObjectBound(Span),
427428/// Some type parameter was instantiated with the given type,
429 /// and that type must outlive some region.
430RelateParamBound(Span, Ty<'tcx>, Option<Span>),
431432/// The given region parameter was instantiated with a region
433 /// that must outlive some other region.
434RelateRegionParamBound(Span, Option<Ty<'tcx>>),
435436/// Creating a pointer `b` to contents of another reference.
437Reborrow(Span),
438439/// (&'a &'b T) where a >= b
440ReferenceOutlivesReferent(Ty<'tcx>, Span),
441442/// Comparing the signature and requirements of an impl method against
443 /// the containing trait.
444CompareImplItemObligation {
445 span: Span,
446 impl_item_def_id: LocalDefId,
447 trait_item_def_id: DefId,
448 },
449450/// Checking that the bounds of a trait's associated type hold for a given impl.
451CheckAssociatedTypeBounds {
452 parent: Box<SubregionOrigin<'tcx>>,
453 impl_item_def_id: LocalDefId,
454 trait_item_def_id: DefId,
455 },
456457 AscribeUserTypeProvePredicate(Span),
458459// FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
460 // proper diagnostics for solver region constraints.
461SolverRegionConstraint(Span),
462}
463464// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
465#[cfg(target_pointer_width = "64")]
466const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
467468impl<'tcx> SubregionOrigin<'tcx> {
469pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
470match self {
471Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
472Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
473Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
474_ => ConstraintCategory::BoringNoLocation,
475 }
476 }
477}
478479/// Times when we replace bound regions with existentials:
480#[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)]
481pub enum BoundRegionConversionTime {
482/// when a fn is called
483FnCall,
484485/// when two higher-ranked types are compared
486HigherRankedType,
487488/// when projecting an associated type
489AssocTypeProjection(DefId),
490}
491492/// Reasons to create a region inference variable.
493///
494/// See `error_reporting` module for more details.
495#[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)]
496pub enum RegionVariableOrigin<'tcx> {
497/// Region variables created for ill-categorized reasons.
498 ///
499 /// They mostly indicate places in need of refactoring.
500Misc(Span),
501502/// Regions created by a `&P` or `[...]` pattern.
503PatternRegion(Span),
504505/// Regions created by `&` operator.
506BorrowRegion(Span),
507508/// Regions created as part of an autoref of a method receiver.
509Autoref(Span),
510511/// Regions created as part of an automatic coercion.
512Coercion(Span),
513514/// Region variables created as the values for early-bound regions.
515 ///
516 /// FIXME(@lcnr): This should also store a `DefId`, similar to
517 /// `TypeVariableOrigin`.
518RegionParameterDefinition(Span, Symbol),
519520/// Region variables created when instantiating a binder with
521 /// existential variables, e.g. when calling a function or method.
522BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
523524 UpvarRegion(ty::UpvarId, Span),
525526/// This origin is used for the inference variables that we create
527 /// during NLL region processing.
528Nll(NllRegionVariableOrigin<'tcx>),
529}
530531#[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)]
532pub enum NllRegionVariableOrigin<'tcx> {
533/// During NLL region processing, we create variables for free
534 /// regions that we encounter in the function signature and
535 /// elsewhere. This origin indices we've got one of those.
536FreeRegion,
537538/// "Universal" instantiation of a higher-ranked region (e.g.,
539 /// from a `for<'a> T` binder). Meant to represent "any region".
540Placeholder(ty::PlaceholderRegion<'tcx>),
541542 Existential {
543 name: Option<Symbol>,
544 },
545}
546547#[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)]
548pub struct FixupError {
549 unresolved: TyOrConstInferVar,
550}
551552impl fmt::Displayfor FixupError {
553fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554match self.unresolved {
555 TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
556f,
557"cannot determine the type of this integer; \
558 add a suffix to specify the type explicitly"
559),
560 TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
561f,
562"cannot determine the type of this number; \
563 add a suffix to specify the type explicitly"
564),
565 TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
566 TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
567 }
568 }
569}
570571/// See the `region_obligations` field for more information.
572#[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)]
573pub struct TypeOutlivesConstraint<'tcx> {
574pub sub_region: ty::Region<'tcx>,
575pub sup_type: Ty<'tcx>,
576pub origin: SubregionOrigin<'tcx>,
577}
578579/// Used to configure inference contexts before their creation.
580pub struct InferCtxtBuilder<'tcx> {
581 tcx: TyCtxt<'tcx>,
582 considering_regions: bool,
583 in_hir_typeck: bool,
584 skip_leak_check: bool,
585/// Whether we should use the new trait solver in the local inference context,
586 /// which affects things like which solver is used in `predicate_may_hold`.
587next_trait_solver: bool,
588 enable_next_solver_overflow_fcw: bool,
589}
590591impl<'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>)]592impl<'tcx> TyCtxt<'tcx> {
593fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
594InferCtxtBuilder {
595 tcx: self,
596 considering_regions: true,
597 in_hir_typeck: false,
598 skip_leak_check: false,
599 next_trait_solver: self.next_trait_solver_globally(),
600 enable_next_solver_overflow_fcw: true,
601 }
602 }
603}
604605impl<'tcx> InferCtxtBuilder<'tcx> {
606pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
607self.next_trait_solver = next_trait_solver;
608self609 }
610611pub fn enable_next_solver_overflow_fcw(
612mut self,
613 enable_next_solver_overflow_fcw: bool,
614 ) -> Self {
615self.enable_next_solver_overflow_fcw = enable_next_solver_overflow_fcw;
616self617 }
618619pub fn ignoring_regions(mut self) -> Self {
620self.considering_regions = false;
621self622 }
623624pub fn in_hir_typeck(mut self) -> Self {
625self.in_hir_typeck = true;
626self627 }
628629pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
630self.skip_leak_check = skip_leak_check;
631self632 }
633634/// Given a canonical value `C` as a starting point, create an
635 /// inference context that contains each of the bound values
636 /// within instantiated as a fresh variable. The `f` closure is
637 /// invoked with the new infcx, along with the instantiated value
638 /// `V` and a instantiation `S`. This instantiation `S` maps from
639 /// the bound values in `C` to their instantiated values in `V`
640 /// (in other words, `S(C) = V`).
641pub fn build_with_canonical<T>(
642mut self,
643 span: Span,
644 input: &CanonicalQueryInput<'tcx, T>,
645 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
646where
647T: TypeFoldable<TyCtxt<'tcx>>,
648 {
649let infcx = self.build(input.typing_mode.0);
650let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
651 (infcx, value, args)
652 }
653654pub fn build_with_typing_env(
655mut self,
656 typing_env: TypingEnv<'tcx>,
657 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
658 (self.build(typing_env.typing_mode()), typing_env.param_env)
659 }
660661pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
662let InferCtxtBuilder {
663 tcx,
664 considering_regions,
665 in_hir_typeck,
666 skip_leak_check,
667 next_trait_solver,
668 enable_next_solver_overflow_fcw,
669 } = *self;
670InferCtxt {
671tcx,
672typing_mode,
673considering_regions,
674in_hir_typeck,
675skip_leak_check,
676 inner: RefCell::new(InferCtxtInner::new()),
677 lexical_region_resolutions: RefCell::new(None),
678 selection_cache: Default::default(),
679 evaluation_cache: Default::default(),
680 reported_trait_errors: Default::default(),
681 reported_signature_mismatch: Default::default(),
682 tainted_by_errors: Cell::new(None),
683 universe: Cell::new(ty::UniverseIndex::ROOT),
684 placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
685next_trait_solver,
686enable_next_solver_overflow_fcw,
687 obligation_inspector: Cell::new(None),
688 }
689 }
690}
691692impl<'tcx, T> InferOk<'tcx, T> {
693/// Extracts `value`, registering any obligations into `fulfill_cx`.
694pub fn into_value_registering_obligations<E: 'tcx>(
695self,
696 infcx: &InferCtxt<'tcx>,
697 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
698 ) -> T {
699let InferOk { value, obligations } = self;
700fulfill_cx.register_predicate_obligations(infcx, obligations);
701value702 }
703}
704705impl<'tcx> InferOk<'tcx, ()> {
706pub fn into_obligations(self) -> PredicateObligations<'tcx> {
707self.obligations
708 }
709}
710711impl<'tcx> InferCtxt<'tcx> {
712pub fn dcx(&self) -> DiagCtxtHandle<'_> {
713self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
714 }
715716pub fn next_trait_solver(&self) -> bool {
717self.next_trait_solver
718 }
719720/// This method is deliberately called `..._raw`,
721 /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
722 /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
723 /// more information.
724 ///
725 /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
726 /// works as a kind of store for for example type unification information.
727 /// `InferCtxt` is also often used outside the trait solver during typeck.
728 /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
729 /// To make sure these two uses are never confused, we want to statically encode this information.
730 ///
731 /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
732 /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
733 /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
734 /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
735 /// match on the variant and can safely ignore it.
736 ///
737 /// Prefer non-raw apis if available. e.g.,
738 /// - On the `FnCtxt`
739 /// - on the `SelectionCtxt`
740#[inline(always)]
741pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
742self.typing_mode
743 }
744745#[inline(always)]
746pub fn disable_trait_solver_fast_paths(&self) -> bool {
747self.tcx.disable_trait_solver_fast_paths()
748 }
749750/// Returns the origin of the type variable identified by `vid`.
751 ///
752 /// No attempt is made to resolve `vid` to its root variable.
753pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
754self.inner.borrow_mut().type_variables().var_origin(vid)
755 }
756757/// Returns the origin of the float type variable identified by `vid`.
758 ///
759 /// No attempt is made to resolve `vid` to its root variable.
760pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
761self.inner.borrow_mut().float_origin_origin_storage[vid]
762 }
763764/// Returns the origin of the const variable identified by `vid`
765// FIXME: We should store origins separately from the unification table
766 // so this doesn't need to be optional.
767pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
768match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
769 ConstVariableValue::Known { .. } => None,
770 ConstVariableValue::Unknown { origin, .. } => Some(origin),
771 }
772 }
773774pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
775let mut inner = self.inner.borrow_mut();
776let mut vars: Vec<Ty<'_>> = inner777 .type_variables()
778 .unresolved_variables()
779 .into_iter()
780 .map(|t| Ty::new_var(self.tcx, t))
781 .collect();
782vars.extend(
783 (0..inner.int_unification_table().len())
784 .map(|i| ty::IntVid::from_usize(i))
785 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
786 .map(|v| Ty::new_int_var(self.tcx, v)),
787 );
788vars.extend(
789 (0..inner.float_unification_table().len())
790 .map(|i| ty::FloatVid::from_usize(i))
791 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
792 .map(|v| Ty::new_float_var(self.tcx, v)),
793 );
794vars795 }
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 }
12301231pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1232if let ty::Infer(v) = *ty.kind() {
1233match v {
1234 ty::TyVar(v) => {
1235// Not entirely obvious: if `typ` is a type variable,
1236 // it can be resolved to an int/float variable, which
1237 // can then be recursively resolved, hence the
1238 // recursion. Note though that we prevent type
1239 // variables from unifying to other type variables
1240 // directly (though they may be embedded
1241 // structurally), and we prevent cycles in any case,
1242 // so this recursion should always be of very limited
1243 // depth.
1244 //
1245 // Note: if these two lines are combined into one we get
1246 // dynamic borrow errors on `self.inner`.
1247let known = self.inner.borrow_mut().type_variables().probe(v).known();
1248known.map_or(ty, |t| self.shallow_resolve(t))
1249 }
12501251 ty::IntVar(v) => {
1252match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1253 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1254 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1255 ty::IntVarValue::Unknown => ty,
1256 }
1257 }
12581259 ty::FloatVar(v) => {
1260match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1261 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1262 ty::FloatVarValue::Unknown => ty,
1263 }
1264 }
12651266 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1267 }
1268 } else {
1269ty1270 }
1271 }
12721273pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1274match ct.kind() {
1275 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1276 InferConst::Var(vid) => self1277 .inner
1278 .borrow_mut()
1279 .const_unification_table()
1280 .probe_value(vid)
1281 .known()
1282 .unwrap_or(ct),
1283 InferConst::Fresh(_) => ct,
1284 },
12851286 ty::ConstKind::Param(_)
1287 | ty::ConstKind::Bound(_, _)
1288 | ty::ConstKind::Placeholder(_)
1289 | ty::ConstKind::Alias(_, _)
1290 | ty::ConstKind::Value(_)
1291 | ty::ConstKind::Error(_)
1292 | ty::ConstKind::Expr(_) => ct,
1293 }
1294 }
12951296pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1297match term.kind() {
1298 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1299 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1300 }
1301 }
13021303pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1304self.inner.borrow_mut().type_variables().root_var(var)
1305 }
13061307pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1308self.inner.borrow_mut().type_variables().sub_unify(a, b);
1309 }
13101311pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1312self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1313 }
13141315pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1316self.inner.borrow_mut().float_unification_table().find(var)
1317 }
13181319pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1320self.inner.borrow_mut().const_unification_table().find(var).vid
1321 }
13221323/// Resolves an int var to a rigid int type, if it was constrained to one,
1324 /// or else the root int var in the unification table.
1325pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1326let mut inner = self.inner.borrow_mut();
1327let value = inner.int_unification_table().probe_value(vid);
1328match value {
1329 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1330 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1331 ty::IntVarValue::Unknown => {
1332Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1333 }
1334 }
1335 }
13361337/// Resolves a float var to a rigid int type, if it was constrained to one,
1338 /// or else the root float var in the unification table.
1339pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1340let mut inner = self.inner.borrow_mut();
1341let value = inner.float_unification_table().probe_value(vid);
1342match value {
1343 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1344 ty::FloatVarValue::Unknown => {
1345Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1346 }
1347 }
1348 }
13491350/// Where possible, replaces type/const variables in
1351 /// `value` with their final value. Note that region variables
1352 /// are unaffected. If a type/const variable has not been unified, it
1353 /// is left as is. This is an idempotent operation that does
1354 /// not affect inference state in any way and so you can do it
1355 /// at will.
1356pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1357where
1358T: TypeFoldable<TyCtxt<'tcx>>,
1359 {
1360if let Err(guar) = value.error_reported() {
1361self.set_tainted_by_errors(guar);
1362 }
1363if !value.has_non_region_infer() {
1364return value;
1365 }
1366let mut r = resolve::OpportunisticVarResolver::new(self);
1367value.fold_with(&mut r)
1368 }
13691370pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1371where
1372T: TypeFoldable<TyCtxt<'tcx>>,
1373 {
1374if !value.has_infer() {
1375return value; // Avoid duplicated type-folding.
1376}
1377let mut r = InferenceLiteralEraser { tcx: self.tcx };
1378value.fold_with(&mut r)
1379 }
13801381pub fn try_resolve_const_var(
1382&self,
1383 vid: ty::ConstVid,
1384 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1385match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1386 ConstVariableValue::Known { value } => Ok(value),
1387 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1388 }
1389 }
13901391/// Attempts to resolve all type/region/const variables in
1392 /// `value`. Region inference must have been run already (e.g.,
1393 /// by calling `resolve_regions_and_report_errors`). If some
1394 /// variable was never unified, an `Err` results.
1395 ///
1396 /// This method is idempotent, but it not typically not invoked
1397 /// except during the writeback phase.
1398pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1399match resolve::fully_resolve(self, value) {
1400Ok(value) => {
1401if value.has_non_region_infer() {
1402::rustc_middle::util::bug::bug_fmt(format_args!("`{0:?}` is not fully resolved",
value));bug!("`{value:?}` is not fully resolved");
1403 }
1404if value.has_infer_regions() {
1405let 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"));
1406Ok(fold_regions(self.tcx, value, |re, _| {
1407if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1408 }))
1409 } else {
1410Ok(value)
1411 }
1412 }
1413Err(e) => Err(e),
1414 }
1415 }
14161417// Instantiates the bound variables in a given binder with fresh inference
1418 // variables in the current universe.
1419 //
1420 // Use this method if you'd like to find some generic parameters of the binder's
1421 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1422 // that corresponds to your use case, consider whether or not you should
1423 // use [`InferCtxt::enter_forall`] instead.
1424pub fn instantiate_binder_with_fresh_vars<T>(
1425&self,
1426 span: Span,
1427 lbrct: BoundRegionConversionTime,
1428 value: ty::Binder<'tcx, T>,
1429 ) -> T
1430where
1431T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1432 {
1433if let Some(inner) = value.no_bound_vars() {
1434return inner;
1435 }
14361437let bound_vars = value.bound_vars();
1438let mut args = Vec::with_capacity(bound_vars.len());
14391440for bound_var_kind in bound_vars {
1441let arg: ty::GenericArg<'_> = match bound_var_kind {
1442 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1443 ty::BoundVariableKind::Region(br) => {
1444self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1445 }
1446 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1447 };
1448 args.push(arg);
1449 }
14501451struct ToFreshVars<'tcx> {
1452 args: Vec<ty::GenericArg<'tcx>>,
1453 }
14541455impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1456fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1457self.args[br.var.index()].expect_region()
1458 }
1459fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1460self.args[bt.var.index()].expect_ty()
1461 }
1462fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1463self.args[bc.var.index()].expect_const()
1464 }
1465 }
1466let delegate = ToFreshVars { args };
1467self.tcx.replace_bound_vars_uncached(value, delegate)
1468 }
14691470/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1471pub(crate) fn verify_generic_bound(
1472&self,
1473 origin: SubregionOrigin<'tcx>,
1474 kind: GenericKind<'tcx>,
1475 a: ty::Region<'tcx>,
1476 bound: VerifyBound<'tcx>,
1477 ) {
1478{
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:1478",
"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(1478u32),
::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);
14791480self.inner
1481 .borrow_mut()
1482 .unwrap_region_constraints()
1483 .verify_generic_bound(origin, kind, a, bound);
1484 }
14851486/// Obtains the latest type of the given closure; this may be a
1487 /// closure in the current function, in which case its
1488 /// `ClosureKind` may not yet be known.
1489pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1490let unresolved_kind_ty = match *closure_ty.kind() {
1491 ty::Closure(_, args) => args.as_closure().kind_ty(),
1492 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1493_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0}",
closure_ty))bug!("unexpected type {closure_ty}"),
1494 };
1495let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1496closure_kind_ty.to_opt_closure_kind()
1497 }
14981499pub fn universe(&self) -> ty::UniverseIndex {
1500self.universe.get()
1501 }
15021503/// Creates and return a fresh universe that extends all previous
1504 /// universes. Updates `self.universe` to that new universe.
1505pub fn create_next_universe(&self) -> ty::UniverseIndex {
1506let u = self.universe.get().next_universe();
1507{
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:1507",
"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(1507u32),
::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:?}");
1508self.universe.set(u);
1509u1510 }
15111512/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1513 /// which contains the necessary information to use the trait system without
1514 /// using canonicalization or carrying this inference context around.
1515pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1516let typing_mode = match self.typing_mode_raw() {
1517// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1518 // to handle them without proper canonicalization. This means we may cause cycle
1519 // errors and fail to reveal opaques while inside of bodies. We should rename this
1520 // function and require explicit comments on all use-sites in the future.
1521ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1522 | ty::TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ } => {
1523TypingMode::non_body_analysis()
1524 }
1525 mode @ (ty::TypingMode::Coherence1526 | ty::TypingMode::PostBorrowck { .. }
1527 | ty::TypingMode::PostAnalysis1528 | ty::TypingMode::Reflection1529 | ty::TypingMode::Codegen) => mode,
1530 ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1531 };
1532 ty::TypingEnv::new(param_env, typing_mode)
1533 }
15341535/// Similar to [`Self::canonicalize_query`], except that it returns
1536 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1537 /// `param_env` to not contain any inference variables or placeholders.
1538pub fn pseudo_canonicalize_query<V>(
1539&self,
1540 param_env: ty::ParamEnv<'tcx>,
1541 value: V,
1542 ) -> PseudoCanonicalInput<'tcx, V>
1543where
1544V: TypeVisitable<TyCtxt<'tcx>>,
1545 {
1546if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1547if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1548if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1549if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1550self.typing_env(param_env).as_query_input(value)
1551 }
15521553/// The returned function is used in a fast path. If it returns `true` the variable is
1554 /// unchanged, `false` indicates that the status is unknown.
1555#[inline]
1556pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1557// This hoists the borrow/release out of the loop body.
1558let inner = self.inner.try_borrow();
15591560move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1561 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1562use self::type_variable::TypeVariableValue;
15631564#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1565 inner.try_type_variables_probe_ref(ty_var),
1566Some(TypeVariableValue::Unknown { .. })
1567 )1568 }
1569_ => false,
1570 }
1571 }
15721573/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1574 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1575 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1576 ///
1577 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1578 /// inlined, despite being large, because it has only two call sites that
1579 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1580 /// inference variables), and it handles both `Ty` and `ty::Const` without
1581 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1582#[inline(always)]
1583pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1584match infer_var {
1585 TyOrConstInferVar::Ty(v) => {
1586use self::type_variable::TypeVariableValue;
15871588// If `inlined_probe` returns a `Known` value, it never equals
1589 // `ty::Infer(ty::TyVar(v))`.
1590match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1591 TypeVariableValue::Unknown { .. } => false,
1592 TypeVariableValue::Known { .. } => true,
1593 }
1594 }
15951596 TyOrConstInferVar::TyInt(v) => {
1597// If `inlined_probe_value` returns a value it's always a
1598 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1599 // `ty::Infer(_)`.
1600self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1601 }
16021603 TyOrConstInferVar::TyFloat(v) => {
1604// If `probe_value` returns a value it's always a
1605 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1606 //
1607 // Not `inlined_probe_value(v)` because this call site is colder.
1608self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1609 }
16101611 TyOrConstInferVar::Const(v) => {
1612// If `probe_value` returns a `Known` value, it never equals
1613 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1614 //
1615 // Not `inlined_probe_value(v)` because this call site is colder.
1616match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1617 ConstVariableValue::Unknown { .. } => false,
1618 ConstVariableValue::Known { .. } => true,
1619 }
1620 }
1621 }
1622 }
16231624/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1625pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1626if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1627self.obligation_inspector.get().is_none(),
1628"shouldn't override a set obligation inspector"
1629);
1630self.obligation_inspector.set(Some(inspector));
1631 }
1632}
16331634/// Helper for [InferCtxt::ty_or_const_infer_var_changed] (see comment on that), currently
1635/// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1636#[derive(#[automatically_derived]
impl ::core::marker::Copy for TyOrConstInferVar { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TyOrConstInferVar {
#[inline]
fn clone(&self) -> TyOrConstInferVar {
let _: ::core::clone::AssertParamIsClone<TyVid>;
let _: ::core::clone::AssertParamIsClone<IntVid>;
let _: ::core::clone::AssertParamIsClone<FloatVid>;
let _: ::core::clone::AssertParamIsClone<ConstVid>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for TyOrConstInferVar {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TyOrConstInferVar::Ty(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ty",
&__self_0),
TyOrConstInferVar::TyInt(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "TyInt",
&__self_0),
TyOrConstInferVar::TyFloat(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TyFloat", &__self_0),
TyOrConstInferVar::Const(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Const",
&__self_0),
}
}
}Debug)]
1637pub enum TyOrConstInferVar {
1638/// Equivalent to `ty::Infer(ty::TyVar(_))`.
1639Ty(TyVid),
1640/// Equivalent to `ty::Infer(ty::IntVar(_))`.
1641TyInt(IntVid),
1642/// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1643TyFloat(FloatVid),
16441645/// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1646Const(ConstVid),
1647}
16481649impl<'tcx> TyOrConstInferVar {
1650/// Tries to extract an inference variable from a type or a constant, returns `None`
1651 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1652 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1653pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1654match arg.kind() {
1655GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1656GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1657GenericArgKind::Lifetime(_) => None,
1658 }
1659 }
16601661/// Tries to extract an inference variable from a type or a constant, returns `None`
1662 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1663 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1664pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1665match term.kind() {
1666TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1667TermKind::Const(ct) => Self::maybe_from_const(ct),
1668 }
1669 }
16701671/// Tries to extract an inference variable from a type, returns `None`
1672 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1673fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1674match *ty.kind() {
1675 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1676 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1677 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1678_ => None,
1679 }
1680 }
16811682/// Tries to extract an inference variable from a constant, returns `None`
1683 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1684fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1685match ct.kind() {
1686 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1687_ => None,
1688 }
1689 }
1690}
16911692/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1693/// Used only for diagnostics.
1694struct InferenceLiteralEraser<'tcx> {
1695 tcx: TyCtxt<'tcx>,
1696}
16971698impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1699fn cx(&self) -> TyCtxt<'tcx> {
1700self.tcx
1701 }
17021703fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1704match ty.kind() {
1705 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1706 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1707_ => ty.super_fold_with(self),
1708 }
1709 }
1710}
17111712impl<'tcx> TypeTrace<'tcx> {
1713pub fn span(&self) -> Span {
1714self.cause.span
1715 }
17161717pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1718TypeTrace {
1719 cause: cause.clone(),
1720 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1721 }
1722 }
17231724pub fn trait_refs(
1725 cause: &ObligationCause<'tcx>,
1726 a: ty::TraitRef<'tcx>,
1727 b: ty::TraitRef<'tcx>,
1728 ) -> TypeTrace<'tcx> {
1729TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1730 }
17311732pub fn consts(
1733 cause: &ObligationCause<'tcx>,
1734 a: ty::Const<'tcx>,
1735 b: ty::Const<'tcx>,
1736 ) -> TypeTrace<'tcx> {
1737TypeTrace {
1738 cause: cause.clone(),
1739 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1740 }
1741 }
1742}
17431744impl<'tcx> SubregionOrigin<'tcx> {
1745pub fn span(&self) -> Span {
1746match *self {
1747 SubregionOrigin::Subtype(ref a) => a.span(),
1748 SubregionOrigin::RelateObjectBound(a) => a,
1749 SubregionOrigin::RelateParamBound(a, ..) => a,
1750 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1751 SubregionOrigin::Reborrow(a) => a,
1752 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1753 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1754 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1755 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1756 SubregionOrigin::SolverRegionConstraint(a) => a,
1757 }
1758 }
17591760pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1761where
1762F: FnOnce() -> Self,
1763 {
1764match *cause.code() {
1765 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1766 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1767 }
17681769 traits::ObligationCauseCode::CompareImplItem {
1770 impl_item_def_id,
1771 trait_item_def_id,
1772 kind: _,
1773 } => SubregionOrigin::CompareImplItemObligation {
1774 span: cause.span,
1775impl_item_def_id,
1776trait_item_def_id,
1777 },
17781779 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1780 impl_item_def_id,
1781 trait_item_def_id,
1782 } => SubregionOrigin::CheckAssociatedTypeBounds {
1783impl_item_def_id,
1784trait_item_def_id,
1785 parent: Box::new(default()),
1786 },
17871788 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1789 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1790 }
17911792 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1793 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1794 }
17951796_ => default(),
1797 }
1798 }
1799}
18001801impl<'tcx> RegionVariableOrigin<'tcx> {
1802pub fn span(&self) -> Span {
1803match *self {
1804 RegionVariableOrigin::Misc(a)
1805 | RegionVariableOrigin::PatternRegion(a)
1806 | RegionVariableOrigin::BorrowRegion(a)
1807 | RegionVariableOrigin::Autoref(a)
1808 | RegionVariableOrigin::Coercion(a)
1809 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1810 | RegionVariableOrigin::BoundRegion(a, ..)
1811 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1812 RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable used with `span`"))bug!("NLL variable used with `span`"),
1813 }
1814 }
1815}
18161817impl<'tcx> InferCtxt<'tcx> {
1818/// Given a [`hir::Block`], get the span of its last expression or
1819 /// statement, peeling off any inner blocks.
1820pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1821let block = block.innermost_block();
1822if let Some(expr) = &block.expr {
1823expr.span
1824 } else if let Some(stmt) = block.stmts.last() {
1825// possibly incorrect trailing `;` in the else arm
1826stmt.span
1827 } else {
1828// empty block; point at its entirety
1829block.span
1830 }
1831 }
18321833/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1834 /// of its last expression or statement, peeling off any inner blocks.
1835pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1836match self.tcx.hir_node(hir_id) {
1837 hir::Node::Block(blk)
1838 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1839self.find_block_span(blk)
1840 }
1841 hir::Node::Expr(e) => e.span,
1842_ => DUMMY_SP,
1843 }
1844 }
1845}
18461847type SolverRegionConstraint<'tcx> =
1848 rustc_type_ir::region_constraint::RegionConstraint<TyCtxt<'tcx>>;
18491850#[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)]
1851struct SolverRegionConstraintStorage<'tcx>(SolverRegionConstraint<'tcx>);
18521853impl<'tcx> SolverRegionConstraintStorage<'tcx> {
1854fn new() -> Self {
1855SolverRegionConstraintStorage(SolverRegionConstraint::And(Box::new([])))
1856 }
18571858fn get_constraint(&self) -> SolverRegionConstraint<'tcx> {
1859self.0.clone()
1860 }
18611862fn pop(&mut self) -> Option<SolverRegionConstraint<'tcx>> {
1863match &mut self.0 {
1864SolverRegionConstraint::And(and) => {
1865let mut and = core::mem::take(and).into_iter().collect::<Vec<_>>();
1866let popped = and.pop()?;
1867self.0 = SolverRegionConstraint::And(and.into_boxed_slice());
1868Some(popped)
1869 }
1870_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1871 }
1872 }
18731874#[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(1874u32),
::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 &mut self.0 {
SolverRegionConstraint::And(and) => {
let and =
core::mem::take(and).into_iter().chain([constraint]).collect::<Vec<_>>().into_boxed_slice();
self.0 = SolverRegionConstraint::And(and);
}
_ =>
::core::panicking::panic("internal error: entered unreachable code"),
}
}
}
}#[instrument(level = "debug")]1875fn push(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1876match &mut self.0 {
1877 SolverRegionConstraint::And(and) => {
1878let and = core::mem::take(and)
1879 .into_iter()
1880 .chain([constraint])
1881 .collect::<Vec<_>>()
1882 .into_boxed_slice();
1883self.0 = SolverRegionConstraint::And(and);
1884 }
1885_ => unreachable!(),
1886 }
1887 }
18881889#[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(1889u32),
::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;
}
{
if !constraint.is_and() {
self.0 =
SolverRegionConstraint::And(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[constraint])).into_boxed_slice())
} else { self.0 = constraint; }
}
}
}#[instrument(level = "debug", skip(self))]1890fn overwrite_solver_region_constraint(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1891if !constraint.is_and() {
1892self.0 = SolverRegionConstraint::And(vec![constraint].into_boxed_slice())
1893 } else {
1894self.0 = constraint;
1895 }
1896 }
1897}