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_hiras hir;
20use rustc_hir::def_id::{DefId, LocalDefId};
21use rustc_macros::extension;
22pub use rustc_macros::{TypeFoldable, TypeVisitable};
23use rustc_middle::bug;
24use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
25use rustc_middle::mir::ConstraintCategory;
26use rustc_middle::traits::select;
27use rustc_middle::traits::solve::Goal;
28use rustc_middle::ty::error::{ExpectedFound, TypeError};
29use rustc_middle::ty::{
30self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
31GenericArgsRef, GenericParamDefKind, InferConst, IntVid, OpaqueTypeKey, ProvisionalHiddenType,
32PseudoCanonicalInput, Term, TermKind, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder,
33TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
34};
35use rustc_span::{DUMMY_SP, Span, Symbol};
36use snapshot::undo_log::InferCtxtUndoLogs;
37use tracing::{debug, instrument};
38use type_variable::TypeVariableOrigin;
3940use crate::infer::snapshot::undo_log::UndoLog;
41use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
42use crate::traits::{
43self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
44TraitEngine,
45};
4647pub mod at;
48pub mod canonical;
49mod context;
50mod free_regions;
51mod freshen;
52mod lexical_region_resolve;
53mod opaque_types;
54pub mod outlives;
55mod projection;
56pub mod region_constraints;
57pub mod relate;
58pub mod resolve;
59pub(crate) mod snapshot;
60mod type_variable;
61mod unify_key;
6263/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
64/// around `PredicateObligations<'tcx>`, but it has one important property:
65/// because `InferOk` is marked with `#[must_use]`, if you have a method
66/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
67/// `infcx.f()?;` you'll get a warning about the obligations being discarded
68/// without use, which is probably unintentional and has been a source of bugs
69/// in the past.
70#[must_use]
71#[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)]
72pub struct InferOk<'tcx, T> {
73pub value: T,
74pub obligations: PredicateObligations<'tcx>,
75}
76pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
7778pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
7980pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
81 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
82>;
8384/// This type contains all the things within `InferCtxt` that sit within a
85/// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
86/// operations are hot enough that we want only one call to `borrow_mut` per
87/// call to `start_snapshot` and `rollback_to`.
88#[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),
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)]
89pub struct InferCtxtInner<'tcx> {
90 undo_log: InferCtxtUndoLogs<'tcx>,
9192/// Cache for projections.
93 ///
94 /// This cache is snapshotted along with the infcx.
95projection_cache: traits::ProjectionCacheStorage<'tcx>,
9697/// We instantiate `UnificationTable` with `bounds<Ty>` because the types
98 /// that might instantiate a general type variable have an order,
99 /// represented by its upper and lower bounds.
100type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
101102/// Map from const parameter variable to the kind of const it represents.
103const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
104105/// Map from integral variable to the kind of integer it represents.
106int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
107108/// Map from floating variable to the kind of float it represents.
109float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
110111/// Tracks the set of region variables and the constraints between them.
112 ///
113 /// This is initially `Some(_)` but when
114 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
115 /// -- further attempts to perform unification, etc., may fail if new
116 /// region constraints would've been added.
117region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
118119/// A set of constraints that regionck must validate.
120 ///
121 /// Each constraint has the form `T:'a`, meaning "some type `T` must
122 /// outlive the lifetime 'a". These constraints derive from
123 /// instantiated type parameters. So if you had a struct defined
124 /// like the following:
125 /// ```ignore (illustrative)
126 /// struct Foo<T: 'static> { ... }
127 /// ```
128 /// In some expression `let x = Foo { ... }`, it will
129 /// instantiate the type parameter `T` with a fresh type `$0`. At
130 /// the same time, it will record a region obligation of
131 /// `$0: 'static`. This will get checked later by regionck. (We
132 /// can't generally check these things right away because we have
133 /// to wait until types are resolved.)
134region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
135136/// The outlives bounds that we assume must hold about placeholders that
137 /// come from instantiating the binder of coroutine-witnesses. These bounds
138 /// are deduced from the well-formedness of the witness's types, and are
139 /// necessary because of the way we anonymize the regions in a coroutine,
140 /// which may cause types to no longer be considered well-formed.
141region_assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
142143/// `-Znext-solver`: Successfully proven goals during HIR typeck which
144 /// reference inference variables and get reproven in case MIR type check
145 /// fails to prove something.
146 ///
147 /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
148hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
149150/// Caches for opaque type inference.
151opaque_type_storage: OpaqueTypeStorage<'tcx>,
152}
153154impl<'tcx> InferCtxtInner<'tcx> {
155fn new() -> InferCtxtInner<'tcx> {
156InferCtxtInner {
157 undo_log: InferCtxtUndoLogs::default(),
158159 projection_cache: Default::default(),
160 type_variable_storage: Default::default(),
161 const_unification_storage: Default::default(),
162 int_unification_storage: Default::default(),
163 float_unification_storage: Default::default(),
164 region_constraint_storage: Some(Default::default()),
165 region_obligations: Default::default(),
166 region_assumptions: Default::default(),
167 hir_typeck_potentially_region_dependent_goals: Default::default(),
168 opaque_type_storage: Default::default(),
169 }
170 }
171172#[inline]
173pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
174&self.region_obligations
175 }
176177#[inline]
178pub fn region_assumptions(&self) -> &[ty::ArgOutlivesPredicate<'tcx>] {
179&self.region_assumptions
180 }
181182#[inline]
183pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
184self.projection_cache.with_log(&mut self.undo_log)
185 }
186187#[inline]
188fn try_type_variables_probe_ref(
189&self,
190 vid: ty::TyVid,
191 ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
192// Uses a read-only view of the unification table, this way we don't
193 // need an undo log.
194self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
195 }
196197#[inline]
198fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
199self.type_variable_storage.with_log(&mut self.undo_log)
200 }
201202#[inline]
203pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
204self.opaque_type_storage.with_log(&mut self.undo_log)
205 }
206207#[inline]
208fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
209self.int_unification_storage.with_log(&mut self.undo_log)
210 }
211212#[inline]
213fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
214self.float_unification_storage.with_log(&mut self.undo_log)
215 }
216217#[inline]
218fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
219self.const_unification_storage.with_log(&mut self.undo_log)
220 }
221222#[inline]
223pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
224self.region_constraint_storage
225 .as_mut()
226 .expect("region constraints already solved")
227 .with_log(&mut self.undo_log)
228 }
229}
230231pub struct InferCtxt<'tcx> {
232pub tcx: TyCtxt<'tcx>,
233234/// The mode of this inference context, see the struct documentation
235 /// for more details.
236typing_mode: TypingMode<'tcx>,
237238/// Whether this inference context should care about region obligations in
239 /// the root universe. Most notably, this is used during HIR typeck as region
240 /// solving is left to borrowck instead.
241pub considering_regions: bool,
242/// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
243 /// need to make sure we don't rely on region identity in the trait solver or when
244 /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
245 /// free region with a unique inference variable. If HIR typeck ends up depending on two
246 /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
247 /// resulting in an ICE.
248 ///
249 /// The trait solver sometimes depends on regions being identical. As a concrete example
250 /// the trait solver ignores other candidates if one candidate exists without any constraints.
251 /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
252 /// occurrence of `'a` with a unique region the goal now equates these regions. See
253 /// the tests in trait-system-refactor-initiative#27 for concrete examples.
254 ///
255 /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
256 /// This is still insufficient as inference variables may *hide* region variables, so e.g.
257 /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
258 /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
259 /// stash all successfully proven goals which reference inference variables and then reprove
260 /// them after writeback.
261pub in_hir_typeck: bool,
262263/// If set, this flag causes us to skip the 'leak check' during
264 /// higher-ranked subtyping operations. This flag is a temporary one used
265 /// to manage the removal of the leak-check: for the time being, we still run the
266 /// leak-check, but we issue warnings.
267skip_leak_check: bool,
268269pub inner: RefCell<InferCtxtInner<'tcx>>,
270271/// Once region inference is done, the values for each variable.
272lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
273274/// Caches the results of trait selection. This cache is used
275 /// for things that depends on inference variables or placeholders.
276pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
277278/// Caches the results of trait evaluation. This cache is used
279 /// for things that depends on inference variables or placeholders.
280pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
281282/// The set of predicates on which errors have been reported, to
283 /// avoid reporting the same error twice.
284pub reported_trait_errors:
285RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
286287pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
288289/// When an error occurs, we want to avoid reporting "derived"
290 /// errors that are due to this original failure. We have this
291 /// flag that one can set whenever one creates a type-error that
292 /// is due to an error in a prior pass.
293 ///
294 /// Don't read this flag directly, call `is_tainted_by_errors()`
295 /// and `set_tainted_by_errors()`.
296tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
297298/// What is the innermost universe we have created? Starts out as
299 /// `UniverseIndex::root()` but grows from there as we enter
300 /// universal quantifiers.
301 ///
302 /// N.B., at present, we exclude the universal quantifiers on the
303 /// item we are type-checking, and just consider those names as
304 /// part of the root universe. So this would only get incremented
305 /// when we enter into a higher-ranked (`for<..>`) type or trait
306 /// bound.
307universe: Cell<ty::UniverseIndex>,
308309 next_trait_solver: bool,
310311pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
312}
313314/// See the `error_reporting` module for more details.
315#[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_receiver_is_total_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)]
316pub enum ValuePairs<'tcx> {
317 Regions(ExpectedFound<ty::Region<'tcx>>),
318 Terms(ExpectedFound<ty::Term<'tcx>>),
319 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
320 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
321 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
322 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
323 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
324}
325326impl<'tcx> ValuePairs<'tcx> {
327pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
328if let ValuePairs::Terms(ExpectedFound { expected, found }) = self329 && let Some(expected) = expected.as_type()
330 && let Some(found) = found.as_type()
331 {
332Some((expected, found))
333 } else {
334None335 }
336 }
337}
338339/// The trace designates the path through inference that we took to
340/// encounter an error or subtyping constraint.
341///
342/// See the `error_reporting` module for more details.
343#[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)]
344pub struct TypeTrace<'tcx> {
345pub cause: ObligationCause<'tcx>,
346pub values: ValuePairs<'tcx>,
347}
348349/// The origin of a `r1 <= r2` constraint.
350///
351/// See `error_reporting` module for more details
352#[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)]
353pub enum SubregionOrigin<'tcx> {
354/// Arose from a subtyping relation
355Subtype(Box<TypeTrace<'tcx>>),
356357/// When casting `&'a T` to an `&'b Trait` object,
358 /// relating `'a` to `'b`.
359RelateObjectBound(Span),
360361/// Some type parameter was instantiated with the given type,
362 /// and that type must outlive some region.
363RelateParamBound(Span, Ty<'tcx>, Option<Span>),
364365/// The given region parameter was instantiated with a region
366 /// that must outlive some other region.
367RelateRegionParamBound(Span, Option<Ty<'tcx>>),
368369/// Creating a pointer `b` to contents of another reference.
370Reborrow(Span),
371372/// (&'a &'b T) where a >= b
373ReferenceOutlivesReferent(Ty<'tcx>, Span),
374375/// Comparing the signature and requirements of an impl method against
376 /// the containing trait.
377CompareImplItemObligation {
378 span: Span,
379 impl_item_def_id: LocalDefId,
380 trait_item_def_id: DefId,
381 },
382383/// Checking that the bounds of a trait's associated type hold for a given impl.
384CheckAssociatedTypeBounds {
385 parent: Box<SubregionOrigin<'tcx>>,
386 impl_item_def_id: LocalDefId,
387 trait_item_def_id: DefId,
388 },
389390 AscribeUserTypeProvePredicate(Span),
391}
392393// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
394#[cfg(target_pointer_width = "64")]
395const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
396397impl<'tcx> SubregionOrigin<'tcx> {
398pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
399match self {
400Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
401Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
402_ => ConstraintCategory::BoringNoLocation,
403 }
404 }
405}
406407/// Times when we replace bound regions with existentials:
408#[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)]
409pub enum BoundRegionConversionTime {
410/// when a fn is called
411FnCall,
412413/// when two higher-ranked types are compared
414HigherRankedType,
415416/// when projecting an associated type
417AssocTypeProjection(DefId),
418}
419420/// Reasons to create a region inference variable.
421///
422/// See `error_reporting` module for more details.
423#[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)]
424pub enum RegionVariableOrigin<'tcx> {
425/// Region variables created for ill-categorized reasons.
426 ///
427 /// They mostly indicate places in need of refactoring.
428Misc(Span),
429430/// Regions created by a `&P` or `[...]` pattern.
431PatternRegion(Span),
432433/// Regions created by `&` operator.
434BorrowRegion(Span),
435436/// Regions created as part of an autoref of a method receiver.
437Autoref(Span),
438439/// Regions created as part of an automatic coercion.
440Coercion(Span),
441442/// Region variables created as the values for early-bound regions.
443 ///
444 /// FIXME(@lcnr): This should also store a `DefId`, similar to
445 /// `TypeVariableOrigin`.
446RegionParameterDefinition(Span, Symbol),
447448/// Region variables created when instantiating a binder with
449 /// existential variables, e.g. when calling a function or method.
450BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
451452 UpvarRegion(ty::UpvarId, Span),
453454/// This origin is used for the inference variables that we create
455 /// during NLL region processing.
456Nll(NllRegionVariableOrigin<'tcx>),
457}
458459#[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)]
460pub enum NllRegionVariableOrigin<'tcx> {
461/// During NLL region processing, we create variables for free
462 /// regions that we encounter in the function signature and
463 /// elsewhere. This origin indices we've got one of those.
464FreeRegion,
465466/// "Universal" instantiation of a higher-ranked region (e.g.,
467 /// from a `for<'a> T` binder). Meant to represent "any region".
468Placeholder(ty::PlaceholderRegion<'tcx>),
469470 Existential {
471 name: Option<Symbol>,
472 },
473}
474475#[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)]
476pub struct FixupError {
477 unresolved: TyOrConstInferVar,
478}
479480impl fmt::Displayfor FixupError {
481fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482match self.unresolved {
483 TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
484f,
485"cannot determine the type of this integer; \
486 add a suffix to specify the type explicitly"
487),
488 TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
489f,
490"cannot determine the type of this number; \
491 add a suffix to specify the type explicitly"
492),
493 TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
494 TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
495 }
496 }
497}
498499/// See the `region_obligations` field for more information.
500#[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)]
501pub struct TypeOutlivesConstraint<'tcx> {
502pub sub_region: ty::Region<'tcx>,
503pub sup_type: Ty<'tcx>,
504pub origin: SubregionOrigin<'tcx>,
505}
506507/// Used to configure inference contexts before their creation.
508pub struct InferCtxtBuilder<'tcx> {
509 tcx: TyCtxt<'tcx>,
510 considering_regions: bool,
511 in_hir_typeck: bool,
512 skip_leak_check: bool,
513/// Whether we should use the new trait solver in the local inference context,
514 /// which affects things like which solver is used in `predicate_may_hold`.
515next_trait_solver: bool,
516}
517518impl<'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>)]519impl<'tcx> TyCtxt<'tcx> {
520fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
521InferCtxtBuilder {
522 tcx: self,
523 considering_regions: true,
524 in_hir_typeck: false,
525 skip_leak_check: false,
526 next_trait_solver: self.next_trait_solver_globally(),
527 }
528 }
529}
530531impl<'tcx> InferCtxtBuilder<'tcx> {
532pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
533self.next_trait_solver = next_trait_solver;
534self535 }
536537pub fn ignoring_regions(mut self) -> Self {
538self.considering_regions = false;
539self540 }
541542pub fn in_hir_typeck(mut self) -> Self {
543self.in_hir_typeck = true;
544self545 }
546547pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
548self.skip_leak_check = skip_leak_check;
549self550 }
551552/// Given a canonical value `C` as a starting point, create an
553 /// inference context that contains each of the bound values
554 /// within instantiated as a fresh variable. The `f` closure is
555 /// invoked with the new infcx, along with the instantiated value
556 /// `V` and a instantiation `S`. This instantiation `S` maps from
557 /// the bound values in `C` to their instantiated values in `V`
558 /// (in other words, `S(C) = V`).
559pub fn build_with_canonical<T>(
560mut self,
561 span: Span,
562 input: &CanonicalQueryInput<'tcx, T>,
563 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
564where
565T: TypeFoldable<TyCtxt<'tcx>>,
566 {
567let infcx = self.build(input.typing_mode);
568let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
569 (infcx, value, args)
570 }
571572pub fn build_with_typing_env(
573mut self,
574TypingEnv { typing_mode, param_env }: TypingEnv<'tcx>,
575 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
576 (self.build(typing_mode), param_env)
577 }
578579pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
580let InferCtxtBuilder {
581 tcx,
582 considering_regions,
583 in_hir_typeck,
584 skip_leak_check,
585 next_trait_solver,
586 } = *self;
587InferCtxt {
588tcx,
589typing_mode,
590considering_regions,
591in_hir_typeck,
592skip_leak_check,
593 inner: RefCell::new(InferCtxtInner::new()),
594 lexical_region_resolutions: RefCell::new(None),
595 selection_cache: Default::default(),
596 evaluation_cache: Default::default(),
597 reported_trait_errors: Default::default(),
598 reported_signature_mismatch: Default::default(),
599 tainted_by_errors: Cell::new(None),
600 universe: Cell::new(ty::UniverseIndex::ROOT),
601next_trait_solver,
602 obligation_inspector: Cell::new(None),
603 }
604 }
605}
606607impl<'tcx, T> InferOk<'tcx, T> {
608/// Extracts `value`, registering any obligations into `fulfill_cx`.
609pub fn into_value_registering_obligations<E: 'tcx>(
610self,
611 infcx: &InferCtxt<'tcx>,
612 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
613 ) -> T {
614let InferOk { value, obligations } = self;
615fulfill_cx.register_predicate_obligations(infcx, obligations);
616value617 }
618}
619620impl<'tcx> InferOk<'tcx, ()> {
621pub fn into_obligations(self) -> PredicateObligations<'tcx> {
622self.obligations
623 }
624}
625626impl<'tcx> InferCtxt<'tcx> {
627pub fn dcx(&self) -> DiagCtxtHandle<'_> {
628self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
629 }
630631pub fn next_trait_solver(&self) -> bool {
632self.next_trait_solver
633 }
634635#[inline(always)]
636pub fn typing_mode(&self) -> TypingMode<'tcx> {
637self.typing_mode
638 }
639640/// Returns the origin of the type variable identified by `vid`.
641 ///
642 /// No attempt is made to resolve `vid` to its root variable.
643pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
644self.inner.borrow_mut().type_variables().var_origin(vid)
645 }
646647/// Returns the origin of the const variable identified by `vid`
648// FIXME: We should store origins separately from the unification table
649 // so this doesn't need to be optional.
650pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
651match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
652 ConstVariableValue::Known { .. } => None,
653 ConstVariableValue::Unknown { origin, .. } => Some(origin),
654 }
655 }
656657pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
658let mut inner = self.inner.borrow_mut();
659let mut vars: Vec<Ty<'_>> = inner660 .type_variables()
661 .unresolved_variables()
662 .into_iter()
663 .map(|t| Ty::new_var(self.tcx, t))
664 .collect();
665vars.extend(
666 (0..inner.int_unification_table().len())
667 .map(|i| ty::IntVid::from_usize(i))
668 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
669 .map(|v| Ty::new_int_var(self.tcx, v)),
670 );
671vars.extend(
672 (0..inner.float_unification_table().len())
673 .map(|i| ty::FloatVid::from_usize(i))
674 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
675 .map(|v| Ty::new_float_var(self.tcx, v)),
676 );
677vars678 }
679680#[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(680u32),
::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")]681pub fn sub_regions(
682&self,
683 origin: SubregionOrigin<'tcx>,
684 a: ty::Region<'tcx>,
685 b: ty::Region<'tcx>,
686 ) {
687self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
688 }
689690/// Processes a `Coerce` predicate from the fulfillment context.
691 /// This is NOT the preferred way to handle coercion, which is to
692 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
693 ///
694 /// This method here is actually a fallback that winds up being
695 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
696 /// and records a coercion predicate. Presently, this method is equivalent
697 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
698 /// actually requiring `a <: b`. This is of course a valid coercion,
699 /// but it's not as flexible as `FnCtxt::coerce` would be.
700 ///
701 /// (We may refactor this in the future, but there are a number of
702 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
703 /// records adjustments that are required on the HIR in order to perform
704 /// the coercion, and we don't currently have a way to manage that.)
705pub fn coerce_predicate(
706&self,
707 cause: &ObligationCause<'tcx>,
708 param_env: ty::ParamEnv<'tcx>,
709 predicate: ty::PolyCoercePredicate<'tcx>,
710 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
711let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
712 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
713a: p.a,
714 b: p.b,
715 });
716self.subtype_predicate(cause, param_env, subtype_predicate)
717 }
718719pub fn subtype_predicate(
720&self,
721 cause: &ObligationCause<'tcx>,
722 param_env: ty::ParamEnv<'tcx>,
723 predicate: ty::PolySubtypePredicate<'tcx>,
724 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
725// Check for two unresolved inference variables, in which case we can
726 // make no progress. This is partly a micro-optimization, but it's
727 // also an opportunity to "sub-unify" the variables. This isn't
728 // *necessary* to prevent cycles, because they would eventually be sub-unified
729 // anyhow during generalization, but it helps with diagnostics (we can detect
730 // earlier that they are sub-unified).
731 //
732 // Note that we can just skip the binders here because
733 // type variables can't (at present, at
734 // least) capture any of the things bound by this binder.
735 //
736 // Note that this sub here is not just for diagnostics - it has semantic
737 // effects as well.
738let r_a = self.shallow_resolve(predicate.skip_binder().a);
739let r_b = self.shallow_resolve(predicate.skip_binder().b);
740match (r_a.kind(), r_b.kind()) {
741 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
742self.sub_unify_ty_vids_raw(a_vid, b_vid);
743return Err((a_vid, b_vid));
744 }
745_ => {}
746 }
747748self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
749if a_is_expected {
750Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
751 } else {
752Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
753 }
754 })
755 }
756757/// Number of type variables created so far.
758pub fn num_ty_vars(&self) -> usize {
759self.inner.borrow_mut().type_variables().num_vars()
760 }
761762pub fn next_ty_vid(&self, span: Span) -> TyVid {
763self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
764 }
765766pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
767self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
768 }
769770pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
771let origin = TypeVariableOrigin { span, param_def_id: None };
772self.inner.borrow_mut().type_variables().new_var(universe, origin)
773 }
774775pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
776self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
777 }
778779pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
780let vid = self.next_ty_vid_with_origin(origin);
781Ty::new_var(self.tcx, vid)
782 }
783784pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
785let vid = self.next_ty_vid_in_universe(span, universe);
786Ty::new_var(self.tcx, vid)
787 }
788789pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
790self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
791 }
792793pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
794let vid = self795 .inner
796 .borrow_mut()
797 .const_unification_table()
798 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
799 .vid;
800 ty::Const::new_var(self.tcx, vid)
801 }
802803pub fn next_const_var_in_universe(
804&self,
805 span: Span,
806 universe: ty::UniverseIndex,
807 ) -> ty::Const<'tcx> {
808let origin = ConstVariableOrigin { span, param_def_id: None };
809let vid = self810 .inner
811 .borrow_mut()
812 .const_unification_table()
813 .new_key(ConstVariableValue::Unknown { origin, universe })
814 .vid;
815 ty::Const::new_var(self.tcx, vid)
816 }
817818pub fn next_int_var(&self) -> Ty<'tcx> {
819let next_int_var_id =
820self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
821Ty::new_int_var(self.tcx, next_int_var_id)
822 }
823824pub fn next_float_var(&self) -> Ty<'tcx> {
825let next_float_var_id =
826self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown);
827Ty::new_float_var(self.tcx, next_float_var_id)
828 }
829830/// Creates a fresh region variable with the next available index.
831 /// The variable will be created in the maximum universe created
832 /// thus far, allowing it to name any region created thus far.
833pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
834self.next_region_var_in_universe(origin, self.universe())
835 }
836837/// Creates a fresh region variable with the next available index
838 /// in the given universe; typically, you can use
839 /// `next_region_var` and just use the maximal universe.
840pub fn next_region_var_in_universe(
841&self,
842 origin: RegionVariableOrigin<'tcx>,
843 universe: ty::UniverseIndex,
844 ) -> ty::Region<'tcx> {
845let region_var =
846self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
847 ty::Region::new_var(self.tcx, region_var)
848 }
849850pub fn next_term_var_of_kind(&self, term: ty::Term<'tcx>, span: Span) -> ty::Term<'tcx> {
851match term.kind() {
852 ty::TermKind::Ty(_) => self.next_ty_var(span).into(),
853 ty::TermKind::Const(_) => self.next_const_var(span).into(),
854 }
855 }
856857/// Return the universe that the region `r` was created in. For
858 /// most regions (e.g., `'static`, named regions from the user,
859 /// etc) this is the root universe U0. For inference variables or
860 /// placeholders, however, it will return the universe which they
861 /// are associated.
862pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
863self.inner.borrow_mut().unwrap_region_constraints().universe(r)
864 }
865866/// Number of region variables created so far.
867pub fn num_region_vars(&self) -> usize {
868self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
869 }
870871/// Just a convenient wrapper of `next_region_var` for using during NLL.
872#[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(872u32),
::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")]873pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
874self.next_region_var(RegionVariableOrigin::Nll(origin))
875 }
876877/// Just a convenient wrapper of `next_region_var` for using during NLL.
878#[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(878u32),
::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")]879pub fn next_nll_region_var_in_universe(
880&self,
881 origin: NllRegionVariableOrigin<'tcx>,
882 universe: ty::UniverseIndex,
883 ) -> ty::Region<'tcx> {
884self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
885 }
886887pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
888match param.kind {
889 GenericParamDefKind::Lifetime => {
890// Create a region inference variable for the given
891 // region parameter definition.
892self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
893span, param.name,
894 ))
895 .into()
896 }
897 GenericParamDefKind::Type { .. } => {
898// Create a type inference variable for the given
899 // type parameter definition. The generic parameters are
900 // for actual parameters that may be referred to by
901 // the default of this type parameter, if it exists.
902 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
903 // used in a path such as `Foo::<T, U>::new()` will
904 // use an inference variable for `C` with `[T, U]`
905 // as the generic parameters for the default, `(T, U)`.
906let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
907self.universe(),
908TypeVariableOrigin { param_def_id: Some(param.def_id), span },
909 );
910911Ty::new_var(self.tcx, ty_var_id).into()
912 }
913 GenericParamDefKind::Const { .. } => {
914let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
915let const_var_id = self916 .inner
917 .borrow_mut()
918 .const_unification_table()
919 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
920 .vid;
921 ty::Const::new_var(self.tcx, const_var_id).into()
922 }
923 }
924 }
925926/// Given a set of generics defined on a type or impl, returns the generic parameters mapping
927 /// each type/region parameter to a fresh inference variable.
928pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
929GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
930 }
931932/// Returns `true` if errors have been reported since this infcx was
933 /// created. This is sometimes used as a heuristic to skip
934 /// reporting errors that often occur as a result of earlier
935 /// errors, but where it's hard to be 100% sure (e.g., unresolved
936 /// inference variables, regionck errors).
937#[must_use = "this method does not have any side effects"]
938pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
939self.tainted_by_errors.get()
940 }
941942/// Set the "tainted by errors" flag to true. We call this when we
943 /// observe an error from a prior pass.
944pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
945{
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:945",
"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(945u32),
::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)");
946self.tainted_by_errors.set(Some(e));
947 }
948949pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
950let mut inner = self.inner.borrow_mut();
951let inner = &mut *inner;
952inner.unwrap_region_constraints().var_origin(vid)
953 }
954955/// Clone the list of variable regions. This is used only during NLL processing
956 /// to put the set of region variables into the NLL region context.
957pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
958let inner = self.inner.borrow();
959if !!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));
960let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
961if !storage.data.is_empty() {
{ ::core::panicking::panic_fmt(format_args!("{0:#?}", storage.data)); }
};assert!(storage.data.is_empty(), "{:#?}", storage.data);
962// We clone instead of taking because borrowck still wants to use the
963 // inference context after calling this for diagnostics and the new
964 // trait solver.
965storage.var_infos.clone()
966 }
967968pub fn has_opaque_types_in_storage(&self) -> bool {
969 !self.inner.borrow().opaque_type_storage.is_empty()
970 }
971972x;#[instrument(level = "debug", skip(self), ret)]973pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
974self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
975 }
976977x;#[instrument(level = "debug", skip(self), ret)]978pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
979self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
980 }
981982pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
983if !self.next_trait_solver() {
984return false;
985 }
986987let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
988let inner = &mut *self.inner.borrow_mut();
989let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
990inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
991if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
992let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
993if opaque_sub_vid == ty_sub_vid {
994return true;
995 }
996 }
997998false
999})
1000 }
10011002/// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1003 ///
1004 /// This only checks for a subtype relation, it does not require equality.
1005pub fn opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> Vec<ty::AliasTy<'tcx>> {
1006// Avoid accidentally allowing more code to compile with the old solver.
1007if !self.next_trait_solver() {
1008return ::alloc::vec::Vec::new()vec![];
1009 }
10101011let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1012let inner = &mut *self.inner.borrow_mut();
1013// This is iffy, can't call `type_variables()` as we're already
1014 // borrowing the `opaque_type_storage` here.
1015let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1016inner1017 .opaque_type_storage
1018 .iter_opaque_types()
1019 .filter_map(|(key, hidden_ty)| {
1020if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1021let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1022if opaque_sub_vid == ty_sub_vid {
1023return Some(ty::AliasTy::new_from_args(
1024self.tcx,
1025key.def_id.into(),
1026key.args,
1027 ));
1028 }
1029 }
10301031None1032 })
1033 .collect()
1034 }
10351036#[inline(always)]
1037pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1038if true {
if !!self.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.next_trait_solver()")
};
};debug_assert!(!self.next_trait_solver());
1039match self.typing_mode() {
1040TypingMode::Analysis {
1041 defining_opaque_types_and_generators: defining_opaque_types,
1042 }
1043 | TypingMode::Borrowck { defining_opaque_types } => {
1044id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1045 }
1046// FIXME(#132279): This function is quite weird in post-analysis
1047 // and post-borrowck analysis mode. We may need to modify its uses
1048 // to support PostBorrowckAnalysis in the old solver as well.
1049TypingMode::Coherence1050 | TypingMode::PostBorrowckAnalysis { .. }
1051 | TypingMode::PostAnalysis => false,
1052 }
1053 }
10541055pub fn push_hir_typeck_potentially_region_dependent_goal(
1056&self,
1057 goal: PredicateObligation<'tcx>,
1058 ) {
1059let mut inner = self.inner.borrow_mut();
1060inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1061inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1062 }
10631064pub fn take_hir_typeck_potentially_region_dependent_goals(
1065&self,
1066 ) -> Vec<PredicateObligation<'tcx>> {
1067if !!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");
1068 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1069 }
10701071pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1072self.resolve_vars_if_possible(t).to_string()
1073 }
10741075/// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1076 /// universe index of `TyVar(vid)`.
1077pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1078use self::type_variable::TypeVariableValue;
10791080match self.inner.borrow_mut().type_variables().probe(vid) {
1081 TypeVariableValue::Known { value } => Ok(value),
1082 TypeVariableValue::Unknown { universe } => Err(universe),
1083 }
1084 }
10851086pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1087if let ty::Infer(v) = *ty.kind() {
1088match v {
1089 ty::TyVar(v) => {
1090// Not entirely obvious: if `typ` is a type variable,
1091 // it can be resolved to an int/float variable, which
1092 // can then be recursively resolved, hence the
1093 // recursion. Note though that we prevent type
1094 // variables from unifying to other type variables
1095 // directly (though they may be embedded
1096 // structurally), and we prevent cycles in any case,
1097 // so this recursion should always be of very limited
1098 // depth.
1099 //
1100 // Note: if these two lines are combined into one we get
1101 // dynamic borrow errors on `self.inner`.
1102let known = self.inner.borrow_mut().type_variables().probe(v).known();
1103known.map_or(ty, |t| self.shallow_resolve(t))
1104 }
11051106 ty::IntVar(v) => {
1107match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1108 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1109 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1110 ty::IntVarValue::Unknown => ty,
1111 }
1112 }
11131114 ty::FloatVar(v) => {
1115match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1116 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1117 ty::FloatVarValue::Unknown => ty,
1118 }
1119 }
11201121 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1122 }
1123 } else {
1124ty1125 }
1126 }
11271128pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1129match ct.kind() {
1130 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1131 InferConst::Var(vid) => self1132 .inner
1133 .borrow_mut()
1134 .const_unification_table()
1135 .probe_value(vid)
1136 .known()
1137 .unwrap_or(ct),
1138 InferConst::Fresh(_) => ct,
1139 },
1140 ty::ConstKind::Param(_)
1141 | ty::ConstKind::Bound(_, _)
1142 | ty::ConstKind::Placeholder(_)
1143 | ty::ConstKind::Unevaluated(_)
1144 | ty::ConstKind::Value(_)
1145 | ty::ConstKind::Error(_)
1146 | ty::ConstKind::Expr(_) => ct,
1147 }
1148 }
11491150pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1151match term.kind() {
1152 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1153 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1154 }
1155 }
11561157pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1158self.inner.borrow_mut().type_variables().root_var(var)
1159 }
11601161pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1162self.inner.borrow_mut().type_variables().sub_unify(a, b);
1163 }
11641165pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1166self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1167 }
11681169pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1170self.inner.borrow_mut().const_unification_table().find(var).vid
1171 }
11721173/// Resolves an int var to a rigid int type, if it was constrained to one,
1174 /// or else the root int var in the unification table.
1175pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1176let mut inner = self.inner.borrow_mut();
1177let value = inner.int_unification_table().probe_value(vid);
1178match value {
1179 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1180 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1181 ty::IntVarValue::Unknown => {
1182Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1183 }
1184 }
1185 }
11861187/// Resolves a float var to a rigid int type, if it was constrained to one,
1188 /// or else the root float var in the unification table.
1189pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1190let mut inner = self.inner.borrow_mut();
1191let value = inner.float_unification_table().probe_value(vid);
1192match value {
1193 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1194 ty::FloatVarValue::Unknown => {
1195Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1196 }
1197 }
1198 }
11991200/// Where possible, replaces type/const variables in
1201 /// `value` with their final value. Note that region variables
1202 /// are unaffected. If a type/const variable has not been unified, it
1203 /// is left as is. This is an idempotent operation that does
1204 /// not affect inference state in any way and so you can do it
1205 /// at will.
1206pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1207where
1208T: TypeFoldable<TyCtxt<'tcx>>,
1209 {
1210if let Err(guar) = value.error_reported() {
1211self.set_tainted_by_errors(guar);
1212 }
1213if !value.has_non_region_infer() {
1214return value;
1215 }
1216let mut r = resolve::OpportunisticVarResolver::new(self);
1217value.fold_with(&mut r)
1218 }
12191220pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1221where
1222T: TypeFoldable<TyCtxt<'tcx>>,
1223 {
1224if !value.has_infer() {
1225return value; // Avoid duplicated type-folding.
1226}
1227let mut r = InferenceLiteralEraser { tcx: self.tcx };
1228value.fold_with(&mut r)
1229 }
12301231pub fn probe_const_var(&self, vid: ty::ConstVid) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1232match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1233 ConstVariableValue::Known { value } => Ok(value),
1234 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1235 }
1236 }
12371238/// Attempts to resolve all type/region/const variables in
1239 /// `value`. Region inference must have been run already (e.g.,
1240 /// by calling `resolve_regions_and_report_errors`). If some
1241 /// variable was never unified, an `Err` results.
1242 ///
1243 /// This method is idempotent, but it not typically not invoked
1244 /// except during the writeback phase.
1245pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1246match resolve::fully_resolve(self, value) {
1247Ok(value) => {
1248if value.has_non_region_infer() {
1249::rustc_middle::util::bug::bug_fmt(format_args!("`{0:?}` is not fully resolved",
value));bug!("`{value:?}` is not fully resolved");
1250 }
1251if value.has_infer_regions() {
1252let 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"));
1253Ok(fold_regions(self.tcx, value, |re, _| {
1254if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1255 }))
1256 } else {
1257Ok(value)
1258 }
1259 }
1260Err(e) => Err(e),
1261 }
1262 }
12631264// Instantiates the bound variables in a given binder with fresh inference
1265 // variables in the current universe.
1266 //
1267 // Use this method if you'd like to find some generic parameters of the binder's
1268 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1269 // that corresponds to your use case, consider whether or not you should
1270 // use [`InferCtxt::enter_forall`] instead.
1271pub fn instantiate_binder_with_fresh_vars<T>(
1272&self,
1273 span: Span,
1274 lbrct: BoundRegionConversionTime,
1275 value: ty::Binder<'tcx, T>,
1276 ) -> T
1277where
1278T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1279 {
1280if let Some(inner) = value.no_bound_vars() {
1281return inner;
1282 }
12831284let bound_vars = value.bound_vars();
1285let mut args = Vec::with_capacity(bound_vars.len());
12861287for bound_var_kind in bound_vars {
1288let arg: ty::GenericArg<'_> = match bound_var_kind {
1289 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1290 ty::BoundVariableKind::Region(br) => {
1291self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1292 }
1293 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1294 };
1295 args.push(arg);
1296 }
12971298struct ToFreshVars<'tcx> {
1299 args: Vec<ty::GenericArg<'tcx>>,
1300 }
13011302impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1303fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1304self.args[br.var.index()].expect_region()
1305 }
1306fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1307self.args[bt.var.index()].expect_ty()
1308 }
1309fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1310self.args[bc.var.index()].expect_const()
1311 }
1312 }
1313let delegate = ToFreshVars { args };
1314self.tcx.replace_bound_vars_uncached(value, delegate)
1315 }
13161317/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1318pub(crate) fn verify_generic_bound(
1319&self,
1320 origin: SubregionOrigin<'tcx>,
1321 kind: GenericKind<'tcx>,
1322 a: ty::Region<'tcx>,
1323 bound: VerifyBound<'tcx>,
1324 ) {
1325{
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:1325",
"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(1325u32),
::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);
13261327self.inner
1328 .borrow_mut()
1329 .unwrap_region_constraints()
1330 .verify_generic_bound(origin, kind, a, bound);
1331 }
13321333/// Obtains the latest type of the given closure; this may be a
1334 /// closure in the current function, in which case its
1335 /// `ClosureKind` may not yet be known.
1336pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1337let unresolved_kind_ty = match *closure_ty.kind() {
1338 ty::Closure(_, args) => args.as_closure().kind_ty(),
1339 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1340_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0}",
closure_ty))bug!("unexpected type {closure_ty}"),
1341 };
1342let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1343closure_kind_ty.to_opt_closure_kind()
1344 }
13451346pub fn universe(&self) -> ty::UniverseIndex {
1347self.universe.get()
1348 }
13491350/// Creates and return a fresh universe that extends all previous
1351 /// universes. Updates `self.universe` to that new universe.
1352pub fn create_next_universe(&self) -> ty::UniverseIndex {
1353let u = self.universe.get().next_universe();
1354{
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:1354",
"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(1354u32),
::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:?}");
1355self.universe.set(u);
1356u1357 }
13581359/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1360 /// which contains the necessary information to use the trait system without
1361 /// using canonicalization or carrying this inference context around.
1362pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1363let typing_mode = match self.typing_mode() {
1364// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1365 // to handle them without proper canonicalization. This means we may cause cycle
1366 // errors and fail to reveal opaques while inside of bodies. We should rename this
1367 // function and require explicit comments on all use-sites in the future.
1368ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1369 | ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1370TypingMode::non_body_analysis()
1371 }
1372 mode @ (ty::TypingMode::Coherence1373 | ty::TypingMode::PostBorrowckAnalysis { .. }
1374 | ty::TypingMode::PostAnalysis) => mode,
1375 };
1376 ty::TypingEnv { typing_mode, param_env }
1377 }
13781379/// Similar to [`Self::canonicalize_query`], except that it returns
1380 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1381 /// `param_env` to not contain any inference variables or placeholders.
1382pub fn pseudo_canonicalize_query<V>(
1383&self,
1384 param_env: ty::ParamEnv<'tcx>,
1385 value: V,
1386 ) -> PseudoCanonicalInput<'tcx, V>
1387where
1388V: TypeVisitable<TyCtxt<'tcx>>,
1389 {
1390if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1391if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1392if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1393if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1394self.typing_env(param_env).as_query_input(value)
1395 }
13961397/// The returned function is used in a fast path. If it returns `true` the variable is
1398 /// unchanged, `false` indicates that the status is unknown.
1399#[inline]
1400pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1401// This hoists the borrow/release out of the loop body.
1402let inner = self.inner.try_borrow();
14031404move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1405 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1406use self::type_variable::TypeVariableValue;
14071408#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1409 inner.try_type_variables_probe_ref(ty_var),
1410Some(TypeVariableValue::Unknown { .. })
1411 )1412 }
1413_ => false,
1414 }
1415 }
14161417/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1418 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1419 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1420 ///
1421 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1422 /// inlined, despite being large, because it has only two call sites that
1423 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1424 /// inference variables), and it handles both `Ty` and `ty::Const` without
1425 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1426#[inline(always)]
1427pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1428match infer_var {
1429 TyOrConstInferVar::Ty(v) => {
1430use self::type_variable::TypeVariableValue;
14311432// If `inlined_probe` returns a `Known` value, it never equals
1433 // `ty::Infer(ty::TyVar(v))`.
1434match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1435 TypeVariableValue::Unknown { .. } => false,
1436 TypeVariableValue::Known { .. } => true,
1437 }
1438 }
14391440 TyOrConstInferVar::TyInt(v) => {
1441// If `inlined_probe_value` returns a value it's always a
1442 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1443 // `ty::Infer(_)`.
1444self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1445 }
14461447 TyOrConstInferVar::TyFloat(v) => {
1448// If `probe_value` returns a value it's always a
1449 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1450 //
1451 // Not `inlined_probe_value(v)` because this call site is colder.
1452self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1453 }
14541455 TyOrConstInferVar::Const(v) => {
1456// If `probe_value` returns a `Known` value, it never equals
1457 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1458 //
1459 // Not `inlined_probe_value(v)` because this call site is colder.
1460match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1461 ConstVariableValue::Unknown { .. } => false,
1462 ConstVariableValue::Known { .. } => true,
1463 }
1464 }
1465 }
1466 }
14671468/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1469pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1470if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1471self.obligation_inspector.get().is_none(),
1472"shouldn't override a set obligation inspector"
1473);
1474self.obligation_inspector.set(Some(inspector));
1475 }
1476}
14771478/// Helper for [InferCtxt::ty_or_const_infer_var_changed] (see comment on that), currently
1479/// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1480#[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)]
1481pub enum TyOrConstInferVar {
1482/// Equivalent to `ty::Infer(ty::TyVar(_))`.
1483Ty(TyVid),
1484/// Equivalent to `ty::Infer(ty::IntVar(_))`.
1485TyInt(IntVid),
1486/// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1487TyFloat(FloatVid),
14881489/// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1490Const(ConstVid),
1491}
14921493impl<'tcx> TyOrConstInferVar {
1494/// Tries to extract an inference variable from a type or a constant, returns `None`
1495 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1496 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1497pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1498match arg.kind() {
1499GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1500GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1501GenericArgKind::Lifetime(_) => None,
1502 }
1503 }
15041505/// Tries to extract an inference variable from a type or a constant, returns `None`
1506 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1507 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1508pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1509match term.kind() {
1510TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1511TermKind::Const(ct) => Self::maybe_from_const(ct),
1512 }
1513 }
15141515/// Tries to extract an inference variable from a type, returns `None`
1516 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1517fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1518match *ty.kind() {
1519 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1520 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1521 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1522_ => None,
1523 }
1524 }
15251526/// Tries to extract an inference variable from a constant, returns `None`
1527 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1528fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1529match ct.kind() {
1530 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1531_ => None,
1532 }
1533 }
1534}
15351536/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1537/// Used only for diagnostics.
1538struct InferenceLiteralEraser<'tcx> {
1539 tcx: TyCtxt<'tcx>,
1540}
15411542impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1543fn cx(&self) -> TyCtxt<'tcx> {
1544self.tcx
1545 }
15461547fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1548match ty.kind() {
1549 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1550 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1551_ => ty.super_fold_with(self),
1552 }
1553 }
1554}
15551556impl<'tcx> TypeTrace<'tcx> {
1557pub fn span(&self) -> Span {
1558self.cause.span
1559 }
15601561pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1562TypeTrace {
1563 cause: cause.clone(),
1564 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1565 }
1566 }
15671568pub fn trait_refs(
1569 cause: &ObligationCause<'tcx>,
1570 a: ty::TraitRef<'tcx>,
1571 b: ty::TraitRef<'tcx>,
1572 ) -> TypeTrace<'tcx> {
1573TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1574 }
15751576pub fn consts(
1577 cause: &ObligationCause<'tcx>,
1578 a: ty::Const<'tcx>,
1579 b: ty::Const<'tcx>,
1580 ) -> TypeTrace<'tcx> {
1581TypeTrace {
1582 cause: cause.clone(),
1583 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1584 }
1585 }
1586}
15871588impl<'tcx> SubregionOrigin<'tcx> {
1589pub fn span(&self) -> Span {
1590match *self {
1591 SubregionOrigin::Subtype(ref a) => a.span(),
1592 SubregionOrigin::RelateObjectBound(a) => a,
1593 SubregionOrigin::RelateParamBound(a, ..) => a,
1594 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1595 SubregionOrigin::Reborrow(a) => a,
1596 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1597 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1598 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1599 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1600 }
1601 }
16021603pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1604where
1605F: FnOnce() -> Self,
1606 {
1607match *cause.code() {
1608 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1609 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1610 }
16111612 traits::ObligationCauseCode::CompareImplItem {
1613 impl_item_def_id,
1614 trait_item_def_id,
1615 kind: _,
1616 } => SubregionOrigin::CompareImplItemObligation {
1617 span: cause.span,
1618impl_item_def_id,
1619trait_item_def_id,
1620 },
16211622 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1623 impl_item_def_id,
1624 trait_item_def_id,
1625 } => SubregionOrigin::CheckAssociatedTypeBounds {
1626impl_item_def_id,
1627trait_item_def_id,
1628 parent: Box::new(default()),
1629 },
16301631 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1632 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1633 }
16341635 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1636 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1637 }
16381639_ => default(),
1640 }
1641 }
1642}
16431644impl<'tcx> RegionVariableOrigin<'tcx> {
1645pub fn span(&self) -> Span {
1646match *self {
1647 RegionVariableOrigin::Misc(a)
1648 | RegionVariableOrigin::PatternRegion(a)
1649 | RegionVariableOrigin::BorrowRegion(a)
1650 | RegionVariableOrigin::Autoref(a)
1651 | RegionVariableOrigin::Coercion(a)
1652 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1653 | RegionVariableOrigin::BoundRegion(a, ..)
1654 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1655 RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable used with `span`"))bug!("NLL variable used with `span`"),
1656 }
1657 }
1658}
16591660impl<'tcx> InferCtxt<'tcx> {
1661/// Given a [`hir::Block`], get the span of its last expression or
1662 /// statement, peeling off any inner blocks.
1663pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1664let block = block.innermost_block();
1665if let Some(expr) = &block.expr {
1666expr.span
1667 } else if let Some(stmt) = block.stmts.last() {
1668// possibly incorrect trailing `;` in the else arm
1669stmt.span
1670 } else {
1671// empty block; point at its entirety
1672block.span
1673 }
1674 }
16751676/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1677 /// of its last expression or statement, peeling off any inner blocks.
1678pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1679match self.tcx.hir_node(hir_id) {
1680 hir::Node::Block(blk)
1681 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1682self.find_block_span(blk)
1683 }
1684 hir::Node::Expr(e) => e.span,
1685_ => DUMMY_SP,
1686 }
1687 }
1688}