1use std::cell::{Cell, RefCell};
2use std::fmt;
3
4pub 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::{
11 GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
12};
13pub use relate::StructurallyRelateAliases;
14pub use relate::combine::PredicateEmittingRelation;
15use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
16use rustc_data_structures::undo_log::{Rollback, UndoLogs};
17use rustc_data_structures::unify as ut;
18use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
19use rustc_hir as hir;
20use rustc_hir::def_id::{DefId, LocalDefId};
21use rustc_macros::extension;
22pub use rustc_macros::{TypeFoldable, TypeVisitable};
23use rustc_middle::bug;
24use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
25use rustc_middle::mir::ConstraintCategory;
26use rustc_middle::traits::select;
27use rustc_middle::traits::solve::Goal;
28use rustc_middle::ty::error::{ExpectedFound, TypeError};
29use rustc_middle::ty::{
30 self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs,
31 GenericArgsRef, GenericParamDefKind, InferConst, IntVid, OpaqueHiddenType, OpaqueTypeKey,
32 PseudoCanonicalInput, Term, TermKind, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder,
33 TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions,
34};
35use rustc_span::{DUMMY_SP, Span, Symbol};
36use snapshot::undo_log::InferCtxtUndoLogs;
37use tracing::{debug, instrument};
38use type_variable::TypeVariableOrigin;
39
40use crate::infer::snapshot::undo_log::UndoLog;
41use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
42use crate::traits::{
43 self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations,
44 TraitEngine,
45};
46
47pub mod at;
48pub mod canonical;
49mod context;
50mod free_regions;
51mod freshen;
52mod lexical_region_resolve;
53mod opaque_types;
54pub mod outlives;
55mod projection;
56pub mod region_constraints;
57pub mod relate;
58pub mod resolve;
59pub(crate) mod snapshot;
60mod type_variable;
61mod unify_key;
62
63#[must_use]
71#[derive(Debug)]
72pub struct InferOk<'tcx, T> {
73 pub value: T,
74 pub obligations: PredicateObligations<'tcx>,
75}
76pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
77
78pub(crate) type FixupResult<T> = Result<T, FixupError>; pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
81 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
82>;
83
84#[derive(Clone)]
89pub struct InferCtxtInner<'tcx> {
90 undo_log: InferCtxtUndoLogs<'tcx>,
91
92 projection_cache: traits::ProjectionCacheStorage<'tcx>,
96
97 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
101
102 const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
104
105 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
107
108 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
110
111 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
118
119 region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
152
153 region_assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
159
160 hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
166
167 opaque_type_storage: OpaqueTypeStorage<'tcx>,
169}
170
171impl<'tcx> InferCtxtInner<'tcx> {
172 fn new() -> InferCtxtInner<'tcx> {
173 InferCtxtInner {
174 undo_log: InferCtxtUndoLogs::default(),
175
176 projection_cache: Default::default(),
177 type_variable_storage: Default::default(),
178 const_unification_storage: Default::default(),
179 int_unification_storage: Default::default(),
180 float_unification_storage: Default::default(),
181 region_constraint_storage: Some(Default::default()),
182 region_obligations: Default::default(),
183 region_assumptions: Default::default(),
184 hir_typeck_potentially_region_dependent_goals: Default::default(),
185 opaque_type_storage: Default::default(),
186 }
187 }
188
189 #[inline]
190 pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
191 &self.region_obligations
192 }
193
194 #[inline]
195 pub fn region_assumptions(&self) -> &[ty::ArgOutlivesPredicate<'tcx>] {
196 &self.region_assumptions
197 }
198
199 #[inline]
200 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
201 self.projection_cache.with_log(&mut self.undo_log)
202 }
203
204 #[inline]
205 fn try_type_variables_probe_ref(
206 &self,
207 vid: ty::TyVid,
208 ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
209 self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
212 }
213
214 #[inline]
215 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
216 self.type_variable_storage.with_log(&mut self.undo_log)
217 }
218
219 #[inline]
220 pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
221 self.opaque_type_storage.with_log(&mut self.undo_log)
222 }
223
224 #[inline]
225 fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
226 self.int_unification_storage.with_log(&mut self.undo_log)
227 }
228
229 #[inline]
230 fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
231 self.float_unification_storage.with_log(&mut self.undo_log)
232 }
233
234 #[inline]
235 fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
236 self.const_unification_storage.with_log(&mut self.undo_log)
237 }
238
239 #[inline]
240 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
241 self.region_constraint_storage
242 .as_mut()
243 .expect("region constraints already solved")
244 .with_log(&mut self.undo_log)
245 }
246}
247
248pub struct InferCtxt<'tcx> {
249 pub tcx: TyCtxt<'tcx>,
250
251 typing_mode: TypingMode<'tcx>,
254
255 pub considering_regions: bool,
259 pub in_hir_typeck: bool,
279
280 skip_leak_check: bool,
285
286 pub inner: RefCell<InferCtxtInner<'tcx>>,
287
288 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
290
291 pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
294
295 pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
298
299 pub reported_trait_errors:
302 RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
303
304 pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
305
306 tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
314
315 universe: Cell<ty::UniverseIndex>,
325
326 next_trait_solver: bool,
327
328 pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
329}
330
331#[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
333pub enum ValuePairs<'tcx> {
334 Regions(ExpectedFound<ty::Region<'tcx>>),
335 Terms(ExpectedFound<ty::Term<'tcx>>),
336 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
337 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
338 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
339 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
340 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
341}
342
343impl<'tcx> ValuePairs<'tcx> {
344 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
345 if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
346 && let Some(expected) = expected.as_type()
347 && let Some(found) = found.as_type()
348 {
349 Some((expected, found))
350 } else {
351 None
352 }
353 }
354}
355
356#[derive(Clone, Debug)]
361pub struct TypeTrace<'tcx> {
362 pub cause: ObligationCause<'tcx>,
363 pub values: ValuePairs<'tcx>,
364}
365
366#[derive(Clone, Debug)]
370pub enum SubregionOrigin<'tcx> {
371 Subtype(Box<TypeTrace<'tcx>>),
373
374 RelateObjectBound(Span),
377
378 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
381
382 RelateRegionParamBound(Span, Option<Ty<'tcx>>),
385
386 Reborrow(Span),
388
389 ReferenceOutlivesReferent(Ty<'tcx>, Span),
391
392 CompareImplItemObligation {
395 span: Span,
396 impl_item_def_id: LocalDefId,
397 trait_item_def_id: DefId,
398 },
399
400 CheckAssociatedTypeBounds {
402 parent: Box<SubregionOrigin<'tcx>>,
403 impl_item_def_id: LocalDefId,
404 trait_item_def_id: DefId,
405 },
406
407 AscribeUserTypeProvePredicate(Span),
408}
409
410#[cfg(target_pointer_width = "64")]
412rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
413
414impl<'tcx> SubregionOrigin<'tcx> {
415 pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
416 match self {
417 Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
418 Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
419 _ => ConstraintCategory::BoringNoLocation,
420 }
421 }
422}
423
424#[derive(Clone, Copy, Debug)]
426pub enum BoundRegionConversionTime {
427 FnCall,
429
430 HigherRankedType,
432
433 AssocTypeProjection(DefId),
435}
436
437#[derive(Copy, Clone, Debug)]
441pub enum RegionVariableOrigin {
442 Misc(Span),
446
447 PatternRegion(Span),
449
450 BorrowRegion(Span),
452
453 Autoref(Span),
455
456 Coercion(Span),
458
459 RegionParameterDefinition(Span, Symbol),
464
465 BoundRegion(Span, ty::BoundRegionKind, BoundRegionConversionTime),
468
469 UpvarRegion(ty::UpvarId, Span),
470
471 Nll(NllRegionVariableOrigin),
474}
475
476#[derive(Copy, Clone, Debug)]
477pub enum NllRegionVariableOrigin {
478 FreeRegion,
482
483 Placeholder(ty::PlaceholderRegion),
486
487 Existential {
488 name: Option<Symbol>,
489 },
490}
491
492#[derive(Copy, Clone, Debug)]
493pub struct FixupError {
494 unresolved: TyOrConstInferVar,
495}
496
497impl fmt::Display for FixupError {
498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499 match self.unresolved {
500 TyOrConstInferVar::TyInt(_) => write!(
501 f,
502 "cannot determine the type of this integer; \
503 add a suffix to specify the type explicitly"
504 ),
505 TyOrConstInferVar::TyFloat(_) => write!(
506 f,
507 "cannot determine the type of this number; \
508 add a suffix to specify the type explicitly"
509 ),
510 TyOrConstInferVar::Ty(_) => write!(f, "unconstrained type"),
511 TyOrConstInferVar::Const(_) => write!(f, "unconstrained const value"),
512 }
513 }
514}
515
516#[derive(Clone, Debug)]
518pub struct TypeOutlivesConstraint<'tcx> {
519 pub sub_region: ty::Region<'tcx>,
520 pub sup_type: Ty<'tcx>,
521 pub origin: SubregionOrigin<'tcx>,
522}
523
524pub struct InferCtxtBuilder<'tcx> {
526 tcx: TyCtxt<'tcx>,
527 considering_regions: bool,
528 in_hir_typeck: bool,
529 skip_leak_check: bool,
530 next_trait_solver: bool,
533}
534
535#[extension(pub trait TyCtxtInferExt<'tcx>)]
536impl<'tcx> TyCtxt<'tcx> {
537 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
538 InferCtxtBuilder {
539 tcx: self,
540 considering_regions: true,
541 in_hir_typeck: false,
542 skip_leak_check: false,
543 next_trait_solver: self.next_trait_solver_globally(),
544 }
545 }
546}
547
548impl<'tcx> InferCtxtBuilder<'tcx> {
549 pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
550 self.next_trait_solver = next_trait_solver;
551 self
552 }
553
554 pub fn ignoring_regions(mut self) -> Self {
555 self.considering_regions = false;
556 self
557 }
558
559 pub fn in_hir_typeck(mut self) -> Self {
560 self.in_hir_typeck = true;
561 self
562 }
563
564 pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
565 self.skip_leak_check = skip_leak_check;
566 self
567 }
568
569 pub fn build_with_canonical<T>(
577 mut self,
578 span: Span,
579 input: &CanonicalQueryInput<'tcx, T>,
580 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
581 where
582 T: TypeFoldable<TyCtxt<'tcx>>,
583 {
584 let infcx = self.build(input.typing_mode);
585 let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
586 (infcx, value, args)
587 }
588
589 pub fn build_with_typing_env(
590 mut self,
591 TypingEnv { typing_mode, param_env }: TypingEnv<'tcx>,
592 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
593 (self.build(typing_mode), param_env)
594 }
595
596 pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
597 let InferCtxtBuilder {
598 tcx,
599 considering_regions,
600 in_hir_typeck,
601 skip_leak_check,
602 next_trait_solver,
603 } = *self;
604 InferCtxt {
605 tcx,
606 typing_mode,
607 considering_regions,
608 in_hir_typeck,
609 skip_leak_check,
610 inner: RefCell::new(InferCtxtInner::new()),
611 lexical_region_resolutions: RefCell::new(None),
612 selection_cache: Default::default(),
613 evaluation_cache: Default::default(),
614 reported_trait_errors: Default::default(),
615 reported_signature_mismatch: Default::default(),
616 tainted_by_errors: Cell::new(None),
617 universe: Cell::new(ty::UniverseIndex::ROOT),
618 next_trait_solver,
619 obligation_inspector: Cell::new(None),
620 }
621 }
622}
623
624impl<'tcx, T> InferOk<'tcx, T> {
625 pub fn into_value_registering_obligations<E: 'tcx>(
627 self,
628 infcx: &InferCtxt<'tcx>,
629 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
630 ) -> T {
631 let InferOk { value, obligations } = self;
632 fulfill_cx.register_predicate_obligations(infcx, obligations);
633 value
634 }
635}
636
637impl<'tcx> InferOk<'tcx, ()> {
638 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
639 self.obligations
640 }
641}
642
643impl<'tcx> InferCtxt<'tcx> {
644 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
645 self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
646 }
647
648 pub fn next_trait_solver(&self) -> bool {
649 self.next_trait_solver
650 }
651
652 #[inline(always)]
653 pub fn typing_mode(&self) -> TypingMode<'tcx> {
654 self.typing_mode
655 }
656
657 pub fn freshen<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> T {
658 t.fold_with(&mut self.freshener())
659 }
660
661 pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
665 self.inner.borrow_mut().type_variables().var_origin(vid)
666 }
667
668 pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
672 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
673 ConstVariableValue::Known { .. } => None,
674 ConstVariableValue::Unknown { origin, .. } => Some(origin),
675 }
676 }
677
678 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
679 freshen::TypeFreshener::new(self)
680 }
681
682 pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
683 let mut inner = self.inner.borrow_mut();
684 let mut vars: Vec<Ty<'_>> = inner
685 .type_variables()
686 .unresolved_variables()
687 .into_iter()
688 .map(|t| Ty::new_var(self.tcx, t))
689 .collect();
690 vars.extend(
691 (0..inner.int_unification_table().len())
692 .map(|i| ty::IntVid::from_usize(i))
693 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
694 .map(|v| Ty::new_int_var(self.tcx, v)),
695 );
696 vars.extend(
697 (0..inner.float_unification_table().len())
698 .map(|i| ty::FloatVid::from_usize(i))
699 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
700 .map(|v| Ty::new_float_var(self.tcx, v)),
701 );
702 vars
703 }
704
705 #[instrument(skip(self), level = "debug")]
706 pub fn sub_regions(
707 &self,
708 origin: SubregionOrigin<'tcx>,
709 a: ty::Region<'tcx>,
710 b: ty::Region<'tcx>,
711 ) {
712 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
713 }
714
715 pub fn coerce_predicate(
731 &self,
732 cause: &ObligationCause<'tcx>,
733 param_env: ty::ParamEnv<'tcx>,
734 predicate: ty::PolyCoercePredicate<'tcx>,
735 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
736 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
737 a_is_expected: false, a: p.a,
739 b: p.b,
740 });
741 self.subtype_predicate(cause, param_env, subtype_predicate)
742 }
743
744 pub fn subtype_predicate(
745 &self,
746 cause: &ObligationCause<'tcx>,
747 param_env: ty::ParamEnv<'tcx>,
748 predicate: ty::PolySubtypePredicate<'tcx>,
749 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
750 let r_a = self.shallow_resolve(predicate.skip_binder().a);
764 let r_b = self.shallow_resolve(predicate.skip_binder().b);
765 match (r_a.kind(), r_b.kind()) {
766 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
767 return Err((a_vid, b_vid));
768 }
769 _ => {}
770 }
771
772 self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
773 if a_is_expected {
774 Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
775 } else {
776 Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
777 }
778 })
779 }
780
781 pub fn num_ty_vars(&self) -> usize {
783 self.inner.borrow_mut().type_variables().num_vars()
784 }
785
786 pub fn next_ty_vid(&self, span: Span) -> TyVid {
787 self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
788 }
789
790 pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
791 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
792 }
793
794 pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
795 let origin = TypeVariableOrigin { span, param_def_id: None };
796 self.inner.borrow_mut().type_variables().new_var(universe, origin)
797 }
798
799 pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
800 self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
801 }
802
803 pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
804 let vid = self.next_ty_vid_with_origin(origin);
805 Ty::new_var(self.tcx, vid)
806 }
807
808 pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
809 let vid = self.next_ty_vid_in_universe(span, universe);
810 Ty::new_var(self.tcx, vid)
811 }
812
813 pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
814 self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
815 }
816
817 pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
818 let vid = self
819 .inner
820 .borrow_mut()
821 .const_unification_table()
822 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
823 .vid;
824 ty::Const::new_var(self.tcx, vid)
825 }
826
827 pub fn next_const_var_in_universe(
828 &self,
829 span: Span,
830 universe: ty::UniverseIndex,
831 ) -> ty::Const<'tcx> {
832 let origin = ConstVariableOrigin { span, param_def_id: None };
833 let vid = self
834 .inner
835 .borrow_mut()
836 .const_unification_table()
837 .new_key(ConstVariableValue::Unknown { origin, universe })
838 .vid;
839 ty::Const::new_var(self.tcx, vid)
840 }
841
842 pub fn next_int_var(&self) -> Ty<'tcx> {
843 let next_int_var_id =
844 self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
845 Ty::new_int_var(self.tcx, next_int_var_id)
846 }
847
848 pub fn next_float_var(&self) -> Ty<'tcx> {
849 let next_float_var_id =
850 self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown);
851 Ty::new_float_var(self.tcx, next_float_var_id)
852 }
853
854 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
858 self.next_region_var_in_universe(origin, self.universe())
859 }
860
861 pub fn next_region_var_in_universe(
865 &self,
866 origin: RegionVariableOrigin,
867 universe: ty::UniverseIndex,
868 ) -> ty::Region<'tcx> {
869 let region_var =
870 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
871 ty::Region::new_var(self.tcx, region_var)
872 }
873
874 pub fn next_term_var_of_kind(&self, term: ty::Term<'tcx>, span: Span) -> ty::Term<'tcx> {
875 match term.kind() {
876 ty::TermKind::Ty(_) => self.next_ty_var(span).into(),
877 ty::TermKind::Const(_) => self.next_const_var(span).into(),
878 }
879 }
880
881 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
887 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
888 }
889
890 pub fn num_region_vars(&self) -> usize {
892 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
893 }
894
895 #[instrument(skip(self), level = "debug")]
897 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
898 self.next_region_var(RegionVariableOrigin::Nll(origin))
899 }
900
901 #[instrument(skip(self), level = "debug")]
903 pub fn next_nll_region_var_in_universe(
904 &self,
905 origin: NllRegionVariableOrigin,
906 universe: ty::UniverseIndex,
907 ) -> ty::Region<'tcx> {
908 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
909 }
910
911 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
912 match param.kind {
913 GenericParamDefKind::Lifetime => {
914 self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
917 span, param.name,
918 ))
919 .into()
920 }
921 GenericParamDefKind::Type { .. } => {
922 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
931 self.universe(),
932 TypeVariableOrigin { param_def_id: Some(param.def_id), span },
933 );
934
935 Ty::new_var(self.tcx, ty_var_id).into()
936 }
937 GenericParamDefKind::Const { .. } => {
938 let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
939 let const_var_id = self
940 .inner
941 .borrow_mut()
942 .const_unification_table()
943 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
944 .vid;
945 ty::Const::new_var(self.tcx, const_var_id).into()
946 }
947 }
948 }
949
950 pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
953 GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
954 }
955
956 #[must_use = "this method does not have any side effects"]
962 pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
963 self.tainted_by_errors.get()
964 }
965
966 pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
969 debug!("set_tainted_by_errors(ErrorGuaranteed)");
970 self.tainted_by_errors.set(Some(e));
971 }
972
973 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
974 let mut inner = self.inner.borrow_mut();
975 let inner = &mut *inner;
976 inner.unwrap_region_constraints().var_origin(vid)
977 }
978
979 pub fn get_region_var_infos(&self) -> VarInfos {
982 let inner = self.inner.borrow();
983 assert!(!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log));
984 let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
985 assert!(storage.data.is_empty(), "{:#?}", storage.data);
986 storage.var_infos.clone()
990 }
991
992 pub fn has_opaque_types_in_storage(&self) -> bool {
993 !self.inner.borrow().opaque_type_storage.is_empty()
994 }
995
996 #[instrument(level = "debug", skip(self), ret)]
997 pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
998 self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
999 }
1000
1001 #[instrument(level = "debug", skip(self), ret)]
1002 pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
1003 self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1004 }
1005
1006 #[inline(always)]
1007 pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1008 debug_assert!(!self.next_trait_solver());
1009 match self.typing_mode() {
1010 TypingMode::Analysis {
1011 defining_opaque_types_and_generators: defining_opaque_types,
1012 }
1013 | TypingMode::Borrowck { defining_opaque_types } => {
1014 id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1015 }
1016 TypingMode::Coherence
1020 | TypingMode::PostBorrowckAnalysis { .. }
1021 | TypingMode::PostAnalysis => false,
1022 }
1023 }
1024
1025 pub fn push_hir_typeck_potentially_region_dependent_goal(
1026 &self,
1027 goal: PredicateObligation<'tcx>,
1028 ) {
1029 let mut inner = self.inner.borrow_mut();
1030 inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1031 inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1032 }
1033
1034 pub fn take_hir_typeck_potentially_region_dependent_goals(
1035 &self,
1036 ) -> Vec<PredicateObligation<'tcx>> {
1037 assert!(!self.in_snapshot(), "cannot take goals in a snapshot");
1038 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1039 }
1040
1041 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1042 self.resolve_vars_if_possible(t).to_string()
1043 }
1044
1045 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1048 use self::type_variable::TypeVariableValue;
1049
1050 match self.inner.borrow_mut().type_variables().probe(vid) {
1051 TypeVariableValue::Known { value } => Ok(value),
1052 TypeVariableValue::Unknown { universe } => Err(universe),
1053 }
1054 }
1055
1056 pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1057 if let ty::Infer(v) = *ty.kind() {
1058 match v {
1059 ty::TyVar(v) => {
1060 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1073 known.map_or(ty, |t| self.shallow_resolve(t))
1074 }
1075
1076 ty::IntVar(v) => {
1077 match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1078 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1079 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1080 ty::IntVarValue::Unknown => ty,
1081 }
1082 }
1083
1084 ty::FloatVar(v) => {
1085 match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1086 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1087 ty::FloatVarValue::Unknown => ty,
1088 }
1089 }
1090
1091 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1092 }
1093 } else {
1094 ty
1095 }
1096 }
1097
1098 pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1099 match ct.kind() {
1100 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1101 InferConst::Var(vid) => self
1102 .inner
1103 .borrow_mut()
1104 .const_unification_table()
1105 .probe_value(vid)
1106 .known()
1107 .unwrap_or(ct),
1108 InferConst::Fresh(_) => ct,
1109 },
1110 ty::ConstKind::Param(_)
1111 | ty::ConstKind::Bound(_, _)
1112 | ty::ConstKind::Placeholder(_)
1113 | ty::ConstKind::Unevaluated(_)
1114 | ty::ConstKind::Value(_)
1115 | ty::ConstKind::Error(_)
1116 | ty::ConstKind::Expr(_) => ct,
1117 }
1118 }
1119
1120 pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1121 match term.kind() {
1122 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1123 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1124 }
1125 }
1126
1127 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1128 self.inner.borrow_mut().type_variables().root_var(var)
1129 }
1130
1131 pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1132 self.inner.borrow_mut().const_unification_table().find(var).vid
1133 }
1134
1135 pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1138 let mut inner = self.inner.borrow_mut();
1139 let value = inner.int_unification_table().probe_value(vid);
1140 match value {
1141 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1142 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1143 ty::IntVarValue::Unknown => {
1144 Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1145 }
1146 }
1147 }
1148
1149 pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1152 let mut inner = self.inner.borrow_mut();
1153 let value = inner.float_unification_table().probe_value(vid);
1154 match value {
1155 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1156 ty::FloatVarValue::Unknown => {
1157 Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1158 }
1159 }
1160 }
1161
1162 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1169 where
1170 T: TypeFoldable<TyCtxt<'tcx>>,
1171 {
1172 if let Err(guar) = value.error_reported() {
1173 self.set_tainted_by_errors(guar);
1174 }
1175 if !value.has_non_region_infer() {
1176 return value;
1177 }
1178 let mut r = resolve::OpportunisticVarResolver::new(self);
1179 value.fold_with(&mut r)
1180 }
1181
1182 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1183 where
1184 T: TypeFoldable<TyCtxt<'tcx>>,
1185 {
1186 if !value.has_infer() {
1187 return value; }
1189 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1190 value.fold_with(&mut r)
1191 }
1192
1193 pub fn probe_const_var(&self, vid: ty::ConstVid) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1194 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1195 ConstVariableValue::Known { value } => Ok(value),
1196 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1197 }
1198 }
1199
1200 pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1208 match resolve::fully_resolve(self, value) {
1209 Ok(value) => {
1210 if value.has_non_region_infer() {
1211 bug!("`{value:?}` is not fully resolved");
1212 }
1213 if value.has_infer_regions() {
1214 let guar = self.dcx().delayed_bug(format!("`{value:?}` is not fully resolved"));
1215 Ok(fold_regions(self.tcx, value, |re, _| {
1216 if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1217 }))
1218 } else {
1219 Ok(value)
1220 }
1221 }
1222 Err(e) => Err(e),
1223 }
1224 }
1225
1226 pub fn instantiate_binder_with_fresh_vars<T>(
1234 &self,
1235 span: Span,
1236 lbrct: BoundRegionConversionTime,
1237 value: ty::Binder<'tcx, T>,
1238 ) -> T
1239 where
1240 T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1241 {
1242 if let Some(inner) = value.no_bound_vars() {
1243 return inner;
1244 }
1245
1246 let bound_vars = value.bound_vars();
1247 let mut args = Vec::with_capacity(bound_vars.len());
1248
1249 for bound_var_kind in bound_vars {
1250 let arg: ty::GenericArg<'_> = match bound_var_kind {
1251 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1252 ty::BoundVariableKind::Region(br) => {
1253 self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1254 }
1255 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1256 };
1257 args.push(arg);
1258 }
1259
1260 struct ToFreshVars<'tcx> {
1261 args: Vec<ty::GenericArg<'tcx>>,
1262 }
1263
1264 impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1265 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1266 self.args[br.var.index()].expect_region()
1267 }
1268 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1269 self.args[bt.var.index()].expect_ty()
1270 }
1271 fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx> {
1272 self.args[bc.var.index()].expect_const()
1273 }
1274 }
1275 let delegate = ToFreshVars { args };
1276 self.tcx.replace_bound_vars_uncached(value, delegate)
1277 }
1278
1279 pub(crate) fn verify_generic_bound(
1281 &self,
1282 origin: SubregionOrigin<'tcx>,
1283 kind: GenericKind<'tcx>,
1284 a: ty::Region<'tcx>,
1285 bound: VerifyBound<'tcx>,
1286 ) {
1287 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1288
1289 self.inner
1290 .borrow_mut()
1291 .unwrap_region_constraints()
1292 .verify_generic_bound(origin, kind, a, bound);
1293 }
1294
1295 pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1299 let unresolved_kind_ty = match *closure_ty.kind() {
1300 ty::Closure(_, args) => args.as_closure().kind_ty(),
1301 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1302 _ => bug!("unexpected type {closure_ty}"),
1303 };
1304 let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1305 closure_kind_ty.to_opt_closure_kind()
1306 }
1307
1308 pub fn universe(&self) -> ty::UniverseIndex {
1309 self.universe.get()
1310 }
1311
1312 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1315 let u = self.universe.get().next_universe();
1316 debug!("create_next_universe {u:?}");
1317 self.universe.set(u);
1318 u
1319 }
1320
1321 pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1325 let typing_mode = match self.typing_mode() {
1326 ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1331 | ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1332 TypingMode::non_body_analysis()
1333 }
1334 mode @ (ty::TypingMode::Coherence
1335 | ty::TypingMode::PostBorrowckAnalysis { .. }
1336 | ty::TypingMode::PostAnalysis) => mode,
1337 };
1338 ty::TypingEnv { typing_mode, param_env }
1339 }
1340
1341 pub fn pseudo_canonicalize_query<V>(
1345 &self,
1346 param_env: ty::ParamEnv<'tcx>,
1347 value: V,
1348 ) -> PseudoCanonicalInput<'tcx, V>
1349 where
1350 V: TypeVisitable<TyCtxt<'tcx>>,
1351 {
1352 debug_assert!(!value.has_infer());
1353 debug_assert!(!value.has_placeholders());
1354 debug_assert!(!param_env.has_infer());
1355 debug_assert!(!param_env.has_placeholders());
1356 self.typing_env(param_env).as_query_input(value)
1357 }
1358
1359 #[inline]
1362 pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1363 let inner = self.inner.try_borrow();
1365
1366 move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1367 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1368 use self::type_variable::TypeVariableValue;
1369
1370 matches!(
1371 inner.try_type_variables_probe_ref(ty_var),
1372 Some(TypeVariableValue::Unknown { .. })
1373 )
1374 }
1375 _ => false,
1376 }
1377 }
1378
1379 #[inline(always)]
1389 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1390 match infer_var {
1391 TyOrConstInferVar::Ty(v) => {
1392 use self::type_variable::TypeVariableValue;
1393
1394 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1397 TypeVariableValue::Unknown { .. } => false,
1398 TypeVariableValue::Known { .. } => true,
1399 }
1400 }
1401
1402 TyOrConstInferVar::TyInt(v) => {
1403 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1407 }
1408
1409 TyOrConstInferVar::TyFloat(v) => {
1410 self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1415 }
1416
1417 TyOrConstInferVar::Const(v) => {
1418 match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1423 ConstVariableValue::Unknown { .. } => false,
1424 ConstVariableValue::Known { .. } => true,
1425 }
1426 }
1427 }
1428 }
1429
1430 pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1432 debug_assert!(
1433 self.obligation_inspector.get().is_none(),
1434 "shouldn't override a set obligation inspector"
1435 );
1436 self.obligation_inspector.set(Some(inspector));
1437 }
1438}
1439
1440#[derive(Copy, Clone, Debug)]
1443pub enum TyOrConstInferVar {
1444 Ty(TyVid),
1446 TyInt(IntVid),
1448 TyFloat(FloatVid),
1450
1451 Const(ConstVid),
1453}
1454
1455impl<'tcx> TyOrConstInferVar {
1456 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1460 match arg.kind() {
1461 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1462 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1463 GenericArgKind::Lifetime(_) => None,
1464 }
1465 }
1466
1467 pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1471 match term.kind() {
1472 TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1473 TermKind::Const(ct) => Self::maybe_from_const(ct),
1474 }
1475 }
1476
1477 fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1480 match *ty.kind() {
1481 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1482 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1483 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1484 _ => None,
1485 }
1486 }
1487
1488 fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1491 match ct.kind() {
1492 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1493 _ => None,
1494 }
1495 }
1496}
1497
1498struct InferenceLiteralEraser<'tcx> {
1501 tcx: TyCtxt<'tcx>,
1502}
1503
1504impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1505 fn cx(&self) -> TyCtxt<'tcx> {
1506 self.tcx
1507 }
1508
1509 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1510 match ty.kind() {
1511 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1512 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1513 _ => ty.super_fold_with(self),
1514 }
1515 }
1516}
1517
1518impl<'tcx> TypeTrace<'tcx> {
1519 pub fn span(&self) -> Span {
1520 self.cause.span
1521 }
1522
1523 pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1524 TypeTrace {
1525 cause: cause.clone(),
1526 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1527 }
1528 }
1529
1530 pub fn trait_refs(
1531 cause: &ObligationCause<'tcx>,
1532 a: ty::TraitRef<'tcx>,
1533 b: ty::TraitRef<'tcx>,
1534 ) -> TypeTrace<'tcx> {
1535 TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1536 }
1537
1538 pub fn consts(
1539 cause: &ObligationCause<'tcx>,
1540 a: ty::Const<'tcx>,
1541 b: ty::Const<'tcx>,
1542 ) -> TypeTrace<'tcx> {
1543 TypeTrace {
1544 cause: cause.clone(),
1545 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1546 }
1547 }
1548}
1549
1550impl<'tcx> SubregionOrigin<'tcx> {
1551 pub fn span(&self) -> Span {
1552 match *self {
1553 SubregionOrigin::Subtype(ref a) => a.span(),
1554 SubregionOrigin::RelateObjectBound(a) => a,
1555 SubregionOrigin::RelateParamBound(a, ..) => a,
1556 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1557 SubregionOrigin::Reborrow(a) => a,
1558 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1559 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1560 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1561 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1562 }
1563 }
1564
1565 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1566 where
1567 F: FnOnce() -> Self,
1568 {
1569 match *cause.code() {
1570 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1571 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1572 }
1573
1574 traits::ObligationCauseCode::CompareImplItem {
1575 impl_item_def_id,
1576 trait_item_def_id,
1577 kind: _,
1578 } => SubregionOrigin::CompareImplItemObligation {
1579 span: cause.span,
1580 impl_item_def_id,
1581 trait_item_def_id,
1582 },
1583
1584 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1585 impl_item_def_id,
1586 trait_item_def_id,
1587 } => SubregionOrigin::CheckAssociatedTypeBounds {
1588 impl_item_def_id,
1589 trait_item_def_id,
1590 parent: Box::new(default()),
1591 },
1592
1593 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1594 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1595 }
1596
1597 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1598 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1599 }
1600
1601 _ => default(),
1602 }
1603 }
1604}
1605
1606impl RegionVariableOrigin {
1607 pub fn span(&self) -> Span {
1608 match *self {
1609 RegionVariableOrigin::Misc(a)
1610 | RegionVariableOrigin::PatternRegion(a)
1611 | RegionVariableOrigin::BorrowRegion(a)
1612 | RegionVariableOrigin::Autoref(a)
1613 | RegionVariableOrigin::Coercion(a)
1614 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1615 | RegionVariableOrigin::BoundRegion(a, ..)
1616 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1617 RegionVariableOrigin::Nll(..) => bug!("NLL variable used with `span`"),
1618 }
1619 }
1620}
1621
1622impl<'tcx> InferCtxt<'tcx> {
1623 pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1626 let block = block.innermost_block();
1627 if let Some(expr) = &block.expr {
1628 expr.span
1629 } else if let Some(stmt) = block.stmts.last() {
1630 stmt.span
1632 } else {
1633 block.span
1635 }
1636 }
1637
1638 pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1641 match self.tcx.hir_node(hir_id) {
1642 hir::Node::Block(blk)
1643 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1644 self.find_block_span(blk)
1645 }
1646 hir::Node::Expr(e) => e.span,
1647 _ => DUMMY_SP,
1648 }
1649 }
1650}