1use std::cell::{Cell, RefCell};
2use std::fmt;
34pub use at::DefineOpaqueTypes;
5use free_regions::RegionRelations;
6pub use freshen::TypeFreshener;
7use lexical_region_resolve::LexicalRegionResolutions;
8pub use lexical_region_resolve::RegionResolutionError;
9pub use opaque_types::{OpaqueTypeStorage, OpaqueTypeStorageEntries, OpaqueTypeTable};
10use region_constraints::{
11GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
12};
13pub use relate::combine::PredicateEmittingRelation;
14use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
15use rustc_data_structures::snapshot_vecas sv;
16use rustc_data_structures::undo_log::{Rollback, UndoLogs};
17use rustc_data_structures::unify::{selfas ut, UnifyKey, UnifyValue};
18use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
19use rustc_hir::def_id::{DefId, LocalDefId};
20use rustc_hir::{selfas hir, HirId};
21use rustc_index::IndexVec;
22use rustc_macros::extension;
23pub use rustc_macros::{TypeFoldable, TypeVisitable};
24use rustc_middle::bug;
25use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
26use rustc_middle::mir::ConstraintCategory;
27use rustc_middle::traits::select;
28use rustc_middle::traits::solve::Goal;
29use rustc_middle::ty::error::{ExpectedFound, TypeError};
30use rustc_middle::ty::{
31self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
32GenericArgsRef, GenericParamDefKind, InferConst, OpaqueTypeKey, ProvisionalHiddenType,
33PseudoCanonicalInput, Term, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable,
34TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
35};
36use rustc_span::{DUMMY_SP, Span, Symbol};
37use rustc_type_ir::{CanonicalizerState, MayBeErased};
38use snapshot::undo_log::InferCtxtUndoLogs;
39use tracing::{debug, instrument};
40use ty::solve::TyOrConstInferVar;
41use type_variable::TypeVariableOrigin;
4243use crate::infer::snapshot::undo_log::UndoLog;
44use crate::infer::type_variable::{FloatVariableOrigin, TypeVariableValue};
45use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
46use crate::traits::{
47self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
48TraitEngine,
49};
5051pub mod at;
52pub mod canonical;
53mod context;
54mod free_regions;
55mod freshen;
56mod lexical_region_resolve;
57mod opaque_types;
58pub mod outlives;
59mod projection;
60pub mod region_constraints;
61pub mod relate;
62pub mod resolve;
63pub(crate) mod snapshot;
64mod solver_region_constraints;
65mod type_variable;
66mod unify_key;
6768pub use solver_region_constraints::SolverRegionConstraint;
69use solver_region_constraints::SolverRegionConstraintStorage;
7071/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
72/// around `PredicateObligations<'tcx>`, but it has one important property:
73/// because `InferOk` is marked with `#[must_use]`, if you have a method
74/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
75/// `infcx.f()?;` you'll get a warning about the obligations being discarded
76/// without use, which is probably unintentional and has been a source of bugs
77/// in the past.
78#[must_use]
79#[derive(#[automatically_derived]
impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug for InferOk<'tcx, T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "InferOk",
"value", &self.value, "obligations", &&self.obligations)
}
}Debug)]
80pub struct InferOk<'tcx, T> {
81pub value: T,
82pub obligations: PredicateObligations<'tcx>,
83}
84pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
8586pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
8788pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
89 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
90>;
9192/// This type contains all the things within [`InferCtxt`] that sit within a
93/// [`RefCell`] and are involved with taking/rolling back snapshots. Snapshot
94/// operations are hot enough that we want only one call to
95/// [`RefCell::borrow_mut`] per call to [`InferCtxt::start_snapshot`] and
96/// [`InferCtxt::rollback_to`].
97#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for InferCtxtInner<'tcx> {
#[inline]
fn clone(&self) -> InferCtxtInner<'tcx> {
InferCtxtInner {
undo_log: ::core::clone::Clone::clone(&self.undo_log),
projection_cache: ::core::clone::Clone::clone(&self.projection_cache),
type_variable_storage: ::core::clone::Clone::clone(&self.type_variable_storage),
const_unification_storage: ::core::clone::Clone::clone(&self.const_unification_storage),
int_unification_storage: ::core::clone::Clone::clone(&self.int_unification_storage),
float_unification_storage: ::core::clone::Clone::clone(&self.float_unification_storage),
float_origin_origin_storage: ::core::clone::Clone::clone(&self.float_origin_origin_storage),
region_constraint_storage: ::core::clone::Clone::clone(&self.region_constraint_storage),
solver_region_constraint_storage: ::core::clone::Clone::clone(&self.solver_region_constraint_storage),
region_obligations: ::core::clone::Clone::clone(&self.region_obligations),
region_assumptions: ::core::clone::Clone::clone(&self.region_assumptions),
hir_typeck_potentially_region_dependent_goals: ::core::clone::Clone::clone(&self.hir_typeck_potentially_region_dependent_goals),
opaque_type_storage: ::core::clone::Clone::clone(&self.opaque_type_storage),
}
}
}Clone)]
98pub struct InferCtxtInner<'tcx> {
99 undo_log: InferCtxtUndoLogs<'tcx>,
100101/// Cache for projections.
102 ///
103 /// This cache is snapshotted along with the infcx.
104projection_cache: traits::ProjectionCacheStorage<'tcx>,
105106/// Primary map of inference variables to the types that they currently
107 /// represent.
108 ///
109 /// We instantiate [`UnificationTable`] with `bounds<Ty>` because the types
110 /// that might instantiate a general type variable have an order,
111 /// represented by its upper and lower bounds.
112type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
113114/// Map from const parameter variable to the kind of const it represents.
115const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
116117/// Map from integral variable to the kind of integer it represents.
118int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
119120/// Map from floating variable to the kind of float it represents.
121float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
122123/// Map from floating variable to the origin span it came from, and the HirId that should be
124 /// used to lint at that location. This is only used for the FCW for the fallback to `f32`,
125 /// so can be removed once the `f32` fallback is removed.
126float_origin_origin_storage: IndexVec<FloatVid, FloatVariableOrigin>,
127128/// Tracks the set of region variables and the constraints between them.
129 ///
130 /// This is initially `Some(_)` but when
131 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
132 /// -- further attempts to perform unification, etc., may fail if new
133 /// region constraints would've been added.
134region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
135136/// Used by the next solver when `-Zassumptions-on-binders` is set.
137solver_region_constraint_storage: SolverRegionConstraintStorage<'tcx>,
138139/// A set of constraints that regionck must validate.
140 ///
141 /// Each constraint has the form `T:'a`, meaning "some type `T` must
142 /// outlive the lifetime 'a". These constraints derive from
143 /// instantiated type parameters. So if you had a struct defined
144 /// like the following:
145 /// ```ignore (illustrative)
146 /// struct Foo<T: 'static> { ... }
147 /// ```
148 /// In some expression `let x = Foo { ... }`, it will
149 /// instantiate the type parameter `T` with a fresh type `$0`. At
150 /// the same time, it will record a region obligation of
151 /// `$0: 'static`. This will get checked later by regionck. (We
152 /// can't generally check these things right away because we have
153 /// to wait until types are resolved.)
154region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
155156/// The outlives bounds that we assume must hold about placeholders that
157 /// come from instantiating the binder of coroutine-witnesses. These bounds
158 /// are deduced from the well-formedness of the witness's types, and are
159 /// necessary because of the way we anonymize the regions in a coroutine,
160 /// which may cause types to no longer be considered well-formed.
161region_assumptions: Vec<ty::ArgOutlivesClause<'tcx>>,
162163/// `-Znext-solver`: Successfully proven goals during HIR typeck which
164 /// reference inference variables and get reproven in case MIR type check
165 /// fails to prove something.
166 ///
167 /// See the documentation of `InferCtxt::in_hir_typeck` for more details.
168hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
169170/// Caches for opaque type inference.
171opaque_type_storage: OpaqueTypeStorage<'tcx>,
172}
173174impl<'tcx> InferCtxtInner<'tcx> {
175fn new() -> InferCtxtInner<'tcx> {
176InferCtxtInner {
177 undo_log: InferCtxtUndoLogs::default(),
178179 projection_cache: Default::default(),
180 type_variable_storage: Default::default(),
181 const_unification_storage: Default::default(),
182 int_unification_storage: Default::default(),
183 float_unification_storage: Default::default(),
184 float_origin_origin_storage: Default::default(),
185 region_constraint_storage: Some(Default::default()),
186 solver_region_constraint_storage: SolverRegionConstraintStorage::new(),
187 region_obligations: Default::default(),
188 region_assumptions: Default::default(),
189 hir_typeck_potentially_region_dependent_goals: Default::default(),
190 opaque_type_storage: Default::default(),
191 }
192 }
193194#[inline]
195pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
196&self.region_obligations
197 }
198199#[inline]
200pub fn region_assumptions(&self) -> &[ty::ArgOutlivesClause<'tcx>] {
201&self.region_assumptions
202 }
203204#[inline]
205pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
206self.projection_cache.with_log(&mut self.undo_log)
207 }
208209#[inline]
210fn try_type_variables_probe_ref(&self, vid: ty::TyVid) -> Option<&TypeVariableValue<'tcx>> {
211// Uses a read-only view of the unification table, this way we don't
212 // need an undo log.
213self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
214 }
215216#[inline]
217fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
218self.type_variable_storage.with_log(&mut self.undo_log)
219 }
220221#[inline]
222pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
223self.opaque_type_storage.with_log(&mut self.undo_log)
224 }
225226#[inline]
227fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
228self.int_unification_storage.with_log(&mut self.undo_log)
229 }
230231#[inline]
232fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
233self.float_unification_storage.with_log(&mut self.undo_log)
234 }
235236#[inline]
237fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
238self.const_unification_storage.with_log(&mut self.undo_log)
239 }
240241#[inline]
242pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
243self.region_constraint_storage
244 .as_mut()
245 .expect("region constraints already solved")
246 .with_log(&mut self.undo_log)
247 }
248}
249250pub struct InferCtxt<'tcx> {
251pub tcx: TyCtxt<'tcx>,
252253/// The mode of this inference context, see the struct documentation
254 /// for more details.
255typing_mode: TypingMode<'tcx>,
256257/// Whether this inference context should care about region obligations in
258 /// the root universe. Most notably, this is used during HIR typeck as region
259 /// solving is left to borrowck instead.
260 ///
261 /// This is used in the old solver to enable the generation of regions constraints.
262 /// In the new solver its only used inside the InferCtxt's `Drop` implementation:
263 /// if we're considering regions, and new opaques are registered, we panic.
264pub considering_regions: bool,
265/// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we
266 /// need to make sure we don't rely on region identity in the trait solver or when
267 /// relating types. This is necessary as borrowck starts by replacing each occurrence of a
268 /// free region with a unique inference variable. If HIR typeck ends up depending on two
269 /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck,
270 /// resulting in an ICE.
271 ///
272 /// The trait solver sometimes depends on regions being identical. As a concrete example
273 /// the trait solver ignores other candidates if one candidate exists without any constraints.
274 /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each
275 /// occurrence of `'a` with a unique region the goal now equates these regions. See
276 /// the tests in trait-system-refactor-initiative#27 for concrete examples.
277 ///
278 /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck.
279 /// This is still insufficient as inference variables may *hide* region variables, so e.g.
280 /// `dyn TwoSuper<?x, ?x>: Super<?x>` may hold but MIR typeck could end up having to prove
281 /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we
282 /// stash all successfully proven goals which reference inference variables and then reprove
283 /// them after writeback.
284pub in_hir_typeck: bool,
285286/// If set, this flag causes us to skip the 'leak check' during
287 /// higher-ranked subtyping operations. This flag is a temporary one used
288 /// to manage the removal of the leak-check: for the time being, we still run the
289 /// leak-check, but we issue warnings.
290skip_leak_check: bool,
291292pub inner: RefCell<InferCtxtInner<'tcx>>,
293294/// Once region inference is done, the values for each variable.
295lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
296297/// Caches the results of trait selection. This cache is used
298 /// for things that depends on inference variables or placeholders.
299pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
300301/// Caches the results of trait evaluation. This cache is used
302 /// for things that depends on inference variables or placeholders.
303pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
304305/// The set of predicates on which errors have been reported, to
306 /// avoid reporting the same error twice.
307pub reported_trait_errors:
308RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
309310pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
311312/// When an error occurs, we want to avoid reporting "derived"
313 /// errors that are due to this original failure. We have this
314 /// flag that one can set whenever one creates a type-error that
315 /// is due to an error in a prior pass.
316 ///
317 /// Don't read this flag directly, call `is_tainted_by_errors()`
318 /// and `set_tainted_by_errors()`.
319tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
320321/// What is the innermost universe we have created? Starts out as
322 /// `UniverseIndex::root()` but grows from there as we enter
323 /// universal quantifiers.
324 ///
325 /// N.B., at present, we exclude the universal quantifiers on the
326 /// item we are type-checking, and just consider those names as
327 /// part of the root universe. So this would only get incremented
328 /// when we enter into a higher-ranked (`for<..>`) type or trait
329 /// bound.
330universe: Cell<ty::UniverseIndex>,
331332/// List of assumed wellformed types which we can derive implied
333 /// bounds on a `for<...>` from. Only used unstabley and by the
334 /// new solver.
335//
336 // FIXME(-Zassumptions-on-binders): This and `universe` should probably be
337 // in `InferCtxtInner` so they can participate in rollbacks and whatnot
338placeholder_assumptions_for_next_solver: RefCell<
339FxIndexMap<
340 ty::UniverseIndex,
341Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
342 >,
343 >,
344345 next_trait_solver: bool,
346347/// We have a `recursion_depth_exceeding_limit` FCW to mitigate breakages
348 /// caused by enabling the next solver globally. But the next solver is
349 /// already used by default in some places so we know they won't have
350 /// additional breakages. We also don't want spurious result in coherence
351 /// checking so we disable the FCW there as well.
352enable_next_solver_overflow_fcw: Cell<bool>,
353354pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
355356/// State reused by each new canonicalizer, and then cleared (but not deallocated) once the
357 /// canonicalizer is finished. A performance win, because it avoids reallocating new
358 /// vecs/hashmaps for every canonicalizer.
359pub canonicalizer_state: RefCell<CanonicalizerState<TyCtxt<'tcx>>>,
360}
361362impl<'tcx> Dropfor InferCtxt<'tcx> {
363fn drop(&mut self) {
364let mut inner = self.inner.borrow_mut();
365let opaque_type_storage = &mut inner.opaque_type_storage;
366367// No need for the drop bomb when we're in `TypingMode::PostTypeckUntilBorrowck`, and the `InferCtxt`
368 // doesn't consider regions. This is okay since after typeck, the only reason we care about opaques is
369 // in relation to regions. In some places *after* typeck that aren't borrowck, we use
370 // `TypingMode::PostTypeckUntilBorrowck` to prevent defining opaque types and we simply don't care about regions.
371match self.typing_mode_raw() {
372TypingMode::Coherence373 | TypingMode::Typeck { .. }
374 | TypingMode::PostBorrowck { .. }
375 | TypingMode::Reflection376 | TypingMode::PostAnalysis377 | TypingMode::Codegen => {}
378// In erased mode, the opaque type storage is always empty
379TypingMode::ErasedNotCoherence(..) => {}
380TypingMode::PostTypeckUntilBorrowck { .. } => {
381if !self.considering_regions {
382return;
383 }
384 }
385 }
386387if !opaque_type_storage.is_empty() {
388 ty::tls::with(|tcx| tcx.dcx().delayed_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", opaque_type_storage))
})format!("{opaque_type_storage:?}")));
389 }
390 }
391}
392393/// See the `error_reporting` module for more details.
394#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for ValuePairs<'tcx> { }
#[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::marker::StructuralPartialEq for ValuePairs<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for ValuePairs<'tcx> {
#[inline]
fn eq(&self, other: &ValuePairs<'tcx>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ValuePairs::Regions(__self_0), ValuePairs::Regions(__arg1_0))
=> __self_0 == __arg1_0,
(ValuePairs::Terms(__self_0), ValuePairs::Terms(__arg1_0)) =>
__self_0 == __arg1_0,
(ValuePairs::Aliases(__self_0), ValuePairs::Aliases(__arg1_0))
=> __self_0 == __arg1_0,
(ValuePairs::TraitRefs(__self_0),
ValuePairs::TraitRefs(__arg1_0)) => __self_0 == __arg1_0,
(ValuePairs::PolySigs(__self_0),
ValuePairs::PolySigs(__arg1_0)) => __self_0 == __arg1_0,
(ValuePairs::ExistentialTraitRef(__self_0),
ValuePairs::ExistentialTraitRef(__arg1_0)) =>
__self_0 == __arg1_0,
(ValuePairs::ExistentialProjection(__self_0),
ValuePairs::ExistentialProjection(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for ValuePairs<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ExpectedFound<ty::Region<'tcx>>>;
let _: ::core::cmp::AssertParamIsEq<ExpectedFound<ty::Term<'tcx>>>;
let _:
::core::cmp::AssertParamIsEq<ExpectedFound<ty::AliasTerm<'tcx>>>;
let _:
::core::cmp::AssertParamIsEq<ExpectedFound<ty::TraitRef<'tcx>>>;
let _:
::core::cmp::AssertParamIsEq<ExpectedFound<ty::PolyFnSig<'tcx>>>;
let _:
::core::cmp::AssertParamIsEq<ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>>;
let _:
::core::cmp::AssertParamIsEq<ExpectedFound<ty::PolyExistentialProjection<'tcx>>>;
}
}Eq, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for ValuePairs<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
ValuePairs::Regions(__binding_0) => {
ValuePairs::Regions(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::Terms(__binding_0) => {
ValuePairs::Terms(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::Aliases(__binding_0) => {
ValuePairs::Aliases(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::TraitRefs(__binding_0) => {
ValuePairs::TraitRefs(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::PolySigs(__binding_0) => {
ValuePairs::PolySigs(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::ExistentialTraitRef(__binding_0) => {
ValuePairs::ExistentialTraitRef(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
ValuePairs::ExistentialProjection(__binding_0) => {
ValuePairs::ExistentialProjection(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
ValuePairs::Regions(__binding_0) => {
ValuePairs::Regions(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::Terms(__binding_0) => {
ValuePairs::Terms(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::Aliases(__binding_0) => {
ValuePairs::Aliases(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::TraitRefs(__binding_0) => {
ValuePairs::TraitRefs(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::PolySigs(__binding_0) => {
ValuePairs::PolySigs(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::ExistentialTraitRef(__binding_0) => {
ValuePairs::ExistentialTraitRef(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
ValuePairs::ExistentialProjection(__binding_0) => {
ValuePairs::ExistentialProjection(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for ValuePairs<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
ValuePairs::Regions(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::Terms(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::Aliases(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::TraitRefs(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::PolySigs(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::ExistentialTraitRef(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
ValuePairs::ExistentialProjection(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
395pub enum ValuePairs<'tcx> {
396 Regions(ExpectedFound<ty::Region<'tcx>>),
397 Terms(ExpectedFound<ty::Term<'tcx>>),
398 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
399 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
400 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
401 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
402 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
403}
404405impl<'tcx> ValuePairs<'tcx> {
406pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
407if let ValuePairs::Terms(ExpectedFound { expected, found }) = self408 && let Some(expected) = expected.as_type()
409 && let Some(found) = found.as_type()
410 {
411Some((expected, found))
412 } else {
413None414 }
415 }
416}
417418/// The trace designates the path through inference that we took to
419/// encounter an error or subtyping constraint.
420///
421/// See the `error_reporting` module for more details.
422#[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)]
423pub struct TypeTrace<'tcx> {
424pub cause: ObligationCause<'tcx>,
425pub values: ValuePairs<'tcx>,
426}
427428/// The origin of a `r1 <= r2` constraint.
429///
430/// See `error_reporting` module for more details
431#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for SubregionOrigin<'tcx> {
#[inline]
fn clone(&self) -> SubregionOrigin<'tcx> {
match self {
SubregionOrigin::Subtype(__self_0) =>
SubregionOrigin::Subtype(::core::clone::Clone::clone(__self_0)),
SubregionOrigin::RelateObjectBound(__self_0) =>
SubregionOrigin::RelateObjectBound(::core::clone::Clone::clone(__self_0)),
SubregionOrigin::RelateParamBound(__self_0, __self_1, __self_2) =>
SubregionOrigin::RelateParamBound(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1),
::core::clone::Clone::clone(__self_2)),
SubregionOrigin::RelateRegionParamBound(__self_0, __self_1) =>
SubregionOrigin::RelateRegionParamBound(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
SubregionOrigin::Reborrow(__self_0) =>
SubregionOrigin::Reborrow(::core::clone::Clone::clone(__self_0)),
SubregionOrigin::ReferenceOutlivesReferent(__self_0, __self_1) =>
SubregionOrigin::ReferenceOutlivesReferent(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
SubregionOrigin::CompareImplItemObligation {
span: __self_0,
impl_item_def_id: __self_1,
trait_item_def_id: __self_2 } =>
SubregionOrigin::CompareImplItemObligation {
span: ::core::clone::Clone::clone(__self_0),
impl_item_def_id: ::core::clone::Clone::clone(__self_1),
trait_item_def_id: ::core::clone::Clone::clone(__self_2),
},
SubregionOrigin::CheckAssociatedTypeBounds {
parent: __self_0,
impl_item_def_id: __self_1,
trait_item_def_id: __self_2 } =>
SubregionOrigin::CheckAssociatedTypeBounds {
parent: ::core::clone::Clone::clone(__self_0),
impl_item_def_id: ::core::clone::Clone::clone(__self_1),
trait_item_def_id: ::core::clone::Clone::clone(__self_2),
},
SubregionOrigin::AscribeUserTypeProvePredicate(__self_0) =>
SubregionOrigin::AscribeUserTypeProvePredicate(::core::clone::Clone::clone(__self_0)),
SubregionOrigin::SolverRegionConstraint(__self_0) =>
SubregionOrigin::SolverRegionConstraint(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for SubregionOrigin<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
SubregionOrigin::Subtype(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Subtype", &__self_0),
SubregionOrigin::RelateObjectBound(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"RelateObjectBound", &__self_0),
SubregionOrigin::RelateParamBound(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"RelateParamBound", __self_0, __self_1, &__self_2),
SubregionOrigin::RelateRegionParamBound(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"RelateRegionParamBound", __self_0, &__self_1),
SubregionOrigin::Reborrow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Reborrow", &__self_0),
SubregionOrigin::ReferenceOutlivesReferent(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ReferenceOutlivesReferent", __self_0, &__self_1),
SubregionOrigin::CompareImplItemObligation {
span: __self_0,
impl_item_def_id: __self_1,
trait_item_def_id: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"CompareImplItemObligation", "span", __self_0,
"impl_item_def_id", __self_1, "trait_item_def_id",
&__self_2),
SubregionOrigin::CheckAssociatedTypeBounds {
parent: __self_0,
impl_item_def_id: __self_1,
trait_item_def_id: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"CheckAssociatedTypeBounds", "parent", __self_0,
"impl_item_def_id", __self_1, "trait_item_def_id",
&__self_2),
SubregionOrigin::AscribeUserTypeProvePredicate(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AscribeUserTypeProvePredicate", &__self_0),
SubregionOrigin::SolverRegionConstraint(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SolverRegionConstraint", &__self_0),
}
}
}Debug)]
432pub enum SubregionOrigin<'tcx> {
433/// Arose from a subtyping relation
434Subtype(Box<TypeTrace<'tcx>>),
435436/// When casting `&'a T` to an `&'b Trait` object,
437 /// relating `'a` to `'b`.
438RelateObjectBound(Span),
439440/// Some type parameter was instantiated with the given type,
441 /// and that type must outlive some region.
442RelateParamBound(Span, Ty<'tcx>, Option<Span>),
443444/// The given region parameter was instantiated with a region
445 /// that must outlive some other region.
446RelateRegionParamBound(Span, Option<Ty<'tcx>>),
447448/// Creating a pointer `b` to contents of another reference.
449Reborrow(Span),
450451/// (&'a &'b T) where a >= b
452ReferenceOutlivesReferent(Ty<'tcx>, Span),
453454/// Comparing the signature and requirements of an impl method against
455 /// the containing trait.
456CompareImplItemObligation {
457 span: Span,
458 impl_item_def_id: LocalDefId,
459 trait_item_def_id: DefId,
460 },
461462/// Checking that the bounds of a trait's associated type hold for a given impl.
463CheckAssociatedTypeBounds {
464 parent: Box<SubregionOrigin<'tcx>>,
465 impl_item_def_id: LocalDefId,
466 trait_item_def_id: DefId,
467 },
468469 AscribeUserTypeProvePredicate(Span),
470471// FIXME(-Zassumptions-on-binders): this is a temporary hack until we support
472 // proper diagnostics for solver region constraints.
473SolverRegionConstraint(Span),
474}
475476// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
477#[cfg(target_pointer_width = "64")]
478const _: [(); 32] = [(); ::std::mem::size_of::<SubregionOrigin<'_>>()];rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
479480impl<'tcx> SubregionOrigin<'tcx> {
481pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
482match self {
483Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
484Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
485Self::SolverRegionConstraint(span) => ConstraintCategory::SolverRegionConstraint(*span),
486_ => ConstraintCategory::BoringNoLocation,
487 }
488 }
489}
490491/// Times when we replace bound regions with existentials:
492#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BoundRegionConversionTime { }
#[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)]
493pub enum BoundRegionConversionTime {
494/// when a fn is called
495FnCall,
496497/// when two higher-ranked types are compared
498HigherRankedType,
499500/// when projecting an associated type
501AssocTypeProjection(DefId),
502}
503504/// Reasons to create a region inference variable.
505///
506/// See `error_reporting` module for more details.
507#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for RegionVariableOrigin<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for RegionVariableOrigin<'tcx> {
}
#[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)]
508pub enum RegionVariableOrigin<'tcx> {
509/// Region variables created for ill-categorized reasons.
510 ///
511 /// They mostly indicate places in need of refactoring.
512Misc(Span),
513514/// Regions created by a `&P` or `[...]` pattern.
515PatternRegion(Span),
516517/// Regions created by `&` operator.
518BorrowRegion(Span),
519520/// Regions created as part of an autoref of a method receiver.
521Autoref(Span),
522523/// Regions created as part of an automatic coercion.
524Coercion(Span),
525526/// Region variables created as the values for early-bound regions.
527 ///
528 /// FIXME(@lcnr): This should also store a `DefId`, similar to
529 /// `TypeVariableOrigin`.
530RegionParameterDefinition(Span, Symbol),
531532/// Region variables created when instantiating a binder with
533 /// existential variables, e.g. when calling a function or method.
534BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime),
535536 UpvarRegion(ty::UpvarId, Span),
537538/// This origin is used for the inference variables that we create
539 /// during NLL region processing.
540Nll(NllRegionVariableOrigin<'tcx>),
541}
542543#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for NllRegionVariableOrigin<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for
NllRegionVariableOrigin<'tcx> {
}
#[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)]
544pub enum NllRegionVariableOrigin<'tcx> {
545/// During NLL region processing, we create variables for free
546 /// regions that we encounter in the function signature and
547 /// elsewhere. This origin indices we've got one of those.
548FreeRegion,
549550/// "Universal" instantiation of a higher-ranked region (e.g.,
551 /// from a `for<'a> T` binder). Meant to represent "any region".
552Placeholder(ty::PlaceholderRegion<'tcx>),
553554 Existential {
555 name: Option<Symbol>,
556 },
557}
558559#[derive(#[automatically_derived]
impl ::core::marker::Copy for FixupError { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for FixupError { }
#[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)]
560pub struct FixupError {
561 unresolved: TyOrConstInferVar,
562}
563564impl fmt::Displayfor FixupError {
565fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
566match self.unresolved {
567 TyOrConstInferVar::TyInt(_) => f.write_fmt(format_args!("cannot determine the type of this integer; add a suffix to specify the type explicitly"))write!(
568f,
569"cannot determine the type of this integer; \
570 add a suffix to specify the type explicitly"
571),
572 TyOrConstInferVar::TyFloat(_) => f.write_fmt(format_args!("cannot determine the type of this number; add a suffix to specify the type explicitly"))write!(
573f,
574"cannot determine the type of this number; \
575 add a suffix to specify the type explicitly"
576),
577 TyOrConstInferVar::Ty(_) => f.write_fmt(format_args!("unconstrained type"))write!(f, "unconstrained type"),
578 TyOrConstInferVar::Const(_) => f.write_fmt(format_args!("unconstrained const value"))write!(f, "unconstrained const value"),
579 }
580 }
581}
582583/// See the `region_obligations` field for more information.
584#[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)]
585pub struct TypeOutlivesConstraint<'tcx> {
586pub sub_region: ty::Region<'tcx>,
587pub sup_type: Ty<'tcx>,
588pub origin: SubregionOrigin<'tcx>,
589}
590591/// Used to configure inference contexts before their creation.
592pub struct InferCtxtBuilder<'tcx> {
593 tcx: TyCtxt<'tcx>,
594 considering_regions: bool,
595 in_hir_typeck: bool,
596 skip_leak_check: bool,
597/// Whether we should use the new trait solver in the local inference context,
598 /// which affects things like which solver is used in `predicate_may_hold`.
599next_trait_solver: bool,
600 enable_next_solver_overflow_fcw: bool,
601}
602603pub trait TyCtxtInferExt<'tcx> {
fn infer_ctxt(self)
-> InferCtxtBuilder<'tcx>;
}
impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
InferCtxtBuilder {
tcx: self,
considering_regions: true,
in_hir_typeck: false,
skip_leak_check: false,
next_trait_solver: self.next_trait_solver_globally(),
enable_next_solver_overflow_fcw: true,
}
}
}#[extension(pub trait TyCtxtInferExt<'tcx>)]604impl<'tcx> TyCtxt<'tcx> {
605fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
606InferCtxtBuilder {
607 tcx: self,
608 considering_regions: true,
609 in_hir_typeck: false,
610 skip_leak_check: false,
611 next_trait_solver: self.next_trait_solver_globally(),
612 enable_next_solver_overflow_fcw: true,
613 }
614 }
615}
616617impl<'tcx> InferCtxtBuilder<'tcx> {
618pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
619self.next_trait_solver = next_trait_solver;
620self621 }
622623pub fn enable_next_solver_overflow_fcw(
624mut self,
625 enable_next_solver_overflow_fcw: bool,
626 ) -> Self {
627self.enable_next_solver_overflow_fcw = enable_next_solver_overflow_fcw;
628self629 }
630631pub fn ignoring_regions(mut self) -> Self {
632self.considering_regions = false;
633self634 }
635636pub fn in_hir_typeck(mut self) -> Self {
637self.in_hir_typeck = true;
638self639 }
640641pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
642self.skip_leak_check = skip_leak_check;
643self644 }
645646/// Given a canonical value `C` as a starting point, create an
647 /// inference context that contains each of the bound values
648 /// within instantiated as a fresh variable. The `f` closure is
649 /// invoked with the new infcx, along with the instantiated value
650 /// `V` and a instantiation `S`. This instantiation `S` maps from
651 /// the bound values in `C` to their instantiated values in `V`
652 /// (in other words, `S(C) = V`).
653pub fn build_with_canonical<T>(
654mut self,
655 span: Span,
656 input: &CanonicalQueryInput<'tcx, T>,
657 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
658where
659T: TypeFoldable<TyCtxt<'tcx>>,
660 {
661let infcx = self.build(input.typing_mode.0);
662let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
663 (infcx, value, args)
664 }
665666pub fn build_with_typing_env(
667mut self,
668 typing_env: TypingEnv<'tcx>,
669 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
670 (self.build(typing_env.typing_mode()), typing_env.param_env)
671 }
672673pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
674let InferCtxtBuilder {
675 tcx,
676 considering_regions,
677 in_hir_typeck,
678 skip_leak_check,
679 next_trait_solver,
680 enable_next_solver_overflow_fcw,
681 } = *self;
682InferCtxt {
683tcx,
684typing_mode,
685considering_regions,
686in_hir_typeck,
687skip_leak_check,
688 inner: RefCell::new(InferCtxtInner::new()),
689 lexical_region_resolutions: RefCell::new(None),
690 selection_cache: Default::default(),
691 evaluation_cache: Default::default(),
692 reported_trait_errors: Default::default(),
693 reported_signature_mismatch: Default::default(),
694 tainted_by_errors: Cell::new(None),
695 universe: Cell::new(ty::UniverseIndex::ROOT),
696 placeholder_assumptions_for_next_solver: RefCell::new(Default::default()),
697next_trait_solver,
698 enable_next_solver_overflow_fcw: Cell::new(enable_next_solver_overflow_fcw),
699 obligation_inspector: Cell::new(None),
700 canonicalizer_state: Default::default(),
701 }
702 }
703}
704705impl<'tcx, T> InferOk<'tcx, T> {
706/// Extracts `value`, registering any obligations into `fulfill_cx`.
707pub fn into_value_registering_obligations<E: 'tcx>(
708self,
709 infcx: &InferCtxt<'tcx>,
710 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
711 ) -> T {
712let InferOk { value, obligations } = self;
713fulfill_cx.register_predicate_obligations(infcx, obligations);
714value715 }
716}
717718impl<'tcx> InferOk<'tcx, ()> {
719pub fn into_obligations(self) -> PredicateObligations<'tcx> {
720self.obligations
721 }
722}
723724impl<'tcx> InferCtxt<'tcx> {
725pub fn dcx(&self) -> DiagCtxtHandle<'_> {
726self.tcx.dcx().into_taintable(&self.tainted_by_errors)
727 }
728729pub fn next_trait_solver(&self) -> bool {
730self.next_trait_solver
731 }
732733/// This method is deliberately called `..._raw`,
734 /// since the output may possibly include [`TypingMode::ErasedNotCoherence`](TypingMode::ErasedNotCoherence).
735 /// `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for
736 /// more information.
737 ///
738 /// `InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt`
739 /// works as a kind of store for for example type unification information.
740 /// `InferCtxt` is also often used outside the trait solver during typeck.
741 /// There, we don't care about the `ErasedNotCoherence` case and should never encounter it.
742 /// To make sure these two uses are never confused, we want to statically encode this information.
743 ///
744 /// The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw
745 /// version of the `typing_mode` method available that asserts `ErasedNotCoherence` is
746 /// impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using
747 /// the [`CantBeErased`](rustc_type_ir::CantBeErased) enum. That way you don't even have to
748 /// match on the variant and can safely ignore it.
749 ///
750 /// Prefer non-raw apis if available. e.g.,
751 /// - On the `FnCtxt`
752 /// - on the `SelectionCtxt`
753#[inline(always)]
754pub fn typing_mode_raw(&self) -> TypingMode<'tcx> {
755self.typing_mode
756 }
757758#[inline(always)]
759pub fn disable_trait_solver_fast_paths(&self) -> bool {
760self.tcx.disable_trait_solver_fast_paths()
761 }
762763/// Returns the origin of the type variable identified by `vid`.
764 ///
765 /// No attempt is made to resolve `vid` to its root variable.
766pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
767self.inner.borrow_mut().type_variables().var_origin(vid)
768 }
769770/// Returns the origin of the float type variable identified by `vid`.
771 ///
772 /// No attempt is made to resolve `vid` to its root variable.
773pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin {
774self.inner.borrow_mut().float_origin_origin_storage[vid]
775 }
776777/// Returns the origin of the const variable identified by `vid`
778// FIXME: We should store origins separately from the unification table
779 // so this doesn't need to be optional.
780pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
781match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
782 ConstVariableValue::Known { .. } => None,
783 ConstVariableValue::Unknown { origin, .. } => Some(origin),
784 }
785 }
786787pub fn unresolved_root_variables(&self) -> (Vec<TyVid>, Vec<ty::IntVid>, Vec<ty::FloatVid>) {
788let mut inner = self.inner.borrow_mut();
789790let ty = inner.type_variables().unresolved_root_variables();
791792let int = unresolved_root_variables_of(
793inner.int_unification_table(),
794 ty::IntVarValue::is_unknown,
795 );
796797let float = unresolved_root_variables_of(
798inner.float_unification_table(),
799 ty::FloatVarValue::is_unknown,
800 );
801802 (ty, int, float)
803 }
804805{}
#[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("/rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(805u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("vis")
}> =
::tracing::__macro_support::FieldName::new("vis");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin,
a, b, vis);
}
}
}#[instrument(skip(self), level = "debug")]806pub fn sub_regions(
807&self,
808 origin: SubregionOrigin<'tcx>,
809 a: ty::Region<'tcx>,
810 b: ty::Region<'tcx>,
811 vis: ty::VisibleForLeakCheck,
812 ) {
813self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b, vis);
814 }
815816{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("equate_regions",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(816u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("vis")
}> =
::tracing::__macro_support::FieldName::new("vis");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin,
a, b, vis);
}
}
}#[instrument(skip(self), level = "debug")]817pub fn equate_regions(
818&self,
819 origin: SubregionOrigin<'tcx>,
820 a: ty::Region<'tcx>,
821 b: ty::Region<'tcx>,
822 vis: ty::VisibleForLeakCheck,
823 ) {
824self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(origin, a, b, vis);
825 }
826827/// Processes a `Coerce` predicate from the fulfillment context.
828 /// This is NOT the preferred way to handle coercion, which is to
829 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
830 ///
831 /// This method here is actually a fallback that winds up being
832 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
833 /// and records a coercion predicate. Presently, this method is equivalent
834 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
835 /// actually requiring `a <: b`. This is of course a valid coercion,
836 /// but it's not as flexible as `FnCtxt::coerce` would be.
837 ///
838 /// (We may refactor this in the future, but there are a number of
839 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
840 /// records adjustments that are required on the HIR in order to perform
841 /// the coercion, and we don't currently have a way to manage that.)
842pub fn coerce_predicate(
843&self,
844 cause: &ObligationCause<'tcx>,
845 param_env: ty::ParamEnv<'tcx>,
846 predicate: ty::PolyCoercePredicate<'tcx>,
847 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
848let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
849 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
850a: p.a,
851 b: p.b,
852 });
853self.subtype_predicate(cause, param_env, subtype_predicate)
854 }
855856pub fn subtype_predicate(
857&self,
858 cause: &ObligationCause<'tcx>,
859 param_env: ty::ParamEnv<'tcx>,
860 predicate: ty::PolySubtypePredicate<'tcx>,
861 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
862// Check for two unresolved inference variables, in which case we can
863 // make no progress. This is partly a micro-optimization, but it's
864 // also an opportunity to "sub-unify" the variables. This isn't
865 // *necessary* to prevent cycles, because they would eventually be sub-unified
866 // anyhow during generalization, but it helps with diagnostics (we can detect
867 // earlier that they are sub-unified).
868 //
869 // Note that we can just skip the binders here because
870 // type variables can't (at present, at
871 // least) capture any of the things bound by this binder.
872 //
873 // Note that this sub here is not just for diagnostics - it has semantic
874 // effects as well.
875let r_a = self.shallow_resolve(predicate.skip_binder().a);
876let r_b = self.shallow_resolve(predicate.skip_binder().b);
877match (r_a.kind(), r_b.kind()) {
878 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
879self.sub_unify_ty_vids_raw(a_vid, b_vid);
880return Err((a_vid, b_vid));
881 }
882_ => {}
883 }
884885self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
886if a_is_expected {
887Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
888 } else {
889Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
890 }
891 })
892 }
893894/// Number of type variables created so far.
895pub fn num_ty_vars(&self) -> usize {
896self.inner.borrow_mut().type_variables().num_vars()
897 }
898899pub fn next_ty_vid(&self, span: Span) -> TyVid {
900self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
901 }
902903pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
904self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
905 }
906907pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
908let origin = TypeVariableOrigin { span, param_def_id: None };
909self.inner.borrow_mut().type_variables().new_var(universe, origin)
910 }
911912pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
913self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
914 }
915916pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
917let vid = self.next_ty_vid_with_origin(origin);
918Ty::new_var(self.tcx, vid)
919 }
920921pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
922let vid = self.next_ty_vid_in_universe(span, universe);
923Ty::new_var(self.tcx, vid)
924 }
925926pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
927self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
928 }
929930pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
931let vid = self932 .inner
933 .borrow_mut()
934 .const_unification_table()
935 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
936 .vid;
937 ty::Const::new_var(self.tcx, vid)
938 }
939940pub fn next_const_var_in_universe(
941&self,
942 span: Span,
943 universe: ty::UniverseIndex,
944 ) -> ty::Const<'tcx> {
945let origin = ConstVariableOrigin { span, param_def_id: None };
946let vid = self947 .inner
948 .borrow_mut()
949 .const_unification_table()
950 .new_key(ConstVariableValue::Unknown { origin, universe })
951 .vid;
952 ty::Const::new_var(self.tcx, vid)
953 }
954955pub fn next_int_var(&self) -> Ty<'tcx> {
956let next_int_var_id =
957self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
958Ty::new_int_var(self.tcx, next_int_var_id)
959 }
960961pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx> {
962let mut inner = self.inner.borrow_mut();
963let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown);
964let origin = FloatVariableOrigin { span, lint_id };
965let span_index = inner.float_origin_origin_storage.push(origin);
966if true {
{
match (&next_float_var_id, &span_index) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(next_float_var_id, span_index);
967Ty::new_float_var(self.tcx, next_float_var_id)
968 }
969970/// Creates a fresh region variable with the next available index.
971 /// The variable will be created in the maximum universe created
972 /// thus far, allowing it to name any region created thus far.
973pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
974self.next_region_var_in_universe(origin, self.universe())
975 }
976977/// Creates a fresh region variable with the next available index
978 /// in the given universe; typically, you can use
979 /// `next_region_var` and just use the maximal universe.
980pub fn next_region_var_in_universe(
981&self,
982 origin: RegionVariableOrigin<'tcx>,
983 universe: ty::UniverseIndex,
984 ) -> ty::Region<'tcx> {
985let region_var =
986self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
987 ty::Region::new_var(self.tcx, region_var)
988 }
989990pub fn next_term_var_of_alias_kind(
991&self,
992 alias_term: ty::AliasTerm<'tcx>,
993 span: Span,
994 ) -> ty::Term<'tcx> {
995match alias_term.kind {
996 ty::AliasTermKind::ProjectionTy { .. }
997 | ty::AliasTermKind::InherentTy { .. }
998 | ty::AliasTermKind::OpaqueTy { .. }
999 | ty::AliasTermKind::FreeTy { .. } => self.next_ty_var(span).into(),
1000 ty::AliasTermKind::FreeConst { .. }
1001 | ty::AliasTermKind::InherentConstSelf { .. }
1002 | ty::AliasTermKind::InherentConstImpl { .. }
1003 | ty::AliasTermKind::AnonConst { .. }
1004 | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_var(span).into(),
1005 }
1006 }
10071008/// Return the universe that the region `r` was created in. For
1009 /// most regions (e.g., `'static`, named regions from the user,
1010 /// etc) this is the root universe U0. For inference variables or
1011 /// placeholders, however, it will return the universe which they
1012 /// are associated.
1013pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1014self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1015 }
10161017/// Number of region variables created so far.
1018pub fn num_region_vars(&self) -> usize {
1019self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1020 }
10211022/// Just a convenient wrapper of `next_region_var` for using during NLL.
1023{}
#[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("/rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1023u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{ self.next_region_var(RegionVariableOrigin::Nll(origin)) }
}
}#[instrument(skip(self), level = "debug")]1024pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
1025self.next_region_var(RegionVariableOrigin::Nll(origin))
1026 }
10271028/// Just a convenient wrapper of `next_region_var` for using during NLL.
1029{}
#[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("/rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1029u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("universe")
}> =
::tracing::__macro_support::FieldName::new("universe");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&universe)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::Region<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin),
universe)
}
}
}#[instrument(skip(self), level = "debug")]1030pub fn next_nll_region_var_in_universe(
1031&self,
1032 origin: NllRegionVariableOrigin<'tcx>,
1033 universe: ty::UniverseIndex,
1034 ) -> ty::Region<'tcx> {
1035self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1036 }
10371038pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1039match param.kind {
1040 GenericParamDefKind::Lifetime => {
1041// Create a region inference variable for the given
1042 // region parameter definition.
1043self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
1044span, param.name,
1045 ))
1046 .into()
1047 }
1048 GenericParamDefKind::Type { .. } => {
1049// Create a type inference variable for the given
1050 // type parameter definition. The generic parameters are
1051 // for actual parameters that may be referred to by
1052 // the default of this type parameter, if it exists.
1053 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1054 // used in a path such as `Foo::<T, U>::new()` will
1055 // use an inference variable for `C` with `[T, U]`
1056 // as the generic parameters for the default, `(T, U)`.
1057let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1058self.universe(),
1059TypeVariableOrigin { param_def_id: Some(param.def_id), span },
1060 );
10611062Ty::new_var(self.tcx, ty_var_id).into()
1063 }
1064 GenericParamDefKind::Const { .. } => {
1065let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
1066let const_var_id = self1067 .inner
1068 .borrow_mut()
1069 .const_unification_table()
1070 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
1071 .vid;
1072 ty::Const::new_var(self.tcx, const_var_id).into()
1073 }
1074 }
1075 }
10761077/// Given a set of generics defined on a type or impl, returns the generic parameters mapping
1078 /// each type/region parameter to a fresh inference variable.
1079pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
1080GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1081 }
10821083/// Returns `true` if errors have been reported since this infcx was
1084 /// created. This is sometimes used as a heuristic to skip
1085 /// reporting errors that often occur as a result of earlier
1086 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1087 /// inference variables, regionck errors).
1088#[must_use = "this method does not have any side effects"]
1089pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
1090self.tainted_by_errors.get()
1091 }
10921093/// Set the "tainted by errors" flag to true. We call this when we
1094 /// observe an error from a prior pass.
1095pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
1096{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs:1096",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1096u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("set_tainted_by_errors(ErrorGuaranteed)")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("set_tainted_by_errors(ErrorGuaranteed)");
1097self.tainted_by_errors.set(Some(e));
1098 }
10991100pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
1101let mut inner = self.inner.borrow_mut();
1102let inner = &mut *inner;
1103inner.unwrap_region_constraints().var_origin(vid)
1104 }
11051106/// Clone the list of variable regions. This is used only during NLL processing
1107 /// to put the set of region variables into the NLL region context.
1108pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
1109let inner = self.inner.borrow();
1110if !!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));
1111let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
1112if !storage.data.is_empty() {
{ ::core::panicking::panic_fmt(format_args!("{0:#?}", storage.data)); }
};assert!(storage.data.is_empty(), "{:#?}", storage.data);
1113// We clone instead of taking because borrowck still wants to use the
1114 // inference context after calling this for diagnostics and the new
1115 // trait solver.
1116storage.var_infos.clone()
1117 }
11181119pub fn has_opaque_types_in_storage(&self) -> bool {
1120 !self.inner.borrow().opaque_type_storage.is_empty()
1121 }
11221123{}
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("take_opaque_types",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1123u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[],
::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,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> =
loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs:1123",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1123u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]1124pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1125self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
1126 }
11271128{}
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("clone_opaque_types",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1128u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[],
::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,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> =
loop {};
return __tracing_attr_fake_return;
}
{
self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs:1128",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1128u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]1129pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
1130self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1131 }
11321133pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
1134if !self.next_trait_solver() {
1135return false;
1136 }
11371138let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1139let inner = &mut *self.inner.borrow_mut();
1140let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1141inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
1142if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1143let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1144if opaque_sub_vid == ty_sub_vid {
1145return true;
1146 }
1147 }
11481149false
1150})
1151 }
11521153/// Searches for an opaque type key whose hidden type is related to `ty_vid`.
1154 ///
1155 /// This only checks for a subtype relation, it does not require equality.
1156pub fn opaques_with_sub_unified_hidden_type(
1157&self,
1158 ty_vid: TyVid,
1159 ) -> Vec<ty::OpaqueAliasTy<'tcx>> {
1160// Avoid accidentally allowing more code to compile with the old solver.
1161if !self.next_trait_solver() {
1162return ::alloc::vec::Vec::new()vec![];
1163 }
11641165let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1166let inner = &mut *self.inner.borrow_mut();
1167// This is iffy, can't call `type_variables()` as we're already
1168 // borrowing the `opaque_type_storage` here.
1169let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1170inner1171 .opaque_type_storage
1172 .iter_opaque_types()
1173 .filter_map(|(key, hidden_ty)| {
1174if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1175let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1176if opaque_sub_vid == ty_sub_vid {
1177return Some(ty::OpaqueAliasTy::new_opaque_from_args(
1178self.tcx,
1179key.def_id.into(),
1180key.args,
1181 ));
1182 }
1183 }
11841185None1186 })
1187 .collect()
1188 }
11891190#[inline(always)]
1191pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1192if true {
if !!self.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.next_trait_solver()")
};
};debug_assert!(!self.next_trait_solver());
1193match self.typing_mode_raw().assert_not_erased() {
1194TypingMode::Typeck { defining_opaque_types_and_generators: defining_opaque_types }
1195 | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types } => {
1196id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1197 }
1198// FIXME(#132279): This function is quite weird in post-analysis
1199 // and post-borrowck analysis mode. We may need to modify its uses
1200 // to support PostBorrowck in the old solver as well.
1201TypingMode::Coherence1202 | TypingMode::Reflection1203 | TypingMode::PostBorrowck { .. }
1204 | TypingMode::PostAnalysis1205 | TypingMode::Codegen => false,
1206 }
1207 }
12081209pub fn push_hir_typeck_potentially_region_dependent_goal(
1210&self,
1211 goal: PredicateObligation<'tcx>,
1212 ) {
1213let mut inner = self.inner.borrow_mut();
1214inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1215inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1216 }
12171218pub fn take_hir_typeck_potentially_region_dependent_goals(
1219&self,
1220 ) -> Vec<PredicateObligation<'tcx>> {
1221if !!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");
1222 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1223 }
12241225pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1226self.deeply_resolve_ignoring_regions(t).to_string()
1227 }
12281229/// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1230 /// universe index of `TyVar(vid)`.
1231pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1232use self::type_variable::TypeVariableValue;
12331234match self.inner.borrow_mut().type_variables().probe(vid) {
1235 TypeVariableValue::Known { value } => Ok(value),
1236 TypeVariableValue::Unknown { universe } => Err(universe),
1237 }
1238 }
12391240/// If `vid` resolves to a type, return that type. Otherwise return the root variable id for `vid`.
1241pub fn shallow_resolve_ty_var_or_get_root(&self, vid: TyVid) -> Result<Ty<'tcx>, TyVid> {
1242let (root, value) = self.inner.borrow_mut().type_variables().probe_with_root_vid(vid);
12431244match value {
1245 TypeVariableValue::Known { value } => Ok(value),
1246 TypeVariableValue::Unknown { universe: _ } => Err(root),
1247 }
1248 }
12491250/// Resolve a type variable. Resolving means the following:
1251 ///
1252 /// - If a `Ty` is a rigid type (like, an integer, or some ADT), do nothing.
1253 /// - If a `Ty` is a type infer variable, but has been equated with an actual type,
1254 /// return that type.
1255 /// - If a `Ty` is an int or float infer variable, and has been equated with an integer
1256 /// or floating point type, return that type.
1257 /// - If a `Ty` is any kind of infer variable that has been equated, but not yet with a rigid
1258 /// type, then this set of equated variables forms an equivalence class. One of the variables
1259 /// in that equivalent class is said to be the root variable, and resolving makes sure to
1260 /// consistently return this root variable. This is beneficial for caching.
1261 /// This behavior, of returning roots, changed in <https://github.com/rust-lang/rust/pull/158447>.
1262 ///
1263 /// Otherwise, resolving simply does nothing.
1264 ///
1265 /// The "shallow" part of the name refers to the fact that types may themselves contain more
1266 /// type variables. e.g. The field types of a struct. `shallow_resolve` does not recurse into
1267 /// these nested variables. If that's what you want, use [`deeply_resolve_ignoring_regions`](Self::deeply_resolve_ignoring_regions),
1268 /// or better [`deeply_resolve_via_unification_table`](rustc_type_ir::InferCtxtLike::deeply_resolve_via_unification_table), if you can, which *does* resolve regions.
1269pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1270if let ty::Infer(v) = *ty.kind() {
1271match v {
1272 ty::TyVar(v) => {
1273// Not entirely obvious: if `typ` is a type variable,
1274 // it can be resolved to an int/float variable, which
1275 // can then be recursively resolved, hence the
1276 // recursion. Note though that we prevent type
1277 // variables from unifying to other type variables
1278 // directly (though they may be embedded
1279 // structurally), and we prevent cycles in any case,
1280 // so this recursion should always be of very limited
1281 // depth.
1282 //
1283 // Note: if these two lines are combined into one we get
1284 // dynamic borrow errors on `self.inner`.
1285let (root_vid, value) =
1286self.inner.borrow_mut().type_variables().probe_with_root_vid(v);
1287value.known().map_or_else(
1288 || if root_vid == v { ty } else { Ty::new_var(self.tcx, root_vid) },
1289 |t| self.shallow_resolve(t),
1290 )
1291 }
12921293 ty::IntVar(v) => {
1294let (root, value) =
1295self.inner.borrow_mut().int_unification_table().inlined_probe_key_value(v);
1296match value {
1297 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1298 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1299 ty::IntVarValue::Unknown => {
1300if root == v {
1301ty1302 } else {
1303Ty::new_int_var(self.tcx, root)
1304 }
1305 }
1306 }
1307 }
13081309 ty::FloatVar(v) => {
1310let (root, value) = self1311 .inner
1312 .borrow_mut()
1313 .float_unification_table()
1314 .inlined_probe_key_value(v);
1315match value {
1316 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1317 ty::FloatVarValue::Unknown => {
1318if root == v {
1319ty1320 } else {
1321Ty::new_float_var(self.tcx, root)
1322 }
1323 }
1324 }
1325 }
13261327 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1328 }
1329 } else {
1330ty1331 }
1332 }
13331334/// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1335 /// It's the same, but for consts.
1336pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1337match ct.kind() {
1338 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1339 InferConst::Var(vid) => {
1340let (root, value) = self1341 .inner
1342 .borrow_mut()
1343 .const_unification_table()
1344 .inlined_probe_key_value(vid);
1345value.known().unwrap_or_else(|| {
1346if root.vid == vid { ct } else { ty::Const::new_var(self.tcx, root.vid) }
1347 })
1348 }
1349 InferConst::Fresh(_) => ct,
1350 },
13511352 ty::ConstKind::Param(_)
1353 | ty::ConstKind::Bound(_, _)
1354 | ty::ConstKind::Placeholder(_)
1355 | ty::ConstKind::Alias(_, _)
1356 | ty::ConstKind::Value(_)
1357 | ty::ConstKind::Error(_)
1358 | ty::ConstKind::Expr(_) => ct,
1359 }
1360 }
13611362/// See docs on [`shallow_resolve`](Self::shallow_resolve) for more explanation.
1363 /// It's the same, but for terms (types or consts).
1364pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1365match term.kind() {
1366 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1367 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1368 }
1369 }
13701371pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1372self.inner.borrow_mut().type_variables().root_var(var)
1373 }
13741375/// If `ty` is an unresolved type variable, returns its root vid.
1376pub fn root_vid(&self, ty: Ty<'tcx>) -> Option<ty::TyVid> {
1377let (root, value) =
1378self.inner.borrow_mut().type_variables().inlined_probe_with_vid(ty.ty_vid()?);
1379value.is_unknown().then_some(root)
1380 }
13811382pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1383self.inner.borrow_mut().type_variables().sub_unify(a, b);
1384 }
13851386pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1387self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1388 }
13891390pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1391self.inner.borrow_mut().float_unification_table().find(var)
1392 }
13931394pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1395self.inner.borrow_mut().const_unification_table().find(var).vid
1396 }
13971398/// Resolves a const var to a rigid const, if it was constrained to one,
1399 /// or else the root const var in the unification table.
1400pub fn shallow_resolve_const_var(&self, vid: ty::ConstVid) -> ty::Const<'tcx> {
1401match self.try_resolve_const_var(vid) {
1402Ok(ct) => ct,
1403Err(_) => ty::Const::new_var(self.tcx, self.root_const_var(vid)),
1404 }
1405 }
14061407/// Resolves a type var to a rigid type, if it was constrained to one,
1408 /// or else the root type var in the unification table.
1409pub fn shallow_resolve_ty_var(&self, vid: ty::TyVid) -> Ty<'tcx> {
1410match self.try_resolve_ty_var(vid) {
1411Ok(ty) => ty,
1412Err(_) => Ty::new_var(self.tcx, self.root_var(vid)),
1413 }
1414 }
14151416/// Resolves an int var to a rigid int type, if it was constrained to one,
1417 /// or else the root int var in the unification table.
1418pub fn shallow_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1419let mut inner = self.inner.borrow_mut();
1420let value = inner.int_unification_table().probe_value(vid);
1421match value {
1422 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1423 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1424 ty::IntVarValue::Unknown => {
1425Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1426 }
1427 }
1428 }
14291430/// Resolves a float var to a rigid type, if it was constrained to one,
1431 /// or else the root float var in the unification table.
1432pub fn shallow_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1433let mut inner = self.inner.borrow_mut();
1434let value = inner.float_unification_table().probe_value(vid);
1435match value {
1436 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1437 ty::FloatVarValue::Unknown => {
1438Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1439 }
1440 }
1441 }
14421443/// If a type/const variable has not (yet) been unified, it is left as is.
1444 ///
1445 /// This is an idempotent operation that does not affect inference state in any way,
1446 /// which means it's safe to call this function at will.
1447 ///
1448 /// Region variables are unaffected.
1449pub fn deeply_resolve_ignoring_regions<T>(&self, value: T) -> T
1450where
1451T: TypeFoldable<TyCtxt<'tcx>>,
1452 {
1453if let Err(guar) = value.error_reported() {
1454self.set_tainted_by_errors(guar);
1455 }
1456if !value.has_non_region_infer() {
1457return value;
1458 }
1459let mut r = resolve::DeepResolverIgnoringRegions::new(self);
1460value.fold_with(&mut r)
1461 }
14621463pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1464where
1465T: TypeFoldable<TyCtxt<'tcx>>,
1466 {
1467if !value.has_infer() {
1468return value; // Avoid duplicated type-folding.
1469}
1470let mut r = InferenceLiteralEraser { tcx: self.tcx };
1471value.fold_with(&mut r)
1472 }
14731474pub fn try_resolve_const_var(
1475&self,
1476 vid: ty::ConstVid,
1477 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1478match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1479 ConstVariableValue::Known { value } => Ok(value),
1480 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1481 }
1482 }
14831484/// Attempts to resolve all type/region/const variables in
1485 /// `value`. Region inference must have been run already (e.g.,
1486 /// by calling `resolve_regions_and_report_errors`). If some
1487 /// variable was never unified, an `Err` results.
1488 ///
1489 /// This method is idempotent, but it not typically not invoked
1490 /// except during the writeback phase.
1491pub fn deeply_resolve_via_region_graph<T: TypeFoldable<TyCtxt<'tcx>>>(
1492&self,
1493 value: T,
1494 ) -> FixupResult<T> {
1495match resolve::deeply_resolve_via_region_graph(self, value) {
1496Ok(value) => {
1497if value.has_non_region_infer() {
1498::rustc_middle::util::bug::bug_fmt(format_args!("`{0:?}` is not fully resolved",
value));bug!("`{value:?}` is not fully resolved");
1499 }
1500if value.has_infer_regions() {
1501let 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"));
1502Ok(fold_regions(self.tcx, value, |re, _| {
1503if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1504 }))
1505 } else {
1506Ok(value)
1507 }
1508 }
1509Err(e) => Err(e),
1510 }
1511 }
15121513// Instantiates the bound variables in a given binder with fresh inference
1514 // variables in the current universe.
1515 //
1516 // Use this method if you'd like to find some generic parameters of the binder's
1517 // variables (e.g. during a method call). If there isn't a [`BoundRegionConversionTime`]
1518 // that corresponds to your use case, consider whether or not you should
1519 // use [`InferCtxt::enter_forall`] instead.
1520pub fn instantiate_binder_with_fresh_vars<T>(
1521&self,
1522 span: Span,
1523 lbrct: BoundRegionConversionTime,
1524 value: ty::Binder<'tcx, T>,
1525 ) -> T
1526where
1527T: TypeFoldable<TyCtxt<'tcx>>,
1528 {
1529if let Some(_) = value.as_ref().no_bound_vars() {
1530return value.skip_binder();
1531 }
15321533let bound_vars = value.bound_vars();
1534let mut args = Vec::with_capacity(bound_vars.len());
15351536for bound_var_kind in bound_vars {
1537let arg: ty::GenericArg<'_> = match bound_var_kind {
1538 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1539 ty::BoundVariableKind::Region(br) => {
1540self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1541 }
1542 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1543 };
1544 args.push(arg);
1545 }
15461547struct ToFreshVars<'tcx> {
1548 args: Vec<ty::GenericArg<'tcx>>,
1549 }
15501551impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1552fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
1553self.args[br.var.index()].expect_region()
1554 }
1555fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
1556self.args[bt.var.index()].expect_ty()
1557 }
1558fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
1559self.args[bc.var.index()].expect_const()
1560 }
1561 }
1562let delegate = ToFreshVars { args };
1563self.tcx.replace_bound_vars_uncached(value, delegate)
1564 }
15651566pub fn insert_placeholder_assumptions(
1567&self,
1568 u: ty::UniverseIndex,
1569 assumptions: Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>>,
1570 ) {
1571if let Some(assumptions) = &assumptions {
1572if !!assumptions.type_outlives.has_escaping_bound_vars() {
{
::core::panicking::panic_fmt(format_args!("assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {0:?}",
assumptions.type_outlives));
}
};assert!(
1573 !assumptions.type_outlives.has_escaping_bound_vars(),
1574"assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1575 assumptions.type_outlives
1576 );
1577if !assumptions.region_outlives.base_edges().all(|r|
!r.has_escaping_bound_vars()) {
{
::core::panicking::panic_fmt(format_args!("assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {0:?}",
assumptions.region_outlives));
}
};assert!(
1578 assumptions.region_outlives.base_edges().all(|r| !r.has_escaping_bound_vars()),
1579"assumptions has escaping bound vars, which is indicative of a bug in how assumptions are handled: {:?}",
1580 assumptions.region_outlives
1581 );
1582 }
1583self.placeholder_assumptions_for_next_solver.borrow_mut().insert(u, assumptions);
1584 }
15851586pub fn get_placeholder_assumptions(
1587&self,
1588 u: ty::UniverseIndex,
1589 ) -> Option<rustc_type_ir::region_constraint::Assumptions<TyCtxt<'tcx>>> {
1590self.placeholder_assumptions_for_next_solver.borrow().get(&u).unwrap().as_ref().cloned()
1591 }
15921593pub fn get_solver_region_constraint(&self) -> SolverRegionConstraint<'tcx> {
1594self.inner.borrow().solver_region_constraint_storage.get_constraint()
1595 }
15961597pub fn overwrite_solver_region_constraint(&self, constraint: SolverRegionConstraint<'tcx>) {
1598if !!constraint.has_escaping_bound_vars() {
{
::core::panicking::panic_fmt(format_args!("solver region constraint has escaping bound vars, which is indicative of a bug in how constraints are handled: {0:?}",
constraint));
}
};assert!(
1599 !constraint.has_escaping_bound_vars(),
1600"solver region constraint has escaping bound vars, which is indicative of a bug in how constraints are handled: {constraint:?}",
1601 );
1602let mut inner = self.inner.borrow_mut();
1603let old_constraint = inner.solver_region_constraint_storage.get_constraint();
1604inner.undo_log.push(UndoLog::OverwriteSolverRegionConstraint { old_constraint });
1605inner.solver_region_constraint_storage.overwrite(constraint);
1606 }
16071608/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1609pub(crate) fn verify_generic_bound(
1610&self,
1611 origin: SubregionOrigin<'tcx>,
1612 kind: GenericKind<'tcx>,
1613 a: ty::Region<'tcx>,
1614 bound: VerifyBound<'tcx>,
1615 ) {
1616{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs:1616",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1616u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("verify_generic_bound({0:?}, {1:?} <: {2:?})",
kind, a, bound) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
16171618self.inner
1619 .borrow_mut()
1620 .unwrap_region_constraints()
1621 .verify_generic_bound(origin, kind, a, bound);
1622 }
16231624/// Obtains the latest type of the given closure; this may be a
1625 /// closure in the current function, in which case its
1626 /// `ClosureKind` may not yet be known.
1627pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1628let unresolved_kind_ty = match *closure_ty.kind() {
1629 ty::Closure(_, args) => args.as_closure().kind_ty(),
1630 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1631_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0}",
closure_ty))bug!("unexpected type {closure_ty}"),
1632 };
1633let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1634closure_kind_ty.to_opt_closure_kind()
1635 }
16361637pub fn universe(&self) -> ty::UniverseIndex {
1638self.universe.get()
1639 }
16401641/// Creates and return a fresh universe that extends all previous
1642 /// universes. Updates `self.universe` to that new universe.
1643pub fn create_next_universe(&self) -> ty::UniverseIndex {
1644let u = self.universe.get().next_universe();
1645{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs:1645",
"rustc_infer::infer", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/215a8af4bb4c106cccf6d6535f84eaae91818265/compiler/rustc_infer/src/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1645u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("create_next_universe {0:?}",
u) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("create_next_universe {u:?}");
1646self.universe.set(u);
1647u1648 }
16491650/// We need to disable the fcw if we're already in a fcw emitting to avoid
1651 /// indefinite triggering.
1652pub fn with_disabled_next_solver_overflow_fcw<F, R>(&self, mut f: F) -> R
1653where
1654F: FnMut() -> R,
1655 {
1656let prev = self.enable_next_solver_overflow_fcw.replace(false);
1657let ret = f();
1658self.enable_next_solver_overflow_fcw.set(prev);
1659ret1660 }
16611662/// Extract [`ty::TypingMode`] of this inference context to get a `TypingEnv`
1663 /// which contains the necessary information to use the trait system without
1664 /// using canonicalization or carrying this inference context around.
1665pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1666let typing_mode = match self.typing_mode_raw() {
1667// FIXME(#132279): This erases the `defining_opaque_types` as it isn't possible
1668 // to handle them without proper canonicalization. This means we may cause cycle
1669 // errors and fail to reveal opaques while inside of bodies. We should rename this
1670 // function and require explicit comments on all use-sites in the future.
1671ty::TypingMode::Typeck { defining_opaque_types_and_generators: _ }
1672 | ty::TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ } => {
1673TypingMode::non_body_analysis()
1674 }
1675 mode @ (ty::TypingMode::Coherence1676 | ty::TypingMode::PostBorrowck { .. }
1677 | ty::TypingMode::PostAnalysis1678 | ty::TypingMode::Reflection1679 | ty::TypingMode::Codegen) => mode,
1680 ty::TypingMode::ErasedNotCoherence(MayBeErased) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1681 };
1682 ty::TypingEnv::new(param_env, typing_mode)
1683 }
16841685/// Similar to [`Self::canonicalize_query`], except that it returns
1686 /// a [`PseudoCanonicalInput`] and requires both the `value` and the
1687 /// `param_env` to not contain any inference variables or placeholders.
1688pub fn pseudo_canonicalize_query<V>(
1689&self,
1690 param_env: ty::ParamEnv<'tcx>,
1691 value: V,
1692 ) -> PseudoCanonicalInput<'tcx, V>
1693where
1694V: TypeVisitable<TyCtxt<'tcx>>,
1695 {
1696if true {
if !!value.has_infer() {
::core::panicking::panic("assertion failed: !value.has_infer()")
};
};debug_assert!(!value.has_infer());
1697if true {
if !!value.has_placeholders() {
::core::panicking::panic("assertion failed: !value.has_placeholders()")
};
};debug_assert!(!value.has_placeholders());
1698if true {
if !!param_env.has_infer() {
::core::panicking::panic("assertion failed: !param_env.has_infer()")
};
};debug_assert!(!param_env.has_infer());
1699if true {
if !!param_env.has_placeholders() {
::core::panicking::panic("assertion failed: !param_env.has_placeholders()")
};
};debug_assert!(!param_env.has_placeholders());
1700self.typing_env(param_env).as_query_input(value)
1701 }
17021703/// The returned function is used in a fast path. If it returns `true` the variable is
1704 /// unchanged, `false` indicates that the status is unknown.
1705#[inline]
1706pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1707// This hoists the borrow/release out of the loop body.
1708let inner = self.inner.try_borrow();
17091710move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1711 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1712use self::type_variable::TypeVariableValue;
17131714#[allow(non_exhaustive_omitted_patterns)] match inner.try_type_variables_probe_ref(ty_var)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1715 inner.try_type_variables_probe_ref(ty_var),
1716Some(TypeVariableValue::Unknown { .. })
1717 )1718 }
1719_ => false,
1720 }
1721 }
17221723/// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1724 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1725 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1726 ///
1727 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1728 /// inlined, despite being large, because it has only two call sites that
1729 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1730 /// inference variables), and it handles both `Ty` and `ty::Const` without
1731 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1732#[inline(always)]
1733pub fn ty_or_const_infer_var_changed(&self, var: TyOrConstInferVar) -> bool {
1734match var {
1735 TyOrConstInferVar::Ty(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().try_type_variables_probe_ref(vid)
{
Some(TypeVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1736self.inner.borrow().try_type_variables_probe_ref(vid),
1737Some(TypeVariableValue::Unknown { .. })
1738 ),
1739 TyOrConstInferVar::TyInt(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().int_unification_storage.try_probe_value(vid)
{
Some(ty::IntVarValue::Unknown) => true,
_ => false,
}matches!(
1740self.inner.borrow().int_unification_storage.try_probe_value(vid),
1741Some(ty::IntVarValue::Unknown)
1742 ),
1743 TyOrConstInferVar::TyFloat(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().float_unification_storage.try_probe_value(vid)
{
Some(ty::FloatVarValue::Unknown) => true,
_ => false,
}matches!(
1744self.inner.borrow().float_unification_storage.try_probe_value(vid),
1745Some(ty::FloatVarValue::Unknown)
1746 ),
1747 TyOrConstInferVar::Const(vid) => !#[allow(non_exhaustive_omitted_patterns)] match self.inner.borrow().const_unification_storage.try_probe_value(vid)
{
Some(ConstVariableValue::Unknown { .. }) => true,
_ => false,
}matches!(
1748self.inner.borrow().const_unification_storage.try_probe_value(vid),
1749Some(ConstVariableValue::Unknown { .. })
1750 ),
1751 }
1752 }
17531754/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
1755pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1756if true {
if !self.obligation_inspector.get().is_none() {
{
::core::panicking::panic_fmt(format_args!("shouldn\'t override a set obligation inspector"));
}
};
};debug_assert!(
1757self.obligation_inspector.get().is_none(),
1758"shouldn't override a set obligation inspector"
1759);
1760self.obligation_inspector.set(Some(inspector));
1761 }
1762}
17631764/// Replace `{integer}` with `i32` and `{float}` with `f64`.
1765/// Used only for diagnostics.
1766struct InferenceLiteralEraser<'tcx> {
1767 tcx: TyCtxt<'tcx>,
1768}
17691770impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1771fn cx(&self) -> TyCtxt<'tcx> {
1772self.tcx
1773 }
17741775fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1776match ty.kind() {
1777 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1778 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1779_ => ty.super_fold_with(self),
1780 }
1781 }
1782}
17831784impl<'tcx> TypeTrace<'tcx> {
1785pub fn span(&self) -> Span {
1786self.cause.span
1787 }
17881789pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1790TypeTrace {
1791 cause: cause.clone(),
1792 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1793 }
1794 }
17951796pub fn trait_refs(
1797 cause: &ObligationCause<'tcx>,
1798 a: ty::TraitRef<'tcx>,
1799 b: ty::TraitRef<'tcx>,
1800 ) -> TypeTrace<'tcx> {
1801TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1802 }
18031804pub fn consts(
1805 cause: &ObligationCause<'tcx>,
1806 a: ty::Const<'tcx>,
1807 b: ty::Const<'tcx>,
1808 ) -> TypeTrace<'tcx> {
1809TypeTrace {
1810 cause: cause.clone(),
1811 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1812 }
1813 }
1814}
18151816impl<'tcx> SubregionOrigin<'tcx> {
1817pub fn span(&self) -> Span {
1818match *self {
1819 SubregionOrigin::Subtype(ref a) => a.span(),
1820 SubregionOrigin::RelateObjectBound(a) => a,
1821 SubregionOrigin::RelateParamBound(a, ..) => a,
1822 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1823 SubregionOrigin::Reborrow(a) => a,
1824 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1825 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1826 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1827 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1828 SubregionOrigin::SolverRegionConstraint(a) => a,
1829 }
1830 }
18311832pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1833where
1834F: FnOnce() -> Self,
1835 {
1836match *cause.code() {
1837 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1838 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1839 }
18401841 traits::ObligationCauseCode::CompareImplItem {
1842 impl_item_def_id,
1843 trait_item_def_id,
1844 kind: _,
1845 } => SubregionOrigin::CompareImplItemObligation {
1846 span: cause.span,
1847impl_item_def_id,
1848trait_item_def_id,
1849 },
18501851 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1852 impl_item_def_id,
1853 trait_item_def_id,
1854 } => SubregionOrigin::CheckAssociatedTypeBounds {
1855impl_item_def_id,
1856trait_item_def_id,
1857 parent: Box::new(default()),
1858 },
18591860 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1861 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1862 }
18631864 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1865 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1866 }
18671868_ => default(),
1869 }
1870 }
1871}
18721873impl<'tcx> RegionVariableOrigin<'tcx> {
1874pub fn span(&self) -> Span {
1875match *self {
1876 RegionVariableOrigin::Misc(a)
1877 | RegionVariableOrigin::PatternRegion(a)
1878 | RegionVariableOrigin::BorrowRegion(a)
1879 | RegionVariableOrigin::Autoref(a)
1880 | RegionVariableOrigin::Coercion(a)
1881 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1882 | RegionVariableOrigin::BoundRegion(a, ..)
1883 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1884 RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable used with `span`"))bug!("NLL variable used with `span`"),
1885 }
1886 }
1887}
18881889impl<'tcx> InferCtxt<'tcx> {
1890/// Given a [`hir::Block`], get the span of its last expression or
1891 /// statement, peeling off any inner blocks.
1892pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1893let block = block.innermost_block();
1894if let Some(expr) = &block.expr {
1895expr.span
1896 } else if let Some(stmt) = block.stmts.last() {
1897// possibly incorrect trailing `;` in the else arm
1898stmt.span
1899 } else {
1900// empty block; point at its entirety
1901block.span
1902 }
1903 }
19041905/// Given a [`hir::HirId`] for a block (or an expr of a block), get the span
1906 /// of its last expression or statement, peeling off any inner blocks.
1907pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1908match self.tcx.hir_node(hir_id) {
1909 hir::Node::Block(blk)
1910 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1911self.find_block_span(blk)
1912 }
1913 hir::Node::Expr(e) => e.span,
1914_ => DUMMY_SP,
1915 }
1916 }
1917}
19181919/// Returns unresolved root variables from `table`, according to `is_unresolved`.
1920fn unresolved_root_variables_of<V: UnifyKey>(
1921mut table: UnificationTable<'_, '_, V>,
1922 is_unresolved: impl Fn(V::Value) -> bool,
1923) -> Vec<V>
1924where
1925V: Eq,
1926 V::Value: UnifyValue,
1927for<'a> UndoLog<'a>: From<sv::UndoLog<ut::Delegate<V>>>,
1928{
1929 (0..table.len() as u32)
1930 .map(V::from_index)
1931 .filter(|&vid| {
1932// NB: as of writing this `ena` doesn't provide a non-inlined `probe_key_value`...
1933let (root, value) = table.inlined_probe_key_value(vid);
1934root == vid && is_unresolved(value)
1935 })
1936 .collect()
1937}