1use std::cell::{Cell, RefCell};
2use std::fmt;
34pub use at::DefineOpaqueTypes;
5use free_regions::RegionRelations;
6pub use freshen::TypeFreshener;
7use lexical_region_resolve::LexicalRegionResolutions;
8pub use lexical_region_resolve::RegionResolutionError;
9pub use opaque_types::{OpaqueTypeStorage, OpaqueTypeStorageEntries, OpaqueTypeTable};
10use region_constraints::{
11GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
12};
13pub use relate::combine::PredicateEmittingRelation;
14use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
15use rustc_data_structures::snapshot_vecas sv;
16use rustc_data_structures::undo_log::{Rollback, UndoLogs};
17use rustc_data_structures::unify::{selfas ut, UnifyKey, UnifyValue};
18use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
19use rustc_hir::def_id::{DefId, LocalDefId};
20use rustc_hir::{selfas hir, HirId};
21use rustc_index::IndexVec;
22use rustc_macros::extension;
23pub use rustc_macros::{TypeFoldable, TypeVisitable};
24use rustc_middle::bug;
25use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
26use rustc_middle::mir::ConstraintCategory;
27use rustc_middle::traits::select;
28use rustc_middle::traits::solve::Goal;
29use rustc_middle::ty::error::{ExpectedFound, TypeError};
30use rustc_middle::ty::{
31self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
32GenericArgsRef, GenericParamDefKind, InferConst, OpaqueTypeKey, ProvisionalHiddenType,
33PseudoCanonicalInput, RegionExt, Term, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder,
34TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
35};
36use rustc_span::{DUMMY_SP, Span, Symbol};
37use rustc_type_ir::{CanonicalizerState, MayBeErased};
38use snapshot::undo_log::InferCtxtUndoLogs;
39use tracing::{debug, instrument};
40use ty::solve::TyOrConstInferVar;
41use type_variable::TypeVariableOrigin;
4243use crate::infer::snapshot::undo_log::UndoLog;
44use crate::infer::type_variable::{FloatVariableOrigin, TypeVariableValue};
45use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
46use crate::traits::{
47self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
48TraitEngine,
49};
5051pub mod at;
52pub mod canonical;
53mod context;
54mod free_regions;
55mod freshen;
56mod lexical_region_resolve;
57mod opaque_types;
58pub mod outlives;
59mod projection;
60pub mod region_constraints;
61pub mod relate;
62pub mod resolve;
63pub(crate) mod snapshot;
64mod solver_region_constraints;
65mod type_variable;
66mod unify_key;
6768pub use solver_region_constraints::SolverRegionConstraint;
69use solver_region_constraints::SolverRegionConstraintStorage;
7071/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
72/// around `PredicateObligations<'tcx>`, but it has one important property:
73/// because `InferOk` is marked with `#[must_use]`, if you have a method
74/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
75/// `infcx.f()?;` you'll get a warning about the obligations being discarded
76/// without use, which is probably unintentional and has been a source of bugs
77/// in the past.
78#[must_use]
79#[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)]
80pub struct InferOk<'tcx, T> {
81pub value: T,
82pub obligations: PredicateObligations<'tcx>,
83}
84pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
8586pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
8788pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
89 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
90>;
9192/// This type contains all the things within `InferCtxt` that sit within a
93/// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
94/// operations are hot enough that we want only one call to `borrow_mut` per
95/// call to `start_snapshot` and `rollback_to`.
96#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for InferCtxtInner<'tcx> {
#[inline]
fn clone(&self) -> InferCtxtInner<'tcx> {
InferCtxtInner {
undo_log: ::core::clone::Clone::clone(&self.undo_log),
projection_cache: ::core::clone::Clone::clone(&self.projection_cache),
type_variable_storage: ::core::clone::Clone::clone(&self.type_variable_storage),
const_unification_storage: ::core::clone::Clone::clone(&self.const_unification_storage),
int_unification_storage: ::core::clone::Clone::clone(&self.int_unification_storage),
float_unification_storage: ::core::clone::Clone::clone(&self.float_unification_storage),
float_origin_origin_storage: ::core::clone::Clone::clone(&self.float_origin_origin_storage),
region_constraint_storage: ::core::clone::Clone::clone(&self.region_constraint_storage),
solver_region_constraint_storage: ::core::clone::Clone::clone(&self.solver_region_constraint_storage),
region_obligations: ::core::clone::Clone::clone(&self.region_obligations),
region_assumptions: ::core::clone::Clone::clone(&self.region_assumptions),
hir_typeck_potentially_region_dependent_goals: ::core::clone::Clone::clone(&self.hir_typeck_potentially_region_dependent_goals),
opaque_type_storage: ::core::clone::Clone::clone(&self.opaque_type_storage),
}
}
}Clone)]
97pub struct InferCtxtInner<'tcx> {
98 undo_log: InferCtxtUndoLogs<'tcx>,
99100/// Cache for projections.
101 ///
102 /// This cache is snapshotted along with the infcx.
103projection_cache: traits::ProjectionCacheStorage<'tcx>,
104105/// We instantiate `UnificationTable` with `bounds<Ty>` because the types
106 /// that might instantiate a general type variable have an order,
107 /// represented by its upper and lower bounds.
108type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
109110/// Map from const parameter variable to the kind of const it represents.
111const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
112113/// Map from integral variable to the kind of integer it represents.
114int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
115116/// Map from floating variable to the kind of float it represents.
117float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
118119/// Map from floating variable to the origin span it came from, and the HirId that should be
120 /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
121 /// so can be removed once the `f32` fallback is removed.
122float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
123124/// Tracks the set of region variables and the constraints between them.
125 ///
126 /// This is initially `Some(_)` but when
127 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
128 /// -- further attempts to perform unification, etc., may fail if new
129 /// region constraints would've been added.
130region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
131132/// Used by the next solver when `-Zassumptions-on-binders` is set.
133solver_region_constraint_storage: SolverRegionConstraintStorage<'tcx>,
134135/// A set of constraints that regionck must validate.
136 ///
137 /// Each constraint has the form `T:'a`, meaning "some type `T` must
138 /// outlive the lifetime 'a". These constraints derive from
139 /// instantiated type parameters. So if you had a struct defined
140 /// like the following:
141 /// ```ignore (illustrative)
142 /// struct Foo<T: 'static> { ... }
143 /// ```
144 /// In some expression `let x = Foo { ... }`, it will
145 /// instantiate the type parameter `T` with a fresh type `$0`. At
146 /// the same time, it will record a region obligation of
147 /// `$0: 'static`. This will get checked later by regionck. (We
148 /// can't generally check these things right away because we have
149 /// to wait until types are resolved.)
150region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
151152/// The outlives bounds that we assume must hold about placeholders that
153 /// come from instantiating the binder of coroutine-witnesses. These bounds
154 /// are deduced from the well-formedness of the witness's types, and are
155 /// necessary because of the way we anonymize the regions in a coroutine,
156 /// which may cause types to no longer be considered well-formed.
157region_assumptions: Vec<ty::ArgOutlivesClause<'tcx>>,
158159/// `-Znext-solver`: Successfully proven goals during HIR typeck which
160 /// reference inference variables and get reproven in case MIR type check
161 /// fails to prove something.
162 ///
163 /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
164hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
165166/// Caches for opaque type inference.
167opaque_type_storage: OpaqueTypeStorage<'tcx>,
168}
169170impl<'tcx> InferCtxtInner<'tcx> {
171fn new() -> InferCtxtInner<'tcx> {
172InferCtxtInner {
173 undo_log: InferCtxtUndoLogs::default(),
174175 projection_cache: Default::default(),
176 type_variable_storage: Default::default(),
177 const_unification_storage: Default::default(),
178 int_unification_storage: Default::default(),
179 float_unification_storage: Default::default(),
180 float_origin_origin_storage: Default::default(),
181 region_constraint_storage: Some(Default::default()),
182 solver_region_constraint_storage: SolverRegionConstraintStorage::new(),
183 region_obligations: Default::default(),
184 region_assumptions: Default::default(),
185 hir_typeck_potentially_region_dependent_goals: Default::default(),
186 opaque_type_storage: Default::default(),
187 }
188 }
189190#[inline]
191pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
192&self.region_obligations
193 }
194195#[inline]
196pub fn region_assumptions(&self) -> &[ty::ArgOutlivesClause<'tcx>] {
197&self.region_assumptions
198 }
199200#[inline]
201pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
202self.projection_cache.with_log(&mut self.undo_log)
203 }
204205#[inline]
206fn try_type_variables_probe_ref(&self, vid: ty::TyVid) -> Option<&TypeVariableValue<'tcx>> {
207// Uses a read-only view of the unification table, this way we don't
208 // need an undo log.
209self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
210 }
211212#[inline]
213fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
214self.type_variable_storage.with_log(&mut self.undo_log)
215 }
216217#[inline]
218pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
219self.opaque_type_storage.with_log(&mut self.undo_log)
220 }
221222#[inline]
223fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
224self.int_unification_storage.with_log(&mut self.undo_log)
225 }
226227#[inline]
228fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
229self.float_unification_storage.with_log(&mut self.undo_log)
230 }
231232#[inline]
233fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
234self.const_unification_storage.with_log(&mut self.undo_log)
235 }
236237#[inline]
238pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
239self.region_constraint_storage
240 .as_mut()
241 .expect("region constraints already solved")
242 .with_log(&mut self.undo_log)
243 }
244}
245246pub struct InferCtxt<'tcx> {
247pub tcx: TyCtxt<'tcx>,
248249/// The mode of this inference context, see the struct documentation
250 /// for more details.
251typing_mode: TypingMode<'tcx>,
252253/// Whether this inference context should care about region obligations in
254 /// the root universe. Most notably, this is used during HIR typeck as region
255 /// solving is left to borrowck instead.
256 ///
257 /// This is used in the old solver to enable the generation of regions constraints.
258 /// In the new solver its only used inside the InferCtxt's `Drop` implementation:
259 /// if we're considering regions, and new opaques are registered, we panic.
260pub considering_regions: bool,
261/// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
262 /// need to make sure we don't rely on region identity in the trait solver or when
263 /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
264 /// free region with a unique inference variable. If HIR typeck ends up depending on two
265 /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
266 /// resulting in an ICE.
267 ///
268 /// The trait solver sometimes depends on regions being identical. As a concrete example
269 /// the trait solver ignores other candidates if one candidate exists without any constraints.
270 /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
271 /// occurrence of `'a` with a unique region the goal now equates these regions. See
272 /// the tests in trait-system-refactor-initiative#27 for concrete examples.
273 ///
274 /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
275 /// This is still insufficient as inference variables may *hide* region variables, so e.g.
276 /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
277 /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
278 /// stash all successfully proven goals which reference inference variables and then reprove
279 /// them after writeback.
280pub in_hir_typeck: bool,
281282/// If set, this flag causes us to skip the 'leak check' during
283 /// higher-ranked subtyping operations. This flag is a temporary one used
284 /// to manage the removal of the leak-check: for the time being, we still run the
285 /// leak-check, but we issue warnings.
286skip_leak_check: bool,
287288pub inner: RefCell<InferCtxtInner<'tcx>>,
289290/// Once region inference is done, the values for each variable.
291lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
292293/// Caches the results of trait selection. This cache is used
294 /// for things that depends on inference variables or placeholders.
295pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
296297/// Caches the results of trait evaluation. This cache is used
298 /// for things that depends on inference variables or placeholders.
299pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
300301/// The set of predicates on which errors have been reported, to
302 /// avoid reporting the same error twice.
303pub reported_trait_errors:
304RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
305306pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
307308/// When an error occurs, we want to avoid reporting "derived"
309 /// errors that are due to this original failure. We have this
310 /// flag that one can set whenever one creates a type-error that
311 /// is due to an error in a prior pass.
312 ///
313 /// Don't read this flag directly, call `is_tainted_by_errors()`
314 /// and `set_tainted_by_errors()`.
315tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
316317/// What is the innermost universe we have created? Starts out as
318 /// `UniverseIndex::root()` but grows from there as we enter
319 /// universal quantifiers.
320 ///
321 /// N.B., at present, we exclude the universal quantifiers on the
322 /// item we are type-checking, and just consider those names as
323 /// part of the root universe. So this would only get incremented
324 /// when we enter into a higher-ranked (`for<..>`) type or trait
325 /// bound.
326universe: Cell<ty::UniverseIndex>,
327328/// List of assumed wellformed types which we can derive implied
329 /// bounds on a `for<...>` from. Only used unstabley and by the
330 /// new solver.
331//
332 // FIXME(-Zassumptions-on-binders): This and `universe` should probably be
333 // in `InferCtxtInner` so they can participate in rollbacks and whatnot
334placeholder_assumptions_for_next_solver: RefCell<
335FxIndexMap<
336 ty::UniverseIndex,
337Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
338 >,
339 >,
340341 next_trait_solver: bool,
342343/// We have a `recursion_depth_exceeding_limit` FCW to mitigate breakages
344 /// caused by enabling the next solver globally. But the next solver is
345 /// already used by default in some places so we know they won't have
346 /// additional breakages. We also don't want spurious result in coherence
347 /// checking so we disable the FCW there as well.
348enable_next_solver_overflow_fcw: Cell<bool>,
349350pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
351352/// State reused by each new canonicalizer, and then cleared (but not deallocated) once the
353 /// canonicalizer is finished. A performance win, because it avoids reallocating new
354 /// vecs/hashmaps for every canonicalizer.
355pub canonicalizer_state: RefCell<CanonicalizerState<TyCtxt<'tcx>>>,
356}
357358impl<'tcx> Dropfor InferCtxt<'tcx> {
359fn drop(&mut self) {
360let mut inner = self.inner.borrow_mut();
361let opaque_type_storage = &mut inner.opaque_type_storage;
362363// No need for the drop bomb when we're in `TypingMode::PostTypeckUntilBorrowck`, and the `InferCtxt`
364 // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
365 // in relation to regions. In some places *after* typeck that aren't borrowck, we use
366 // `TypingMode::PostTypeckUntilBorrowck` to prevent defining opaque types and we simply don't care about regions.
367match self.typing_mode_raw() {
368TypingMode::Coherence369 | TypingMode::Typeck { .. }
370 | TypingMode::PostBorrowck { .. }
371 | TypingMode::Reflection372 | TypingMode::PostAnalysis373 | TypingMode::Codegen => {}
374// In erased mode, the opaque type storage is always empty
375TypingMode::ErasedNotCoherence(..) => {}
376TypingMode::PostTypeckUntilBorrowck { .. } => {
377if !self.considering_regions {
378return;
379 }
380 }
381 }
382383if !opaque_type_storage.is_empty() {
384 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:?}")));
385 }
386 }
387}
388389/// See the `error_reporting` module for more details.
390#[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)]
391pub enum ValuePairs<'tcx> {
392 Regions(ExpectedFound<ty::Region<'tcx>>),
393 Terms(ExpectedFound<ty::Term<'tcx>>),
394 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
395 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
396 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
397 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
398 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
399}
400401impl<'tcx> ValuePairs<'tcx> {
402pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
403if let ValuePairs::Terms(ExpectedFound { expected, found }) = self404 && let Some(expected) = expected.as_type()
405 && let Some(found) = found.as_type()
406 {
407Some((expected, found))
408 } else {
409None410 }
411 }
412}
413414/// The trace designates the path through inference that we took to
415/// encounter an error or subtyping constraint.
416///
417/// See the `error_reporting` module for more details.
418#[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)]
419pub struct TypeTrace<'tcx> {
420pub cause: ObligationCause<'tcx>,
421pub values: ValuePairs<'tcx>,
422}
423424/// The origin of a `r1 <= r2` constraint.
425///
426/// See `error_reporting` module for more details
427#[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)]
428pub enum SubregionOrigin<'tcx> {
429/// Arose from a subtyping relation
430Subtype(Box<TypeTrace<'tcx>>),
431432/// When casting `&'a T` to an `&'b Trait` object,
433 /// relating `'a` to `'b`.
434RelateObjectBound(Span),
435436/// Some type parameter was instantiated with the given type,
437 /// and that type must outlive some region.
438RelateParamBound(Span, Ty<'tcx>, Option<Span>),
439440/// The given region parameter was instantiated with a region
441 /// that must outlive some other region.
442RelateRegionParamBound(Span, Option<Ty<'tcx>>),
443444/// Creating a pointer `b` to contents of another reference.
445Reborrow(Span),
446447/// (&'a &'b T) where a >= b
448ReferenceOutlivesReferent(Ty<'tcx>, Span),
449450/// Comparing the signature and requirements of an impl method against
451 /// the containing trait.
452CompareImplItemObligation {
453 span: Span,
454 impl_item_def_id: LocalDefId,
455 trait_item_def_id: DefId,
456 },
457458/// Checking that the bounds of a trait's associated type hold for a given impl.
459CheckAssociatedTypeBounds {
460 parent: Box<SubregionOrigin<'tcx>>,
461 impl_item_def_id: LocalDefId,
462 trait_item_def_id: DefId,
463 },
464465 AscribeUserTypeProvePredicate(Span),
466467// FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
468 // proper diagnostics for solver region constraints.
469SolverRegionConstraint(Span),
470}
471472// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
473#[cfg(target_pointer_width = "64")]
474const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
475476impl<'tcx> SubregionOrigin<'tcx> {
477pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
478match self {
479Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
480Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
481Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
482_ => ConstraintCategory::BoringNoLocation,
483 }
484 }
485}
486487/// Times when we replace bound regions with existentials:
488#[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)]
489pub enum BoundRegionConversionTime {
490/// when a fn is called
491FnCall,
492493/// when two higher-ranked types are compared
494HigherRankedType,
495496/// when projecting an associated type
497AssocTypeProjection(DefId),
498}
499500/// Reasons to create a region inference variable.
501///
502/// See `error_reporting` module for more details.
503#[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)]
504pub enum RegionVariableOrigin<'tcx> {
505/// Region variables created for ill-categorized reasons.
506 ///
507 /// They mostly indicate places in need of refactoring.
508Misc(Span),
509510/// Regions created by a `&P` or `[...]` pattern.
511PatternRegion(Span),
512513/// Regions created by `&` operator.
514BorrowRegion(Span),
515516/// Regions created as part of an autoref of a method receiver.
517Autoref(Span),
518519/// Regions created as part of an automatic coercion.
520Coercion(Span),
521522/// Region variables created as the values for early-bound regions.
523 ///
524 /// FIXME(@lcnr): This should also store a `DefId`, similar to
525 /// `TypeVariableOrigin`.
526RegionParameterDefinition(Span, Symbol),
527528/// Region variables created when instantiating a binder with
529 /// existential variables, e.g. when calling a function or method.
530BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
531532 UpvarRegion(ty::UpvarId, Span),
533534/// This origin is used for the inference variables that we create
535 /// during NLL region processing.
536Nll(NllRegionVariableOrigin<'tcx>),
537}
538539#[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)]
540pub enum NllRegionVariableOrigin<'tcx> {
541/// During NLL region processing, we create variables for free
542 /// regions that we encounter in the function signature and
543 /// elsewhere. This origin indices we've got one of those.
544FreeRegion,
545546/// "Universal" instantiation of a higher-ranked region (e.g.,
547 /// from a `for<'a> T` binder). Meant to represent "any region".
548Placeholder(ty::PlaceholderRegion<'tcx>),
549550 Existential {
551 name: Option<Symbol>,
552 },
553}
554555#[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)]
556pub struct FixupError {
557 unresolved: TyOrConstInferVar,
558}
559560impl fmt::Displayfor FixupError {
561fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562match self.unresolved {
563 TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
564f,
565"cannot determine the type of this integer; \
566 add a suffix to specify the type explicitly"
567),
568 TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
569f,
570"cannot determine the type of this number; \
571 add a suffix to specify the type explicitly"
572),
573 TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
574 TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
575 }
576 }
577}
578579/// See the `region_obligations` field for more information.
580#[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)]
581pub struct TypeOutlivesConstraint<'tcx> {
582pub sub_region: ty::Region<'tcx>,
583pub sup_type: Ty<'tcx>,
584pub origin: SubregionOrigin<'tcx>,
585}
586587/// Used to configure inference contexts before their creation.
588pub struct InferCtxtBuilder<'tcx> {
589 tcx: TyCtxt<'tcx>,
590 considering_regions: bool,
591 in_hir_typeck: bool,
592 skip_leak_check: bool,
593/// Whether we should use the new trait solver in the local inference context,
594 /// which affects things like which solver is used in `predicate_may_hold`.
595next_trait_solver: bool,
596 enable_next_solver_overflow_fcw: bool,
597}
598599impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
InferCtxtBuilder {
tcx: self,
considering_regions: true,
in_hir_typeck: false,
skip_leak_check: false,
next_trait_solver: self.next_trait_solver_globally(),
enable_next_solver_overflow_fcw: true,
}
}
}#[extension(pub trait TyCtxtInferExt<'tcx>)]600impl<'tcx> TyCtxt<'tcx> {
601fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
602InferCtxtBuilder {
603 tcx: self,
604 considering_regions: true,
605 in_hir_typeck: false,
606 skip_leak_check: false,
607 next_trait_solver: self.next_trait_solver_globally(),
608 enable_next_solver_overflow_fcw: true,
609 }
610 }
611}
612613impl<'tcx> InferCtxtBuilder<'tcx> {
614pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
615self.next_trait_solver = next_trait_solver;
616self617 }
618619pub fn enable_next_solver_overflow_fcw(
620mut self,
621 enable_next_solver_overflow_fcw: bool,
622 ) -> Self {
623self.enable_next_solver_overflow_fcw = enable_next_solver_overflow_fcw;
624self625 }
626627pub fn ignoring_regions(mut self) -> Self {
628self.considering_regions = false;
629self630 }
631632pub fn in_hir_typeck(mut self) -> Self {
633self.in_hir_typeck = true;
634self635 }
636637pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
638self.skip_leak_check = skip_leak_check;
639self640 }
641642/// Given a canonical value `C` as a starting point, create an
643 /// inference context that contains each of the bound values
644 /// within instantiated as a fresh variable. The `f` closure is
645 /// invoked with the new infcx, along with the instantiated value
646 /// `V` and a instantiation `S`. This instantiation `S` maps from
647 /// the bound values in `C` to their instantiated values in `V`
648 /// (in other words, `S(C) = V`).
649pub fn build_with_canonical<T>(
650mut self,
651 span: Span,
652 input: &CanonicalQueryInput<'tcx, T>,
653 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
654where
655T: TypeFoldable<TyCtxt<'tcx>>,
656 {
657let infcx = self.build(input.typing_mode.0);
658let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
659 (infcx, value, args)
660 }
661662pub fn build_with_typing_env(
663mut self,
664 typing_env: TypingEnv<'tcx>,
665 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
666 (self.build(typing_env.typing_mode()), typing_env.param_env)
667 }
668669pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
670let InferCtxtBuilder {
671 tcx,
672 considering_regions,
673 in_hir_typeck,
674 skip_leak_check,
675 next_trait_solver,
676 enable_next_solver_overflow_fcw,
677 } = *self;
678InferCtxt {
679tcx,
680typing_mode,
681considering_regions,
682in_hir_typeck,
683skip_leak_check,
684 inner: RefCell::new(InferCtxtInner::new()),
685 lexical_region_resolutions: RefCell::new(None),
686 selection_cache: Default::default(),
687 evaluation_cache: Default::default(),
688 reported_trait_errors: Default::default(),
689 reported_signature_mismatch: Default::default(),
690 tainted_by_errors: Cell::new(None),
691 universe: Cell::new(ty::UniverseIndex::ROOT),
692 placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
693next_trait_solver,
694 enable_next_solver_overflow_fcw: Cell::new(enable_next_solver_overflow_fcw),
695 obligation_inspector: Cell::new(None),
696 canonicalizer_state: Default::default(),
697 }
698 }
699}
700701impl<'tcx, T> InferOk<'tcx, T> {
702/// Extracts `value`, registering any obligations into `fulfill_cx`.
703pub fn into_value_registering_obligations<E: 'tcx>(
704self,
705 infcx: &InferCtxt<'tcx>,
706 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
707 ) -> T {
708let InferOk { value, obligations } = self;
709fulfill_cx.register_predicate_obligations(infcx, obligations);
710value711 }
712}
713714impl<'tcx> InferOk<'tcx, ()> {
715pub fn into_obligations(self) -> PredicateObligations<'tcx> {
716self.obligations
717 }
718}
719720impl<'tcx> InferCtxt<'tcx> {
721pub fn dcx(&self) -> DiagCtxtHandle<'_> {
722self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
723 }
724725pub fn next_trait_solver(&self) -> bool {
726self.next_trait_solver
727 }
728729/// This method is deliberately called `..._raw`,
730 /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
731 /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
732 /// more information.
733 ///
734 /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
735 /// works as a kind of store for for example type unification information.
736 /// `InferCtxt` is also often used outside the trait solver during typeck.
737 /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
738 /// To make sure these two uses are never confused, we want to statically encode this information.
739 ///
740 /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
741 /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
742 /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
743 /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
744 /// match on the variant and can safely ignore it.
745 ///
746 /// Prefer non-raw apis if available. e.g.,
747 /// - On the `FnCtxt`
748 /// - on the `SelectionCtxt`
749#[inline(always)]
750pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
751self.typing_mode
752 }
753754#[inline(always)]
755pub fn disable_trait_solver_fast_paths(&self) -> bool {
756self.tcx.disable_trait_solver_fast_paths()
757 }
758759/// Returns the origin of the type variable identified by `vid`.
760 ///
761 /// No attempt is made to resolve `vid` to its root variable.
762pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
763self.inner.borrow_mut().type_variables().var_origin(vid)
764 }
765766/// Returns the origin of the float type variable identified by `vid`.
767 ///
768 /// No attempt is made to resolve `vid` to its root variable.
769pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
770self.inner.borrow_mut().float_origin_origin_storage[vid]
771 }
772773/// Returns the origin of the const variable identified by `vid`
774// FIXME: We should store origins separately from the unification table
775 // so this doesn't need to be optional.
776pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
777match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
778 ConstVariableValue::Known { .. } => None,
779 ConstVariableValue::Unknown { origin, .. } => Some(origin),
780 }
781 }
782783pub fn unresolved_root_variables(&self) -> (Vec<TyVid>, Vec<ty::IntVid>, Vec<ty::FloatVid>) {
784let mut inner = self.inner.borrow_mut();
785786let ty = inner.type_variables().unresolved_root_variables();
787788let int = unresolved_root_variables_of(
789inner.int_unification_table(),
790 ty::IntVarValue::is_unknown,
791 );
792793let float = unresolved_root_variables_of(
794inner.float_unification_table(),
795 ty::FloatVarValue::is_unknown,
796 );
797798 (ty, int, float)
799 }
800801#[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(801u32),
::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")]802pub fn sub_regions(
803&self,
804 origin: SubregionOrigin<'tcx>,
805 a: ty::Region<'tcx>,
806 b: ty::Region<'tcx>,
807 vis: ty::VisibleForLeakCheck,
808 ) {
809self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
810 }
811812#[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(812u32),
::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")]813pub fn equate_regions(
814&self,
815 origin: SubregionOrigin<'tcx>,
816 a: ty::Region<'tcx>,
817 b: ty::Region<'tcx>,
818 vis: ty::VisibleForLeakCheck,
819 ) {
820self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
821 }
822823/// Processes a `Coerce` predicate from the fulfillment context.
824 /// This is NOT the preferred way to handle coercion, which is to
825 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
826 ///
827 /// This method here is actually a fallback that winds up being
828 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
829 /// and records a coercion predicate. Presently, this method is equivalent
830 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
831 /// actually requiring `a <: b`. This is of course a valid coercion,
832 /// but it's not as flexible as `FnCtxt::coerce` would be.
833 ///
834 /// (We may refactor this in the future, but there are a number of
835 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
836 /// records adjustments that are required on the HIR in order to perform
837 /// the coercion, and we don't currently have a way to manage that.)
838pub fn coerce_predicate(
839&self,
840 cause: &ObligationCause<'tcx>,
841 param_env: ty::ParamEnv<'tcx>,
842 predicate: ty::PolyCoercePredicate<'tcx>,
843 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
844let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
845 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
846a: p.a,
847 b: p.b,
848 });
849self.subtype_predicate(cause, param_env, subtype_predicate)
850 }
851852pub fn subtype_predicate(
853&self,
854 cause: &ObligationCause<'tcx>,
855 param_env: ty::ParamEnv<'tcx>,
856 predicate: ty::PolySubtypePredicate<'tcx>,
857 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
858// Check for two unresolved inference variables, in which case we can
859 // make no progress. This is partly a micro-optimization, but it's
860 // also an opportunity to "sub-unify" the variables. This isn't
861 // *necessary* to prevent cycles, because they would eventually be sub-unified
862 // anyhow during generalization, but it helps with diagnostics (we can detect
863 // earlier that they are sub-unified).
864 //
865 // Note that we can just skip the binders here because
866 // type variables can't (at present, at
867 // least) capture any of the things bound by this binder.
868 //
869 // Note that this sub here is not just for diagnostics - it has semantic
870 // effects as well.
871let r_a = self.shallow_resolve(predicate.skip_binder().a);
872let r_b = self.shallow_resolve(predicate.skip_binder().b);
873match (r_a.kind(), r_b.kind()) {
874 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
875self.sub_unify_ty_vids_raw(a_vid, b_vid);
876return Err((a_vid, b_vid));
877 }
878_ => {}
879 }
880881self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
882if a_is_expected {
883Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
884 } else {
885Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
886 }
887 })
888 }
889890/// Number of type variables created so far.
891pub fn num_ty_vars(&self) -> usize {
892self.inner.borrow_mut().type_variables().num_vars()
893 }
894895pub fn next_ty_vid(&self, span: Span) -> TyVid {
896self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
897 }
898899pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
900self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
901 }
902903pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
904let origin = TypeVariableOrigin { span, param_def_id: None };
905self.inner.borrow_mut().type_variables().new_var(universe, origin)
906 }
907908pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
909self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
910 }
911912pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
913let vid = self.next_ty_vid_with_origin(origin);
914Ty::new_var(self.tcx, vid)
915 }
916917pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
918let vid = self.next_ty_vid_in_universe(span, universe);
919Ty::new_var(self.tcx, vid)
920 }
921922pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
923self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
924 }
925926pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
927let vid = self928 .inner
929 .borrow_mut()
930 .const_unification_table()
931 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
932 .vid;
933 ty::Const::new_var(self.tcx, vid)
934 }
935936pub fn next_const_var_in_universe(
937&self,
938 span: Span,
939 universe: ty::UniverseIndex,
940 ) -> ty::Const<'tcx> {
941let origin = ConstVariableOrigin { span, param_def_id: None };
942let vid = self943 .inner
944 .borrow_mut()
945 .const_unification_table()
946 .new_key(ConstVariableValue::Unknown { origin, universe })
947 .vid;
948 ty::Const::new_var(self.tcx, vid)
949 }
950951pub fn next_int_var(&self) -> Ty<'tcx> {
952let next_int_var_id =
953self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
954Ty::new_int_var(self.tcx, next_int_var_id)
955 }
956957pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
958let mut inner = self.inner.borrow_mut();
959let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
960let origin = FloatVariableOrigin { span, lint_id };
961let span_index = inner.float_origin_origin_storage.push(origin);
962if 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);
963Ty::new_float_var(self.tcx, next_float_var_id)
964 }
965966/// Creates a fresh region variable with the next available index.
967 /// The variable will be created in the maximum universe created
968 /// thus far, allowing it to name any region created thus far.
969pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
970self.next_region_var_in_universe(origin, self.universe())
971 }
972973/// Creates a fresh region variable with the next available index
974 /// in the given universe; typically, you can use
975 /// `next_region_var` and just use the maximal universe.
976pub fn next_region_var_in_universe(
977&self,
978 origin: RegionVariableOrigin<'tcx>,
979 universe: ty::UniverseIndex,
980 ) -> ty::Region<'tcx> {
981let region_var =
982self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
983 ty::Region::new_var(self.tcx, region_var)
984 }
985986pub fn next_term_var_of_alias_kind(
987&self,
988 alias_term: ty::AliasTerm<'tcx>,
989 span: Span,
990 ) -> ty::Term<'tcx> {
991match alias_term.kind {
992 ty::AliasTermKind::ProjectionTy { .. }
993 | ty::AliasTermKind::InherentTy { .. }
994 | ty::AliasTermKind::OpaqueTy { .. }
995 | ty::AliasTermKind::FreeTy { .. } => self.next_ty_var(span).into(),
996 ty::AliasTermKind::FreeConst { .. }
997 | ty::AliasTermKind::InherentConst { .. }
998 | ty::AliasTermKind::AnonConst { .. }
999 | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_var(span).into(),
1000 }
1001 }
10021003/// Return the universe that the region `r` was created in. For
1004 /// most regions (e.g., `'static`, named regions from the user,
1005 /// etc) this is the root universe U0. For inference variables or
1006 /// placeholders, however, it will return the universe which they
1007 /// are associated.
1008pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1009self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1010 }
10111012/// Number of region variables created so far.
1013pub fn num_region_vars(&self) -> usize {
1014self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1015 }
10161017/// Just a convenient wrapper of `next_region_var` for using during NLL.
1018#[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(1018u32),
::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")]1019pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
1020self.next_region_var(RegionVariableOrigin::Nll(origin))
1021 }
10221023/// Just a convenient wrapper of `next_region_var` for using during NLL.
1024#[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(1024u32),
::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")]1025pub fn next_nll_region_var_in_universe(
1026&self,
1027 origin: NllRegionVariableOrigin<'tcx>,
1028 universe: ty::UniverseIndex,
1029 ) -> ty::Region<'tcx> {
1030self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1031 }
10321033pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1034match param.kind {
1035 GenericParamDefKind::Lifetime => {
1036// Create a region inference variable for the given
1037 // region parameter definition.
1038self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1039span, param.name,
1040 ))
1041 .into()
1042 }
1043 GenericParamDefKind::Type { .. } => {
1044// Create a type inference variable for the given
1045 // type parameter definition. The generic parameters are
1046 // for actual parameters that may be referred to by
1047 // the default of this type parameter, if it exists.
1048 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1049 // used in a path such as `Foo::<T, U>::new()` will
1050 // use an inference variable for `C` with `[T, U]`
1051 // as the generic parameters for the default, `(T, U)`.
1052let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1053self.universe(),
1054TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1055 );
10561057Ty::new_var(self.tcx, ty_var_id).into()
1058 }
1059 GenericParamDefKind::Const { .. } => {
1060let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1061let const_var_id = self1062 .inner
1063 .borrow_mut()
1064 .const_unification_table()
1065 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1066 .vid;
1067 ty::Const::new_var(self.tcx, const_var_id).into()
1068 }
1069 }
1070 }
10711072/// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1073 /// each type/region parameter to a fresh inference variable.
1074pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
1075GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1076 }
10771078/// Returns `true` if errors have been reported since this infcx was
1079 /// created. This is sometimes used as a heuristic to skip
1080 /// reporting errors that often occur as a result of earlier
1081 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1082 /// inference variables, regionck errors).
1083#[must_use = "this method does not have any side effects"]
1084pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1085self.tainted_by_errors.get()
1086 }
10871088/// Set the "tainted by errors" flag to true. We call this when we
1089 /// observe an error from a prior pass.
1090pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1091{
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:1091",
"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(1091u32),
::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)");
1092self.tainted_by_errors.set(Some(e));
1093 }
10941095pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1096let mut inner = self.inner.borrow_mut();
1097let inner = &mut *inner;
1098inner.unwrap_region_constraints().var_origin(vid)
1099 }
11001101/// Clone the list of variable regions. This is used only during NLL processing
1102 /// to put the set of region variables into the NLL region context.
1103pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1104let inner = self.inner.borrow();
1105if !!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));
1106let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1107if !storage.data.is_empty() {
{ ::core::panicking::panic_fmt(format_args!("{0:#?}", storage.data)); }
};assert!(storage.data.is_empty(), "{:#?}", storage.data);
1108// We clone instead of taking because borrowck still wants to use the
1109 // inference context after calling this for diagnostics and the new
1110 // trait solver.
1111storage.var_infos.clone()
1112 }
11131114pub fn has_opaque_types_in_storage(&self) -> bool {
1115 !self.inner.borrow().opaque_type_storage.is_empty()
1116 }
11171118x;#[instrument(level = "debug", skip(self), ret)]1119pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1120self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1121 }
11221123x;#[instrument(level = "debug", skip(self), ret)]1124pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1125self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1126 }
11271128pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1129if !self.next_trait_solver() {
1130return false;
1131 }
11321133let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1134let inner = &mut *self.inner.borrow_mut();
1135let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1136inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1137if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1138let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1139if opaque_sub_vid == ty_sub_vid {
1140return true;
1141 }
1142 }
11431144false
1145})
1146 }
11471148/// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1149 ///
1150 /// This only checks for a subtype relation, it does not require equality.
1151pub fn opaques_with_sub_unified_hidden_type(
1152&self,
1153 ty_vid: TyVid,
1154 ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1155// Avoid accidentally allowing more code to compile with the old solver.
1156if !self.next_trait_solver() {
1157return ::alloc::vec::Vec::new()vec![];
1158 }
11591160let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1161let inner = &mut *self.inner.borrow_mut();
1162// This is iffy, can't call `type_variables()` as we're already
1163 // borrowing the `opaque_type_storage` here.
1164let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1165inner1166 .opaque_type_storage
1167 .iter_opaque_types()
1168 .filter_map(|(key, hidden_ty)| {
1169if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1170let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1171if opaque_sub_vid == ty_sub_vid {
1172return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1173self.tcx,
1174key.def_id.into(),
1175key.args,
1176 ));
1177 }
1178 }
11791180None1181 })
1182 .collect()
1183 }
11841185#[inline(always)]
1186pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1187if true {
if !!self.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.next_trait_solver()")
};
};debug_assert!(!self.next_trait_solver());
1188match self.typing_mode_raw().assert_not_erased() {
1189TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1190 | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types } => {
1191id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1192 }
1193// FIXME(#132279): This function is quite weird in post-analysis
1194 // and post-borrowck analysis mode. We may need to modify its uses
1195 // to support PostBorrowck in the old solver as well.
1196TypingMode::Coherence1197 | TypingMode::Reflection1198 | TypingMode::PostBorrowck { .. }
1199 | TypingMode::PostAnalysis1200 | TypingMode::Codegen => false,
1201 }
1202 }
12031204pub fn push_hir_typeck_potentially_region_dependent_goal(
1205&self,
1206 goal: PredicateObligation<'tcx>,
1207 ) {
1208let mut inner = self.inner.borrow_mut();
1209inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1210inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1211 }
12121213pub fn take_hir_typeck_potentially_region_dependent_goals(
1214&self,
1215 ) -> Vec<PredicateObligation<'tcx>> {
1216if !!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");
1217 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1218 }
12191220pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1221self.resolve_vars_if_possible(t).to_string()
1222 }
12231224/// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1225 /// universe index of `TyVar(vid)`.
1226pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1227use self::type_variable::TypeVariableValue;
12281229match self.inner.borrow_mut().type_variables().probe(vid) {
1230 TypeVariableValue::Known { value } => Ok(value),
1231 TypeVariableValue::Unknown { universe } => Err(universe),
1232 }
1233 }
12341235/// If `vid` resolves to a type, return that type. Otherwise return the root variable id for `vid`.
1236pub fn shallow_resolve_ty_var_or_get_root(&self, vid: TyVid) -> Result<Ty<'tcx>, TyVid> {
1237let (root, value) = self.inner.borrow_mut().type_variables().probe_with_root_vid(vid);
12381239match value {
1240 TypeVariableValue::Known { value } => Ok(value),
1241 TypeVariableValue::Unknown { universe: _ } => Err(root),
1242 }
1243 }
12441245pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1246if let ty::Infer(v) = *ty.kind() {
1247match v {
1248 ty::TyVar(v) => {
1249// Not entirely obvious: if `typ` is a type variable,
1250 // it can be resolved to an int/float variable, which
1251 // can then be recursively resolved, hence the
1252 // recursion. Note though that we prevent type
1253 // variables from unifying to other type variables
1254 // directly (though they may be embedded
1255 // structurally), and we prevent cycles in any case,
1256 // so this recursion should always be of very limited
1257 // depth.
1258 //
1259 // Note: if these two lines are combined into one we get
1260 // dynamic borrow errors on `self.inner`.
1261let (root_vid, value) =
1262self.inner.borrow_mut().type_variables().probe_with_root_vid(v);
1263value.known().map_or_else(
1264 || if root_vid == v { ty } else { Ty::new_var(self.tcx, root_vid) },
1265 |t| self.shallow_resolve(t),
1266 )
1267 }
12681269 ty::IntVar(v) => {
1270let (root, value) =
1271self.inner.borrow_mut().int_unification_table().inlined_probe_key_value(v);
1272match value {
1273 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1274 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1275 ty::IntVarValue::Unknown => {
1276if root == v {
1277ty1278 } else {
1279Ty::new_int_var(self.tcx, root)
1280 }
1281 }
1282 }
1283 }
12841285 ty::FloatVar(v) => {
1286let (root, value) = self1287 .inner
1288 .borrow_mut()
1289 .float_unification_table()
1290 .inlined_probe_key_value(v);
1291match value {
1292 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1293 ty::FloatVarValue::Unknown => {
1294if root == v {
1295ty1296 } else {
1297Ty::new_float_var(self.tcx, root)
1298 }
1299 }
1300 }
1301 }
13021303 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1304 }
1305 } else {
1306ty1307 }
1308 }
13091310pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1311match ct.kind() {
1312 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1313 InferConst::Var(vid) => {
1314let (root, value) = self1315 .inner
1316 .borrow_mut()
1317 .const_unification_table()
1318 .inlined_probe_key_value(vid);
1319value.known().unwrap_or_else(|| {
1320if root.vid == vid { ct } else { ty::Const::new_var(self.tcx, root.vid) }
1321 })
1322 }
1323 InferConst::Fresh(_) => ct,
1324 },
13251326 ty::ConstKind::Param(_)
1327 | ty::ConstKind::Bound(_, _)
1328 | ty::ConstKind::Placeholder(_)
1329 | ty::ConstKind::Alias(_, _)
1330 | ty::ConstKind::Value(_)
1331 | ty::ConstKind::Error(_)
1332 | ty::ConstKind::Expr(_) => ct,
1333 }
1334 }
13351336pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1337match term.kind() {
1338 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1339 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1340 }
1341 }
13421343pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1344self.inner.borrow_mut().type_variables().root_var(var)
1345 }
13461347/// If `ty` is an unresolved type variable, returns its root vid.
1348pub fn root_vid(&self, ty: Ty<'tcx>) -> Option<ty::TyVid> {
1349let (root, value) =
1350self.inner.borrow_mut().type_variables().inlined_probe_with_vid(ty.ty_vid()?);
1351value.is_unknown().then_some(root)
1352 }
13531354pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1355self.inner.borrow_mut().type_variables().sub_unify(a, b);
1356 }
13571358pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1359self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1360 }
13611362pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1363self.inner.borrow_mut().float_unification_table().find(var)
1364 }
13651366pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1367self.inner.borrow_mut().const_unification_table().find(var).vid
1368 }
13691370/// Resolves an int var to a rigid int type, if it was constrained to one,
1371 /// or else the root int var in the unification table.
1372pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1373let mut inner = self.inner.borrow_mut();
1374let value = inner.int_unification_table().probe_value(vid);
1375match value {
1376 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1377 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1378 ty::IntVarValue::Unknown => {
1379Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1380 }
1381 }
1382 }
13831384/// Resolves a float var to a rigid int type, if it was constrained to one,
1385 /// or else the root float var in the unification table.
1386pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1387let mut inner = self.inner.borrow_mut();
1388let value = inner.float_unification_table().probe_value(vid);
1389match value {
1390 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1391 ty::FloatVarValue::Unknown => {
1392Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1393 }
1394 }
1395 }
13961397/// Where possible, replaces type/const variables in
1398 /// `value` with their final value. Note that region variables
1399 /// are unaffected. If a type/const variable has not been unified, it
1400 /// is left as is. This is an idempotent operation that does
1401 /// not affect inference state in any way and so you can do it
1402 /// at will.
1403pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1404where
1405T: TypeFoldable<TyCtxt<'tcx>>,
1406 {
1407if let Err(guar) = value.error_reported() {
1408self.set_tainted_by_errors(guar);
1409 }
1410if !value.has_non_region_infer() {
1411return value;
1412 }
1413let mut r = resolve::OpportunisticVarResolver::new(self);
1414value.fold_with(&mut r)
1415 }
14161417pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1418where
1419T: TypeFoldable<TyCtxt<'tcx>>,
1420 {
1421if !value.has_infer() {
1422return value; // Avoid duplicated type-folding.
1423}
1424let mut r = InferenceLiteralEraser { tcx: self.tcx };
1425value.fold_with(&mut r)
1426 }
14271428pub fn try_resolve_const_var(
1429&self,
1430 vid: ty::ConstVid,
1431 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1432match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1433 ConstVariableValue::Known { value } => Ok(value),
1434 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1435 }
1436 }
14371438/// Attempts to resolve all type/region/const variables in
1439 /// `value`. Region inference must have been run already (e.g.,
1440 /// by calling `resolve_regions_and_report_errors`). If some
1441 /// variable was never unified, an `Err` results.
1442 ///
1443 /// This method is idempotent, but it not typically not invoked
1444 /// except during the writeback phase.
1445pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1446match resolve::fully_resolve(self, value) {
1447Ok(value) => {
1448if value.has_non_region_infer() {
1449::rustc_middle::util::bug::bug_fmt(format_args!("`{0:?}` is not fully resolved",
value));bug!("`{value:?}` is not fully resolved");
1450 }
1451if value.has_infer_regions() {
1452let 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"));
1453Ok(fold_regions(self.tcx, value, |re, _| {
1454if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1455 }))
1456 } else {
1457Ok(value)
1458 }
1459 }
1460Err(e) => Err(e),
1461 }
1462 }
14631464// Instantiates the bound variables in a given binder with fresh inference
1465 // variables in the current universe.
1466 //
1467 // Use this method if you'd like to find some generic parameters of the binder's
1468 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1469 // that corresponds to your use case, consider whether or not you should
1470 // use [`InferCtxt::enter_forall`] instead.
1471pub fn instantiate_binder_with_fresh_vars<T>(
1472&self,
1473 span: Span,
1474 lbrct: BoundRegionConversionTime,
1475 value: ty::Binder<'tcx, T>,
1476 ) -> T
1477where
1478T: TypeFoldable<TyCtxt<'tcx>>,
1479 {
1480if let Some(_) = value.as_ref().no_bound_vars() {
1481return value.skip_binder();
1482 }
14831484let bound_vars = value.bound_vars();
1485let mut args = Vec::with_capacity(bound_vars.len());
14861487for bound_var_kind in bound_vars {
1488let arg: ty::GenericArg<'_> = match bound_var_kind {
1489 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1490 ty::BoundVariableKind::Region(br) => {
1491self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1492 }
1493 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1494 };
1495 args.push(arg);
1496 }
14971498struct ToFreshVars<'tcx> {
1499 args: Vec<ty::GenericArg<'tcx>>,
1500 }
15011502impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1503fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1504self.args[br.var.index()].expect_region()
1505 }
1506fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1507self.args[bt.var.index()].expect_ty()
1508 }
1509fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1510self.args[bc.var.index()].expect_const()
1511 }
1512 }
1513let delegate = ToFreshVars { args };
1514self.tcx.replace_bound_vars_uncached(value, delegate)
1515 }
15161517pub fn insert_placeholder_assumptions(
1518&self,
1519 u: ty::UniverseIndex,
1520 assumptions: Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
1521 ) {
1522if let Some(assumptions) = &assumptions {
1523if !!assumptions.type_outlives.has_escaping_bound_vars() {
{
::core::panicking::panic_fmt(format_args!("assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {0:?}",
assumptions.type_outlives));
}
};assert!(
1524 !assumptions.type_outlives.has_escaping_bound_vars(),
1525"assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1526 assumptions.type_outlives
1527 );
1528if !assumptions.region_outlives.base_edges().all(|r|
!r.has_escaping_bound_vars()) {
{
::core::panicking::panic_fmt(format_args!("assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {0:?}",
assumptions.region_outlives));
}
};assert!(
1529 assumptions.region_outlives.base_edges().all(|r| !r.has_escaping_bound_vars()),
1530"assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1531 assumptions.region_outlives
1532 );
1533 }
1534self.placeholder_assumptions_for_next_solver.borrow_mut().insert(u, assumptions);
1535 }
15361537pub fn get_placeholder_assumptions(
1538&self,
1539 u: ty::UniverseIndex,
1540 ) -> Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>> {
1541self.placeholder_assumptions_for_next_solver.borrow().get(&u).unwrap().as_ref().cloned()
1542 }
15431544pub fn get_solver_region_constraint(&self) -> SolverRegionConstraint<'tcx> {
1545self.inner.borrow().solver_region_constraint_storage.get_constraint()
1546 }
15471548pub fn overwrite_solver_region_constraint(&self, constraint: SolverRegionConstraint<'tcx>) {
1549if !!constraint.has_escaping_bound_vars() {
{
::core::panicking::panic_fmt(format_args!("solver region constraint has escaping bound vars, which is indicative of a bug in how constraints are handled: {0:?}",
constraint));
}
};assert!(
1550 !constraint.has_escaping_bound_vars(),
1551"solver region constraint has escaping bound vars, which is indicative of a bug in how constraints are handled: {constraint:?}",
1552 );
1553let mut inner = self.inner.borrow_mut();
1554let old_constraint = inner.solver_region_constraint_storage.get_constraint();
1555inner.undo_log.push(UndoLog::OverwriteSolverRegionConstraint { old_constraint });
1556inner.solver_region_constraint_storage.overwrite(constraint);
1557 }
15581559/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1560pub(crate) fn verify_generic_bound(
1561&self,
1562 origin: SubregionOrigin<'tcx>,
1563 kind: GenericKind<'tcx>,
1564 a: ty::Region<'tcx>,
1565 bound: VerifyBound<'tcx>,
1566 ) {
1567{
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:1567",
"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(1567u32),
::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);
15681569self.inner
1570 .borrow_mut()
1571 .unwrap_region_constraints()
1572 .verify_generic_bound(origin, kind, a, bound);
1573 }
15741575/// Obtains the latest type of the given closure; this may be a
1576 /// closure in the current function, in which case its
1577 /// `ClosureKind` may not yet be known.
1578pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1579let unresolved_kind_ty = match *closure_ty.kind() {
1580 ty::Closure(_, args) => args.as_closure().kind_ty(),
1581 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1582_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0}",
closure_ty))bug!("unexpected type {closure_ty}"),
1583 };
1584let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1585closure_kind_ty.to_opt_closure_kind()
1586 }
15871588pub fn universe(&self) -> ty::UniverseIndex {
1589self.universe.get()
1590 }
15911592/// Creates and return a fresh universe that extends all previous
1593 /// universes. Updates `self.universe` to that new universe.
1594pub fn create_next_universe(&self) -> ty::UniverseIndex {
1595let u = self.universe.get().next_universe();
1596{
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:1596",
"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(1596u32),
::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:?}");
1597self.universe.set(u);
1598u1599 }
16001601/// We need to disable the fcw if we're already in a fcw emitting to avoid
1602 /// indefinite triggering.
1603pub fn with_disabled_next_solver_overflow_fcw<F, R>(&self, mut f: F) -> R
1604where
1605F: FnMut() -> R,
1606 {
1607let prev = self.enable_next_solver_overflow_fcw.replace(false);
1608let ret = f();
1609self.enable_next_solver_overflow_fcw.set(prev);
1610ret1611 }
16121613/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1614 /// which contains the necessary information to use the trait system without
1615 /// using canonicalization or carrying this inference context around.
1616pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1617let typing_mode = match self.typing_mode_raw() {
1618// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1619 // to handle them without proper canonicalization. This means we may cause cycle
1620 // errors and fail to reveal opaques while inside of bodies. We should rename this
1621 // function and require explicit comments on all use-sites in the future.
1622ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1623 | ty::TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ } => {
1624TypingMode::non_body_analysis()
1625 }
1626 mode @ (ty::TypingMode::Coherence1627 | ty::TypingMode::PostBorrowck { .. }
1628 | ty::TypingMode::PostAnalysis1629 | ty::TypingMode::Reflection1630 | ty::TypingMode::Codegen) => mode,
1631 ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1632 };
1633 ty::TypingEnv::new(param_env, typing_mode)
1634 }
16351636/// Similar to [`Self::canonicalize_query`], except that it returns
1637 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1638 /// `param_env` to not contain any inference variables or placeholders.
1639pub fn pseudo_canonicalize_query<V>(
1640&self,
1641 param_env: ty::ParamEnv<'tcx>,
1642 value: V,
1643 ) -> PseudoCanonicalInput<'tcx, V>
1644where
1645V: TypeVisitable<TyCtxt<'tcx>>,
1646 {
1647if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1648if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1649if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1650if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1651self.typing_env(param_env).as_query_input(value)
1652 }
16531654/// The returned function is used in a fast path. If it returns `true` the variable is
1655 /// unchanged, `false` indicates that the status is unknown.
1656#[inline]
1657pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1658// This hoists the borrow/release out of the loop body.
1659let inner = self.inner.try_borrow();
16601661move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1662 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1663use self::type_variable::TypeVariableValue;
16641665#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1666 inner.try_type_variables_probe_ref(ty_var),
1667Some(TypeVariableValue::Unknown { .. })
1668 )1669 }
1670_ => false,
1671 }
1672 }
16731674/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1675 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1676 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1677 ///
1678 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1679 /// inlined, despite being large, because it has only two call sites that
1680 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1681 /// inference variables), and it handles both `Ty` and `ty::Const` without
1682 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1683#[inline(always)]
1684pub fn ty_or_const_infer_var_changed(&self, var: TyOrConstInferVar) -> bool {
1685match var {
1686 TyOrConstInferVar::Ty(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().try_type_variables_probe_ref(vid)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1687self.inner.borrow().try_type_variables_probe_ref(vid),
1688Some(TypeVariableValue::Unknown { .. })
1689 ),
1690 TyOrConstInferVar::TyInt(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().int_unification_storage.try_probe_value(vid)
{
Some(ty::IntVarValue::Unknown) => true,
_ => false,
}matches!(
1691self.inner.borrow().int_unification_storage.try_probe_value(vid),
1692Some(ty::IntVarValue::Unknown)
1693 ),
1694 TyOrConstInferVar::TyFloat(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().float_unification_storage.try_probe_value(vid)
{
Some(ty::FloatVarValue::Unknown) => true,
_ => false,
}matches!(
1695self.inner.borrow().float_unification_storage.try_probe_value(vid),
1696Some(ty::FloatVarValue::Unknown)
1697 ),
1698 TyOrConstInferVar::Const(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().const_unification_storage.try_probe_value(vid)
{
Some(ConstVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1699self.inner.borrow().const_unification_storage.try_probe_value(vid),
1700Some(ConstVariableValue::Unknown { .. })
1701 ),
1702 }
1703 }
17041705/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1706pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1707if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1708self.obligation_inspector.get().is_none(),
1709"shouldn't override a set obligation inspector"
1710);
1711self.obligation_inspector.set(Some(inspector));
1712 }
1713}
17141715/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1716/// Used only for diagnostics.
1717struct InferenceLiteralEraser<'tcx> {
1718 tcx: TyCtxt<'tcx>,
1719}
17201721impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1722fn cx(&self) -> TyCtxt<'tcx> {
1723self.tcx
1724 }
17251726fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1727match ty.kind() {
1728 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1729 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1730_ => ty.super_fold_with(self),
1731 }
1732 }
1733}
17341735impl<'tcx> TypeTrace<'tcx> {
1736pub fn span(&self) -> Span {
1737self.cause.span
1738 }
17391740pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1741TypeTrace {
1742 cause: cause.clone(),
1743 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1744 }
1745 }
17461747pub fn trait_refs(
1748 cause: &ObligationCause<'tcx>,
1749 a: ty::TraitRef<'tcx>,
1750 b: ty::TraitRef<'tcx>,
1751 ) -> TypeTrace<'tcx> {
1752TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1753 }
17541755pub fn consts(
1756 cause: &ObligationCause<'tcx>,
1757 a: ty::Const<'tcx>,
1758 b: ty::Const<'tcx>,
1759 ) -> TypeTrace<'tcx> {
1760TypeTrace {
1761 cause: cause.clone(),
1762 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1763 }
1764 }
1765}
17661767impl<'tcx> SubregionOrigin<'tcx> {
1768pub fn span(&self) -> Span {
1769match *self {
1770 SubregionOrigin::Subtype(ref a) => a.span(),
1771 SubregionOrigin::RelateObjectBound(a) => a,
1772 SubregionOrigin::RelateParamBound(a, ..) => a,
1773 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1774 SubregionOrigin::Reborrow(a) => a,
1775 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1776 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1777 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1778 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1779 SubregionOrigin::SolverRegionConstraint(a) => a,
1780 }
1781 }
17821783pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1784where
1785F: FnOnce() -> Self,
1786 {
1787match *cause.code() {
1788 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1789 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1790 }
17911792 traits::ObligationCauseCode::CompareImplItem {
1793 impl_item_def_id,
1794 trait_item_def_id,
1795 kind: _,
1796 } => SubregionOrigin::CompareImplItemObligation {
1797 span: cause.span,
1798impl_item_def_id,
1799trait_item_def_id,
1800 },
18011802 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1803 impl_item_def_id,
1804 trait_item_def_id,
1805 } => SubregionOrigin::CheckAssociatedTypeBounds {
1806impl_item_def_id,
1807trait_item_def_id,
1808 parent: Box::new(default()),
1809 },
18101811 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1812 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1813 }
18141815 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1816 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1817 }
18181819_ => default(),
1820 }
1821 }
1822}
18231824impl<'tcx> RegionVariableOrigin<'tcx> {
1825pub fn span(&self) -> Span {
1826match *self {
1827 RegionVariableOrigin::Misc(a)
1828 | RegionVariableOrigin::PatternRegion(a)
1829 | RegionVariableOrigin::BorrowRegion(a)
1830 | RegionVariableOrigin::Autoref(a)
1831 | RegionVariableOrigin::Coercion(a)
1832 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1833 | RegionVariableOrigin::BoundRegion(a, ..)
1834 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1835 RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable used with `span`"))bug!("NLL variable used with `span`"),
1836 }
1837 }
1838}
18391840impl<'tcx> InferCtxt<'tcx> {
1841/// Given a [`hir::Block`], get the span of its last expression or
1842 /// statement, peeling off any inner blocks.
1843pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1844let block = block.innermost_block();
1845if let Some(expr) = &block.expr {
1846expr.span
1847 } else if let Some(stmt) = block.stmts.last() {
1848// possibly incorrect trailing `;` in the else arm
1849stmt.span
1850 } else {
1851// empty block; point at its entirety
1852block.span
1853 }
1854 }
18551856/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1857 /// of its last expression or statement, peeling off any inner blocks.
1858pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1859match self.tcx.hir_node(hir_id) {
1860 hir::Node::Block(blk)
1861 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1862self.find_block_span(blk)
1863 }
1864 hir::Node::Expr(e) => e.span,
1865_ => DUMMY_SP,
1866 }
1867 }
1868}
18691870/// Returns unresolved root variables from `table`, according to `is_unresolved`.
1871fn unresolved_root_variables_of<V: UnifyKey>(
1872mut table: UnificationTable<'_, '_, V>,
1873 is_unresolved: impl Fn(V::Value) -> bool,
1874) -> Vec<V>
1875where
1876V: Eq,
1877 V::Value: UnifyValue,
1878for<'a> UndoLog<'a>: From<sv::UndoLog<ut::Delegate<V>>>,
1879{
1880 (0..table.len() as u32)
1881 .map(V::from_index)
1882 .filter(|&vid| {
1883// NB: as of writing this `ena` doesn't provide a non-inlined `probe_key_value`...
1884let (root, value) = table.inlined_probe_key_value(vid);
1885root == vid && is_unresolved(value)
1886 })
1887 .collect()
1888}