1use std::cell::{Cell, RefCell};
2use std::fmt;
3
4pub use BoundRegionConversionTime::*;
5pub use RegionVariableOrigin::*;
6pub use SubregionOrigin::*;
7pub use at::DefineOpaqueTypes;
8use free_regions::RegionRelations;
9pub use freshen::TypeFreshener;
10use lexical_region_resolve::LexicalRegionResolutions;
11pub use lexical_region_resolve::RegionResolutionError;
12use opaque_types::OpaqueTypeStorage;
13use region_constraints::{
14 GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
15};
16pub use relate::StructurallyRelateAliases;
17pub use relate::combine::PredicateEmittingRelation;
18use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
19use rustc_data_structures::undo_log::{Rollback, UndoLogs};
20use rustc_data_structures::unify as ut;
21use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
22use rustc_hir as hir;
23use rustc_hir::def_id::{DefId, LocalDefId};
24use rustc_macros::extension;
25pub use rustc_macros::{TypeFoldable, TypeVisitable};
26use rustc_middle::bug;
27use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
28use rustc_middle::mir::ConstraintCategory;
29use rustc_middle::traits::select;
30use rustc_middle::ty::error::{ExpectedFound, TypeError};
31use rustc_middle::ty::{
32 self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
33 GenericArgsRef, GenericParamDefKind, InferConst, IntVid, PseudoCanonicalInput, Ty, TyCtxt,
34 TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv,
35 TypingMode, fold_regions,
36};
37use rustc_span::{Span, Symbol};
38use snapshot::undo_log::InferCtxtUndoLogs;
39use tracing::{debug, instrument};
40use type_variable::TypeVariableOrigin;
41
42use crate::infer::region_constraints::UndoLog;
43use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
44use crate::traits::{
45 self, ObligationCause, ObligationInspector, PredicateObligations, TraitEngine,
46};
47
48pub mod at;
49pub mod canonical;
50mod context;
51mod free_regions;
52mod freshen;
53mod lexical_region_resolve;
54mod opaque_types;
55pub mod outlives;
56mod projection;
57pub mod region_constraints;
58pub mod relate;
59pub mod resolve;
60pub(crate) mod snapshot;
61mod type_variable;
62mod unify_key;
63
64#[must_use]
72#[derive(Debug)]
73pub struct InferOk<'tcx, T> {
74 pub value: T,
75 pub obligations: PredicateObligations<'tcx>,
76}
77pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
78
79pub(crate) type FixupResult<T> = Result<T, FixupError>; pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
82 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
83>;
84
85#[derive(Clone)]
90pub struct InferCtxtInner<'tcx> {
91 undo_log: InferCtxtUndoLogs<'tcx>,
92
93 projection_cache: traits::ProjectionCacheStorage<'tcx>,
97
98 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
102
103 const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
105
106 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
108
109 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
111
112 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
119
120 region_obligations: Vec<RegionObligation<'tcx>>,
153
154 opaque_type_storage: OpaqueTypeStorage<'tcx>,
156}
157
158impl<'tcx> InferCtxtInner<'tcx> {
159 fn new() -> InferCtxtInner<'tcx> {
160 InferCtxtInner {
161 undo_log: InferCtxtUndoLogs::default(),
162
163 projection_cache: Default::default(),
164 type_variable_storage: Default::default(),
165 const_unification_storage: Default::default(),
166 int_unification_storage: Default::default(),
167 float_unification_storage: Default::default(),
168 region_constraint_storage: Some(Default::default()),
169 region_obligations: vec![],
170 opaque_type_storage: Default::default(),
171 }
172 }
173
174 #[inline]
175 pub fn region_obligations(&self) -> &[RegionObligation<'tcx>] {
176 &self.region_obligations
177 }
178
179 #[inline]
180 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
181 self.projection_cache.with_log(&mut self.undo_log)
182 }
183
184 #[inline]
185 fn try_type_variables_probe_ref(
186 &self,
187 vid: ty::TyVid,
188 ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
189 self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
192 }
193
194 #[inline]
195 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
196 self.type_variable_storage.with_log(&mut self.undo_log)
197 }
198
199 #[inline]
200 fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
201 self.opaque_type_storage.with_log(&mut self.undo_log)
202 }
203
204 #[inline]
205 fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
206 self.int_unification_storage.with_log(&mut self.undo_log)
207 }
208
209 #[inline]
210 fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
211 self.float_unification_storage.with_log(&mut self.undo_log)
212 }
213
214 #[inline]
215 fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
216 self.const_unification_storage.with_log(&mut self.undo_log)
217 }
218
219 #[inline]
220 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
221 self.region_constraint_storage
222 .as_mut()
223 .expect("region constraints already solved")
224 .with_log(&mut self.undo_log)
225 }
226
227 pub fn iter_opaque_types(
231 &self,
232 ) -> impl Iterator<Item = (ty::OpaqueTypeKey<'tcx>, ty::OpaqueHiddenType<'tcx>)> {
233 self.opaque_type_storage.opaque_types.iter().map(|(&k, &v)| (k, v))
234 }
235}
236
237pub struct InferCtxt<'tcx> {
238 pub tcx: TyCtxt<'tcx>,
239
240 typing_mode: TypingMode<'tcx>,
243
244 pub considering_regions: bool,
248
249 skip_leak_check: bool,
254
255 pub inner: RefCell<InferCtxtInner<'tcx>>,
256
257 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
259
260 pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
263
264 pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
267
268 pub reported_trait_errors:
271 RefCell<FxIndexMap<Span, (Vec<ty::Predicate<'tcx>>, ErrorGuaranteed)>>,
272
273 pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
274
275 tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
283
284 universe: Cell<ty::UniverseIndex>,
294
295 next_trait_solver: bool,
296
297 pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
298}
299
300#[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
302pub enum ValuePairs<'tcx> {
303 Regions(ExpectedFound<ty::Region<'tcx>>),
304 Terms(ExpectedFound<ty::Term<'tcx>>),
305 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
306 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
307 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
308 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
309 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
310}
311
312impl<'tcx> ValuePairs<'tcx> {
313 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
314 if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
315 && let Some(expected) = expected.as_type()
316 && let Some(found) = found.as_type()
317 {
318 Some((expected, found))
319 } else {
320 None
321 }
322 }
323}
324
325#[derive(Clone, Debug)]
330pub struct TypeTrace<'tcx> {
331 pub cause: ObligationCause<'tcx>,
332 pub values: ValuePairs<'tcx>,
333}
334
335#[derive(Clone, Debug)]
339pub enum SubregionOrigin<'tcx> {
340 Subtype(Box<TypeTrace<'tcx>>),
342
343 RelateObjectBound(Span),
346
347 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
350
351 RelateRegionParamBound(Span, Option<Ty<'tcx>>),
354
355 Reborrow(Span),
357
358 ReferenceOutlivesReferent(Ty<'tcx>, Span),
360
361 CompareImplItemObligation {
364 span: Span,
365 impl_item_def_id: LocalDefId,
366 trait_item_def_id: DefId,
367 },
368
369 CheckAssociatedTypeBounds {
371 parent: Box<SubregionOrigin<'tcx>>,
372 impl_item_def_id: LocalDefId,
373 trait_item_def_id: DefId,
374 },
375
376 AscribeUserTypeProvePredicate(Span),
377}
378
379#[cfg(target_pointer_width = "64")]
381rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
382
383impl<'tcx> SubregionOrigin<'tcx> {
384 pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
385 match self {
386 Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
387 Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
388 _ => ConstraintCategory::BoringNoLocation,
389 }
390 }
391}
392
393#[derive(Clone, Copy, Debug)]
395pub enum BoundRegionConversionTime {
396 FnCall,
398
399 HigherRankedType,
401
402 AssocTypeProjection(DefId),
404}
405
406#[derive(Copy, Clone, Debug)]
410pub enum RegionVariableOrigin {
411 MiscVariable(Span),
415
416 PatternRegion(Span),
418
419 BorrowRegion(Span),
421
422 Autoref(Span),
424
425 Coercion(Span),
427
428 RegionParameterDefinition(Span, Symbol),
433
434 BoundRegion(Span, ty::BoundRegionKind, BoundRegionConversionTime),
437
438 UpvarRegion(ty::UpvarId, Span),
439
440 Nll(NllRegionVariableOrigin),
443}
444
445#[derive(Copy, Clone, Debug)]
446pub enum NllRegionVariableOrigin {
447 FreeRegion,
451
452 Placeholder(ty::PlaceholderRegion),
455
456 Existential {
457 from_forall: bool,
468 },
469}
470
471#[derive(Copy, Clone, Debug)]
472pub struct FixupError {
473 unresolved: TyOrConstInferVar,
474}
475
476impl fmt::Display for FixupError {
477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478 use TyOrConstInferVar::*;
479
480 match self.unresolved {
481 TyInt(_) => write!(
482 f,
483 "cannot determine the type of this integer; \
484 add a suffix to specify the type explicitly"
485 ),
486 TyFloat(_) => write!(
487 f,
488 "cannot determine the type of this number; \
489 add a suffix to specify the type explicitly"
490 ),
491 Ty(_) => write!(f, "unconstrained type"),
492 Const(_) => write!(f, "unconstrained const value"),
493 }
494 }
495}
496
497#[derive(Clone, Debug)]
499pub struct RegionObligation<'tcx> {
500 pub sub_region: ty::Region<'tcx>,
501 pub sup_type: Ty<'tcx>,
502 pub origin: SubregionOrigin<'tcx>,
503}
504
505pub struct InferCtxtBuilder<'tcx> {
507 tcx: TyCtxt<'tcx>,
508 considering_regions: bool,
509 skip_leak_check: bool,
510 next_trait_solver: bool,
513}
514
515#[extension(pub trait TyCtxtInferExt<'tcx>)]
516impl<'tcx> TyCtxt<'tcx> {
517 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
518 InferCtxtBuilder {
519 tcx: self,
520 considering_regions: true,
521 skip_leak_check: false,
522 next_trait_solver: self.next_trait_solver_globally(),
523 }
524 }
525}
526
527impl<'tcx> InferCtxtBuilder<'tcx> {
528 pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
529 self.next_trait_solver = next_trait_solver;
530 self
531 }
532
533 pub fn ignoring_regions(mut self) -> Self {
534 self.considering_regions = false;
535 self
536 }
537
538 pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
539 self.skip_leak_check = skip_leak_check;
540 self
541 }
542
543 pub fn build_with_canonical<T>(
551 mut self,
552 span: Span,
553 input: &CanonicalQueryInput<'tcx, T>,
554 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
555 where
556 T: TypeFoldable<TyCtxt<'tcx>>,
557 {
558 let infcx = self.build(input.typing_mode);
559 let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
560 (infcx, value, args)
561 }
562
563 pub fn build_with_typing_env(
564 mut self,
565 TypingEnv { typing_mode, param_env }: TypingEnv<'tcx>,
566 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
567 (self.build(typing_mode), param_env)
568 }
569
570 pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
571 let InferCtxtBuilder { tcx, considering_regions, skip_leak_check, next_trait_solver } =
572 *self;
573 InferCtxt {
574 tcx,
575 typing_mode,
576 considering_regions,
577 skip_leak_check,
578 inner: RefCell::new(InferCtxtInner::new()),
579 lexical_region_resolutions: RefCell::new(None),
580 selection_cache: Default::default(),
581 evaluation_cache: Default::default(),
582 reported_trait_errors: Default::default(),
583 reported_signature_mismatch: Default::default(),
584 tainted_by_errors: Cell::new(None),
585 universe: Cell::new(ty::UniverseIndex::ROOT),
586 next_trait_solver,
587 obligation_inspector: Cell::new(None),
588 }
589 }
590}
591
592impl<'tcx, T> InferOk<'tcx, T> {
593 pub fn into_value_registering_obligations<E: 'tcx>(
595 self,
596 infcx: &InferCtxt<'tcx>,
597 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
598 ) -> T {
599 let InferOk { value, obligations } = self;
600 fulfill_cx.register_predicate_obligations(infcx, obligations);
601 value
602 }
603}
604
605impl<'tcx> InferOk<'tcx, ()> {
606 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
607 self.obligations
608 }
609}
610
611impl<'tcx> InferCtxt<'tcx> {
612 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
613 self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
614 }
615
616 pub fn next_trait_solver(&self) -> bool {
617 self.next_trait_solver
618 }
619
620 #[inline(always)]
621 pub fn typing_mode(&self) -> TypingMode<'tcx> {
622 self.typing_mode
623 }
624
625 pub fn freshen<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> T {
626 t.fold_with(&mut self.freshener())
627 }
628
629 pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
633 self.inner.borrow_mut().type_variables().var_origin(vid)
634 }
635
636 pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
640 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
641 ConstVariableValue::Known { .. } => None,
642 ConstVariableValue::Unknown { origin, .. } => Some(origin),
643 }
644 }
645
646 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
647 freshen::TypeFreshener::new(self)
648 }
649
650 pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
651 let mut inner = self.inner.borrow_mut();
652 let mut vars: Vec<Ty<'_>> = inner
653 .type_variables()
654 .unresolved_variables()
655 .into_iter()
656 .map(|t| Ty::new_var(self.tcx, t))
657 .collect();
658 vars.extend(
659 (0..inner.int_unification_table().len())
660 .map(|i| ty::IntVid::from_usize(i))
661 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
662 .map(|v| Ty::new_int_var(self.tcx, v)),
663 );
664 vars.extend(
665 (0..inner.float_unification_table().len())
666 .map(|i| ty::FloatVid::from_usize(i))
667 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
668 .map(|v| Ty::new_float_var(self.tcx, v)),
669 );
670 vars
671 }
672
673 #[instrument(skip(self), level = "debug")]
674 pub fn sub_regions(
675 &self,
676 origin: SubregionOrigin<'tcx>,
677 a: ty::Region<'tcx>,
678 b: ty::Region<'tcx>,
679 ) {
680 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
681 }
682
683 pub fn coerce_predicate(
699 &self,
700 cause: &ObligationCause<'tcx>,
701 param_env: ty::ParamEnv<'tcx>,
702 predicate: ty::PolyCoercePredicate<'tcx>,
703 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
704 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
705 a_is_expected: false, a: p.a,
707 b: p.b,
708 });
709 self.subtype_predicate(cause, param_env, subtype_predicate)
710 }
711
712 pub fn subtype_predicate(
713 &self,
714 cause: &ObligationCause<'tcx>,
715 param_env: ty::ParamEnv<'tcx>,
716 predicate: ty::PolySubtypePredicate<'tcx>,
717 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
718 let r_a = self.shallow_resolve(predicate.skip_binder().a);
732 let r_b = self.shallow_resolve(predicate.skip_binder().b);
733 match (r_a.kind(), r_b.kind()) {
734 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
735 return Err((a_vid, b_vid));
736 }
737 _ => {}
738 }
739
740 self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
741 if a_is_expected {
742 Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
743 } else {
744 Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
745 }
746 })
747 }
748
749 pub fn region_outlives_predicate(
750 &self,
751 cause: &traits::ObligationCause<'tcx>,
752 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
753 ) {
754 self.enter_forall(predicate, |ty::OutlivesPredicate(r_a, r_b)| {
755 let origin = SubregionOrigin::from_obligation_cause(cause, || {
756 RelateRegionParamBound(cause.span, None)
757 });
758 self.sub_regions(origin, r_b, r_a); })
760 }
761
762 pub fn num_ty_vars(&self) -> usize {
764 self.inner.borrow_mut().type_variables().num_vars()
765 }
766
767 pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
768 self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
769 }
770
771 pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
772 let vid = self.inner.borrow_mut().type_variables().new_var(self.universe(), origin);
773 Ty::new_var(self.tcx, vid)
774 }
775
776 pub fn next_ty_var_id_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
777 let origin = TypeVariableOrigin { span, param_def_id: None };
778 self.inner.borrow_mut().type_variables().new_var(universe, origin)
779 }
780
781 pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
782 let vid = self.next_ty_var_id_in_universe(span, universe);
783 Ty::new_var(self.tcx, vid)
784 }
785
786 pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
787 self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
788 }
789
790 pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
791 let vid = self
792 .inner
793 .borrow_mut()
794 .const_unification_table()
795 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
796 .vid;
797 ty::Const::new_var(self.tcx, vid)
798 }
799
800 pub fn next_const_var_in_universe(
801 &self,
802 span: Span,
803 universe: ty::UniverseIndex,
804 ) -> ty::Const<'tcx> {
805 let origin = ConstVariableOrigin { span, param_def_id: None };
806 let vid = self
807 .inner
808 .borrow_mut()
809 .const_unification_table()
810 .new_key(ConstVariableValue::Unknown { origin, universe })
811 .vid;
812 ty::Const::new_var(self.tcx, vid)
813 }
814
815 pub fn next_int_var(&self) -> Ty<'tcx> {
816 let next_int_var_id =
817 self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
818 Ty::new_int_var(self.tcx, next_int_var_id)
819 }
820
821 pub fn next_float_var(&self) -> Ty<'tcx> {
822 let next_float_var_id =
823 self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown);
824 Ty::new_float_var(self.tcx, next_float_var_id)
825 }
826
827 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
831 self.next_region_var_in_universe(origin, self.universe())
832 }
833
834 pub fn next_region_var_in_universe(
838 &self,
839 origin: RegionVariableOrigin,
840 universe: ty::UniverseIndex,
841 ) -> ty::Region<'tcx> {
842 let region_var =
843 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
844 ty::Region::new_var(self.tcx, region_var)
845 }
846
847 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
853 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
854 }
855
856 pub fn num_region_vars(&self) -> usize {
858 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
859 }
860
861 #[instrument(skip(self), level = "debug")]
863 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
864 self.next_region_var(RegionVariableOrigin::Nll(origin))
865 }
866
867 #[instrument(skip(self), level = "debug")]
869 pub fn next_nll_region_var_in_universe(
870 &self,
871 origin: NllRegionVariableOrigin,
872 universe: ty::UniverseIndex,
873 ) -> ty::Region<'tcx> {
874 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
875 }
876
877 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
878 match param.kind {
879 GenericParamDefKind::Lifetime => {
880 self.next_region_var(RegionParameterDefinition(span, param.name)).into()
883 }
884 GenericParamDefKind::Type { .. } => {
885 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
894 self.universe(),
895 TypeVariableOrigin { param_def_id: Some(param.def_id), span },
896 );
897
898 Ty::new_var(self.tcx, ty_var_id).into()
899 }
900 GenericParamDefKind::Const { .. } => {
901 let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
902 let const_var_id = self
903 .inner
904 .borrow_mut()
905 .const_unification_table()
906 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
907 .vid;
908 ty::Const::new_var(self.tcx, const_var_id).into()
909 }
910 }
911 }
912
913 pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
916 GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
917 }
918
919 #[must_use = "this method does not have any side effects"]
925 pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
926 self.tainted_by_errors.get()
927 }
928
929 pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
932 debug!("set_tainted_by_errors(ErrorGuaranteed)");
933 self.tainted_by_errors.set(Some(e));
934 }
935
936 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
937 let mut inner = self.inner.borrow_mut();
938 let inner = &mut *inner;
939 inner.unwrap_region_constraints().var_origin(vid)
940 }
941
942 pub fn get_region_var_infos(&self) -> VarInfos {
945 let inner = self.inner.borrow();
946 assert!(!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log));
947 let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
948 assert!(storage.data.is_empty(), "{:#?}", storage.data);
949 storage.var_infos.clone()
953 }
954
955 #[instrument(level = "debug", skip(self), ret)]
956 pub fn take_opaque_types(&self) -> opaque_types::OpaqueTypeMap<'tcx> {
957 std::mem::take(&mut self.inner.borrow_mut().opaque_type_storage.opaque_types)
958 }
959
960 #[instrument(level = "debug", skip(self), ret)]
961 pub fn clone_opaque_types(&self) -> opaque_types::OpaqueTypeMap<'tcx> {
962 self.inner.borrow().opaque_type_storage.opaque_types.clone()
963 }
964
965 #[inline(always)]
966 pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
967 debug_assert!(!self.next_trait_solver());
968 match self.typing_mode() {
969 TypingMode::Analysis { defining_opaque_types } => {
970 id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
971 }
972 TypingMode::Coherence
976 | TypingMode::PostBorrowckAnalysis { .. }
977 | TypingMode::PostAnalysis => false,
978 }
979 }
980
981 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
982 self.resolve_vars_if_possible(t).to_string()
983 }
984
985 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
988 use self::type_variable::TypeVariableValue;
989
990 match self.inner.borrow_mut().type_variables().probe(vid) {
991 TypeVariableValue::Known { value } => Ok(value),
992 TypeVariableValue::Unknown { universe } => Err(universe),
993 }
994 }
995
996 pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
997 if let ty::Infer(v) = *ty.kind() {
998 match v {
999 ty::TyVar(v) => {
1000 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1013 known.map_or(ty, |t| self.shallow_resolve(t))
1014 }
1015
1016 ty::IntVar(v) => {
1017 match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1018 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1019 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1020 ty::IntVarValue::Unknown => ty,
1021 }
1022 }
1023
1024 ty::FloatVar(v) => {
1025 match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1026 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1027 ty::FloatVarValue::Unknown => ty,
1028 }
1029 }
1030
1031 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1032 }
1033 } else {
1034 ty
1035 }
1036 }
1037
1038 pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1039 match ct.kind() {
1040 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1041 InferConst::Var(vid) => self
1042 .inner
1043 .borrow_mut()
1044 .const_unification_table()
1045 .probe_value(vid)
1046 .known()
1047 .unwrap_or(ct),
1048 InferConst::Fresh(_) => ct,
1049 },
1050 ty::ConstKind::Param(_)
1051 | ty::ConstKind::Bound(_, _)
1052 | ty::ConstKind::Placeholder(_)
1053 | ty::ConstKind::Unevaluated(_)
1054 | ty::ConstKind::Value(_)
1055 | ty::ConstKind::Error(_)
1056 | ty::ConstKind::Expr(_) => ct,
1057 }
1058 }
1059
1060 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1061 self.inner.borrow_mut().type_variables().root_var(var)
1062 }
1063
1064 pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1065 self.inner.borrow_mut().const_unification_table().find(var).vid
1066 }
1067
1068 pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1071 let mut inner = self.inner.borrow_mut();
1072 let value = inner.int_unification_table().probe_value(vid);
1073 match value {
1074 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1075 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1076 ty::IntVarValue::Unknown => {
1077 Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1078 }
1079 }
1080 }
1081
1082 pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1085 let mut inner = self.inner.borrow_mut();
1086 let value = inner.float_unification_table().probe_value(vid);
1087 match value {
1088 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1089 ty::FloatVarValue::Unknown => {
1090 Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1091 }
1092 }
1093 }
1094
1095 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1102 where
1103 T: TypeFoldable<TyCtxt<'tcx>>,
1104 {
1105 if let Err(guar) = value.error_reported() {
1106 self.set_tainted_by_errors(guar);
1107 }
1108 if !value.has_non_region_infer() {
1109 return value;
1110 }
1111 let mut r = resolve::OpportunisticVarResolver::new(self);
1112 value.fold_with(&mut r)
1113 }
1114
1115 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1116 where
1117 T: TypeFoldable<TyCtxt<'tcx>>,
1118 {
1119 if !value.has_infer() {
1120 return value; }
1122 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1123 value.fold_with(&mut r)
1124 }
1125
1126 pub fn probe_const_var(&self, vid: ty::ConstVid) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1127 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1128 ConstVariableValue::Known { value } => Ok(value),
1129 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1130 }
1131 }
1132
1133 pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1141 match resolve::fully_resolve(self, value) {
1142 Ok(value) => {
1143 if value.has_non_region_infer() {
1144 bug!("`{value:?}` is not fully resolved");
1145 }
1146 if value.has_infer_regions() {
1147 let guar = self.dcx().delayed_bug(format!("`{value:?}` is not fully resolved"));
1148 Ok(fold_regions(self.tcx, value, |re, _| {
1149 if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1150 }))
1151 } else {
1152 Ok(value)
1153 }
1154 }
1155 Err(e) => Err(e),
1156 }
1157 }
1158
1159 pub fn instantiate_binder_with_fresh_vars<T>(
1167 &self,
1168 span: Span,
1169 lbrct: BoundRegionConversionTime,
1170 value: ty::Binder<'tcx, T>,
1171 ) -> T
1172 where
1173 T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1174 {
1175 if let Some(inner) = value.no_bound_vars() {
1176 return inner;
1177 }
1178
1179 let bound_vars = value.bound_vars();
1180 let mut args = Vec::with_capacity(bound_vars.len());
1181
1182 for bound_var_kind in bound_vars {
1183 let arg: ty::GenericArg<'_> = match bound_var_kind {
1184 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1185 ty::BoundVariableKind::Region(br) => {
1186 self.next_region_var(BoundRegion(span, br, lbrct)).into()
1187 }
1188 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1189 };
1190 args.push(arg);
1191 }
1192
1193 struct ToFreshVars<'tcx> {
1194 args: Vec<ty::GenericArg<'tcx>>,
1195 }
1196
1197 impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1198 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1199 self.args[br.var.index()].expect_region()
1200 }
1201 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1202 self.args[bt.var.index()].expect_ty()
1203 }
1204 fn replace_const(&mut self, bv: ty::BoundVar) -> ty::Const<'tcx> {
1205 self.args[bv.index()].expect_const()
1206 }
1207 }
1208 let delegate = ToFreshVars { args };
1209 self.tcx.replace_bound_vars_uncached(value, delegate)
1210 }
1211
1212 pub(crate) fn verify_generic_bound(
1214 &self,
1215 origin: SubregionOrigin<'tcx>,
1216 kind: GenericKind<'tcx>,
1217 a: ty::Region<'tcx>,
1218 bound: VerifyBound<'tcx>,
1219 ) {
1220 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1221
1222 self.inner
1223 .borrow_mut()
1224 .unwrap_region_constraints()
1225 .verify_generic_bound(origin, kind, a, bound);
1226 }
1227
1228 pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1232 let unresolved_kind_ty = match *closure_ty.kind() {
1233 ty::Closure(_, args) => args.as_closure().kind_ty(),
1234 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1235 _ => bug!("unexpected type {closure_ty}"),
1236 };
1237 let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1238 closure_kind_ty.to_opt_closure_kind()
1239 }
1240
1241 pub fn universe(&self) -> ty::UniverseIndex {
1242 self.universe.get()
1243 }
1244
1245 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1248 let u = self.universe.get().next_universe();
1249 debug!("create_next_universe {u:?}");
1250 self.universe.set(u);
1251 u
1252 }
1253
1254 pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1258 let typing_mode = match self.typing_mode() {
1259 ty::TypingMode::Analysis { defining_opaque_types: _ } => {
1264 TypingMode::non_body_analysis()
1265 }
1266 mode @ (ty::TypingMode::Coherence
1267 | ty::TypingMode::PostBorrowckAnalysis { .. }
1268 | ty::TypingMode::PostAnalysis) => mode,
1269 };
1270 ty::TypingEnv { typing_mode, param_env }
1271 }
1272
1273 pub fn pseudo_canonicalize_query<V>(
1277 &self,
1278 param_env: ty::ParamEnv<'tcx>,
1279 value: V,
1280 ) -> PseudoCanonicalInput<'tcx, V>
1281 where
1282 V: TypeVisitable<TyCtxt<'tcx>>,
1283 {
1284 debug_assert!(!value.has_infer());
1285 debug_assert!(!value.has_placeholders());
1286 debug_assert!(!param_env.has_infer());
1287 debug_assert!(!param_env.has_placeholders());
1288 self.typing_env(param_env).as_query_input(value)
1289 }
1290
1291 #[inline]
1294 pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1295 let inner = self.inner.try_borrow();
1297
1298 move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1299 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1300 use self::type_variable::TypeVariableValue;
1301
1302 matches!(
1303 inner.try_type_variables_probe_ref(ty_var),
1304 Some(TypeVariableValue::Unknown { .. })
1305 )
1306 }
1307 _ => false,
1308 }
1309 }
1310
1311 #[inline(always)]
1321 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1322 match infer_var {
1323 TyOrConstInferVar::Ty(v) => {
1324 use self::type_variable::TypeVariableValue;
1325
1326 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1329 TypeVariableValue::Unknown { .. } => false,
1330 TypeVariableValue::Known { .. } => true,
1331 }
1332 }
1333
1334 TyOrConstInferVar::TyInt(v) => {
1335 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1339 }
1340
1341 TyOrConstInferVar::TyFloat(v) => {
1342 self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1347 }
1348
1349 TyOrConstInferVar::Const(v) => {
1350 match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1355 ConstVariableValue::Unknown { .. } => false,
1356 ConstVariableValue::Known { .. } => true,
1357 }
1358 }
1359 }
1360 }
1361
1362 pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1364 debug_assert!(
1365 self.obligation_inspector.get().is_none(),
1366 "shouldn't override a set obligation inspector"
1367 );
1368 self.obligation_inspector.set(Some(inspector));
1369 }
1370}
1371
1372#[derive(Copy, Clone, Debug)]
1375pub enum TyOrConstInferVar {
1376 Ty(TyVid),
1378 TyInt(IntVid),
1380 TyFloat(FloatVid),
1382
1383 Const(ConstVid),
1385}
1386
1387impl<'tcx> TyOrConstInferVar {
1388 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1392 match arg.unpack() {
1393 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1394 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1395 GenericArgKind::Lifetime(_) => None,
1396 }
1397 }
1398
1399 fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1402 match *ty.kind() {
1403 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1404 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1405 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1406 _ => None,
1407 }
1408 }
1409
1410 fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1413 match ct.kind() {
1414 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1415 _ => None,
1416 }
1417 }
1418}
1419
1420struct InferenceLiteralEraser<'tcx> {
1423 tcx: TyCtxt<'tcx>,
1424}
1425
1426impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1427 fn cx(&self) -> TyCtxt<'tcx> {
1428 self.tcx
1429 }
1430
1431 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1432 match ty.kind() {
1433 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1434 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1435 _ => ty.super_fold_with(self),
1436 }
1437 }
1438}
1439
1440impl<'tcx> TypeTrace<'tcx> {
1441 pub fn span(&self) -> Span {
1442 self.cause.span
1443 }
1444
1445 pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1446 TypeTrace {
1447 cause: cause.clone(),
1448 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1449 }
1450 }
1451
1452 pub fn trait_refs(
1453 cause: &ObligationCause<'tcx>,
1454 a: ty::TraitRef<'tcx>,
1455 b: ty::TraitRef<'tcx>,
1456 ) -> TypeTrace<'tcx> {
1457 TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1458 }
1459
1460 pub fn consts(
1461 cause: &ObligationCause<'tcx>,
1462 a: ty::Const<'tcx>,
1463 b: ty::Const<'tcx>,
1464 ) -> TypeTrace<'tcx> {
1465 TypeTrace {
1466 cause: cause.clone(),
1467 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1468 }
1469 }
1470}
1471
1472impl<'tcx> SubregionOrigin<'tcx> {
1473 pub fn span(&self) -> Span {
1474 match *self {
1475 Subtype(ref a) => a.span(),
1476 RelateObjectBound(a) => a,
1477 RelateParamBound(a, ..) => a,
1478 RelateRegionParamBound(a, _) => a,
1479 Reborrow(a) => a,
1480 ReferenceOutlivesReferent(_, a) => a,
1481 CompareImplItemObligation { span, .. } => span,
1482 AscribeUserTypeProvePredicate(span) => span,
1483 CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1484 }
1485 }
1486
1487 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1488 where
1489 F: FnOnce() -> Self,
1490 {
1491 match *cause.code() {
1492 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1493 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1494 }
1495
1496 traits::ObligationCauseCode::CompareImplItem {
1497 impl_item_def_id,
1498 trait_item_def_id,
1499 kind: _,
1500 } => SubregionOrigin::CompareImplItemObligation {
1501 span: cause.span,
1502 impl_item_def_id,
1503 trait_item_def_id,
1504 },
1505
1506 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1507 impl_item_def_id,
1508 trait_item_def_id,
1509 } => SubregionOrigin::CheckAssociatedTypeBounds {
1510 impl_item_def_id,
1511 trait_item_def_id,
1512 parent: Box::new(default()),
1513 },
1514
1515 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1516 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1517 }
1518
1519 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1520 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1521 }
1522
1523 _ => default(),
1524 }
1525 }
1526}
1527
1528impl RegionVariableOrigin {
1529 pub fn span(&self) -> Span {
1530 match *self {
1531 MiscVariable(a)
1532 | PatternRegion(a)
1533 | BorrowRegion(a)
1534 | Autoref(a)
1535 | Coercion(a)
1536 | RegionParameterDefinition(a, ..)
1537 | BoundRegion(a, ..)
1538 | UpvarRegion(_, a) => a,
1539 Nll(..) => bug!("NLL variable used with `span`"),
1540 }
1541 }
1542}
1543
1544impl<'tcx> InferCtxt<'tcx> {
1545 pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1548 let block = block.innermost_block();
1549 if let Some(expr) = &block.expr {
1550 expr.span
1551 } else if let Some(stmt) = block.stmts.last() {
1552 stmt.span
1554 } else {
1555 block.span
1557 }
1558 }
1559
1560 pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1563 match self.tcx.hir_node(hir_id) {
1564 hir::Node::Block(blk) => self.find_block_span(blk),
1565 hir::Node::Expr(e) => e.span,
1568 _ => rustc_span::DUMMY_SP,
1569 }
1570 }
1571}