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, 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,
339340pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
341}
342343impl<'tcx> Dropfor InferCtxt<'tcx> {
344fn drop(&mut self) {
345let mut inner = self.inner.borrow_mut();
346let opaque_type_storage = &mut inner.opaque_type_storage;
347348// No need for the drop bomb when we're in `TypingMode::PostTypeckUntilBorrowck`, and the `InferCtxt`
349 // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
350 // in relation to regions. In some places *after* typeck that aren't borrowck, like in lints we use
351 // `TypingMode::PostTypeckUntilBorrowck` to prevent defining opaque types and we simply don't care about regions.
352match self.typing_mode_raw() {
353TypingMode::Coherence354 | TypingMode::Typeck { .. }
355 | TypingMode::PostBorrowck { .. }
356 | TypingMode::PostAnalysis357 | TypingMode::Codegen => {}
358// In erased mode, the opaque type storage is always empty
359TypingMode::ErasedNotCoherence(..) => {}
360TypingMode::PostTypeckUntilBorrowck { .. } => {
361if !self.considering_regions {
362return;
363 }
364 }
365 }
366367if !opaque_type_storage.is_empty() {
368 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:?}")));
369 }
370 }
371}
372373/// See the `error_reporting` module for more details.
374#[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)]
375pub enum ValuePairs<'tcx> {
376 Regions(ExpectedFound<ty::Region<'tcx>>),
377 Terms(ExpectedFound<ty::Term<'tcx>>),
378 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
379 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
380 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
381 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
382 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
383}
384385impl<'tcx> ValuePairs<'tcx> {
386pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
387if let ValuePairs::Terms(ExpectedFound { expected, found }) = self388 && let Some(expected) = expected.as_type()
389 && let Some(found) = found.as_type()
390 {
391Some((expected, found))
392 } else {
393None394 }
395 }
396}
397398/// The trace designates the path through inference that we took to
399/// encounter an error or subtyping constraint.
400///
401/// See the `error_reporting` module for more details.
402#[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)]
403pub struct TypeTrace<'tcx> {
404pub cause: ObligationCause<'tcx>,
405pub values: ValuePairs<'tcx>,
406}
407408/// The origin of a `r1 <= r2` constraint.
409///
410/// See `error_reporting` module for more details
411#[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)]
412pub enum SubregionOrigin<'tcx> {
413/// Arose from a subtyping relation
414Subtype(Box<TypeTrace<'tcx>>),
415416/// When casting `&'a T` to an `&'b Trait` object,
417 /// relating `'a` to `'b`.
418RelateObjectBound(Span),
419420/// Some type parameter was instantiated with the given type,
421 /// and that type must outlive some region.
422RelateParamBound(Span, Ty<'tcx>, Option<Span>),
423424/// The given region parameter was instantiated with a region
425 /// that must outlive some other region.
426RelateRegionParamBound(Span, Option<Ty<'tcx>>),
427428/// Creating a pointer `b` to contents of another reference.
429Reborrow(Span),
430431/// (&'a &'b T) where a >= b
432ReferenceOutlivesReferent(Ty<'tcx>, Span),
433434/// Comparing the signature and requirements of an impl method against
435 /// the containing trait.
436CompareImplItemObligation {
437 span: Span,
438 impl_item_def_id: LocalDefId,
439 trait_item_def_id: DefId,
440 },
441442/// Checking that the bounds of a trait's associated type hold for a given impl.
443CheckAssociatedTypeBounds {
444 parent: Box<SubregionOrigin<'tcx>>,
445 impl_item_def_id: LocalDefId,
446 trait_item_def_id: DefId,
447 },
448449 AscribeUserTypeProvePredicate(Span),
450451// FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
452 // proper diagnostics for solver region constraints.
453SolverRegionConstraint(Span),
454}
455456// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
457#[cfg(target_pointer_width = "64")]
458const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
459460impl<'tcx> SubregionOrigin<'tcx> {
461pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
462match self {
463Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
464Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
465Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
466_ => ConstraintCategory::BoringNoLocation,
467 }
468 }
469}
470471/// Times when we replace bound regions with existentials:
472#[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)]
473pub enum BoundRegionConversionTime {
474/// when a fn is called
475FnCall,
476477/// when two higher-ranked types are compared
478HigherRankedType,
479480/// when projecting an associated type
481AssocTypeProjection(DefId),
482}
483484/// Reasons to create a region inference variable.
485///
486/// See `error_reporting` module for more details.
487#[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)]
488pub enum RegionVariableOrigin<'tcx> {
489/// Region variables created for ill-categorized reasons.
490 ///
491 /// They mostly indicate places in need of refactoring.
492Misc(Span),
493494/// Regions created by a `&P` or `[...]` pattern.
495PatternRegion(Span),
496497/// Regions created by `&` operator.
498BorrowRegion(Span),
499500/// Regions created as part of an autoref of a method receiver.
501Autoref(Span),
502503/// Regions created as part of an automatic coercion.
504Coercion(Span),
505506/// Region variables created as the values for early-bound regions.
507 ///
508 /// FIXME(@lcnr): This should also store a `DefId`, similar to
509 /// `TypeVariableOrigin`.
510RegionParameterDefinition(Span, Symbol),
511512/// Region variables created when instantiating a binder with
513 /// existential variables, e.g. when calling a function or method.
514BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
515516 UpvarRegion(ty::UpvarId, Span),
517518/// This origin is used for the inference variables that we create
519 /// during NLL region processing.
520Nll(NllRegionVariableOrigin<'tcx>),
521}
522523#[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)]
524pub enum NllRegionVariableOrigin<'tcx> {
525/// During NLL region processing, we create variables for free
526 /// regions that we encounter in the function signature and
527 /// elsewhere. This origin indices we've got one of those.
528FreeRegion,
529530/// "Universal" instantiation of a higher-ranked region (e.g.,
531 /// from a `for<'a> T` binder). Meant to represent "any region".
532Placeholder(ty::PlaceholderRegion<'tcx>),
533534 Existential {
535 name: Option<Symbol>,
536 },
537}
538539#[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)]
540pub struct FixupError {
541 unresolved: TyOrConstInferVar,
542}
543544impl fmt::Displayfor FixupError {
545fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546match self.unresolved {
547 TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
548f,
549"cannot determine the type of this integer; \
550 add a suffix to specify the type explicitly"
551),
552 TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
553f,
554"cannot determine the type of this number; \
555 add a suffix to specify the type explicitly"
556),
557 TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
558 TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
559 }
560 }
561}
562563/// See the `region_obligations` field for more information.
564#[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)]
565pub struct TypeOutlivesConstraint<'tcx> {
566pub sub_region: ty::Region<'tcx>,
567pub sup_type: Ty<'tcx>,
568pub origin: SubregionOrigin<'tcx>,
569}
570571/// Used to configure inference contexts before their creation.
572pub struct InferCtxtBuilder<'tcx> {
573 tcx: TyCtxt<'tcx>,
574 considering_regions: bool,
575 in_hir_typeck: bool,
576 skip_leak_check: bool,
577/// Whether we should use the new trait solver in the local inference context,
578 /// which affects things like which solver is used in `predicate_may_hold`.
579next_trait_solver: bool,
580}
581582impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
InferCtxtBuilder {
tcx: self,
considering_regions: true,
in_hir_typeck: false,
skip_leak_check: false,
next_trait_solver: self.next_trait_solver_globally(),
}
}
}#[extension(pub trait TyCtxtInferExt<'tcx>)]583impl<'tcx> TyCtxt<'tcx> {
584fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
585InferCtxtBuilder {
586 tcx: self,
587 considering_regions: true,
588 in_hir_typeck: false,
589 skip_leak_check: false,
590 next_trait_solver: self.next_trait_solver_globally(),
591 }
592 }
593}
594595impl<'tcx> InferCtxtBuilder<'tcx> {
596pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
597self.next_trait_solver = next_trait_solver;
598self599 }
600601pub fn ignoring_regions(mut self) -> Self {
602self.considering_regions = false;
603self604 }
605606pub fn in_hir_typeck(mut self) -> Self {
607self.in_hir_typeck = true;
608self609 }
610611pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
612self.skip_leak_check = skip_leak_check;
613self614 }
615616/// Given a canonical value `C` as a starting point, create an
617 /// inference context that contains each of the bound values
618 /// within instantiated as a fresh variable. The `f` closure is
619 /// invoked with the new infcx, along with the instantiated value
620 /// `V` and a instantiation `S`. This instantiation `S` maps from
621 /// the bound values in `C` to their instantiated values in `V`
622 /// (in other words, `S(C) = V`).
623pub fn build_with_canonical<T>(
624mut self,
625 span: Span,
626 input: &CanonicalQueryInput<'tcx, T>,
627 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
628where
629T: TypeFoldable<TyCtxt<'tcx>>,
630 {
631let infcx = self.build(input.typing_mode.0);
632let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
633 (infcx, value, args)
634 }
635636pub fn build_with_typing_env(
637mut self,
638 typing_env: TypingEnv<'tcx>,
639 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
640 (self.build(typing_env.typing_mode()), typing_env.param_env)
641 }
642643pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
644let InferCtxtBuilder {
645 tcx,
646 considering_regions,
647 in_hir_typeck,
648 skip_leak_check,
649 next_trait_solver,
650 } = *self;
651InferCtxt {
652tcx,
653typing_mode,
654considering_regions,
655in_hir_typeck,
656skip_leak_check,
657 inner: RefCell::new(InferCtxtInner::new()),
658 lexical_region_resolutions: RefCell::new(None),
659 selection_cache: Default::default(),
660 evaluation_cache: Default::default(),
661 reported_trait_errors: Default::default(),
662 reported_signature_mismatch: Default::default(),
663 tainted_by_errors: Cell::new(None),
664 universe: Cell::new(ty::UniverseIndex::ROOT),
665 placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
666next_trait_solver,
667 obligation_inspector: Cell::new(None),
668 }
669 }
670}
671672impl<'tcx, T> InferOk<'tcx, T> {
673/// Extracts `value`, registering any obligations into `fulfill_cx`.
674pub fn into_value_registering_obligations<E: 'tcx>(
675self,
676 infcx: &InferCtxt<'tcx>,
677 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
678 ) -> T {
679let InferOk { value, obligations } = self;
680fulfill_cx.register_predicate_obligations(infcx, obligations);
681value682 }
683}
684685impl<'tcx> InferOk<'tcx, ()> {
686pub fn into_obligations(self) -> PredicateObligations<'tcx> {
687self.obligations
688 }
689}
690691impl<'tcx> InferCtxt<'tcx> {
692pub fn dcx(&self) -> DiagCtxtHandle<'_> {
693self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
694 }
695696pub fn next_trait_solver(&self) -> bool {
697self.next_trait_solver
698 }
699700/// This method is deliberately called `..._raw`,
701 /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
702 /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
703 /// more information.
704 ///
705 /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
706 /// works as a kind of store for for example type unification information.
707 /// `InferCtxt` is also often used outside the trait solver during typeck.
708 /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
709 /// To make sure these two uses are never confused, we want to statically encode this information.
710 ///
711 /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
712 /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
713 /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
714 /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
715 /// match on the variant and can safely ignore it.
716 ///
717 /// Prefer non-raw apis if available. e.g.,
718 /// - On the `FnCtxt`
719 /// - on the `SelectionCtxt`
720#[inline(always)]
721pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
722self.typing_mode
723 }
724725#[inline(always)]
726pub fn disable_trait_solver_fast_paths(&self) -> bool {
727self.tcx.disable_trait_solver_fast_paths()
728 }
729730/// Returns the origin of the type variable identified by `vid`.
731 ///
732 /// No attempt is made to resolve `vid` to its root variable.
733pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
734self.inner.borrow_mut().type_variables().var_origin(vid)
735 }
736737/// Returns the origin of the float type variable identified by `vid`.
738 ///
739 /// No attempt is made to resolve `vid` to its root variable.
740pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
741self.inner.borrow_mut().float_origin_origin_storage[vid]
742 }
743744/// Returns the origin of the const variable identified by `vid`
745// FIXME: We should store origins separately from the unification table
746 // so this doesn't need to be optional.
747pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
748match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
749 ConstVariableValue::Known { .. } => None,
750 ConstVariableValue::Unknown { origin, .. } => Some(origin),
751 }
752 }
753754pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
755let mut inner = self.inner.borrow_mut();
756let mut vars: Vec<Ty<'_>> = inner757 .type_variables()
758 .unresolved_variables()
759 .into_iter()
760 .map(|t| Ty::new_var(self.tcx, t))
761 .collect();
762vars.extend(
763 (0..inner.int_unification_table().len())
764 .map(|i| ty::IntVid::from_usize(i))
765 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
766 .map(|v| Ty::new_int_var(self.tcx, v)),
767 );
768vars.extend(
769 (0..inner.float_unification_table().len())
770 .map(|i| ty::FloatVid::from_usize(i))
771 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
772 .map(|v| Ty::new_float_var(self.tcx, v)),
773 );
774vars775 }
776777#[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(777u32),
::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")]778pub fn sub_regions(
779&self,
780 origin: SubregionOrigin<'tcx>,
781 a: ty::Region<'tcx>,
782 b: ty::Region<'tcx>,
783 vis: ty::VisibleForLeakCheck,
784 ) {
785self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
786 }
787788#[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(788u32),
::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")]789pub fn equate_regions(
790&self,
791 origin: SubregionOrigin<'tcx>,
792 a: ty::Region<'tcx>,
793 b: ty::Region<'tcx>,
794 vis: ty::VisibleForLeakCheck,
795 ) {
796self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
797 }
798799/// Processes a `Coerce` predicate from the fulfillment context.
800 /// This is NOT the preferred way to handle coercion, which is to
801 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
802 ///
803 /// This method here is actually a fallback that winds up being
804 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
805 /// and records a coercion predicate. Presently, this method is equivalent
806 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
807 /// actually requiring `a <: b`. This is of course a valid coercion,
808 /// but it's not as flexible as `FnCtxt::coerce` would be.
809 ///
810 /// (We may refactor this in the future, but there are a number of
811 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
812 /// records adjustments that are required on the HIR in order to perform
813 /// the coercion, and we don't currently have a way to manage that.)
814pub fn coerce_predicate(
815&self,
816 cause: &ObligationCause<'tcx>,
817 param_env: ty::ParamEnv<'tcx>,
818 predicate: ty::PolyCoercePredicate<'tcx>,
819 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
820let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
821 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
822a: p.a,
823 b: p.b,
824 });
825self.subtype_predicate(cause, param_env, subtype_predicate)
826 }
827828pub fn subtype_predicate(
829&self,
830 cause: &ObligationCause<'tcx>,
831 param_env: ty::ParamEnv<'tcx>,
832 predicate: ty::PolySubtypePredicate<'tcx>,
833 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
834// Check for two unresolved inference variables, in which case we can
835 // make no progress. This is partly a micro-optimization, but it's
836 // also an opportunity to "sub-unify" the variables. This isn't
837 // *necessary* to prevent cycles, because they would eventually be sub-unified
838 // anyhow during generalization, but it helps with diagnostics (we can detect
839 // earlier that they are sub-unified).
840 //
841 // Note that we can just skip the binders here because
842 // type variables can't (at present, at
843 // least) capture any of the things bound by this binder.
844 //
845 // Note that this sub here is not just for diagnostics - it has semantic
846 // effects as well.
847let r_a = self.shallow_resolve(predicate.skip_binder().a);
848let r_b = self.shallow_resolve(predicate.skip_binder().b);
849match (r_a.kind(), r_b.kind()) {
850 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
851self.sub_unify_ty_vids_raw(a_vid, b_vid);
852return Err((a_vid, b_vid));
853 }
854_ => {}
855 }
856857self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
858if a_is_expected {
859Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
860 } else {
861Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
862 }
863 })
864 }
865866/// Number of type variables created so far.
867pub fn num_ty_vars(&self) -> usize {
868self.inner.borrow_mut().type_variables().num_vars()
869 }
870871pub fn next_ty_vid(&self, span: Span) -> TyVid {
872self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
873 }
874875pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
876self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
877 }
878879pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
880let origin = TypeVariableOrigin { span, param_def_id: None };
881self.inner.borrow_mut().type_variables().new_var(universe, origin)
882 }
883884pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
885self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
886 }
887888pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
889let vid = self.next_ty_vid_with_origin(origin);
890Ty::new_var(self.tcx, vid)
891 }
892893pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
894let vid = self.next_ty_vid_in_universe(span, universe);
895Ty::new_var(self.tcx, vid)
896 }
897898pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
899self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
900 }
901902pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
903let vid = self904 .inner
905 .borrow_mut()
906 .const_unification_table()
907 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
908 .vid;
909 ty::Const::new_var(self.tcx, vid)
910 }
911912pub fn next_const_var_in_universe(
913&self,
914 span: Span,
915 universe: ty::UniverseIndex,
916 ) -> ty::Const<'tcx> {
917let origin = ConstVariableOrigin { span, param_def_id: None };
918let vid = self919 .inner
920 .borrow_mut()
921 .const_unification_table()
922 .new_key(ConstVariableValue::Unknown { origin, universe })
923 .vid;
924 ty::Const::new_var(self.tcx, vid)
925 }
926927pub fn next_int_var(&self) -> Ty<'tcx> {
928let next_int_var_id =
929self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
930Ty::new_int_var(self.tcx, next_int_var_id)
931 }
932933pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
934let mut inner = self.inner.borrow_mut();
935let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
936let origin = FloatVariableOrigin { span, lint_id };
937let span_index = inner.float_origin_origin_storage.push(origin);
938if 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);
939Ty::new_float_var(self.tcx, next_float_var_id)
940 }
941942/// Creates a fresh region variable with the next available index.
943 /// The variable will be created in the maximum universe created
944 /// thus far, allowing it to name any region created thus far.
945pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
946self.next_region_var_in_universe(origin, self.universe())
947 }
948949/// Creates a fresh region variable with the next available index
950 /// in the given universe; typically, you can use
951 /// `next_region_var` and just use the maximal universe.
952pub fn next_region_var_in_universe(
953&self,
954 origin: RegionVariableOrigin<'tcx>,
955 universe: ty::UniverseIndex,
956 ) -> ty::Region<'tcx> {
957let region_var =
958self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
959 ty::Region::new_var(self.tcx, region_var)
960 }
961962pub fn next_term_var_of_alias_kind(
963&self,
964 alias_term: ty::AliasTerm<'tcx>,
965 span: Span,
966 ) -> ty::Term<'tcx> {
967match alias_term.kind {
968 ty::AliasTermKind::ProjectionTy { .. }
969 | ty::AliasTermKind::InherentTy { .. }
970 | ty::AliasTermKind::OpaqueTy { .. }
971 | ty::AliasTermKind::FreeTy { .. } => self.next_ty_var(span).into(),
972 ty::AliasTermKind::FreeConst { .. }
973 | ty::AliasTermKind::InherentConst { .. }
974 | ty::AliasTermKind::AnonConst { .. }
975 | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_var(span).into(),
976 }
977 }
978979/// Return the universe that the region `r` was created in. For
980 /// most regions (e.g., `'static`, named regions from the user,
981 /// etc) this is the root universe U0. For inference variables or
982 /// placeholders, however, it will return the universe which they
983 /// are associated.
984pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
985self.inner.borrow_mut().unwrap_region_constraints().universe(r)
986 }
987988/// Number of region variables created so far.
989pub fn num_region_vars(&self) -> usize {
990self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
991 }
992993/// Just a convenient wrapper of `next_region_var` for using during NLL.
994#[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(994u32),
::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")]995pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
996self.next_region_var(RegionVariableOrigin::Nll(origin))
997 }
998999/// Just a convenient wrapper of `next_region_var` for using during NLL.
1000#[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(1000u32),
::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")]1001pub fn next_nll_region_var_in_universe(
1002&self,
1003 origin: NllRegionVariableOrigin<'tcx>,
1004 universe: ty::UniverseIndex,
1005 ) -> ty::Region<'tcx> {
1006self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1007 }
10081009pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1010match param.kind {
1011 GenericParamDefKind::Lifetime => {
1012// Create a region inference variable for the given
1013 // region parameter definition.
1014self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1015span, param.name,
1016 ))
1017 .into()
1018 }
1019 GenericParamDefKind::Type { .. } => {
1020// Create a type inference variable for the given
1021 // type parameter definition. The generic parameters are
1022 // for actual parameters that may be referred to by
1023 // the default of this type parameter, if it exists.
1024 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1025 // used in a path such as `Foo::<T, U>::new()` will
1026 // use an inference variable for `C` with `[T, U]`
1027 // as the generic parameters for the default, `(T, U)`.
1028let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1029self.universe(),
1030TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1031 );
10321033Ty::new_var(self.tcx, ty_var_id).into()
1034 }
1035 GenericParamDefKind::Const { .. } => {
1036let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1037let const_var_id = self1038 .inner
1039 .borrow_mut()
1040 .const_unification_table()
1041 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1042 .vid;
1043 ty::Const::new_var(self.tcx, const_var_id).into()
1044 }
1045 }
1046 }
10471048/// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1049 /// each type/region parameter to a fresh inference variable.
1050pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
1051GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1052 }
10531054/// Returns `true` if errors have been reported since this infcx was
1055 /// created. This is sometimes used as a heuristic to skip
1056 /// reporting errors that often occur as a result of earlier
1057 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1058 /// inference variables, regionck errors).
1059#[must_use = "this method does not have any side effects"]
1060pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1061self.tainted_by_errors.get()
1062 }
10631064/// Set the "tainted by errors" flag to true. We call this when we
1065 /// observe an error from a prior pass.
1066pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1067{
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:1067",
"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(1067u32),
::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)");
1068self.tainted_by_errors.set(Some(e));
1069 }
10701071pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1072let mut inner = self.inner.borrow_mut();
1073let inner = &mut *inner;
1074inner.unwrap_region_constraints().var_origin(vid)
1075 }
10761077/// Clone the list of variable regions. This is used only during NLL processing
1078 /// to put the set of region variables into the NLL region context.
1079pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1080let inner = self.inner.borrow();
1081if !!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));
1082let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1083if !storage.data.is_empty() {
{ ::core::panicking::panic_fmt(format_args!("{0:#?}", storage.data)); }
};assert!(storage.data.is_empty(), "{:#?}", storage.data);
1084// We clone instead of taking because borrowck still wants to use the
1085 // inference context after calling this for diagnostics and the new
1086 // trait solver.
1087storage.var_infos.clone()
1088 }
10891090pub fn has_opaque_types_in_storage(&self) -> bool {
1091 !self.inner.borrow().opaque_type_storage.is_empty()
1092 }
10931094x;#[instrument(level = "debug", skip(self), ret)]1095pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1096self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1097 }
10981099x;#[instrument(level = "debug", skip(self), ret)]1100pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1101self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1102 }
11031104pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1105if !self.next_trait_solver() {
1106return false;
1107 }
11081109let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1110let inner = &mut *self.inner.borrow_mut();
1111let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1112inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1113if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1114let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1115if opaque_sub_vid == ty_sub_vid {
1116return true;
1117 }
1118 }
11191120false
1121})
1122 }
11231124/// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1125 ///
1126 /// This only checks for a subtype relation, it does not require equality.
1127pub fn opaques_with_sub_unified_hidden_type(
1128&self,
1129 ty_vid: TyVid,
1130 ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1131// Avoid accidentally allowing more code to compile with the old solver.
1132if !self.next_trait_solver() {
1133return ::alloc::vec::Vec::new()vec![];
1134 }
11351136let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1137let inner = &mut *self.inner.borrow_mut();
1138// This is iffy, can't call `type_variables()` as we're already
1139 // borrowing the `opaque_type_storage` here.
1140let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1141inner1142 .opaque_type_storage
1143 .iter_opaque_types()
1144 .filter_map(|(key, hidden_ty)| {
1145if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1146let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1147if opaque_sub_vid == ty_sub_vid {
1148return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1149self.tcx,
1150key.def_id.into(),
1151key.args,
1152 ));
1153 }
1154 }
11551156None1157 })
1158 .collect()
1159 }
11601161#[inline(always)]
1162pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1163if true {
if !!self.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.next_trait_solver()")
};
};debug_assert!(!self.next_trait_solver());
1164match self.typing_mode_raw().assert_not_erased() {
1165TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1166 | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types } => {
1167id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1168 }
1169// FIXME(#132279): This function is quite weird in post-analysis
1170 // and post-borrowck analysis mode. We may need to modify its uses
1171 // to support PostBorrowck in the old solver as well.
1172TypingMode::Coherence1173 | TypingMode::PostBorrowck { .. }
1174 | TypingMode::PostAnalysis1175 | TypingMode::Codegen => false,
1176 }
1177 }
11781179pub fn push_hir_typeck_potentially_region_dependent_goal(
1180&self,
1181 goal: PredicateObligation<'tcx>,
1182 ) {
1183let mut inner = self.inner.borrow_mut();
1184inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1185inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1186 }
11871188pub fn take_hir_typeck_potentially_region_dependent_goals(
1189&self,
1190 ) -> Vec<PredicateObligation<'tcx>> {
1191if !!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");
1192 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1193 }
11941195pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1196self.resolve_vars_if_possible(t).to_string()
1197 }
11981199/// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1200 /// universe index of `TyVar(vid)`.
1201pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1202use self::type_variable::TypeVariableValue;
12031204match self.inner.borrow_mut().type_variables().probe(vid) {
1205 TypeVariableValue::Known { value } => Ok(value),
1206 TypeVariableValue::Unknown { universe } => Err(universe),
1207 }
1208 }
12091210pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1211if let ty::Infer(v) = *ty.kind() {
1212match v {
1213 ty::TyVar(v) => {
1214// Not entirely obvious: if `typ` is a type variable,
1215 // it can be resolved to an int/float variable, which
1216 // can then be recursively resolved, hence the
1217 // recursion. Note though that we prevent type
1218 // variables from unifying to other type variables
1219 // directly (though they may be embedded
1220 // structurally), and we prevent cycles in any case,
1221 // so this recursion should always be of very limited
1222 // depth.
1223 //
1224 // Note: if these two lines are combined into one we get
1225 // dynamic borrow errors on `self.inner`.
1226let known = self.inner.borrow_mut().type_variables().probe(v).known();
1227known.map_or(ty, |t| self.shallow_resolve(t))
1228 }
12291230 ty::IntVar(v) => {
1231match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1232 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1233 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1234 ty::IntVarValue::Unknown => ty,
1235 }
1236 }
12371238 ty::FloatVar(v) => {
1239match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1240 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1241 ty::FloatVarValue::Unknown => ty,
1242 }
1243 }
12441245 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1246 }
1247 } else {
1248ty1249 }
1250 }
12511252pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1253match ct.kind() {
1254 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1255 InferConst::Var(vid) => self1256 .inner
1257 .borrow_mut()
1258 .const_unification_table()
1259 .probe_value(vid)
1260 .known()
1261 .unwrap_or(ct),
1262 InferConst::Fresh(_) => ct,
1263 },
12641265 ty::ConstKind::Param(_)
1266 | ty::ConstKind::Bound(_, _)
1267 | ty::ConstKind::Placeholder(_)
1268 | ty::ConstKind::Alias(_, _)
1269 | ty::ConstKind::Value(_)
1270 | ty::ConstKind::Error(_)
1271 | ty::ConstKind::Expr(_) => ct,
1272 }
1273 }
12741275pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1276match term.kind() {
1277 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1278 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1279 }
1280 }
12811282pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1283self.inner.borrow_mut().type_variables().root_var(var)
1284 }
12851286pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1287self.inner.borrow_mut().type_variables().sub_unify(a, b);
1288 }
12891290pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1291self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1292 }
12931294pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1295self.inner.borrow_mut().float_unification_table().find(var)
1296 }
12971298pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1299self.inner.borrow_mut().const_unification_table().find(var).vid
1300 }
13011302/// Resolves an int var to a rigid int type, if it was constrained to one,
1303 /// or else the root int var in the unification table.
1304pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1305let mut inner = self.inner.borrow_mut();
1306let value = inner.int_unification_table().probe_value(vid);
1307match value {
1308 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1309 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1310 ty::IntVarValue::Unknown => {
1311Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1312 }
1313 }
1314 }
13151316/// Resolves a float var to a rigid int type, if it was constrained to one,
1317 /// or else the root float var in the unification table.
1318pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1319let mut inner = self.inner.borrow_mut();
1320let value = inner.float_unification_table().probe_value(vid);
1321match value {
1322 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1323 ty::FloatVarValue::Unknown => {
1324Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1325 }
1326 }
1327 }
13281329/// Where possible, replaces type/const variables in
1330 /// `value` with their final value. Note that region variables
1331 /// are unaffected. If a type/const variable has not been unified, it
1332 /// is left as is. This is an idempotent operation that does
1333 /// not affect inference state in any way and so you can do it
1334 /// at will.
1335pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1336where
1337T: TypeFoldable<TyCtxt<'tcx>>,
1338 {
1339if let Err(guar) = value.error_reported() {
1340self.set_tainted_by_errors(guar);
1341 }
1342if !value.has_non_region_infer() {
1343return value;
1344 }
1345let mut r = resolve::OpportunisticVarResolver::new(self);
1346value.fold_with(&mut r)
1347 }
13481349pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1350where
1351T: TypeFoldable<TyCtxt<'tcx>>,
1352 {
1353if !value.has_infer() {
1354return value; // Avoid duplicated type-folding.
1355}
1356let mut r = InferenceLiteralEraser { tcx: self.tcx };
1357value.fold_with(&mut r)
1358 }
13591360pub fn try_resolve_const_var(
1361&self,
1362 vid: ty::ConstVid,
1363 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1364match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1365 ConstVariableValue::Known { value } => Ok(value),
1366 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1367 }
1368 }
13691370/// Attempts to resolve all type/region/const variables in
1371 /// `value`. Region inference must have been run already (e.g.,
1372 /// by calling `resolve_regions_and_report_errors`). If some
1373 /// variable was never unified, an `Err` results.
1374 ///
1375 /// This method is idempotent, but it not typically not invoked
1376 /// except during the writeback phase.
1377pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1378match resolve::fully_resolve(self, value) {
1379Ok(value) => {
1380if value.has_non_region_infer() {
1381::rustc_middle::util::bug::bug_fmt(format_args!("`{0:?}` is not fully resolved",
value));bug!("`{value:?}` is not fully resolved");
1382 }
1383if value.has_infer_regions() {
1384let 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"));
1385Ok(fold_regions(self.tcx, value, |re, _| {
1386if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1387 }))
1388 } else {
1389Ok(value)
1390 }
1391 }
1392Err(e) => Err(e),
1393 }
1394 }
13951396// Instantiates the bound variables in a given binder with fresh inference
1397 // variables in the current universe.
1398 //
1399 // Use this method if you'd like to find some generic parameters of the binder's
1400 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1401 // that corresponds to your use case, consider whether or not you should
1402 // use [`InferCtxt::enter_forall`] instead.
1403pub fn instantiate_binder_with_fresh_vars<T>(
1404&self,
1405 span: Span,
1406 lbrct: BoundRegionConversionTime,
1407 value: ty::Binder<'tcx, T>,
1408 ) -> T
1409where
1410T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1411 {
1412if let Some(inner) = value.no_bound_vars() {
1413return inner;
1414 }
14151416let bound_vars = value.bound_vars();
1417let mut args = Vec::with_capacity(bound_vars.len());
14181419for bound_var_kind in bound_vars {
1420let arg: ty::GenericArg<'_> = match bound_var_kind {
1421 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1422 ty::BoundVariableKind::Region(br) => {
1423self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1424 }
1425 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1426 };
1427 args.push(arg);
1428 }
14291430struct ToFreshVars<'tcx> {
1431 args: Vec<ty::GenericArg<'tcx>>,
1432 }
14331434impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1435fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1436self.args[br.var.index()].expect_region()
1437 }
1438fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1439self.args[bt.var.index()].expect_ty()
1440 }
1441fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1442self.args[bc.var.index()].expect_const()
1443 }
1444 }
1445let delegate = ToFreshVars { args };
1446self.tcx.replace_bound_vars_uncached(value, delegate)
1447 }
14481449/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1450pub(crate) fn verify_generic_bound(
1451&self,
1452 origin: SubregionOrigin<'tcx>,
1453 kind: GenericKind<'tcx>,
1454 a: ty::Region<'tcx>,
1455 bound: VerifyBound<'tcx>,
1456 ) {
1457{
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:1457",
"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(1457u32),
::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);
14581459self.inner
1460 .borrow_mut()
1461 .unwrap_region_constraints()
1462 .verify_generic_bound(origin, kind, a, bound);
1463 }
14641465/// Obtains the latest type of the given closure; this may be a
1466 /// closure in the current function, in which case its
1467 /// `ClosureKind` may not yet be known.
1468pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1469let unresolved_kind_ty = match *closure_ty.kind() {
1470 ty::Closure(_, args) => args.as_closure().kind_ty(),
1471 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1472_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0}",
closure_ty))bug!("unexpected type {closure_ty}"),
1473 };
1474let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1475closure_kind_ty.to_opt_closure_kind()
1476 }
14771478pub fn universe(&self) -> ty::UniverseIndex {
1479self.universe.get()
1480 }
14811482/// Creates and return a fresh universe that extends all previous
1483 /// universes. Updates `self.universe` to that new universe.
1484pub fn create_next_universe(&self) -> ty::UniverseIndex {
1485let u = self.universe.get().next_universe();
1486{
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:1486",
"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(1486u32),
::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:?}");
1487self.universe.set(u);
1488u1489 }
14901491/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1492 /// which contains the necessary information to use the trait system without
1493 /// using canonicalization or carrying this inference context around.
1494pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1495let typing_mode = match self.typing_mode_raw() {
1496// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1497 // to handle them without proper canonicalization. This means we may cause cycle
1498 // errors and fail to reveal opaques while inside of bodies. We should rename this
1499 // function and require explicit comments on all use-sites in the future.
1500ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1501 | ty::TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ } => {
1502TypingMode::non_body_analysis()
1503 }
1504 mode @ (ty::TypingMode::Coherence1505 | ty::TypingMode::PostBorrowck { .. }
1506 | ty::TypingMode::PostAnalysis1507 | ty::TypingMode::Codegen) => mode,
1508 ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1509 };
1510 ty::TypingEnv::new(param_env, typing_mode)
1511 }
15121513/// Similar to [`Self::canonicalize_query`], except that it returns
1514 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1515 /// `param_env` to not contain any inference variables or placeholders.
1516pub fn pseudo_canonicalize_query<V>(
1517&self,
1518 param_env: ty::ParamEnv<'tcx>,
1519 value: V,
1520 ) -> PseudoCanonicalInput<'tcx, V>
1521where
1522V: TypeVisitable<TyCtxt<'tcx>>,
1523 {
1524if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1525if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1526if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1527if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1528self.typing_env(param_env).as_query_input(value)
1529 }
15301531/// The returned function is used in a fast path. If it returns `true` the variable is
1532 /// unchanged, `false` indicates that the status is unknown.
1533#[inline]
1534pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1535// This hoists the borrow/release out of the loop body.
1536let inner = self.inner.try_borrow();
15371538move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1539 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1540use self::type_variable::TypeVariableValue;
15411542#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1543 inner.try_type_variables_probe_ref(ty_var),
1544Some(TypeVariableValue::Unknown { .. })
1545 )1546 }
1547_ => false,
1548 }
1549 }
15501551/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1552 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1553 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1554 ///
1555 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1556 /// inlined, despite being large, because it has only two call sites that
1557 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1558 /// inference variables), and it handles both `Ty` and `ty::Const` without
1559 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1560#[inline(always)]
1561pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1562match infer_var {
1563 TyOrConstInferVar::Ty(v) => {
1564use self::type_variable::TypeVariableValue;
15651566// If `inlined_probe` returns a `Known` value, it never equals
1567 // `ty::Infer(ty::TyVar(v))`.
1568match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1569 TypeVariableValue::Unknown { .. } => false,
1570 TypeVariableValue::Known { .. } => true,
1571 }
1572 }
15731574 TyOrConstInferVar::TyInt(v) => {
1575// If `inlined_probe_value` returns a value it's always a
1576 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1577 // `ty::Infer(_)`.
1578self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1579 }
15801581 TyOrConstInferVar::TyFloat(v) => {
1582// If `probe_value` returns a value it's always a
1583 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1584 //
1585 // Not `inlined_probe_value(v)` because this call site is colder.
1586self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1587 }
15881589 TyOrConstInferVar::Const(v) => {
1590// If `probe_value` returns a `Known` value, it never equals
1591 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1592 //
1593 // Not `inlined_probe_value(v)` because this call site is colder.
1594match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1595 ConstVariableValue::Unknown { .. } => false,
1596 ConstVariableValue::Known { .. } => true,
1597 }
1598 }
1599 }
1600 }
16011602/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1603pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1604if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1605self.obligation_inspector.get().is_none(),
1606"shouldn't override a set obligation inspector"
1607);
1608self.obligation_inspector.set(Some(inspector));
1609 }
1610}
16111612/// Helper for [InferCtxt::ty_or_const_infer_var_changed] (see comment on that), currently
1613/// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1614#[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)]
1615pub enum TyOrConstInferVar {
1616/// Equivalent to `ty::Infer(ty::TyVar(_))`.
1617Ty(TyVid),
1618/// Equivalent to `ty::Infer(ty::IntVar(_))`.
1619TyInt(IntVid),
1620/// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1621TyFloat(FloatVid),
16221623/// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1624Const(ConstVid),
1625}
16261627impl<'tcx> TyOrConstInferVar {
1628/// Tries to extract an inference variable from a type or a constant, returns `None`
1629 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1630 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1631pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1632match arg.kind() {
1633GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1634GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1635GenericArgKind::Lifetime(_) => None,
1636 }
1637 }
16381639/// Tries to extract an inference variable from a type or a constant, returns `None`
1640 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1641 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1642pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1643match term.kind() {
1644TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1645TermKind::Const(ct) => Self::maybe_from_const(ct),
1646 }
1647 }
16481649/// Tries to extract an inference variable from a type, returns `None`
1650 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1651fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1652match *ty.kind() {
1653 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1654 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1655 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1656_ => None,
1657 }
1658 }
16591660/// Tries to extract an inference variable from a constant, returns `None`
1661 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1662fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1663match ct.kind() {
1664 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1665_ => None,
1666 }
1667 }
1668}
16691670/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1671/// Used only for diagnostics.
1672struct InferenceLiteralEraser<'tcx> {
1673 tcx: TyCtxt<'tcx>,
1674}
16751676impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1677fn cx(&self) -> TyCtxt<'tcx> {
1678self.tcx
1679 }
16801681fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1682match ty.kind() {
1683 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1684 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1685_ => ty.super_fold_with(self),
1686 }
1687 }
1688}
16891690impl<'tcx> TypeTrace<'tcx> {
1691pub fn span(&self) -> Span {
1692self.cause.span
1693 }
16941695pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1696TypeTrace {
1697 cause: cause.clone(),
1698 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1699 }
1700 }
17011702pub fn trait_refs(
1703 cause: &ObligationCause<'tcx>,
1704 a: ty::TraitRef<'tcx>,
1705 b: ty::TraitRef<'tcx>,
1706 ) -> TypeTrace<'tcx> {
1707TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1708 }
17091710pub fn consts(
1711 cause: &ObligationCause<'tcx>,
1712 a: ty::Const<'tcx>,
1713 b: ty::Const<'tcx>,
1714 ) -> TypeTrace<'tcx> {
1715TypeTrace {
1716 cause: cause.clone(),
1717 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1718 }
1719 }
1720}
17211722impl<'tcx> SubregionOrigin<'tcx> {
1723pub fn span(&self) -> Span {
1724match *self {
1725 SubregionOrigin::Subtype(ref a) => a.span(),
1726 SubregionOrigin::RelateObjectBound(a) => a,
1727 SubregionOrigin::RelateParamBound(a, ..) => a,
1728 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1729 SubregionOrigin::Reborrow(a) => a,
1730 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1731 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1732 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1733 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1734 SubregionOrigin::SolverRegionConstraint(a) => a,
1735 }
1736 }
17371738pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1739where
1740F: FnOnce() -> Self,
1741 {
1742match *cause.code() {
1743 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1744 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1745 }
17461747 traits::ObligationCauseCode::CompareImplItem {
1748 impl_item_def_id,
1749 trait_item_def_id,
1750 kind: _,
1751 } => SubregionOrigin::CompareImplItemObligation {
1752 span: cause.span,
1753impl_item_def_id,
1754trait_item_def_id,
1755 },
17561757 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1758 impl_item_def_id,
1759 trait_item_def_id,
1760 } => SubregionOrigin::CheckAssociatedTypeBounds {
1761impl_item_def_id,
1762trait_item_def_id,
1763 parent: Box::new(default()),
1764 },
17651766 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1767 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1768 }
17691770 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1771 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1772 }
17731774_ => default(),
1775 }
1776 }
1777}
17781779impl<'tcx> RegionVariableOrigin<'tcx> {
1780pub fn span(&self) -> Span {
1781match *self {
1782 RegionVariableOrigin::Misc(a)
1783 | RegionVariableOrigin::PatternRegion(a)
1784 | RegionVariableOrigin::BorrowRegion(a)
1785 | RegionVariableOrigin::Autoref(a)
1786 | RegionVariableOrigin::Coercion(a)
1787 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1788 | RegionVariableOrigin::BoundRegion(a, ..)
1789 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1790 RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable used with `span`"))bug!("NLL variable used with `span`"),
1791 }
1792 }
1793}
17941795impl<'tcx> InferCtxt<'tcx> {
1796/// Given a [`hir::Block`], get the span of its last expression or
1797 /// statement, peeling off any inner blocks.
1798pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1799let block = block.innermost_block();
1800if let Some(expr) = &block.expr {
1801expr.span
1802 } else if let Some(stmt) = block.stmts.last() {
1803// possibly incorrect trailing `;` in the else arm
1804stmt.span
1805 } else {
1806// empty block; point at its entirety
1807block.span
1808 }
1809 }
18101811/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1812 /// of its last expression or statement, peeling off any inner blocks.
1813pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1814match self.tcx.hir_node(hir_id) {
1815 hir::Node::Block(blk)
1816 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1817self.find_block_span(blk)
1818 }
1819 hir::Node::Expr(e) => e.span,
1820_ => DUMMY_SP,
1821 }
1822 }
1823}
18241825type SolverRegionConstraint<'tcx> =
1826 rustc_type_ir::region_constraint::RegionConstraint<TyCtxt<'tcx>>;
18271828#[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)]
1829struct SolverRegionConstraintStorage<'tcx>(SolverRegionConstraint<'tcx>);
18301831impl<'tcx> SolverRegionConstraintStorage<'tcx> {
1832fn new() -> Self {
1833SolverRegionConstraintStorage(SolverRegionConstraint::And(Box::new([])))
1834 }
18351836fn get_constraint(&self) -> SolverRegionConstraint<'tcx> {
1837self.0.clone()
1838 }
18391840fn pop(&mut self) -> Option<SolverRegionConstraint<'tcx>> {
1841match &mut self.0 {
1842SolverRegionConstraint::And(and) => {
1843let mut and = core::mem::take(and).into_iter().collect::<Vec<_>>();
1844let popped = and.pop()?;
1845self.0 = SolverRegionConstraint::And(and.into_boxed_slice());
1846Some(popped)
1847 }
1848_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1849 }
1850 }
18511852#[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(1852u32),
::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")]1853fn push(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1854match &mut self.0 {
1855 SolverRegionConstraint::And(and) => {
1856let and = core::mem::take(and)
1857 .into_iter()
1858 .chain([constraint])
1859 .collect::<Vec<_>>()
1860 .into_boxed_slice();
1861self.0 = SolverRegionConstraint::And(and);
1862 }
1863_ => unreachable!(),
1864 }
1865 }
18661867#[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(1867u32),
::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))]1868fn overwrite_solver_region_constraint(&mut self, constraint: SolverRegionConstraint<'tcx>) {
1869if !constraint.is_and() {
1870self.0 = SolverRegionConstraint::And(vec![constraint].into_boxed_slice())
1871 } else {
1872self.0 = constraint;
1873 }
1874 }
1875}