1use std::cell::{Cell, RefCell};
2use std::fmt;
34pub use at::DefineOpaqueTypes;
5use free_regions::RegionRelations;
6pub use freshen::TypeFreshener;
7use lexical_region_resolve::LexicalRegionResolutions;
8pub use lexical_region_resolve::RegionResolutionError;
9pub use opaque_types::{OpaqueTypeStorage, OpaqueTypeStorageEntries, OpaqueTypeTable};
10use region_constraints::{
11GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
12};
13pub use relate::StructurallyRelateAliases;
14pub use relate::combine::PredicateEmittingRelation;
15use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
16use rustc_data_structures::undo_log::{Rollback, UndoLogs};
17use rustc_data_structures::unifyas ut;
18use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
19use rustc_hir::def_id::{DefId, LocalDefId};
20use rustc_hir::{selfas hir, HirId};
21use rustc_index::IndexVec;
22use rustc_macros::extension;
23pub use rustc_macros::{TypeFoldable, TypeVisitable};
24use rustc_middle::bug;
25use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
26use rustc_middle::mir::ConstraintCategory;
27use rustc_middle::traits::select;
28use rustc_middle::traits::solve::Goal;
29use rustc_middle::ty::error::{ExpectedFound, TypeError};
30use rustc_middle::ty::{
31self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
32GenericArgsRef, GenericParamDefKind, InferConst, IntVid, OpaqueTypeKey, ProvisionalHiddenType,
33PseudoCanonicalInput, Term, TermKind, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder,
34TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
35};
36use rustc_span::{DUMMY_SP, Span, Symbol};
37use snapshot::undo_log::InferCtxtUndoLogs;
38use tracing::{debug, instrument};
39use type_variable::TypeVariableOrigin;
4041use crate::infer::snapshot::undo_log::UndoLog;
42use crate::infer::type_variable::FloatVariableOrigin;
43use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
44use crate::traits::{
45self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
46TraitEngine,
47};
4849pub mod at;
50pub mod canonical;
51mod context;
52mod free_regions;
53mod freshen;
54mod lexical_region_resolve;
55mod opaque_types;
56pub mod outlives;
57mod projection;
58pub mod region_constraints;
59pub mod relate;
60pub mod resolve;
61pub(crate) mod snapshot;
62mod type_variable;
63mod unify_key;
6465/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
66/// around `PredicateObligations<'tcx>`, but it has one important property:
67/// because `InferOk` is marked with `#[must_use]`, if you have a method
68/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
69/// `infcx.f()?;` you'll get a warning about the obligations being discarded
70/// without use, which is probably unintentional and has been a source of bugs
71/// in the past.
72#[must_use]
73#[derive(#[automatically_derived]
impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug for InferOk<'tcx, T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "InferOk",
"value", &self.value, "obligations", &&self.obligations)
}
}Debug)]
74pub struct InferOk<'tcx, T> {
75pub value: T,
76pub obligations: PredicateObligations<'tcx>,
77}
78pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
7980pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
8182pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
83 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
84>;
8586/// This type contains all the things within `InferCtxt` that sit within a
87/// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
88/// operations are hot enough that we want only one call to `borrow_mut` per
89/// call to `start_snapshot` and `rollback_to`.
90#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for InferCtxtInner<'tcx> {
#[inline]
fn clone(&self) -> InferCtxtInner<'tcx> {
InferCtxtInner {
undo_log: ::core::clone::Clone::clone(&self.undo_log),
projection_cache: ::core::clone::Clone::clone(&self.projection_cache),
type_variable_storage: ::core::clone::Clone::clone(&self.type_variable_storage),
const_unification_storage: ::core::clone::Clone::clone(&self.const_unification_storage),
int_unification_storage: ::core::clone::Clone::clone(&self.int_unification_storage),
float_unification_storage: ::core::clone::Clone::clone(&self.float_unification_storage),
float_origin_origin_storage: ::core::clone::Clone::clone(&self.float_origin_origin_storage),
region_constraint_storage: ::core::clone::Clone::clone(&self.region_constraint_storage),
region_obligations: ::core::clone::Clone::clone(&self.region_obligations),
region_assumptions: ::core::clone::Clone::clone(&self.region_assumptions),
hir_typeck_potentially_region_dependent_goals: ::core::clone::Clone::clone(&self.hir_typeck_potentially_region_dependent_goals),
opaque_type_storage: ::core::clone::Clone::clone(&self.opaque_type_storage),
}
}
}Clone)]
91pub struct InferCtxtInner<'tcx> {
92 undo_log: InferCtxtUndoLogs<'tcx>,
9394/// Cache for projections.
95 ///
96 /// This cache is snapshotted along with the infcx.
97projection_cache: traits::ProjectionCacheStorage<'tcx>,
9899/// We instantiate `UnificationTable` with `bounds<Ty>` because the types
100 /// that might instantiate a general type variable have an order,
101 /// represented by its upper and lower bounds.
102type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
103104/// Map from const parameter variable to the kind of const it represents.
105const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
106107/// Map from integral variable to the kind of integer it represents.
108int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
109110/// Map from floating variable to the kind of float it represents.
111float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
112113/// Map from floating variable to the origin span it came from, and the HirId that should be
114 /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
115 /// so can be removed once the `f32` fallback is removed.
116float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
117118/// Tracks the set of region variables and the constraints between them.
119 ///
120 /// This is initially `Some(_)` but when
121 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
122 /// -- further attempts to perform unification, etc., may fail if new
123 /// region constraints would've been added.
124region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
125126/// A set of constraints that regionck must validate.
127 ///
128 /// Each constraint has the form `T:'a`, meaning "some type `T` must
129 /// outlive the lifetime 'a". These constraints derive from
130 /// instantiated type parameters. So if you had a struct defined
131 /// like the following:
132 /// ```ignore (illustrative)
133 /// struct Foo<T: 'static> { ... }
134 /// ```
135 /// In some expression `let x = Foo { ... }`, it will
136 /// instantiate the type parameter `T` with a fresh type `$0`. At
137 /// the same time, it will record a region obligation of
138 /// `$0: 'static`. This will get checked later by regionck. (We
139 /// can't generally check these things right away because we have
140 /// to wait until types are resolved.)
141region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
142143/// The outlives bounds that we assume must hold about placeholders that
144 /// come from instantiating the binder of coroutine-witnesses. These bounds
145 /// are deduced from the well-formedness of the witness's types, and are
146 /// necessary because of the way we anonymize the regions in a coroutine,
147 /// which may cause types to no longer be considered well-formed.
148region_assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
149150/// `-Znext-solver`: Successfully proven goals during HIR typeck which
151 /// reference inference variables and get reproven in case MIR type check
152 /// fails to prove something.
153 ///
154 /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
155hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
156157/// Caches for opaque type inference.
158opaque_type_storage: OpaqueTypeStorage<'tcx>,
159}
160161impl<'tcx> InferCtxtInner<'tcx> {
162fn new() -> InferCtxtInner<'tcx> {
163InferCtxtInner {
164 undo_log: InferCtxtUndoLogs::default(),
165166 projection_cache: Default::default(),
167 type_variable_storage: Default::default(),
168 const_unification_storage: Default::default(),
169 int_unification_storage: Default::default(),
170 float_unification_storage: Default::default(),
171 float_origin_origin_storage: Default::default(),
172 region_constraint_storage: Some(Default::default()),
173 region_obligations: Default::default(),
174 region_assumptions: Default::default(),
175 hir_typeck_potentially_region_dependent_goals: Default::default(),
176 opaque_type_storage: Default::default(),
177 }
178 }
179180#[inline]
181pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
182&self.region_obligations
183 }
184185#[inline]
186pub fn region_assumptions(&self) -> &[ty::ArgOutlivesPredicate<'tcx>] {
187&self.region_assumptions
188 }
189190#[inline]
191pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
192self.projection_cache.with_log(&mut self.undo_log)
193 }
194195#[inline]
196fn try_type_variables_probe_ref(
197&self,
198 vid: ty::TyVid,
199 ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
200// Uses a read-only view of the unification table, this way we don't
201 // need an undo log.
202self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
203 }
204205#[inline]
206fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
207self.type_variable_storage.with_log(&mut self.undo_log)
208 }
209210#[inline]
211pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
212self.opaque_type_storage.with_log(&mut self.undo_log)
213 }
214215#[inline]
216fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
217self.int_unification_storage.with_log(&mut self.undo_log)
218 }
219220#[inline]
221fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
222self.float_unification_storage.with_log(&mut self.undo_log)
223 }
224225#[inline]
226fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
227self.const_unification_storage.with_log(&mut self.undo_log)
228 }
229230#[inline]
231pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
232self.region_constraint_storage
233 .as_mut()
234 .expect("region constraints already solved")
235 .with_log(&mut self.undo_log)
236 }
237}
238239pub struct InferCtxt<'tcx> {
240pub tcx: TyCtxt<'tcx>,
241242/// The mode of this inference context, see the struct documentation
243 /// for more details.
244typing_mode: TypingMode<'tcx>,
245246/// Whether this inference context should care about region obligations in
247 /// the root universe. Most notably, this is used during HIR typeck as region
248 /// solving is left to borrowck instead.
249pub considering_regions: bool,
250/// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
251 /// need to make sure we don't rely on region identity in the trait solver or when
252 /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
253 /// free region with a unique inference variable. If HIR typeck ends up depending on two
254 /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
255 /// resulting in an ICE.
256 ///
257 /// The trait solver sometimes depends on regions being identical. As a concrete example
258 /// the trait solver ignores other candidates if one candidate exists without any constraints.
259 /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
260 /// occurrence of `'a` with a unique region the goal now equates these regions. See
261 /// the tests in trait-system-refactor-initiative#27 for concrete examples.
262 ///
263 /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
264 /// This is still insufficient as inference variables may *hide* region variables, so e.g.
265 /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
266 /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
267 /// stash all successfully proven goals which reference inference variables and then reprove
268 /// them after writeback.
269pub in_hir_typeck: bool,
270271/// If set, this flag causes us to skip the 'leak check' during
272 /// higher-ranked subtyping operations. This flag is a temporary one used
273 /// to manage the removal of the leak-check: for the time being, we still run the
274 /// leak-check, but we issue warnings.
275skip_leak_check: bool,
276277pub inner: RefCell<InferCtxtInner<'tcx>>,
278279/// Once region inference is done, the values for each variable.
280lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
281282/// Caches the results of trait selection. This cache is used
283 /// for things that depends on inference variables or placeholders.
284pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
285286/// Caches the results of trait evaluation. This cache is used
287 /// for things that depends on inference variables or placeholders.
288pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
289290/// The set of predicates on which errors have been reported, to
291 /// avoid reporting the same error twice.
292pub reported_trait_errors:
293RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
294295pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
296297/// When an error occurs, we want to avoid reporting "derived"
298 /// errors that are due to this original failure. We have this
299 /// flag that one can set whenever one creates a type-error that
300 /// is due to an error in a prior pass.
301 ///
302 /// Don't read this flag directly, call `is_tainted_by_errors()`
303 /// and `set_tainted_by_errors()`.
304tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
305306/// What is the innermost universe we have created? Starts out as
307 /// `UniverseIndex::root()` but grows from there as we enter
308 /// universal quantifiers.
309 ///
310 /// N.B., at present, we exclude the universal quantifiers on the
311 /// item we are type-checking, and just consider those names as
312 /// part of the root universe. So this would only get incremented
313 /// when we enter into a higher-ranked (`for<..>`) type or trait
314 /// bound.
315universe: Cell<ty::UniverseIndex>,
316317 next_trait_solver: bool,
318319pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
320}
321322/// See the `error_reporting` module for more details.
323#[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)]
324pub enum ValuePairs<'tcx> {
325 Regions(ExpectedFound<ty::Region<'tcx>>),
326 Terms(ExpectedFound<ty::Term<'tcx>>),
327 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
328 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
329 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
330 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
331 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
332}
333334impl<'tcx> ValuePairs<'tcx> {
335pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
336if let ValuePairs::Terms(ExpectedFound { expected, found }) = self337 && let Some(expected) = expected.as_type()
338 && let Some(found) = found.as_type()
339 {
340Some((expected, found))
341 } else {
342None343 }
344 }
345}
346347/// The trace designates the path through inference that we took to
348/// encounter an error or subtyping constraint.
349///
350/// See the `error_reporting` module for more details.
351#[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)]
352pub struct TypeTrace<'tcx> {
353pub cause: ObligationCause<'tcx>,
354pub values: ValuePairs<'tcx>,
355}
356357/// The origin of a `r1 <= r2` constraint.
358///
359/// See `error_reporting` module for more details
360#[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)),
}
}
}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),
}
}
}Debug)]
361pub enum SubregionOrigin<'tcx> {
362/// Arose from a subtyping relation
363Subtype(Box<TypeTrace<'tcx>>),
364365/// When casting `&'a T` to an `&'b Trait` object,
366 /// relating `'a` to `'b`.
367RelateObjectBound(Span),
368369/// Some type parameter was instantiated with the given type,
370 /// and that type must outlive some region.
371RelateParamBound(Span, Ty<'tcx>, Option<Span>),
372373/// The given region parameter was instantiated with a region
374 /// that must outlive some other region.
375RelateRegionParamBound(Span, Option<Ty<'tcx>>),
376377/// Creating a pointer `b` to contents of another reference.
378Reborrow(Span),
379380/// (&'a &'b T) where a >= b
381ReferenceOutlivesReferent(Ty<'tcx>, Span),
382383/// Comparing the signature and requirements of an impl method against
384 /// the containing trait.
385CompareImplItemObligation {
386 span: Span,
387 impl_item_def_id: LocalDefId,
388 trait_item_def_id: DefId,
389 },
390391/// Checking that the bounds of a trait's associated type hold for a given impl.
392CheckAssociatedTypeBounds {
393 parent: Box<SubregionOrigin<'tcx>>,
394 impl_item_def_id: LocalDefId,
395 trait_item_def_id: DefId,
396 },
397398 AscribeUserTypeProvePredicate(Span),
399}
400401// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
402#[cfg(target_pointer_width = "64")]
403const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
404405impl<'tcx> SubregionOrigin<'tcx> {
406pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
407match self {
408Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
409Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
410_ => ConstraintCategory::BoringNoLocation,
411 }
412 }
413}
414415/// Times when we replace bound regions with existentials:
416#[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)]
417pub enum BoundRegionConversionTime {
418/// when a fn is called
419FnCall,
420421/// when two higher-ranked types are compared
422HigherRankedType,
423424/// when projecting an associated type
425AssocTypeProjection(DefId),
426}
427428/// Reasons to create a region inference variable.
429///
430/// See `error_reporting` module for more details.
431#[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)]
432pub enum RegionVariableOrigin<'tcx> {
433/// Region variables created for ill-categorized reasons.
434 ///
435 /// They mostly indicate places in need of refactoring.
436Misc(Span),
437438/// Regions created by a `&P` or `[...]` pattern.
439PatternRegion(Span),
440441/// Regions created by `&` operator.
442BorrowRegion(Span),
443444/// Regions created as part of an autoref of a method receiver.
445Autoref(Span),
446447/// Regions created as part of an automatic coercion.
448Coercion(Span),
449450/// Region variables created as the values for early-bound regions.
451 ///
452 /// FIXME(@lcnr): This should also store a `DefId`, similar to
453 /// `TypeVariableOrigin`.
454RegionParameterDefinition(Span, Symbol),
455456/// Region variables created when instantiating a binder with
457 /// existential variables, e.g. when calling a function or method.
458BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
459460 UpvarRegion(ty::UpvarId, Span),
461462/// This origin is used for the inference variables that we create
463 /// during NLL region processing.
464Nll(NllRegionVariableOrigin<'tcx>),
465}
466467#[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)]
468pub enum NllRegionVariableOrigin<'tcx> {
469/// During NLL region processing, we create variables for free
470 /// regions that we encounter in the function signature and
471 /// elsewhere. This origin indices we've got one of those.
472FreeRegion,
473474/// "Universal" instantiation of a higher-ranked region (e.g.,
475 /// from a `for<'a> T` binder). Meant to represent "any region".
476Placeholder(ty::PlaceholderRegion<'tcx>),
477478 Existential {
479 name: Option<Symbol>,
480 },
481}
482483#[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)]
484pub struct FixupError {
485 unresolved: TyOrConstInferVar,
486}
487488impl fmt::Displayfor FixupError {
489fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
490match self.unresolved {
491 TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
492f,
493"cannot determine the type of this integer; \
494 add a suffix to specify the type explicitly"
495),
496 TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
497f,
498"cannot determine the type of this number; \
499 add a suffix to specify the type explicitly"
500),
501 TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
502 TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
503 }
504 }
505}
506507/// See the `region_obligations` field for more information.
508#[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)]
509pub struct TypeOutlivesConstraint<'tcx> {
510pub sub_region: ty::Region<'tcx>,
511pub sup_type: Ty<'tcx>,
512pub origin: SubregionOrigin<'tcx>,
513}
514515/// Used to configure inference contexts before their creation.
516pub struct InferCtxtBuilder<'tcx> {
517 tcx: TyCtxt<'tcx>,
518 considering_regions: bool,
519 in_hir_typeck: bool,
520 skip_leak_check: bool,
521/// Whether we should use the new trait solver in the local inference context,
522 /// which affects things like which solver is used in `predicate_may_hold`.
523next_trait_solver: bool,
524}
525526impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
InferCtxtBuilder {
tcx: self,
considering_regions: true,
in_hir_typeck: false,
skip_leak_check: false,
next_trait_solver: self.next_trait_solver_globally(),
}
}
}#[extension(pub trait TyCtxtInferExt<'tcx>)]527impl<'tcx> TyCtxt<'tcx> {
528fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
529InferCtxtBuilder {
530 tcx: self,
531 considering_regions: true,
532 in_hir_typeck: false,
533 skip_leak_check: false,
534 next_trait_solver: self.next_trait_solver_globally(),
535 }
536 }
537}
538539impl<'tcx> InferCtxtBuilder<'tcx> {
540pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
541self.next_trait_solver = next_trait_solver;
542self543 }
544545pub fn ignoring_regions(mut self) -> Self {
546self.considering_regions = false;
547self548 }
549550pub fn in_hir_typeck(mut self) -> Self {
551self.in_hir_typeck = true;
552self553 }
554555pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
556self.skip_leak_check = skip_leak_check;
557self558 }
559560/// Given a canonical value `C` as a starting point, create an
561 /// inference context that contains each of the bound values
562 /// within instantiated as a fresh variable. The `f` closure is
563 /// invoked with the new infcx, along with the instantiated value
564 /// `V` and a instantiation `S`. This instantiation `S` maps from
565 /// the bound values in `C` to their instantiated values in `V`
566 /// (in other words, `S(C) = V`).
567pub fn build_with_canonical<T>(
568mut self,
569 span: Span,
570 input: &CanonicalQueryInput<'tcx, T>,
571 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
572where
573T: TypeFoldable<TyCtxt<'tcx>>,
574 {
575let infcx = self.build(input.typing_mode.0);
576let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
577 (infcx, value, args)
578 }
579580pub fn build_with_typing_env(
581mut self,
582 typing_env: TypingEnv<'tcx>,
583 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
584 (self.build(typing_env.typing_mode()), typing_env.param_env)
585 }
586587pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
588let InferCtxtBuilder {
589 tcx,
590 considering_regions,
591 in_hir_typeck,
592 skip_leak_check,
593 next_trait_solver,
594 } = *self;
595InferCtxt {
596tcx,
597typing_mode,
598considering_regions,
599in_hir_typeck,
600skip_leak_check,
601 inner: RefCell::new(InferCtxtInner::new()),
602 lexical_region_resolutions: RefCell::new(None),
603 selection_cache: Default::default(),
604 evaluation_cache: Default::default(),
605 reported_trait_errors: Default::default(),
606 reported_signature_mismatch: Default::default(),
607 tainted_by_errors: Cell::new(None),
608 universe: Cell::new(ty::UniverseIndex::ROOT),
609next_trait_solver,
610 obligation_inspector: Cell::new(None),
611 }
612 }
613}
614615impl<'tcx, T> InferOk<'tcx, T> {
616/// Extracts `value`, registering any obligations into `fulfill_cx`.
617pub fn into_value_registering_obligations<E: 'tcx>(
618self,
619 infcx: &InferCtxt<'tcx>,
620 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
621 ) -> T {
622let InferOk { value, obligations } = self;
623fulfill_cx.register_predicate_obligations(infcx, obligations);
624value625 }
626}
627628impl<'tcx> InferOk<'tcx, ()> {
629pub fn into_obligations(self) -> PredicateObligations<'tcx> {
630self.obligations
631 }
632}
633634impl<'tcx> InferCtxt<'tcx> {
635pub fn dcx(&self) -> DiagCtxtHandle<'_> {
636self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
637 }
638639pub fn next_trait_solver(&self) -> bool {
640self.next_trait_solver
641 }
642643#[inline(always)]
644pub fn typing_mode(&self) -> TypingMode<'tcx> {
645self.typing_mode
646 }
647648/// Returns the origin of the type variable identified by `vid`.
649 ///
650 /// No attempt is made to resolve `vid` to its root variable.
651pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
652self.inner.borrow_mut().type_variables().var_origin(vid)
653 }
654655/// Returns the origin of the float type variable identified by `vid`.
656 ///
657 /// No attempt is made to resolve `vid` to its root variable.
658pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
659self.inner.borrow_mut().float_origin_origin_storage[vid]
660 }
661662/// Returns the origin of the const variable identified by `vid`
663// FIXME: We should store origins separately from the unification table
664 // so this doesn't need to be optional.
665pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
666match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
667 ConstVariableValue::Known { .. } => None,
668 ConstVariableValue::Unknown { origin, .. } => Some(origin),
669 }
670 }
671672pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
673let mut inner = self.inner.borrow_mut();
674let mut vars: Vec<Ty<'_>> = inner675 .type_variables()
676 .unresolved_variables()
677 .into_iter()
678 .map(|t| Ty::new_var(self.tcx, t))
679 .collect();
680vars.extend(
681 (0..inner.int_unification_table().len())
682 .map(|i| ty::IntVid::from_usize(i))
683 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
684 .map(|v| Ty::new_int_var(self.tcx, v)),
685 );
686vars.extend(
687 (0..inner.float_unification_table().len())
688 .map(|i| ty::FloatVid::from_usize(i))
689 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
690 .map(|v| Ty::new_float_var(self.tcx, v)),
691 );
692vars693 }
694695#[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(695u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["origin", "a", "b"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn Value))])
})
} 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);
}
}
}#[instrument(skip(self), level = "debug")]696pub fn sub_regions(
697&self,
698 origin: SubregionOrigin<'tcx>,
699 a: ty::Region<'tcx>,
700 b: ty::Region<'tcx>,
701 ) {
702self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
703 }
704705#[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(705u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["origin", "a", "b"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn Value))])
})
} 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);
}
}
}#[instrument(skip(self), level = "debug")]706pub fn equate_regions(
707&self,
708 origin: SubregionOrigin<'tcx>,
709 a: ty::Region<'tcx>,
710 b: ty::Region<'tcx>,
711 ) {
712self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b);
713 }
714715/// Processes a `Coerce` predicate from the fulfillment context.
716 /// This is NOT the preferred way to handle coercion, which is to
717 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
718 ///
719 /// This method here is actually a fallback that winds up being
720 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
721 /// and records a coercion predicate. Presently, this method is equivalent
722 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
723 /// actually requiring `a <: b`. This is of course a valid coercion,
724 /// but it's not as flexible as `FnCtxt::coerce` would be.
725 ///
726 /// (We may refactor this in the future, but there are a number of
727 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
728 /// records adjustments that are required on the HIR in order to perform
729 /// the coercion, and we don't currently have a way to manage that.)
730pub fn coerce_predicate(
731&self,
732 cause: &ObligationCause<'tcx>,
733 param_env: ty::ParamEnv<'tcx>,
734 predicate: ty::PolyCoercePredicate<'tcx>,
735 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
736let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
737 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
738a: p.a,
739 b: p.b,
740 });
741self.subtype_predicate(cause, param_env, subtype_predicate)
742 }
743744pub fn subtype_predicate(
745&self,
746 cause: &ObligationCause<'tcx>,
747 param_env: ty::ParamEnv<'tcx>,
748 predicate: ty::PolySubtypePredicate<'tcx>,
749 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
750// Check for two unresolved inference variables, in which case we can
751 // make no progress. This is partly a micro-optimization, but it's
752 // also an opportunity to "sub-unify" the variables. This isn't
753 // *necessary* to prevent cycles, because they would eventually be sub-unified
754 // anyhow during generalization, but it helps with diagnostics (we can detect
755 // earlier that they are sub-unified).
756 //
757 // Note that we can just skip the binders here because
758 // type variables can't (at present, at
759 // least) capture any of the things bound by this binder.
760 //
761 // Note that this sub here is not just for diagnostics - it has semantic
762 // effects as well.
763let r_a = self.shallow_resolve(predicate.skip_binder().a);
764let r_b = self.shallow_resolve(predicate.skip_binder().b);
765match (r_a.kind(), r_b.kind()) {
766 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
767self.sub_unify_ty_vids_raw(a_vid, b_vid);
768return Err((a_vid, b_vid));
769 }
770_ => {}
771 }
772773self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
774if a_is_expected {
775Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
776 } else {
777Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
778 }
779 })
780 }
781782/// Number of type variables created so far.
783pub fn num_ty_vars(&self) -> usize {
784self.inner.borrow_mut().type_variables().num_vars()
785 }
786787pub fn next_ty_vid(&self, span: Span) -> TyVid {
788self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
789 }
790791pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
792self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
793 }
794795pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
796let origin = TypeVariableOrigin { span, param_def_id: None };
797self.inner.borrow_mut().type_variables().new_var(universe, origin)
798 }
799800pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
801self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
802 }
803804pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
805let vid = self.next_ty_vid_with_origin(origin);
806Ty::new_var(self.tcx, vid)
807 }
808809pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
810let vid = self.next_ty_vid_in_universe(span, universe);
811Ty::new_var(self.tcx, vid)
812 }
813814pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
815self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
816 }
817818pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
819let vid = self820 .inner
821 .borrow_mut()
822 .const_unification_table()
823 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
824 .vid;
825 ty::Const::new_var(self.tcx, vid)
826 }
827828pub fn next_const_var_in_universe(
829&self,
830 span: Span,
831 universe: ty::UniverseIndex,
832 ) -> ty::Const<'tcx> {
833let origin = ConstVariableOrigin { span, param_def_id: None };
834let vid = self835 .inner
836 .borrow_mut()
837 .const_unification_table()
838 .new_key(ConstVariableValue::Unknown { origin, universe })
839 .vid;
840 ty::Const::new_var(self.tcx, vid)
841 }
842843pub fn next_int_var(&self) -> Ty<'tcx> {
844let next_int_var_id =
845self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
846Ty::new_int_var(self.tcx, next_int_var_id)
847 }
848849pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
850let mut inner = self.inner.borrow_mut();
851let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
852let origin = FloatVariableOrigin { span, lint_id };
853let span_index = inner.float_origin_origin_storage.push(origin);
854if 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);
855Ty::new_float_var(self.tcx, next_float_var_id)
856 }
857858/// Creates a fresh region variable with the next available index.
859 /// The variable will be created in the maximum universe created
860 /// thus far, allowing it to name any region created thus far.
861pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
862self.next_region_var_in_universe(origin, self.universe())
863 }
864865/// Creates a fresh region variable with the next available index
866 /// in the given universe; typically, you can use
867 /// `next_region_var` and just use the maximal universe.
868pub fn next_region_var_in_universe(
869&self,
870 origin: RegionVariableOrigin<'tcx>,
871 universe: ty::UniverseIndex,
872 ) -> ty::Region<'tcx> {
873let region_var =
874self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
875 ty::Region::new_var(self.tcx, region_var)
876 }
877878pub fn next_term_var_of_kind(&self, term: ty::Term<'tcx>, span: Span) -> ty::Term<'tcx> {
879match term.kind() {
880 ty::TermKind::Ty(_) => self.next_ty_var(span).into(),
881 ty::TermKind::Const(_) => self.next_const_var(span).into(),
882 }
883 }
884885/// Return the universe that the region `r` was created in. For
886 /// most regions (e.g., `'static`, named regions from the user,
887 /// etc) this is the root universe U0. For inference variables or
888 /// placeholders, however, it will return the universe which they
889 /// are associated.
890pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
891self.inner.borrow_mut().unwrap_region_constraints().universe(r)
892 }
893894/// Number of region variables created so far.
895pub fn num_region_vars(&self) -> usize {
896self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
897 }
898899/// Just a convenient wrapper of `next_region_var` for using during NLL.
900#[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(900u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["origin"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{ self.next_region_var(RegionVariableOrigin::Nll(origin)) }
}
}#[instrument(skip(self), level = "debug")]901pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
902self.next_region_var(RegionVariableOrigin::Nll(origin))
903 }
904905/// Just a convenient wrapper of `next_region_var` for using during NLL.
906#[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(906u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["origin",
"universe"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&universe)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin),
universe)
}
}
}#[instrument(skip(self), level = "debug")]907pub fn next_nll_region_var_in_universe(
908&self,
909 origin: NllRegionVariableOrigin<'tcx>,
910 universe: ty::UniverseIndex,
911 ) -> ty::Region<'tcx> {
912self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
913 }
914915pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
916match param.kind {
917 GenericParamDefKind::Lifetime => {
918// Create a region inference variable for the given
919 // region parameter definition.
920self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
921span, param.name,
922 ))
923 .into()
924 }
925 GenericParamDefKind::Type { .. } => {
926// Create a type inference variable for the given
927 // type parameter definition. The generic parameters are
928 // for actual parameters that may be referred to by
929 // the default of this type parameter, if it exists.
930 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
931 // used in a path such as `Foo::<T, U>::new()` will
932 // use an inference variable for `C` with `[T, U]`
933 // as the generic parameters for the default, `(T, U)`.
934let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
935self.universe(),
936TypeVariableOrigin { param_def_id: Some(param.def_id), span },
937 );
938939Ty::new_var(self.tcx, ty_var_id).into()
940 }
941 GenericParamDefKind::Const { .. } => {
942let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
943let const_var_id = self944 .inner
945 .borrow_mut()
946 .const_unification_table()
947 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
948 .vid;
949 ty::Const::new_var(self.tcx, const_var_id).into()
950 }
951 }
952 }
953954/// Given a set of generics defined on a type or impl, returns the generic parameters mapping
955 /// each type/region parameter to a fresh inference variable.
956pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
957GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
958 }
959960/// Returns `true` if errors have been reported since this infcx was
961 /// created. This is sometimes used as a heuristic to skip
962 /// reporting errors that often occur as a result of earlier
963 /// errors, but where it's hard to be 100% sure (e.g., unresolved
964 /// inference variables, regionck errors).
965#[must_use = "this method does not have any side effects"]
966pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
967self.tainted_by_errors.get()
968 }
969970/// Set the "tainted by errors" flag to true. We call this when we
971 /// observe an error from a prior pass.
972pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
973{
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:973",
"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(973u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("set_tainted_by_errors(ErrorGuaranteed)")
as &dyn Value))])
});
} else { ; }
};debug!("set_tainted_by_errors(ErrorGuaranteed)");
974self.tainted_by_errors.set(Some(e));
975 }
976977pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
978let mut inner = self.inner.borrow_mut();
979let inner = &mut *inner;
980inner.unwrap_region_constraints().var_origin(vid)
981 }
982983/// Clone the list of variable regions. This is used only during NLL processing
984 /// to put the set of region variables into the NLL region context.
985pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
986let inner = self.inner.borrow();
987if !!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));
988let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
989if !storage.data.is_empty() {
{ ::core::panicking::panic_fmt(format_args!("{0:#?}", storage.data)); }
};assert!(storage.data.is_empty(), "{:#?}", storage.data);
990// We clone instead of taking because borrowck still wants to use the
991 // inference context after calling this for diagnostics and the new
992 // trait solver.
993storage.var_infos.clone()
994 }
995996pub fn has_opaque_types_in_storage(&self) -> bool {
997 !self.inner.borrow().opaque_type_storage.is_empty()
998 }
9991000x;#[instrument(level = "debug", skip(self), ret)]1001pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1002self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1003 }
10041005x;#[instrument(level = "debug", skip(self), ret)]1006pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1007self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1008 }
10091010pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1011if !self.next_trait_solver() {
1012return false;
1013 }
10141015let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1016let inner = &mut *self.inner.borrow_mut();
1017let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1018inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1019if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1020let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1021if opaque_sub_vid == ty_sub_vid {
1022return true;
1023 }
1024 }
10251026false
1027})
1028 }
10291030/// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1031 ///
1032 /// This only checks for a subtype relation, it does not require equality.
1033pub fn opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> Vec<ty::AliasTy<'tcx>> {
1034// Avoid accidentally allowing more code to compile with the old solver.
1035if !self.next_trait_solver() {
1036return ::alloc::vec::Vec::new()vec![];
1037 }
10381039let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1040let inner = &mut *self.inner.borrow_mut();
1041// This is iffy, can't call `type_variables()` as we're already
1042 // borrowing the `opaque_type_storage` here.
1043let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1044inner1045 .opaque_type_storage
1046 .iter_opaque_types()
1047 .filter_map(|(key, hidden_ty)| {
1048if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1049let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1050if opaque_sub_vid == ty_sub_vid {
1051return Some(ty::AliasTy::new_from_args(
1052self.tcx,
1053 ty::Opaque { def_id: key.def_id.into() },
1054key.args,
1055 ));
1056 }
1057 }
10581059None1060 })
1061 .collect()
1062 }
10631064#[inline(always)]
1065pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1066if true {
if !!self.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.next_trait_solver()")
};
};debug_assert!(!self.next_trait_solver());
1067match self.typing_mode() {
1068TypingMode::Analysis {
1069 defining_opaque_types_and_generators: defining_opaque_types,
1070 }
1071 | TypingMode::Borrowck { defining_opaque_types } => {
1072id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1073 }
1074// FIXME(#132279): This function is quite weird in post-analysis
1075 // and post-borrowck analysis mode. We may need to modify its uses
1076 // to support PostBorrowckAnalysis in the old solver as well.
1077TypingMode::Coherence1078 | TypingMode::PostBorrowckAnalysis { .. }
1079 | TypingMode::PostAnalysis => false,
1080 }
1081 }
10821083pub fn push_hir_typeck_potentially_region_dependent_goal(
1084&self,
1085 goal: PredicateObligation<'tcx>,
1086 ) {
1087let mut inner = self.inner.borrow_mut();
1088inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1089inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1090 }
10911092pub fn take_hir_typeck_potentially_region_dependent_goals(
1093&self,
1094 ) -> Vec<PredicateObligation<'tcx>> {
1095if !!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");
1096 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1097 }
10981099pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1100self.resolve_vars_if_possible(t).to_string()
1101 }
11021103/// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1104 /// universe index of `TyVar(vid)`.
1105pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1106use self::type_variable::TypeVariableValue;
11071108match self.inner.borrow_mut().type_variables().probe(vid) {
1109 TypeVariableValue::Known { value } => Ok(value),
1110 TypeVariableValue::Unknown { universe } => Err(universe),
1111 }
1112 }
11131114pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1115if let ty::Infer(v) = *ty.kind() {
1116match v {
1117 ty::TyVar(v) => {
1118// Not entirely obvious: if `typ` is a type variable,
1119 // it can be resolved to an int/float variable, which
1120 // can then be recursively resolved, hence the
1121 // recursion. Note though that we prevent type
1122 // variables from unifying to other type variables
1123 // directly (though they may be embedded
1124 // structurally), and we prevent cycles in any case,
1125 // so this recursion should always be of very limited
1126 // depth.
1127 //
1128 // Note: if these two lines are combined into one we get
1129 // dynamic borrow errors on `self.inner`.
1130let known = self.inner.borrow_mut().type_variables().probe(v).known();
1131known.map_or(ty, |t| self.shallow_resolve(t))
1132 }
11331134 ty::IntVar(v) => {
1135match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1136 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1137 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1138 ty::IntVarValue::Unknown => ty,
1139 }
1140 }
11411142 ty::FloatVar(v) => {
1143match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1144 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1145 ty::FloatVarValue::Unknown => ty,
1146 }
1147 }
11481149 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1150 }
1151 } else {
1152ty1153 }
1154 }
11551156pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1157match ct.kind() {
1158 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1159 InferConst::Var(vid) => self1160 .inner
1161 .borrow_mut()
1162 .const_unification_table()
1163 .probe_value(vid)
1164 .known()
1165 .unwrap_or(ct),
1166 InferConst::Fresh(_) => ct,
1167 },
1168 ty::ConstKind::Param(_)
1169 | ty::ConstKind::Bound(_, _)
1170 | ty::ConstKind::Placeholder(_)
1171 | ty::ConstKind::Unevaluated(_)
1172 | ty::ConstKind::Value(_)
1173 | ty::ConstKind::Error(_)
1174 | ty::ConstKind::Expr(_) => ct,
1175 }
1176 }
11771178pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1179match term.kind() {
1180 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1181 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1182 }
1183 }
11841185pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1186self.inner.borrow_mut().type_variables().root_var(var)
1187 }
11881189pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1190self.inner.borrow_mut().type_variables().sub_unify(a, b);
1191 }
11921193pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1194self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1195 }
11961197pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1198self.inner.borrow_mut().float_unification_table().find(var)
1199 }
12001201pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1202self.inner.borrow_mut().const_unification_table().find(var).vid
1203 }
12041205/// Resolves an int var to a rigid int type, if it was constrained to one,
1206 /// or else the root int var in the unification table.
1207pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1208let mut inner = self.inner.borrow_mut();
1209let value = inner.int_unification_table().probe_value(vid);
1210match value {
1211 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1212 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1213 ty::IntVarValue::Unknown => {
1214Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1215 }
1216 }
1217 }
12181219/// Resolves a float var to a rigid int type, if it was constrained to one,
1220 /// or else the root float var in the unification table.
1221pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1222let mut inner = self.inner.borrow_mut();
1223let value = inner.float_unification_table().probe_value(vid);
1224match value {
1225 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1226 ty::FloatVarValue::Unknown => {
1227Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1228 }
1229 }
1230 }
12311232/// Where possible, replaces type/const variables in
1233 /// `value` with their final value. Note that region variables
1234 /// are unaffected. If a type/const variable has not been unified, it
1235 /// is left as is. This is an idempotent operation that does
1236 /// not affect inference state in any way and so you can do it
1237 /// at will.
1238pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1239where
1240T: TypeFoldable<TyCtxt<'tcx>>,
1241 {
1242if let Err(guar) = value.error_reported() {
1243self.set_tainted_by_errors(guar);
1244 }
1245if !value.has_non_region_infer() {
1246return value;
1247 }
1248let mut r = resolve::OpportunisticVarResolver::new(self);
1249value.fold_with(&mut r)
1250 }
12511252pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1253where
1254T: TypeFoldable<TyCtxt<'tcx>>,
1255 {
1256if !value.has_infer() {
1257return value; // Avoid duplicated type-folding.
1258}
1259let mut r = InferenceLiteralEraser { tcx: self.tcx };
1260value.fold_with(&mut r)
1261 }
12621263pub fn try_resolve_const_var(
1264&self,
1265 vid: ty::ConstVid,
1266 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1267match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1268 ConstVariableValue::Known { value } => Ok(value),
1269 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1270 }
1271 }
12721273/// Attempts to resolve all type/region/const variables in
1274 /// `value`. Region inference must have been run already (e.g.,
1275 /// by calling `resolve_regions_and_report_errors`). If some
1276 /// variable was never unified, an `Err` results.
1277 ///
1278 /// This method is idempotent, but it not typically not invoked
1279 /// except during the writeback phase.
1280pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1281match resolve::fully_resolve(self, value) {
1282Ok(value) => {
1283if value.has_non_region_infer() {
1284::rustc_middle::util::bug::bug_fmt(format_args!("`{0:?}` is not fully resolved",
value));bug!("`{value:?}` is not fully resolved");
1285 }
1286if value.has_infer_regions() {
1287let 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"));
1288Ok(fold_regions(self.tcx, value, |re, _| {
1289if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1290 }))
1291 } else {
1292Ok(value)
1293 }
1294 }
1295Err(e) => Err(e),
1296 }
1297 }
12981299// Instantiates the bound variables in a given binder with fresh inference
1300 // variables in the current universe.
1301 //
1302 // Use this method if you'd like to find some generic parameters of the binder's
1303 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1304 // that corresponds to your use case, consider whether or not you should
1305 // use [`InferCtxt::enter_forall`] instead.
1306pub fn instantiate_binder_with_fresh_vars<T>(
1307&self,
1308 span: Span,
1309 lbrct: BoundRegionConversionTime,
1310 value: ty::Binder<'tcx, T>,
1311 ) -> T
1312where
1313T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1314 {
1315if let Some(inner) = value.no_bound_vars() {
1316return inner;
1317 }
13181319let bound_vars = value.bound_vars();
1320let mut args = Vec::with_capacity(bound_vars.len());
13211322for bound_var_kind in bound_vars {
1323let arg: ty::GenericArg<'_> = match bound_var_kind {
1324 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1325 ty::BoundVariableKind::Region(br) => {
1326self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1327 }
1328 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1329 };
1330 args.push(arg);
1331 }
13321333struct ToFreshVars<'tcx> {
1334 args: Vec<ty::GenericArg<'tcx>>,
1335 }
13361337impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1338fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1339self.args[br.var.index()].expect_region()
1340 }
1341fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1342self.args[bt.var.index()].expect_ty()
1343 }
1344fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1345self.args[bc.var.index()].expect_const()
1346 }
1347 }
1348let delegate = ToFreshVars { args };
1349self.tcx.replace_bound_vars_uncached(value, delegate)
1350 }
13511352/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1353pub(crate) fn verify_generic_bound(
1354&self,
1355 origin: SubregionOrigin<'tcx>,
1356 kind: GenericKind<'tcx>,
1357 a: ty::Region<'tcx>,
1358 bound: VerifyBound<'tcx>,
1359 ) {
1360{
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:1360",
"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(1360u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("verify_generic_bound({0:?}, {1:?} <: {2:?})",
kind, a, bound) as &dyn Value))])
});
} else { ; }
};debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
13611362self.inner
1363 .borrow_mut()
1364 .unwrap_region_constraints()
1365 .verify_generic_bound(origin, kind, a, bound);
1366 }
13671368/// Obtains the latest type of the given closure; this may be a
1369 /// closure in the current function, in which case its
1370 /// `ClosureKind` may not yet be known.
1371pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1372let unresolved_kind_ty = match *closure_ty.kind() {
1373 ty::Closure(_, args) => args.as_closure().kind_ty(),
1374 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1375_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0}",
closure_ty))bug!("unexpected type {closure_ty}"),
1376 };
1377let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1378closure_kind_ty.to_opt_closure_kind()
1379 }
13801381pub fn universe(&self) -> ty::UniverseIndex {
1382self.universe.get()
1383 }
13841385/// Creates and return a fresh universe that extends all previous
1386 /// universes. Updates `self.universe` to that new universe.
1387pub fn create_next_universe(&self) -> ty::UniverseIndex {
1388let u = self.universe.get().next_universe();
1389{
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:1389",
"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(1389u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("create_next_universe {0:?}",
u) as &dyn Value))])
});
} else { ; }
};debug!("create_next_universe {u:?}");
1390self.universe.set(u);
1391u1392 }
13931394/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1395 /// which contains the necessary information to use the trait system without
1396 /// using canonicalization or carrying this inference context around.
1397pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1398let typing_mode = match self.typing_mode() {
1399// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1400 // to handle them without proper canonicalization. This means we may cause cycle
1401 // errors and fail to reveal opaques while inside of bodies. We should rename this
1402 // function and require explicit comments on all use-sites in the future.
1403ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1404 | ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1405TypingMode::non_body_analysis()
1406 }
1407 mode @ (ty::TypingMode::Coherence1408 | ty::TypingMode::PostBorrowckAnalysis { .. }
1409 | ty::TypingMode::PostAnalysis) => mode,
1410 };
1411 ty::TypingEnv::new(param_env, typing_mode)
1412 }
14131414/// Similar to [`Self::canonicalize_query`], except that it returns
1415 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1416 /// `param_env` to not contain any inference variables or placeholders.
1417pub fn pseudo_canonicalize_query<V>(
1418&self,
1419 param_env: ty::ParamEnv<'tcx>,
1420 value: V,
1421 ) -> PseudoCanonicalInput<'tcx, V>
1422where
1423V: TypeVisitable<TyCtxt<'tcx>>,
1424 {
1425if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1426if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1427if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1428if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1429self.typing_env(param_env).as_query_input(value)
1430 }
14311432/// The returned function is used in a fast path. If it returns `true` the variable is
1433 /// unchanged, `false` indicates that the status is unknown.
1434#[inline]
1435pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1436// This hoists the borrow/release out of the loop body.
1437let inner = self.inner.try_borrow();
14381439move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1440 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1441use self::type_variable::TypeVariableValue;
14421443#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1444 inner.try_type_variables_probe_ref(ty_var),
1445Some(TypeVariableValue::Unknown { .. })
1446 )1447 }
1448_ => false,
1449 }
1450 }
14511452/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1453 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1454 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1455 ///
1456 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1457 /// inlined, despite being large, because it has only two call sites that
1458 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1459 /// inference variables), and it handles both `Ty` and `ty::Const` without
1460 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1461#[inline(always)]
1462pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1463match infer_var {
1464 TyOrConstInferVar::Ty(v) => {
1465use self::type_variable::TypeVariableValue;
14661467// If `inlined_probe` returns a `Known` value, it never equals
1468 // `ty::Infer(ty::TyVar(v))`.
1469match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1470 TypeVariableValue::Unknown { .. } => false,
1471 TypeVariableValue::Known { .. } => true,
1472 }
1473 }
14741475 TyOrConstInferVar::TyInt(v) => {
1476// If `inlined_probe_value` returns a value it's always a
1477 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1478 // `ty::Infer(_)`.
1479self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1480 }
14811482 TyOrConstInferVar::TyFloat(v) => {
1483// If `probe_value` returns a value it's always a
1484 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1485 //
1486 // Not `inlined_probe_value(v)` because this call site is colder.
1487self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1488 }
14891490 TyOrConstInferVar::Const(v) => {
1491// If `probe_value` returns a `Known` value, it never equals
1492 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1493 //
1494 // Not `inlined_probe_value(v)` because this call site is colder.
1495match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1496 ConstVariableValue::Unknown { .. } => false,
1497 ConstVariableValue::Known { .. } => true,
1498 }
1499 }
1500 }
1501 }
15021503/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1504pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1505if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1506self.obligation_inspector.get().is_none(),
1507"shouldn't override a set obligation inspector"
1508);
1509self.obligation_inspector.set(Some(inspector));
1510 }
1511}
15121513/// Helper for [InferCtxt::ty_or_const_infer_var_changed] (see comment on that), currently
1514/// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1515#[derive(#[automatically_derived]
impl ::core::marker::Copy for TyOrConstInferVar { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TyOrConstInferVar {
#[inline]
fn clone(&self) -> TyOrConstInferVar {
let _: ::core::clone::AssertParamIsClone<TyVid>;
let _: ::core::clone::AssertParamIsClone<IntVid>;
let _: ::core::clone::AssertParamIsClone<FloatVid>;
let _: ::core::clone::AssertParamIsClone<ConstVid>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for TyOrConstInferVar {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TyOrConstInferVar::Ty(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ty",
&__self_0),
TyOrConstInferVar::TyInt(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "TyInt",
&__self_0),
TyOrConstInferVar::TyFloat(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TyFloat", &__self_0),
TyOrConstInferVar::Const(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Const",
&__self_0),
}
}
}Debug)]
1516pub enum TyOrConstInferVar {
1517/// Equivalent to `ty::Infer(ty::TyVar(_))`.
1518Ty(TyVid),
1519/// Equivalent to `ty::Infer(ty::IntVar(_))`.
1520TyInt(IntVid),
1521/// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1522TyFloat(FloatVid),
15231524/// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1525Const(ConstVid),
1526}
15271528impl<'tcx> TyOrConstInferVar {
1529/// Tries to extract an inference variable from a type or a constant, returns `None`
1530 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1531 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1532pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1533match arg.kind() {
1534GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1535GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1536GenericArgKind::Lifetime(_) => None,
1537 }
1538 }
15391540/// Tries to extract an inference variable from a type or a constant, returns `None`
1541 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1542 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1543pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1544match term.kind() {
1545TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1546TermKind::Const(ct) => Self::maybe_from_const(ct),
1547 }
1548 }
15491550/// Tries to extract an inference variable from a type, returns `None`
1551 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1552fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1553match *ty.kind() {
1554 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1555 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1556 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1557_ => None,
1558 }
1559 }
15601561/// Tries to extract an inference variable from a constant, returns `None`
1562 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1563fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1564match ct.kind() {
1565 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1566_ => None,
1567 }
1568 }
1569}
15701571/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1572/// Used only for diagnostics.
1573struct InferenceLiteralEraser<'tcx> {
1574 tcx: TyCtxt<'tcx>,
1575}
15761577impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1578fn cx(&self) -> TyCtxt<'tcx> {
1579self.tcx
1580 }
15811582fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1583match ty.kind() {
1584 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1585 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1586_ => ty.super_fold_with(self),
1587 }
1588 }
1589}
15901591impl<'tcx> TypeTrace<'tcx> {
1592pub fn span(&self) -> Span {
1593self.cause.span
1594 }
15951596pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1597TypeTrace {
1598 cause: cause.clone(),
1599 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1600 }
1601 }
16021603pub fn trait_refs(
1604 cause: &ObligationCause<'tcx>,
1605 a: ty::TraitRef<'tcx>,
1606 b: ty::TraitRef<'tcx>,
1607 ) -> TypeTrace<'tcx> {
1608TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1609 }
16101611pub fn consts(
1612 cause: &ObligationCause<'tcx>,
1613 a: ty::Const<'tcx>,
1614 b: ty::Const<'tcx>,
1615 ) -> TypeTrace<'tcx> {
1616TypeTrace {
1617 cause: cause.clone(),
1618 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1619 }
1620 }
1621}
16221623impl<'tcx> SubregionOrigin<'tcx> {
1624pub fn span(&self) -> Span {
1625match *self {
1626 SubregionOrigin::Subtype(ref a) => a.span(),
1627 SubregionOrigin::RelateObjectBound(a) => a,
1628 SubregionOrigin::RelateParamBound(a, ..) => a,
1629 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1630 SubregionOrigin::Reborrow(a) => a,
1631 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1632 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1633 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1634 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1635 }
1636 }
16371638pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1639where
1640F: FnOnce() -> Self,
1641 {
1642match *cause.code() {
1643 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1644 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1645 }
16461647 traits::ObligationCauseCode::CompareImplItem {
1648 impl_item_def_id,
1649 trait_item_def_id,
1650 kind: _,
1651 } => SubregionOrigin::CompareImplItemObligation {
1652 span: cause.span,
1653impl_item_def_id,
1654trait_item_def_id,
1655 },
16561657 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1658 impl_item_def_id,
1659 trait_item_def_id,
1660 } => SubregionOrigin::CheckAssociatedTypeBounds {
1661impl_item_def_id,
1662trait_item_def_id,
1663 parent: Box::new(default()),
1664 },
16651666 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1667 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1668 }
16691670 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1671 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1672 }
16731674_ => default(),
1675 }
1676 }
1677}
16781679impl<'tcx> RegionVariableOrigin<'tcx> {
1680pub fn span(&self) -> Span {
1681match *self {
1682 RegionVariableOrigin::Misc(a)
1683 | RegionVariableOrigin::PatternRegion(a)
1684 | RegionVariableOrigin::BorrowRegion(a)
1685 | RegionVariableOrigin::Autoref(a)
1686 | RegionVariableOrigin::Coercion(a)
1687 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1688 | RegionVariableOrigin::BoundRegion(a, ..)
1689 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1690 RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable used with `span`"))bug!("NLL variable used with `span`"),
1691 }
1692 }
1693}
16941695impl<'tcx> InferCtxt<'tcx> {
1696/// Given a [`hir::Block`], get the span of its last expression or
1697 /// statement, peeling off any inner blocks.
1698pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1699let block = block.innermost_block();
1700if let Some(expr) = &block.expr {
1701expr.span
1702 } else if let Some(stmt) = block.stmts.last() {
1703// possibly incorrect trailing `;` in the else arm
1704stmt.span
1705 } else {
1706// empty block; point at its entirety
1707block.span
1708 }
1709 }
17101711/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1712 /// of its last expression or statement, peeling off any inner blocks.
1713pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1714match self.tcx.hir_node(hir_id) {
1715 hir::Node::Block(blk)
1716 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1717self.find_block_span(blk)
1718 }
1719 hir::Node::Expr(e) => e.span,
1720_ => DUMMY_SP,
1721 }
1722 }
1723}