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>>,
165
166 opaque_type_storage: OpaqueTypeStorage<'tcx>,
168}
169
170impl<'tcx> InferCtxtInner<'tcx> {
171 fn new() -> InferCtxtInner<'tcx> {
172 InferCtxtInner {
173 undo_log: InferCtxtUndoLogs::default(),
174
175 projection_cache: Default::default(),
176 type_variable_storage: Default::default(),
177 const_unification_storage: Default::default(),
178 int_unification_storage: Default::default(),
179 float_unification_storage: Default::default(),
180 region_constraint_storage: Some(Default::default()),
181 region_obligations: Default::default(),
182 region_assumptions: Default::default(),
183 hir_typeck_potentially_region_dependent_goals: Default::default(),
184 opaque_type_storage: Default::default(),
185 }
186 }
187
188 #[inline]
189 pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
190 &self.region_obligations
191 }
192
193 #[inline]
194 pub fn region_assumptions(&self) -> &[ty::ArgOutlivesPredicate<'tcx>] {
195 &self.region_assumptions
196 }
197
198 #[inline]
199 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
200 self.projection_cache.with_log(&mut self.undo_log)
201 }
202
203 #[inline]
204 fn try_type_variables_probe_ref(
205 &self,
206 vid: ty::TyVid,
207 ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
208 self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
211 }
212
213 #[inline]
214 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
215 self.type_variable_storage.with_log(&mut self.undo_log)
216 }
217
218 #[inline]
219 pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
220 self.opaque_type_storage.with_log(&mut self.undo_log)
221 }
222
223 #[inline]
224 fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
225 self.int_unification_storage.with_log(&mut self.undo_log)
226 }
227
228 #[inline]
229 fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
230 self.float_unification_storage.with_log(&mut self.undo_log)
231 }
232
233 #[inline]
234 fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
235 self.const_unification_storage.with_log(&mut self.undo_log)
236 }
237
238 #[inline]
239 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
240 self.region_constraint_storage
241 .as_mut()
242 .expect("region constraints already solved")
243 .with_log(&mut self.undo_log)
244 }
245}
246
247pub struct InferCtxt<'tcx> {
248 pub tcx: TyCtxt<'tcx>,
249
250 typing_mode: TypingMode<'tcx>,
253
254 pub considering_regions: bool,
258 pub in_hir_typeck: bool,
278
279 skip_leak_check: bool,
284
285 pub inner: RefCell<InferCtxtInner<'tcx>>,
286
287 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
289
290 pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
293
294 pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
297
298 pub reported_trait_errors:
301 RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
302
303 pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
304
305 tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
313
314 universe: Cell<ty::UniverseIndex>,
324
325 next_trait_solver: bool,
326
327 pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
328}
329
330#[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
332pub enum ValuePairs<'tcx> {
333 Regions(ExpectedFound<ty::Region<'tcx>>),
334 Terms(ExpectedFound<ty::Term<'tcx>>),
335 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
336 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
337 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
338 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
339 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
340}
341
342impl<'tcx> ValuePairs<'tcx> {
343 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
344 if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
345 && let Some(expected) = expected.as_type()
346 && let Some(found) = found.as_type()
347 {
348 Some((expected, found))
349 } else {
350 None
351 }
352 }
353}
354
355#[derive(Clone, Debug)]
360pub struct TypeTrace<'tcx> {
361 pub cause: ObligationCause<'tcx>,
362 pub values: ValuePairs<'tcx>,
363}
364
365#[derive(Clone, Debug)]
369pub enum SubregionOrigin<'tcx> {
370 Subtype(Box<TypeTrace<'tcx>>),
372
373 RelateObjectBound(Span),
376
377 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
380
381 RelateRegionParamBound(Span, Option<Ty<'tcx>>),
384
385 Reborrow(Span),
387
388 ReferenceOutlivesReferent(Ty<'tcx>, Span),
390
391 CompareImplItemObligation {
394 span: Span,
395 impl_item_def_id: LocalDefId,
396 trait_item_def_id: DefId,
397 },
398
399 CheckAssociatedTypeBounds {
401 parent: Box<SubregionOrigin<'tcx>>,
402 impl_item_def_id: LocalDefId,
403 trait_item_def_id: DefId,
404 },
405
406 AscribeUserTypeProvePredicate(Span),
407}
408
409#[cfg(target_pointer_width = "64")]
411rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
412
413impl<'tcx> SubregionOrigin<'tcx> {
414 pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
415 match self {
416 Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
417 Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
418 _ => ConstraintCategory::BoringNoLocation,
419 }
420 }
421}
422
423#[derive(Clone, Copy, Debug)]
425pub enum BoundRegionConversionTime {
426 FnCall,
428
429 HigherRankedType,
431
432 AssocTypeProjection(DefId),
434}
435
436#[derive(Copy, Clone, Debug)]
440pub enum RegionVariableOrigin {
441 Misc(Span),
445
446 PatternRegion(Span),
448
449 BorrowRegion(Span),
451
452 Autoref(Span),
454
455 Coercion(Span),
457
458 RegionParameterDefinition(Span, Symbol),
463
464 BoundRegion(Span, ty::BoundRegionKind, BoundRegionConversionTime),
467
468 UpvarRegion(ty::UpvarId, Span),
469
470 Nll(NllRegionVariableOrigin),
473}
474
475#[derive(Copy, Clone, Debug)]
476pub enum NllRegionVariableOrigin {
477 FreeRegion,
481
482 Placeholder(ty::PlaceholderRegion),
485
486 Existential {
487 from_forall: bool,
498 },
499}
500
501#[derive(Copy, Clone, Debug)]
502pub struct FixupError {
503 unresolved: TyOrConstInferVar,
504}
505
506impl fmt::Display for FixupError {
507 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508 match self.unresolved {
509 TyOrConstInferVar::TyInt(_) => write!(
510 f,
511 "cannot determine the type of this integer; \
512 add a suffix to specify the type explicitly"
513 ),
514 TyOrConstInferVar::TyFloat(_) => write!(
515 f,
516 "cannot determine the type of this number; \
517 add a suffix to specify the type explicitly"
518 ),
519 TyOrConstInferVar::Ty(_) => write!(f, "unconstrained type"),
520 TyOrConstInferVar::Const(_) => write!(f, "unconstrained const value"),
521 }
522 }
523}
524
525#[derive(Clone, Debug)]
527pub struct TypeOutlivesConstraint<'tcx> {
528 pub sub_region: ty::Region<'tcx>,
529 pub sup_type: Ty<'tcx>,
530 pub origin: SubregionOrigin<'tcx>,
531}
532
533pub struct InferCtxtBuilder<'tcx> {
535 tcx: TyCtxt<'tcx>,
536 considering_regions: bool,
537 in_hir_typeck: bool,
538 skip_leak_check: bool,
539 next_trait_solver: bool,
542}
543
544#[extension(pub trait TyCtxtInferExt<'tcx>)]
545impl<'tcx> TyCtxt<'tcx> {
546 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
547 InferCtxtBuilder {
548 tcx: self,
549 considering_regions: true,
550 in_hir_typeck: false,
551 skip_leak_check: false,
552 next_trait_solver: self.next_trait_solver_globally(),
553 }
554 }
555}
556
557impl<'tcx> InferCtxtBuilder<'tcx> {
558 pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
559 self.next_trait_solver = next_trait_solver;
560 self
561 }
562
563 pub fn ignoring_regions(mut self) -> Self {
564 self.considering_regions = false;
565 self
566 }
567
568 pub fn in_hir_typeck(mut self) -> Self {
569 self.in_hir_typeck = true;
570 self
571 }
572
573 pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
574 self.skip_leak_check = skip_leak_check;
575 self
576 }
577
578 pub fn build_with_canonical<T>(
586 mut self,
587 span: Span,
588 input: &CanonicalQueryInput<'tcx, T>,
589 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
590 where
591 T: TypeFoldable<TyCtxt<'tcx>>,
592 {
593 let infcx = self.build(input.typing_mode);
594 let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
595 (infcx, value, args)
596 }
597
598 pub fn build_with_typing_env(
599 mut self,
600 TypingEnv { typing_mode, param_env }: TypingEnv<'tcx>,
601 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
602 (self.build(typing_mode), param_env)
603 }
604
605 pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
606 let InferCtxtBuilder {
607 tcx,
608 considering_regions,
609 in_hir_typeck,
610 skip_leak_check,
611 next_trait_solver,
612 } = *self;
613 InferCtxt {
614 tcx,
615 typing_mode,
616 considering_regions,
617 in_hir_typeck,
618 skip_leak_check,
619 inner: RefCell::new(InferCtxtInner::new()),
620 lexical_region_resolutions: RefCell::new(None),
621 selection_cache: Default::default(),
622 evaluation_cache: Default::default(),
623 reported_trait_errors: Default::default(),
624 reported_signature_mismatch: Default::default(),
625 tainted_by_errors: Cell::new(None),
626 universe: Cell::new(ty::UniverseIndex::ROOT),
627 next_trait_solver,
628 obligation_inspector: Cell::new(None),
629 }
630 }
631}
632
633impl<'tcx, T> InferOk<'tcx, T> {
634 pub fn into_value_registering_obligations<E: 'tcx>(
636 self,
637 infcx: &InferCtxt<'tcx>,
638 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
639 ) -> T {
640 let InferOk { value, obligations } = self;
641 fulfill_cx.register_predicate_obligations(infcx, obligations);
642 value
643 }
644}
645
646impl<'tcx> InferOk<'tcx, ()> {
647 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
648 self.obligations
649 }
650}
651
652impl<'tcx> InferCtxt<'tcx> {
653 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
654 self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
655 }
656
657 pub fn next_trait_solver(&self) -> bool {
658 self.next_trait_solver
659 }
660
661 #[inline(always)]
662 pub fn typing_mode(&self) -> TypingMode<'tcx> {
663 self.typing_mode
664 }
665
666 pub fn freshen<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> T {
667 t.fold_with(&mut self.freshener())
668 }
669
670 pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
674 self.inner.borrow_mut().type_variables().var_origin(vid)
675 }
676
677 pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
681 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
682 ConstVariableValue::Known { .. } => None,
683 ConstVariableValue::Unknown { origin, .. } => Some(origin),
684 }
685 }
686
687 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
688 freshen::TypeFreshener::new(self)
689 }
690
691 pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
692 let mut inner = self.inner.borrow_mut();
693 let mut vars: Vec<Ty<'_>> = inner
694 .type_variables()
695 .unresolved_variables()
696 .into_iter()
697 .map(|t| Ty::new_var(self.tcx, t))
698 .collect();
699 vars.extend(
700 (0..inner.int_unification_table().len())
701 .map(|i| ty::IntVid::from_usize(i))
702 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
703 .map(|v| Ty::new_int_var(self.tcx, v)),
704 );
705 vars.extend(
706 (0..inner.float_unification_table().len())
707 .map(|i| ty::FloatVid::from_usize(i))
708 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
709 .map(|v| Ty::new_float_var(self.tcx, v)),
710 );
711 vars
712 }
713
714 #[instrument(skip(self), level = "debug")]
715 pub fn sub_regions(
716 &self,
717 origin: SubregionOrigin<'tcx>,
718 a: ty::Region<'tcx>,
719 b: ty::Region<'tcx>,
720 ) {
721 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
722 }
723
724 pub fn coerce_predicate(
740 &self,
741 cause: &ObligationCause<'tcx>,
742 param_env: ty::ParamEnv<'tcx>,
743 predicate: ty::PolyCoercePredicate<'tcx>,
744 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
745 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
746 a_is_expected: false, a: p.a,
748 b: p.b,
749 });
750 self.subtype_predicate(cause, param_env, subtype_predicate)
751 }
752
753 pub fn subtype_predicate(
754 &self,
755 cause: &ObligationCause<'tcx>,
756 param_env: ty::ParamEnv<'tcx>,
757 predicate: ty::PolySubtypePredicate<'tcx>,
758 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
759 let r_a = self.shallow_resolve(predicate.skip_binder().a);
773 let r_b = self.shallow_resolve(predicate.skip_binder().b);
774 match (r_a.kind(), r_b.kind()) {
775 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
776 return Err((a_vid, b_vid));
777 }
778 _ => {}
779 }
780
781 self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
782 if a_is_expected {
783 Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
784 } else {
785 Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
786 }
787 })
788 }
789
790 pub fn num_ty_vars(&self) -> usize {
792 self.inner.borrow_mut().type_variables().num_vars()
793 }
794
795 pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
796 self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
797 }
798
799 pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
800 let vid = self.inner.borrow_mut().type_variables().new_var(self.universe(), origin);
801 Ty::new_var(self.tcx, vid)
802 }
803
804 pub fn next_ty_var_id_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
805 let origin = TypeVariableOrigin { span, param_def_id: None };
806 self.inner.borrow_mut().type_variables().new_var(universe, origin)
807 }
808
809 pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
810 let vid = self.next_ty_var_id_in_universe(span, universe);
811 Ty::new_var(self.tcx, vid)
812 }
813
814 pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
815 self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
816 }
817
818 pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
819 let vid = self
820 .inner
821 .borrow_mut()
822 .const_unification_table()
823 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
824 .vid;
825 ty::Const::new_var(self.tcx, vid)
826 }
827
828 pub fn next_const_var_in_universe(
829 &self,
830 span: Span,
831 universe: ty::UniverseIndex,
832 ) -> ty::Const<'tcx> {
833 let origin = ConstVariableOrigin { span, param_def_id: None };
834 let vid = self
835 .inner
836 .borrow_mut()
837 .const_unification_table()
838 .new_key(ConstVariableValue::Unknown { origin, universe })
839 .vid;
840 ty::Const::new_var(self.tcx, vid)
841 }
842
843 pub fn next_int_var(&self) -> Ty<'tcx> {
844 let next_int_var_id =
845 self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
846 Ty::new_int_var(self.tcx, next_int_var_id)
847 }
848
849 pub fn next_float_var(&self) -> Ty<'tcx> {
850 let next_float_var_id =
851 self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown);
852 Ty::new_float_var(self.tcx, next_float_var_id)
853 }
854
855 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
859 self.next_region_var_in_universe(origin, self.universe())
860 }
861
862 pub fn next_region_var_in_universe(
866 &self,
867 origin: RegionVariableOrigin,
868 universe: ty::UniverseIndex,
869 ) -> ty::Region<'tcx> {
870 let region_var =
871 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
872 ty::Region::new_var(self.tcx, region_var)
873 }
874
875 pub fn next_term_var_of_kind(&self, term: ty::Term<'tcx>, span: Span) -> ty::Term<'tcx> {
876 match term.kind() {
877 ty::TermKind::Ty(_) => self.next_ty_var(span).into(),
878 ty::TermKind::Const(_) => self.next_const_var(span).into(),
879 }
880 }
881
882 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
888 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
889 }
890
891 pub fn num_region_vars(&self) -> usize {
893 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
894 }
895
896 #[instrument(skip(self), level = "debug")]
898 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
899 self.next_region_var(RegionVariableOrigin::Nll(origin))
900 }
901
902 #[instrument(skip(self), level = "debug")]
904 pub fn next_nll_region_var_in_universe(
905 &self,
906 origin: NllRegionVariableOrigin,
907 universe: ty::UniverseIndex,
908 ) -> ty::Region<'tcx> {
909 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
910 }
911
912 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
913 match param.kind {
914 GenericParamDefKind::Lifetime => {
915 self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
918 span, param.name,
919 ))
920 .into()
921 }
922 GenericParamDefKind::Type { .. } => {
923 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
932 self.universe(),
933 TypeVariableOrigin { param_def_id: Some(param.def_id), span },
934 );
935
936 Ty::new_var(self.tcx, ty_var_id).into()
937 }
938 GenericParamDefKind::Const { .. } => {
939 let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
940 let const_var_id = self
941 .inner
942 .borrow_mut()
943 .const_unification_table()
944 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
945 .vid;
946 ty::Const::new_var(self.tcx, const_var_id).into()
947 }
948 }
949 }
950
951 pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
954 GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
955 }
956
957 #[must_use = "this method does not have any side effects"]
963 pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
964 self.tainted_by_errors.get()
965 }
966
967 pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
970 debug!("set_tainted_by_errors(ErrorGuaranteed)");
971 self.tainted_by_errors.set(Some(e));
972 }
973
974 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
975 let mut inner = self.inner.borrow_mut();
976 let inner = &mut *inner;
977 inner.unwrap_region_constraints().var_origin(vid)
978 }
979
980 pub fn get_region_var_infos(&self) -> VarInfos {
983 let inner = self.inner.borrow();
984 assert!(!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log));
985 let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
986 assert!(storage.data.is_empty(), "{:#?}", storage.data);
987 storage.var_infos.clone()
991 }
992
993 #[instrument(level = "debug", skip(self), ret)]
994 pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
995 self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
996 }
997
998 #[instrument(level = "debug", skip(self), ret)]
999 pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
1000 self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
1001 }
1002
1003 #[inline(always)]
1004 pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1005 debug_assert!(!self.next_trait_solver());
1006 match self.typing_mode() {
1007 TypingMode::Analysis {
1008 defining_opaque_types_and_generators: defining_opaque_types,
1009 }
1010 | TypingMode::Borrowck { defining_opaque_types } => {
1011 id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1012 }
1013 TypingMode::Coherence
1017 | TypingMode::PostBorrowckAnalysis { .. }
1018 | TypingMode::PostAnalysis => false,
1019 }
1020 }
1021
1022 pub fn push_hir_typeck_potentially_region_dependent_goal(
1023 &self,
1024 goal: PredicateObligation<'tcx>,
1025 ) {
1026 let mut inner = self.inner.borrow_mut();
1027 inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1028 inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1029 }
1030
1031 pub fn take_hir_typeck_potentially_region_dependent_goals(
1032 &self,
1033 ) -> Vec<PredicateObligation<'tcx>> {
1034 assert!(!self.in_snapshot(), "cannot take goals in a snapshot");
1035 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1036 }
1037
1038 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1039 self.resolve_vars_if_possible(t).to_string()
1040 }
1041
1042 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1045 use self::type_variable::TypeVariableValue;
1046
1047 match self.inner.borrow_mut().type_variables().probe(vid) {
1048 TypeVariableValue::Known { value } => Ok(value),
1049 TypeVariableValue::Unknown { universe } => Err(universe),
1050 }
1051 }
1052
1053 pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1054 if let ty::Infer(v) = *ty.kind() {
1055 match v {
1056 ty::TyVar(v) => {
1057 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1070 known.map_or(ty, |t| self.shallow_resolve(t))
1071 }
1072
1073 ty::IntVar(v) => {
1074 match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1075 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1076 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1077 ty::IntVarValue::Unknown => ty,
1078 }
1079 }
1080
1081 ty::FloatVar(v) => {
1082 match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1083 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1084 ty::FloatVarValue::Unknown => ty,
1085 }
1086 }
1087
1088 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1089 }
1090 } else {
1091 ty
1092 }
1093 }
1094
1095 pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1096 match ct.kind() {
1097 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1098 InferConst::Var(vid) => self
1099 .inner
1100 .borrow_mut()
1101 .const_unification_table()
1102 .probe_value(vid)
1103 .known()
1104 .unwrap_or(ct),
1105 InferConst::Fresh(_) => ct,
1106 },
1107 ty::ConstKind::Param(_)
1108 | ty::ConstKind::Bound(_, _)
1109 | ty::ConstKind::Placeholder(_)
1110 | ty::ConstKind::Unevaluated(_)
1111 | ty::ConstKind::Value(_)
1112 | ty::ConstKind::Error(_)
1113 | ty::ConstKind::Expr(_) => ct,
1114 }
1115 }
1116
1117 pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1118 match term.kind() {
1119 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1120 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1121 }
1122 }
1123
1124 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1125 self.inner.borrow_mut().type_variables().root_var(var)
1126 }
1127
1128 pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1129 self.inner.borrow_mut().const_unification_table().find(var).vid
1130 }
1131
1132 pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1135 let mut inner = self.inner.borrow_mut();
1136 let value = inner.int_unification_table().probe_value(vid);
1137 match value {
1138 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1139 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1140 ty::IntVarValue::Unknown => {
1141 Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1142 }
1143 }
1144 }
1145
1146 pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1149 let mut inner = self.inner.borrow_mut();
1150 let value = inner.float_unification_table().probe_value(vid);
1151 match value {
1152 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1153 ty::FloatVarValue::Unknown => {
1154 Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1155 }
1156 }
1157 }
1158
1159 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1166 where
1167 T: TypeFoldable<TyCtxt<'tcx>>,
1168 {
1169 if let Err(guar) = value.error_reported() {
1170 self.set_tainted_by_errors(guar);
1171 }
1172 if !value.has_non_region_infer() {
1173 return value;
1174 }
1175 let mut r = resolve::OpportunisticVarResolver::new(self);
1176 value.fold_with(&mut r)
1177 }
1178
1179 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1180 where
1181 T: TypeFoldable<TyCtxt<'tcx>>,
1182 {
1183 if !value.has_infer() {
1184 return value; }
1186 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1187 value.fold_with(&mut r)
1188 }
1189
1190 pub fn probe_const_var(&self, vid: ty::ConstVid) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1191 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1192 ConstVariableValue::Known { value } => Ok(value),
1193 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1194 }
1195 }
1196
1197 pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1205 match resolve::fully_resolve(self, value) {
1206 Ok(value) => {
1207 if value.has_non_region_infer() {
1208 bug!("`{value:?}` is not fully resolved");
1209 }
1210 if value.has_infer_regions() {
1211 let guar = self.dcx().delayed_bug(format!("`{value:?}` is not fully resolved"));
1212 Ok(fold_regions(self.tcx, value, |re, _| {
1213 if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1214 }))
1215 } else {
1216 Ok(value)
1217 }
1218 }
1219 Err(e) => Err(e),
1220 }
1221 }
1222
1223 pub fn instantiate_binder_with_fresh_vars<T>(
1231 &self,
1232 span: Span,
1233 lbrct: BoundRegionConversionTime,
1234 value: ty::Binder<'tcx, T>,
1235 ) -> T
1236 where
1237 T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1238 {
1239 if let Some(inner) = value.no_bound_vars() {
1240 return inner;
1241 }
1242
1243 let bound_vars = value.bound_vars();
1244 let mut args = Vec::with_capacity(bound_vars.len());
1245
1246 for bound_var_kind in bound_vars {
1247 let arg: ty::GenericArg<'_> = match bound_var_kind {
1248 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1249 ty::BoundVariableKind::Region(br) => {
1250 self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1251 }
1252 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1253 };
1254 args.push(arg);
1255 }
1256
1257 struct ToFreshVars<'tcx> {
1258 args: Vec<ty::GenericArg<'tcx>>,
1259 }
1260
1261 impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1262 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1263 self.args[br.var.index()].expect_region()
1264 }
1265 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1266 self.args[bt.var.index()].expect_ty()
1267 }
1268 fn replace_const(&mut self, bv: ty::BoundVar) -> ty::Const<'tcx> {
1269 self.args[bv.index()].expect_const()
1270 }
1271 }
1272 let delegate = ToFreshVars { args };
1273 self.tcx.replace_bound_vars_uncached(value, delegate)
1274 }
1275
1276 pub(crate) fn verify_generic_bound(
1278 &self,
1279 origin: SubregionOrigin<'tcx>,
1280 kind: GenericKind<'tcx>,
1281 a: ty::Region<'tcx>,
1282 bound: VerifyBound<'tcx>,
1283 ) {
1284 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1285
1286 self.inner
1287 .borrow_mut()
1288 .unwrap_region_constraints()
1289 .verify_generic_bound(origin, kind, a, bound);
1290 }
1291
1292 pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1296 let unresolved_kind_ty = match *closure_ty.kind() {
1297 ty::Closure(_, args) => args.as_closure().kind_ty(),
1298 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1299 _ => bug!("unexpected type {closure_ty}"),
1300 };
1301 let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1302 closure_kind_ty.to_opt_closure_kind()
1303 }
1304
1305 pub fn universe(&self) -> ty::UniverseIndex {
1306 self.universe.get()
1307 }
1308
1309 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1312 let u = self.universe.get().next_universe();
1313 debug!("create_next_universe {u:?}");
1314 self.universe.set(u);
1315 u
1316 }
1317
1318 pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1322 let typing_mode = match self.typing_mode() {
1323 ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1328 | ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1329 TypingMode::non_body_analysis()
1330 }
1331 mode @ (ty::TypingMode::Coherence
1332 | ty::TypingMode::PostBorrowckAnalysis { .. }
1333 | ty::TypingMode::PostAnalysis) => mode,
1334 };
1335 ty::TypingEnv { typing_mode, param_env }
1336 }
1337
1338 pub fn pseudo_canonicalize_query<V>(
1342 &self,
1343 param_env: ty::ParamEnv<'tcx>,
1344 value: V,
1345 ) -> PseudoCanonicalInput<'tcx, V>
1346 where
1347 V: TypeVisitable<TyCtxt<'tcx>>,
1348 {
1349 debug_assert!(!value.has_infer());
1350 debug_assert!(!value.has_placeholders());
1351 debug_assert!(!param_env.has_infer());
1352 debug_assert!(!param_env.has_placeholders());
1353 self.typing_env(param_env).as_query_input(value)
1354 }
1355
1356 #[inline]
1359 pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1360 let inner = self.inner.try_borrow();
1362
1363 move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1364 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1365 use self::type_variable::TypeVariableValue;
1366
1367 matches!(
1368 inner.try_type_variables_probe_ref(ty_var),
1369 Some(TypeVariableValue::Unknown { .. })
1370 )
1371 }
1372 _ => false,
1373 }
1374 }
1375
1376 #[inline(always)]
1386 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1387 match infer_var {
1388 TyOrConstInferVar::Ty(v) => {
1389 use self::type_variable::TypeVariableValue;
1390
1391 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1394 TypeVariableValue::Unknown { .. } => false,
1395 TypeVariableValue::Known { .. } => true,
1396 }
1397 }
1398
1399 TyOrConstInferVar::TyInt(v) => {
1400 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1404 }
1405
1406 TyOrConstInferVar::TyFloat(v) => {
1407 self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1412 }
1413
1414 TyOrConstInferVar::Const(v) => {
1415 match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1420 ConstVariableValue::Unknown { .. } => false,
1421 ConstVariableValue::Known { .. } => true,
1422 }
1423 }
1424 }
1425 }
1426
1427 pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1429 debug_assert!(
1430 self.obligation_inspector.get().is_none(),
1431 "shouldn't override a set obligation inspector"
1432 );
1433 self.obligation_inspector.set(Some(inspector));
1434 }
1435}
1436
1437#[derive(Copy, Clone, Debug)]
1440pub enum TyOrConstInferVar {
1441 Ty(TyVid),
1443 TyInt(IntVid),
1445 TyFloat(FloatVid),
1447
1448 Const(ConstVid),
1450}
1451
1452impl<'tcx> TyOrConstInferVar {
1453 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1457 match arg.kind() {
1458 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1459 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1460 GenericArgKind::Lifetime(_) => None,
1461 }
1462 }
1463
1464 pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1468 match term.kind() {
1469 TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1470 TermKind::Const(ct) => Self::maybe_from_const(ct),
1471 }
1472 }
1473
1474 fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1477 match *ty.kind() {
1478 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1479 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1480 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1481 _ => None,
1482 }
1483 }
1484
1485 fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1488 match ct.kind() {
1489 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1490 _ => None,
1491 }
1492 }
1493}
1494
1495struct InferenceLiteralEraser<'tcx> {
1498 tcx: TyCtxt<'tcx>,
1499}
1500
1501impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1502 fn cx(&self) -> TyCtxt<'tcx> {
1503 self.tcx
1504 }
1505
1506 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1507 match ty.kind() {
1508 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1509 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1510 _ => ty.super_fold_with(self),
1511 }
1512 }
1513}
1514
1515impl<'tcx> TypeTrace<'tcx> {
1516 pub fn span(&self) -> Span {
1517 self.cause.span
1518 }
1519
1520 pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1521 TypeTrace {
1522 cause: cause.clone(),
1523 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1524 }
1525 }
1526
1527 pub fn trait_refs(
1528 cause: &ObligationCause<'tcx>,
1529 a: ty::TraitRef<'tcx>,
1530 b: ty::TraitRef<'tcx>,
1531 ) -> TypeTrace<'tcx> {
1532 TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1533 }
1534
1535 pub fn consts(
1536 cause: &ObligationCause<'tcx>,
1537 a: ty::Const<'tcx>,
1538 b: ty::Const<'tcx>,
1539 ) -> TypeTrace<'tcx> {
1540 TypeTrace {
1541 cause: cause.clone(),
1542 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1543 }
1544 }
1545}
1546
1547impl<'tcx> SubregionOrigin<'tcx> {
1548 pub fn span(&self) -> Span {
1549 match *self {
1550 SubregionOrigin::Subtype(ref a) => a.span(),
1551 SubregionOrigin::RelateObjectBound(a) => a,
1552 SubregionOrigin::RelateParamBound(a, ..) => a,
1553 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1554 SubregionOrigin::Reborrow(a) => a,
1555 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1556 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1557 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1558 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1559 }
1560 }
1561
1562 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1563 where
1564 F: FnOnce() -> Self,
1565 {
1566 match *cause.code() {
1567 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1568 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1569 }
1570
1571 traits::ObligationCauseCode::CompareImplItem {
1572 impl_item_def_id,
1573 trait_item_def_id,
1574 kind: _,
1575 } => SubregionOrigin::CompareImplItemObligation {
1576 span: cause.span,
1577 impl_item_def_id,
1578 trait_item_def_id,
1579 },
1580
1581 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1582 impl_item_def_id,
1583 trait_item_def_id,
1584 } => SubregionOrigin::CheckAssociatedTypeBounds {
1585 impl_item_def_id,
1586 trait_item_def_id,
1587 parent: Box::new(default()),
1588 },
1589
1590 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1591 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1592 }
1593
1594 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1595 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1596 }
1597
1598 _ => default(),
1599 }
1600 }
1601}
1602
1603impl RegionVariableOrigin {
1604 pub fn span(&self) -> Span {
1605 match *self {
1606 RegionVariableOrigin::Misc(a)
1607 | RegionVariableOrigin::PatternRegion(a)
1608 | RegionVariableOrigin::BorrowRegion(a)
1609 | RegionVariableOrigin::Autoref(a)
1610 | RegionVariableOrigin::Coercion(a)
1611 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1612 | RegionVariableOrigin::BoundRegion(a, ..)
1613 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1614 RegionVariableOrigin::Nll(..) => bug!("NLL variable used with `span`"),
1615 }
1616 }
1617}
1618
1619impl<'tcx> InferCtxt<'tcx> {
1620 pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1623 let block = block.innermost_block();
1624 if let Some(expr) = &block.expr {
1625 expr.span
1626 } else if let Some(stmt) = block.stmts.last() {
1627 stmt.span
1629 } else {
1630 block.span
1632 }
1633 }
1634
1635 pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1638 match self.tcx.hir_node(hir_id) {
1639 hir::Node::Block(blk)
1640 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1641 self.find_block_span(blk)
1642 }
1643 hir::Node::Expr(e) => e.span,
1644 _ => DUMMY_SP,
1645 }
1646 }
1647}