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 (root_vid, value) =
1103self.inner.borrow_mut().type_variables().probe_with_root_vid(v);
1104value.known().map_or_else(
1105 || if root_vid == v { ty } else { Ty::new_var(self.tcx, root_vid) },
1106 |t| self.shallow_resolve(t),
1107 )
1108 }
11091110 ty::IntVar(v) => {
1111let (root, value) =
1112self.inner.borrow_mut().int_unification_table().inlined_probe_key_value(v);
1113match value {
1114 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1115 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1116 ty::IntVarValue::Unknown => {
1117if root == v {
1118ty1119 } else {
1120Ty::new_int_var(self.tcx, root)
1121 }
1122 }
1123 }
1124 }
11251126 ty::FloatVar(v) => {
1127let (root, value) = self1128 .inner
1129 .borrow_mut()
1130 .float_unification_table()
1131 .inlined_probe_key_value(v);
1132match value {
1133 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1134 ty::FloatVarValue::Unknown => {
1135if root == v {
1136ty1137 } else {
1138Ty::new_float_var(self.tcx, root)
1139 }
1140 }
1141 }
1142 }
11431144 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1145 }
1146 } else {
1147ty1148 }
1149 }
11501151pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1152match ct.kind() {
1153 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1154 InferConst::Var(vid) => {
1155let (root, value) = self1156 .inner
1157 .borrow_mut()
1158 .const_unification_table()
1159 .inlined_probe_key_value(vid);
1160value.known().unwrap_or_else(|| {
1161if root.vid == vid { ct } else { ty::Const::new_var(self.tcx, root.vid) }
1162 })
1163 }
1164 InferConst::Fresh(_) => ct,
1165 },
1166 ty::ConstKind::Param(_)
1167 | ty::ConstKind::Bound(_, _)
1168 | ty::ConstKind::Placeholder(_)
1169 | ty::ConstKind::Unevaluated(_)
1170 | ty::ConstKind::Value(_)
1171 | ty::ConstKind::Error(_)
1172 | ty::ConstKind::Expr(_) => ct,
1173 }
1174 }
11751176pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1177match term.kind() {
1178 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1179 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1180 }
1181 }
11821183pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1184self.inner.borrow_mut().type_variables().root_var(var)
1185 }
11861187/// If `ty` is an unresolved type variable, returns its root vid.
1188pub fn root_vid(&self, ty: Ty<'tcx>) -> Option<ty::TyVid> {
1189let (root, value) =
1190self.inner.borrow_mut().type_variables().inlined_probe_with_vid(ty.ty_vid()?);
1191value.is_unknown().then_some(root)
1192 }
11931194pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1195self.inner.borrow_mut().type_variables().sub_unify(a, b);
1196 }
11971198pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1199self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1200 }
12011202pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1203self.inner.borrow_mut().const_unification_table().find(var).vid
1204 }
12051206/// Resolves an int var to a rigid int type, if it was constrained to one,
1207 /// or else the root int var in the unification table.
1208pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1209let mut inner = self.inner.borrow_mut();
1210let value = inner.int_unification_table().probe_value(vid);
1211match value {
1212 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1213 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1214 ty::IntVarValue::Unknown => {
1215Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1216 }
1217 }
1218 }
12191220/// Resolves a float var to a rigid int type, if it was constrained to one,
1221 /// or else the root float var in the unification table.
1222pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1223let mut inner = self.inner.borrow_mut();
1224let value = inner.float_unification_table().probe_value(vid);
1225match value {
1226 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1227 ty::FloatVarValue::Unknown => {
1228Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1229 }
1230 }
1231 }
12321233/// Where possible, replaces type/const variables in
1234 /// `value` with their final value. Note that region variables
1235 /// are unaffected. If a type/const variable has not been unified, it
1236 /// is left as is. This is an idempotent operation that does
1237 /// not affect inference state in any way and so you can do it
1238 /// at will.
1239pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1240where
1241T: TypeFoldable<TyCtxt<'tcx>>,
1242 {
1243if let Err(guar) = value.error_reported() {
1244self.set_tainted_by_errors(guar);
1245 }
1246if !value.has_non_region_infer() {
1247return value;
1248 }
1249let mut r = resolve::OpportunisticVarResolver::new(self);
1250value.fold_with(&mut r)
1251 }
12521253pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1254where
1255T: TypeFoldable<TyCtxt<'tcx>>,
1256 {
1257if !value.has_infer() {
1258return value; // Avoid duplicated type-folding.
1259}
1260let mut r = InferenceLiteralEraser { tcx: self.tcx };
1261value.fold_with(&mut r)
1262 }
12631264pub fn probe_const_var(&self, vid: ty::ConstVid) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1265match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1266 ConstVariableValue::Known { value } => Ok(value),
1267 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1268 }
1269 }
12701271/// Attempts to resolve all type/region/const variables in
1272 /// `value`. Region inference must have been run already (e.g.,
1273 /// by calling `resolve_regions_and_report_errors`). If some
1274 /// variable was never unified, an `Err` results.
1275 ///
1276 /// This method is idempotent, but it not typically not invoked
1277 /// except during the writeback phase.
1278pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1279match resolve::fully_resolve(self, value) {
1280Ok(value) => {
1281if value.has_non_region_infer() {
1282::rustc_middle::util::bug::bug_fmt(format_args!("`{0:?}` is not fully resolved",
value));bug!("`{value:?}` is not fully resolved");
1283 }
1284if value.has_infer_regions() {
1285let 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"));
1286Ok(fold_regions(self.tcx, value, |re, _| {
1287if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1288 }))
1289 } else {
1290Ok(value)
1291 }
1292 }
1293Err(e) => Err(e),
1294 }
1295 }
12961297// Instantiates the bound variables in a given binder with fresh inference
1298 // variables in the current universe.
1299 //
1300 // Use this method if you'd like to find some generic parameters of the binder's
1301 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1302 // that corresponds to your use case, consider whether or not you should
1303 // use [`InferCtxt::enter_forall`] instead.
1304pub fn instantiate_binder_with_fresh_vars<T>(
1305&self,
1306 span: Span,
1307 lbrct: BoundRegionConversionTime,
1308 value: ty::Binder<'tcx, T>,
1309 ) -> T
1310where
1311T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1312 {
1313if let Some(inner) = value.no_bound_vars() {
1314return inner;
1315 }
13161317let bound_vars = value.bound_vars();
1318let mut args = Vec::with_capacity(bound_vars.len());
13191320for bound_var_kind in bound_vars {
1321let arg: ty::GenericArg<'_> = match bound_var_kind {
1322 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1323 ty::BoundVariableKind::Region(br) => {
1324self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1325 }
1326 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1327 };
1328 args.push(arg);
1329 }
13301331struct ToFreshVars<'tcx> {
1332 args: Vec<ty::GenericArg<'tcx>>,
1333 }
13341335impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1336fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1337self.args[br.var.index()].expect_region()
1338 }
1339fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1340self.args[bt.var.index()].expect_ty()
1341 }
1342fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1343self.args[bc.var.index()].expect_const()
1344 }
1345 }
1346let delegate = ToFreshVars { args };
1347self.tcx.replace_bound_vars_uncached(value, delegate)
1348 }
13491350/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1351pub(crate) fn verify_generic_bound(
1352&self,
1353 origin: SubregionOrigin<'tcx>,
1354 kind: GenericKind<'tcx>,
1355 a: ty::Region<'tcx>,
1356 bound: VerifyBound<'tcx>,
1357 ) {
1358{
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:1358",
"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(1358u32),
::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);
13591360self.inner
1361 .borrow_mut()
1362 .unwrap_region_constraints()
1363 .verify_generic_bound(origin, kind, a, bound);
1364 }
13651366/// Obtains the latest type of the given closure; this may be a
1367 /// closure in the current function, in which case its
1368 /// `ClosureKind` may not yet be known.
1369pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1370let unresolved_kind_ty = match *closure_ty.kind() {
1371 ty::Closure(_, args) => args.as_closure().kind_ty(),
1372 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1373_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0}",
closure_ty))bug!("unexpected type {closure_ty}"),
1374 };
1375let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1376closure_kind_ty.to_opt_closure_kind()
1377 }
13781379pub fn universe(&self) -> ty::UniverseIndex {
1380self.universe.get()
1381 }
13821383/// Creates and return a fresh universe that extends all previous
1384 /// universes. Updates `self.universe` to that new universe.
1385pub fn create_next_universe(&self) -> ty::UniverseIndex {
1386let u = self.universe.get().next_universe();
1387{
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:1387",
"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(1387u32),
::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:?}");
1388self.universe.set(u);
1389u1390 }
13911392/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1393 /// which contains the necessary information to use the trait system without
1394 /// using canonicalization or carrying this inference context around.
1395pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1396let typing_mode = match self.typing_mode() {
1397// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1398 // to handle them without proper canonicalization. This means we may cause cycle
1399 // errors and fail to reveal opaques while inside of bodies. We should rename this
1400 // function and require explicit comments on all use-sites in the future.
1401ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1402 | ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1403TypingMode::non_body_analysis()
1404 }
1405 mode @ (ty::TypingMode::Coherence1406 | ty::TypingMode::PostBorrowckAnalysis { .. }
1407 | ty::TypingMode::PostAnalysis) => mode,
1408 };
1409 ty::TypingEnv { typing_mode, param_env }
1410 }
14111412/// Similar to [`Self::canonicalize_query`], except that it returns
1413 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1414 /// `param_env` to not contain any inference variables or placeholders.
1415pub fn pseudo_canonicalize_query<V>(
1416&self,
1417 param_env: ty::ParamEnv<'tcx>,
1418 value: V,
1419 ) -> PseudoCanonicalInput<'tcx, V>
1420where
1421V: TypeVisitable<TyCtxt<'tcx>>,
1422 {
1423if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1424if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1425if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1426if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1427self.typing_env(param_env).as_query_input(value)
1428 }
14291430/// The returned function is used in a fast path. If it returns `true` the variable is
1431 /// unchanged, `false` indicates that the status is unknown.
1432#[inline]
1433pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1434// This hoists the borrow/release out of the loop body.
1435let inner = self.inner.try_borrow();
14361437move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1438 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1439use self::type_variable::TypeVariableValue;
14401441#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1442 inner.try_type_variables_probe_ref(ty_var),
1443Some(TypeVariableValue::Unknown { .. })
1444 )1445 }
1446_ => false,
1447 }
1448 }
14491450/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1451 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1452 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1453 ///
1454 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1455 /// inlined, despite being large, because it has only two call sites that
1456 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1457 /// inference variables), and it handles both `Ty` and `ty::Const` without
1458 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1459#[inline(always)]
1460pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1461match infer_var {
1462 TyOrConstInferVar::Ty(v) => {
1463use self::type_variable::TypeVariableValue;
14641465// If `inlined_probe` returns a `Known` value, it never equals
1466 // `ty::Infer(ty::TyVar(v))`.
1467match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1468 TypeVariableValue::Unknown { .. } => false,
1469 TypeVariableValue::Known { .. } => true,
1470 }
1471 }
14721473 TyOrConstInferVar::TyInt(v) => {
1474// If `inlined_probe_value` returns a value it's always a
1475 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1476 // `ty::Infer(_)`.
1477self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1478 }
14791480 TyOrConstInferVar::TyFloat(v) => {
1481// If `probe_value` returns a value it's always a
1482 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1483 //
1484 // Not `inlined_probe_value(v)` because this call site is colder.
1485self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1486 }
14871488 TyOrConstInferVar::Const(v) => {
1489// If `probe_value` returns a `Known` value, it never equals
1490 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1491 //
1492 // Not `inlined_probe_value(v)` because this call site is colder.
1493match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1494 ConstVariableValue::Unknown { .. } => false,
1495 ConstVariableValue::Known { .. } => true,
1496 }
1497 }
1498 }
1499 }
15001501/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1502pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1503if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1504self.obligation_inspector.get().is_none(),
1505"shouldn't override a set obligation inspector"
1506);
1507self.obligation_inspector.set(Some(inspector));
1508 }
1509}
15101511/// Helper for [InferCtxt::ty_or_const_infer_var_changed] (see comment on that), currently
1512/// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1513#[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)]
1514pub enum TyOrConstInferVar {
1515/// Equivalent to `ty::Infer(ty::TyVar(_))`.
1516Ty(TyVid),
1517/// Equivalent to `ty::Infer(ty::IntVar(_))`.
1518TyInt(IntVid),
1519/// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1520TyFloat(FloatVid),
15211522/// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1523Const(ConstVid),
1524}
15251526impl<'tcx> TyOrConstInferVar {
1527/// Tries to extract an inference variable from a type or a constant, returns `None`
1528 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1529 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1530pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1531match arg.kind() {
1532GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1533GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1534GenericArgKind::Lifetime(_) => None,
1535 }
1536 }
15371538/// Tries to extract an inference variable from a type or a constant, returns `None`
1539 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1540 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1541pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1542match term.kind() {
1543TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1544TermKind::Const(ct) => Self::maybe_from_const(ct),
1545 }
1546 }
15471548/// Tries to extract an inference variable from a type, returns `None`
1549 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1550fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1551match *ty.kind() {
1552 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1553 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1554 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1555_ => None,
1556 }
1557 }
15581559/// Tries to extract an inference variable from a constant, returns `None`
1560 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1561fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1562match ct.kind() {
1563 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1564_ => None,
1565 }
1566 }
1567}
15681569/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1570/// Used only for diagnostics.
1571struct InferenceLiteralEraser<'tcx> {
1572 tcx: TyCtxt<'tcx>,
1573}
15741575impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1576fn cx(&self) -> TyCtxt<'tcx> {
1577self.tcx
1578 }
15791580fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1581match ty.kind() {
1582 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1583 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1584_ => ty.super_fold_with(self),
1585 }
1586 }
1587}
15881589impl<'tcx> TypeTrace<'tcx> {
1590pub fn span(&self) -> Span {
1591self.cause.span
1592 }
15931594pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1595TypeTrace {
1596 cause: cause.clone(),
1597 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1598 }
1599 }
16001601pub fn trait_refs(
1602 cause: &ObligationCause<'tcx>,
1603 a: ty::TraitRef<'tcx>,
1604 b: ty::TraitRef<'tcx>,
1605 ) -> TypeTrace<'tcx> {
1606TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1607 }
16081609pub fn consts(
1610 cause: &ObligationCause<'tcx>,
1611 a: ty::Const<'tcx>,
1612 b: ty::Const<'tcx>,
1613 ) -> TypeTrace<'tcx> {
1614TypeTrace {
1615 cause: cause.clone(),
1616 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1617 }
1618 }
1619}
16201621impl<'tcx> SubregionOrigin<'tcx> {
1622pub fn span(&self) -> Span {
1623match *self {
1624 SubregionOrigin::Subtype(ref a) => a.span(),
1625 SubregionOrigin::RelateObjectBound(a) => a,
1626 SubregionOrigin::RelateParamBound(a, ..) => a,
1627 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1628 SubregionOrigin::Reborrow(a) => a,
1629 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1630 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1631 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1632 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1633 }
1634 }
16351636pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1637where
1638F: FnOnce() -> Self,
1639 {
1640match *cause.code() {
1641 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1642 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1643 }
16441645 traits::ObligationCauseCode::CompareImplItem {
1646 impl_item_def_id,
1647 trait_item_def_id,
1648 kind: _,
1649 } => SubregionOrigin::CompareImplItemObligation {
1650 span: cause.span,
1651impl_item_def_id,
1652trait_item_def_id,
1653 },
16541655 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1656 impl_item_def_id,
1657 trait_item_def_id,
1658 } => SubregionOrigin::CheckAssociatedTypeBounds {
1659impl_item_def_id,
1660trait_item_def_id,
1661 parent: Box::new(default()),
1662 },
16631664 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1665 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1666 }
16671668 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1669 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1670 }
16711672_ => default(),
1673 }
1674 }
1675}
16761677impl<'tcx> RegionVariableOrigin<'tcx> {
1678pub fn span(&self) -> Span {
1679match *self {
1680 RegionVariableOrigin::Misc(a)
1681 | RegionVariableOrigin::PatternRegion(a)
1682 | RegionVariableOrigin::BorrowRegion(a)
1683 | RegionVariableOrigin::Autoref(a)
1684 | RegionVariableOrigin::Coercion(a)
1685 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1686 | RegionVariableOrigin::BoundRegion(a, ..)
1687 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1688 RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable used with `span`"))bug!("NLL variable used with `span`"),
1689 }
1690 }
1691}
16921693impl<'tcx> InferCtxt<'tcx> {
1694/// Given a [`hir::Block`], get the span of its last expression or
1695 /// statement, peeling off any inner blocks.
1696pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1697let block = block.innermost_block();
1698if let Some(expr) = &block.expr {
1699expr.span
1700 } else if let Some(stmt) = block.stmts.last() {
1701// possibly incorrect trailing `;` in the else arm
1702stmt.span
1703 } else {
1704// empty block; point at its entirety
1705block.span
1706 }
1707 }
17081709/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1710 /// of its last expression or statement, peeling off any inner blocks.
1711pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1712match self.tcx.hir_node(hir_id) {
1713 hir::Node::Block(blk)
1714 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1715self.find_block_span(blk)
1716 }
1717 hir::Node::Expr(e) => e.span,
1718_ => DUMMY_SP,
1719 }
1720 }
1721}