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 name: Option<Symbol>,
488 },
489}
490
491#[derive(Copy, Clone, Debug)]
492pub struct FixupError {
493 unresolved: TyOrConstInferVar,
494}
495
496impl fmt::Display for FixupError {
497 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498 match self.unresolved {
499 TyOrConstInferVar::TyInt(_) => write!(
500 f,
501 "cannot determine the type of this integer; \
502 add a suffix to specify the type explicitly"
503 ),
504 TyOrConstInferVar::TyFloat(_) => write!(
505 f,
506 "cannot determine the type of this number; \
507 add a suffix to specify the type explicitly"
508 ),
509 TyOrConstInferVar::Ty(_) => write!(f, "unconstrained type"),
510 TyOrConstInferVar::Const(_) => write!(f, "unconstrained const value"),
511 }
512 }
513}
514
515#[derive(Clone, Debug)]
517pub struct TypeOutlivesConstraint<'tcx> {
518 pub sub_region: ty::Region<'tcx>,
519 pub sup_type: Ty<'tcx>,
520 pub origin: SubregionOrigin<'tcx>,
521}
522
523pub struct InferCtxtBuilder<'tcx> {
525 tcx: TyCtxt<'tcx>,
526 considering_regions: bool,
527 in_hir_typeck: bool,
528 skip_leak_check: bool,
529 next_trait_solver: bool,
532}
533
534#[extension(pub trait TyCtxtInferExt<'tcx>)]
535impl<'tcx> TyCtxt<'tcx> {
536 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
537 InferCtxtBuilder {
538 tcx: self,
539 considering_regions: true,
540 in_hir_typeck: false,
541 skip_leak_check: false,
542 next_trait_solver: self.next_trait_solver_globally(),
543 }
544 }
545}
546
547impl<'tcx> InferCtxtBuilder<'tcx> {
548 pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
549 self.next_trait_solver = next_trait_solver;
550 self
551 }
552
553 pub fn ignoring_regions(mut self) -> Self {
554 self.considering_regions = false;
555 self
556 }
557
558 pub fn in_hir_typeck(mut self) -> Self {
559 self.in_hir_typeck = true;
560 self
561 }
562
563 pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
564 self.skip_leak_check = skip_leak_check;
565 self
566 }
567
568 pub fn build_with_canonical<T>(
576 mut self,
577 span: Span,
578 input: &CanonicalQueryInput<'tcx, T>,
579 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
580 where
581 T: TypeFoldable<TyCtxt<'tcx>>,
582 {
583 let infcx = self.build(input.typing_mode);
584 let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
585 (infcx, value, args)
586 }
587
588 pub fn build_with_typing_env(
589 mut self,
590 TypingEnv { typing_mode, param_env }: TypingEnv<'tcx>,
591 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
592 (self.build(typing_mode), param_env)
593 }
594
595 pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
596 let InferCtxtBuilder {
597 tcx,
598 considering_regions,
599 in_hir_typeck,
600 skip_leak_check,
601 next_trait_solver,
602 } = *self;
603 InferCtxt {
604 tcx,
605 typing_mode,
606 considering_regions,
607 in_hir_typeck,
608 skip_leak_check,
609 inner: RefCell::new(InferCtxtInner::new()),
610 lexical_region_resolutions: RefCell::new(None),
611 selection_cache: Default::default(),
612 evaluation_cache: Default::default(),
613 reported_trait_errors: Default::default(),
614 reported_signature_mismatch: Default::default(),
615 tainted_by_errors: Cell::new(None),
616 universe: Cell::new(ty::UniverseIndex::ROOT),
617 next_trait_solver,
618 obligation_inspector: Cell::new(None),
619 }
620 }
621}
622
623impl<'tcx, T> InferOk<'tcx, T> {
624 pub fn into_value_registering_obligations<E: 'tcx>(
626 self,
627 infcx: &InferCtxt<'tcx>,
628 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
629 ) -> T {
630 let InferOk { value, obligations } = self;
631 fulfill_cx.register_predicate_obligations(infcx, obligations);
632 value
633 }
634}
635
636impl<'tcx> InferOk<'tcx, ()> {
637 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
638 self.obligations
639 }
640}
641
642impl<'tcx> InferCtxt<'tcx> {
643 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
644 self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
645 }
646
647 pub fn next_trait_solver(&self) -> bool {
648 self.next_trait_solver
649 }
650
651 #[inline(always)]
652 pub fn typing_mode(&self) -> TypingMode<'tcx> {
653 self.typing_mode
654 }
655
656 pub fn freshen<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> T {
657 t.fold_with(&mut self.freshener())
658 }
659
660 pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
664 self.inner.borrow_mut().type_variables().var_origin(vid)
665 }
666
667 pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
671 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
672 ConstVariableValue::Known { .. } => None,
673 ConstVariableValue::Unknown { origin, .. } => Some(origin),
674 }
675 }
676
677 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
678 freshen::TypeFreshener::new(self)
679 }
680
681 pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
682 let mut inner = self.inner.borrow_mut();
683 let mut vars: Vec<Ty<'_>> = inner
684 .type_variables()
685 .unresolved_variables()
686 .into_iter()
687 .map(|t| Ty::new_var(self.tcx, t))
688 .collect();
689 vars.extend(
690 (0..inner.int_unification_table().len())
691 .map(|i| ty::IntVid::from_usize(i))
692 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
693 .map(|v| Ty::new_int_var(self.tcx, v)),
694 );
695 vars.extend(
696 (0..inner.float_unification_table().len())
697 .map(|i| ty::FloatVid::from_usize(i))
698 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
699 .map(|v| Ty::new_float_var(self.tcx, v)),
700 );
701 vars
702 }
703
704 #[instrument(skip(self), level = "debug")]
705 pub fn sub_regions(
706 &self,
707 origin: SubregionOrigin<'tcx>,
708 a: ty::Region<'tcx>,
709 b: ty::Region<'tcx>,
710 ) {
711 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
712 }
713
714 pub fn coerce_predicate(
730 &self,
731 cause: &ObligationCause<'tcx>,
732 param_env: ty::ParamEnv<'tcx>,
733 predicate: ty::PolyCoercePredicate<'tcx>,
734 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
735 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
736 a_is_expected: false, a: p.a,
738 b: p.b,
739 });
740 self.subtype_predicate(cause, param_env, subtype_predicate)
741 }
742
743 pub fn subtype_predicate(
744 &self,
745 cause: &ObligationCause<'tcx>,
746 param_env: ty::ParamEnv<'tcx>,
747 predicate: ty::PolySubtypePredicate<'tcx>,
748 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
749 let r_a = self.shallow_resolve(predicate.skip_binder().a);
763 let r_b = self.shallow_resolve(predicate.skip_binder().b);
764 match (r_a.kind(), r_b.kind()) {
765 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
766 return Err((a_vid, b_vid));
767 }
768 _ => {}
769 }
770
771 self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
772 if a_is_expected {
773 Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
774 } else {
775 Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
776 }
777 })
778 }
779
780 pub fn num_ty_vars(&self) -> usize {
782 self.inner.borrow_mut().type_variables().num_vars()
783 }
784
785 pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
786 self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
787 }
788
789 pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
790 let vid = self.inner.borrow_mut().type_variables().new_var(self.universe(), origin);
791 Ty::new_var(self.tcx, vid)
792 }
793
794 pub fn next_ty_var_id_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_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
800 let vid = self.next_ty_var_id_in_universe(span, universe);
801 Ty::new_var(self.tcx, vid)
802 }
803
804 pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
805 self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
806 }
807
808 pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
809 let vid = self
810 .inner
811 .borrow_mut()
812 .const_unification_table()
813 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
814 .vid;
815 ty::Const::new_var(self.tcx, vid)
816 }
817
818 pub fn next_const_var_in_universe(
819 &self,
820 span: Span,
821 universe: ty::UniverseIndex,
822 ) -> ty::Const<'tcx> {
823 let origin = ConstVariableOrigin { span, param_def_id: None };
824 let vid = self
825 .inner
826 .borrow_mut()
827 .const_unification_table()
828 .new_key(ConstVariableValue::Unknown { origin, universe })
829 .vid;
830 ty::Const::new_var(self.tcx, vid)
831 }
832
833 pub fn next_int_var(&self) -> Ty<'tcx> {
834 let next_int_var_id =
835 self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
836 Ty::new_int_var(self.tcx, next_int_var_id)
837 }
838
839 pub fn next_float_var(&self) -> Ty<'tcx> {
840 let next_float_var_id =
841 self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown);
842 Ty::new_float_var(self.tcx, next_float_var_id)
843 }
844
845 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
849 self.next_region_var_in_universe(origin, self.universe())
850 }
851
852 pub fn next_region_var_in_universe(
856 &self,
857 origin: RegionVariableOrigin,
858 universe: ty::UniverseIndex,
859 ) -> ty::Region<'tcx> {
860 let region_var =
861 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
862 ty::Region::new_var(self.tcx, region_var)
863 }
864
865 pub fn next_term_var_of_kind(&self, term: ty::Term<'tcx>, span: Span) -> ty::Term<'tcx> {
866 match term.kind() {
867 ty::TermKind::Ty(_) => self.next_ty_var(span).into(),
868 ty::TermKind::Const(_) => self.next_const_var(span).into(),
869 }
870 }
871
872 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
878 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
879 }
880
881 pub fn num_region_vars(&self) -> usize {
883 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
884 }
885
886 #[instrument(skip(self), level = "debug")]
888 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
889 self.next_region_var(RegionVariableOrigin::Nll(origin))
890 }
891
892 #[instrument(skip(self), level = "debug")]
894 pub fn next_nll_region_var_in_universe(
895 &self,
896 origin: NllRegionVariableOrigin,
897 universe: ty::UniverseIndex,
898 ) -> ty::Region<'tcx> {
899 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
900 }
901
902 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
903 match param.kind {
904 GenericParamDefKind::Lifetime => {
905 self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
908 span, param.name,
909 ))
910 .into()
911 }
912 GenericParamDefKind::Type { .. } => {
913 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
922 self.universe(),
923 TypeVariableOrigin { param_def_id: Some(param.def_id), span },
924 );
925
926 Ty::new_var(self.tcx, ty_var_id).into()
927 }
928 GenericParamDefKind::Const { .. } => {
929 let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
930 let const_var_id = self
931 .inner
932 .borrow_mut()
933 .const_unification_table()
934 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
935 .vid;
936 ty::Const::new_var(self.tcx, const_var_id).into()
937 }
938 }
939 }
940
941 pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
944 GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
945 }
946
947 #[must_use = "this method does not have any side effects"]
953 pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
954 self.tainted_by_errors.get()
955 }
956
957 pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
960 debug!("set_tainted_by_errors(ErrorGuaranteed)");
961 self.tainted_by_errors.set(Some(e));
962 }
963
964 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
965 let mut inner = self.inner.borrow_mut();
966 let inner = &mut *inner;
967 inner.unwrap_region_constraints().var_origin(vid)
968 }
969
970 pub fn get_region_var_infos(&self) -> VarInfos {
973 let inner = self.inner.borrow();
974 assert!(!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log));
975 let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
976 assert!(storage.data.is_empty(), "{:#?}", storage.data);
977 storage.var_infos.clone()
981 }
982
983 #[instrument(level = "debug", skip(self), ret)]
984 pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
985 self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
986 }
987
988 #[instrument(level = "debug", skip(self), ret)]
989 pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
990 self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
991 }
992
993 #[inline(always)]
994 pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
995 debug_assert!(!self.next_trait_solver());
996 match self.typing_mode() {
997 TypingMode::Analysis {
998 defining_opaque_types_and_generators: defining_opaque_types,
999 }
1000 | TypingMode::Borrowck { defining_opaque_types } => {
1001 id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1002 }
1003 TypingMode::Coherence
1007 | TypingMode::PostBorrowckAnalysis { .. }
1008 | TypingMode::PostAnalysis => false,
1009 }
1010 }
1011
1012 pub fn push_hir_typeck_potentially_region_dependent_goal(
1013 &self,
1014 goal: PredicateObligation<'tcx>,
1015 ) {
1016 let mut inner = self.inner.borrow_mut();
1017 inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1018 inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1019 }
1020
1021 pub fn take_hir_typeck_potentially_region_dependent_goals(
1022 &self,
1023 ) -> Vec<PredicateObligation<'tcx>> {
1024 assert!(!self.in_snapshot(), "cannot take goals in a snapshot");
1025 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1026 }
1027
1028 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1029 self.resolve_vars_if_possible(t).to_string()
1030 }
1031
1032 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1035 use self::type_variable::TypeVariableValue;
1036
1037 match self.inner.borrow_mut().type_variables().probe(vid) {
1038 TypeVariableValue::Known { value } => Ok(value),
1039 TypeVariableValue::Unknown { universe } => Err(universe),
1040 }
1041 }
1042
1043 pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1044 if let ty::Infer(v) = *ty.kind() {
1045 match v {
1046 ty::TyVar(v) => {
1047 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1060 known.map_or(ty, |t| self.shallow_resolve(t))
1061 }
1062
1063 ty::IntVar(v) => {
1064 match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1065 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1066 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1067 ty::IntVarValue::Unknown => ty,
1068 }
1069 }
1070
1071 ty::FloatVar(v) => {
1072 match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1073 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1074 ty::FloatVarValue::Unknown => ty,
1075 }
1076 }
1077
1078 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1079 }
1080 } else {
1081 ty
1082 }
1083 }
1084
1085 pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1086 match ct.kind() {
1087 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1088 InferConst::Var(vid) => self
1089 .inner
1090 .borrow_mut()
1091 .const_unification_table()
1092 .probe_value(vid)
1093 .known()
1094 .unwrap_or(ct),
1095 InferConst::Fresh(_) => ct,
1096 },
1097 ty::ConstKind::Param(_)
1098 | ty::ConstKind::Bound(_, _)
1099 | ty::ConstKind::Placeholder(_)
1100 | ty::ConstKind::Unevaluated(_)
1101 | ty::ConstKind::Value(_)
1102 | ty::ConstKind::Error(_)
1103 | ty::ConstKind::Expr(_) => ct,
1104 }
1105 }
1106
1107 pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1108 match term.kind() {
1109 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1110 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1111 }
1112 }
1113
1114 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1115 self.inner.borrow_mut().type_variables().root_var(var)
1116 }
1117
1118 pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1119 self.inner.borrow_mut().const_unification_table().find(var).vid
1120 }
1121
1122 pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1125 let mut inner = self.inner.borrow_mut();
1126 let value = inner.int_unification_table().probe_value(vid);
1127 match value {
1128 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1129 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1130 ty::IntVarValue::Unknown => {
1131 Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1132 }
1133 }
1134 }
1135
1136 pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1139 let mut inner = self.inner.borrow_mut();
1140 let value = inner.float_unification_table().probe_value(vid);
1141 match value {
1142 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1143 ty::FloatVarValue::Unknown => {
1144 Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1145 }
1146 }
1147 }
1148
1149 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1156 where
1157 T: TypeFoldable<TyCtxt<'tcx>>,
1158 {
1159 if let Err(guar) = value.error_reported() {
1160 self.set_tainted_by_errors(guar);
1161 }
1162 if !value.has_non_region_infer() {
1163 return value;
1164 }
1165 let mut r = resolve::OpportunisticVarResolver::new(self);
1166 value.fold_with(&mut r)
1167 }
1168
1169 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1170 where
1171 T: TypeFoldable<TyCtxt<'tcx>>,
1172 {
1173 if !value.has_infer() {
1174 return value; }
1176 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1177 value.fold_with(&mut r)
1178 }
1179
1180 pub fn probe_const_var(&self, vid: ty::ConstVid) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1181 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1182 ConstVariableValue::Known { value } => Ok(value),
1183 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1184 }
1185 }
1186
1187 pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1195 match resolve::fully_resolve(self, value) {
1196 Ok(value) => {
1197 if value.has_non_region_infer() {
1198 bug!("`{value:?}` is not fully resolved");
1199 }
1200 if value.has_infer_regions() {
1201 let guar = self.dcx().delayed_bug(format!("`{value:?}` is not fully resolved"));
1202 Ok(fold_regions(self.tcx, value, |re, _| {
1203 if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1204 }))
1205 } else {
1206 Ok(value)
1207 }
1208 }
1209 Err(e) => Err(e),
1210 }
1211 }
1212
1213 pub fn instantiate_binder_with_fresh_vars<T>(
1221 &self,
1222 span: Span,
1223 lbrct: BoundRegionConversionTime,
1224 value: ty::Binder<'tcx, T>,
1225 ) -> T
1226 where
1227 T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1228 {
1229 if let Some(inner) = value.no_bound_vars() {
1230 return inner;
1231 }
1232
1233 let bound_vars = value.bound_vars();
1234 let mut args = Vec::with_capacity(bound_vars.len());
1235
1236 for bound_var_kind in bound_vars {
1237 let arg: ty::GenericArg<'_> = match bound_var_kind {
1238 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1239 ty::BoundVariableKind::Region(br) => {
1240 self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1241 }
1242 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1243 };
1244 args.push(arg);
1245 }
1246
1247 struct ToFreshVars<'tcx> {
1248 args: Vec<ty::GenericArg<'tcx>>,
1249 }
1250
1251 impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1252 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1253 self.args[br.var.index()].expect_region()
1254 }
1255 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1256 self.args[bt.var.index()].expect_ty()
1257 }
1258 fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx> {
1259 self.args[bc.var.index()].expect_const()
1260 }
1261 }
1262 let delegate = ToFreshVars { args };
1263 self.tcx.replace_bound_vars_uncached(value, delegate)
1264 }
1265
1266 pub(crate) fn verify_generic_bound(
1268 &self,
1269 origin: SubregionOrigin<'tcx>,
1270 kind: GenericKind<'tcx>,
1271 a: ty::Region<'tcx>,
1272 bound: VerifyBound<'tcx>,
1273 ) {
1274 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1275
1276 self.inner
1277 .borrow_mut()
1278 .unwrap_region_constraints()
1279 .verify_generic_bound(origin, kind, a, bound);
1280 }
1281
1282 pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1286 let unresolved_kind_ty = match *closure_ty.kind() {
1287 ty::Closure(_, args) => args.as_closure().kind_ty(),
1288 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1289 _ => bug!("unexpected type {closure_ty}"),
1290 };
1291 let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1292 closure_kind_ty.to_opt_closure_kind()
1293 }
1294
1295 pub fn universe(&self) -> ty::UniverseIndex {
1296 self.universe.get()
1297 }
1298
1299 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1302 let u = self.universe.get().next_universe();
1303 debug!("create_next_universe {u:?}");
1304 self.universe.set(u);
1305 u
1306 }
1307
1308 pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1312 let typing_mode = match self.typing_mode() {
1313 ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1318 | ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1319 TypingMode::non_body_analysis()
1320 }
1321 mode @ (ty::TypingMode::Coherence
1322 | ty::TypingMode::PostBorrowckAnalysis { .. }
1323 | ty::TypingMode::PostAnalysis) => mode,
1324 };
1325 ty::TypingEnv { typing_mode, param_env }
1326 }
1327
1328 pub fn pseudo_canonicalize_query<V>(
1332 &self,
1333 param_env: ty::ParamEnv<'tcx>,
1334 value: V,
1335 ) -> PseudoCanonicalInput<'tcx, V>
1336 where
1337 V: TypeVisitable<TyCtxt<'tcx>>,
1338 {
1339 debug_assert!(!value.has_infer());
1340 debug_assert!(!value.has_placeholders());
1341 debug_assert!(!param_env.has_infer());
1342 debug_assert!(!param_env.has_placeholders());
1343 self.typing_env(param_env).as_query_input(value)
1344 }
1345
1346 #[inline]
1349 pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1350 let inner = self.inner.try_borrow();
1352
1353 move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1354 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1355 use self::type_variable::TypeVariableValue;
1356
1357 matches!(
1358 inner.try_type_variables_probe_ref(ty_var),
1359 Some(TypeVariableValue::Unknown { .. })
1360 )
1361 }
1362 _ => false,
1363 }
1364 }
1365
1366 #[inline(always)]
1376 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1377 match infer_var {
1378 TyOrConstInferVar::Ty(v) => {
1379 use self::type_variable::TypeVariableValue;
1380
1381 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1384 TypeVariableValue::Unknown { .. } => false,
1385 TypeVariableValue::Known { .. } => true,
1386 }
1387 }
1388
1389 TyOrConstInferVar::TyInt(v) => {
1390 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1394 }
1395
1396 TyOrConstInferVar::TyFloat(v) => {
1397 self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1402 }
1403
1404 TyOrConstInferVar::Const(v) => {
1405 match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1410 ConstVariableValue::Unknown { .. } => false,
1411 ConstVariableValue::Known { .. } => true,
1412 }
1413 }
1414 }
1415 }
1416
1417 pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1419 debug_assert!(
1420 self.obligation_inspector.get().is_none(),
1421 "shouldn't override a set obligation inspector"
1422 );
1423 self.obligation_inspector.set(Some(inspector));
1424 }
1425}
1426
1427#[derive(Copy, Clone, Debug)]
1430pub enum TyOrConstInferVar {
1431 Ty(TyVid),
1433 TyInt(IntVid),
1435 TyFloat(FloatVid),
1437
1438 Const(ConstVid),
1440}
1441
1442impl<'tcx> TyOrConstInferVar {
1443 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1447 match arg.kind() {
1448 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1449 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1450 GenericArgKind::Lifetime(_) => None,
1451 }
1452 }
1453
1454 pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1458 match term.kind() {
1459 TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1460 TermKind::Const(ct) => Self::maybe_from_const(ct),
1461 }
1462 }
1463
1464 fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1467 match *ty.kind() {
1468 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1469 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1470 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1471 _ => None,
1472 }
1473 }
1474
1475 fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1478 match ct.kind() {
1479 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1480 _ => None,
1481 }
1482 }
1483}
1484
1485struct InferenceLiteralEraser<'tcx> {
1488 tcx: TyCtxt<'tcx>,
1489}
1490
1491impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1492 fn cx(&self) -> TyCtxt<'tcx> {
1493 self.tcx
1494 }
1495
1496 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1497 match ty.kind() {
1498 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1499 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1500 _ => ty.super_fold_with(self),
1501 }
1502 }
1503}
1504
1505impl<'tcx> TypeTrace<'tcx> {
1506 pub fn span(&self) -> Span {
1507 self.cause.span
1508 }
1509
1510 pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1511 TypeTrace {
1512 cause: cause.clone(),
1513 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1514 }
1515 }
1516
1517 pub fn trait_refs(
1518 cause: &ObligationCause<'tcx>,
1519 a: ty::TraitRef<'tcx>,
1520 b: ty::TraitRef<'tcx>,
1521 ) -> TypeTrace<'tcx> {
1522 TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1523 }
1524
1525 pub fn consts(
1526 cause: &ObligationCause<'tcx>,
1527 a: ty::Const<'tcx>,
1528 b: ty::Const<'tcx>,
1529 ) -> TypeTrace<'tcx> {
1530 TypeTrace {
1531 cause: cause.clone(),
1532 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1533 }
1534 }
1535}
1536
1537impl<'tcx> SubregionOrigin<'tcx> {
1538 pub fn span(&self) -> Span {
1539 match *self {
1540 SubregionOrigin::Subtype(ref a) => a.span(),
1541 SubregionOrigin::RelateObjectBound(a) => a,
1542 SubregionOrigin::RelateParamBound(a, ..) => a,
1543 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1544 SubregionOrigin::Reborrow(a) => a,
1545 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1546 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1547 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1548 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1549 }
1550 }
1551
1552 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1553 where
1554 F: FnOnce() -> Self,
1555 {
1556 match *cause.code() {
1557 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1558 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1559 }
1560
1561 traits::ObligationCauseCode::CompareImplItem {
1562 impl_item_def_id,
1563 trait_item_def_id,
1564 kind: _,
1565 } => SubregionOrigin::CompareImplItemObligation {
1566 span: cause.span,
1567 impl_item_def_id,
1568 trait_item_def_id,
1569 },
1570
1571 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1572 impl_item_def_id,
1573 trait_item_def_id,
1574 } => SubregionOrigin::CheckAssociatedTypeBounds {
1575 impl_item_def_id,
1576 trait_item_def_id,
1577 parent: Box::new(default()),
1578 },
1579
1580 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1581 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1582 }
1583
1584 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1585 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1586 }
1587
1588 _ => default(),
1589 }
1590 }
1591}
1592
1593impl RegionVariableOrigin {
1594 pub fn span(&self) -> Span {
1595 match *self {
1596 RegionVariableOrigin::Misc(a)
1597 | RegionVariableOrigin::PatternRegion(a)
1598 | RegionVariableOrigin::BorrowRegion(a)
1599 | RegionVariableOrigin::Autoref(a)
1600 | RegionVariableOrigin::Coercion(a)
1601 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1602 | RegionVariableOrigin::BoundRegion(a, ..)
1603 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1604 RegionVariableOrigin::Nll(..) => bug!("NLL variable used with `span`"),
1605 }
1606 }
1607}
1608
1609impl<'tcx> InferCtxt<'tcx> {
1610 pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1613 let block = block.innermost_block();
1614 if let Some(expr) = &block.expr {
1615 expr.span
1616 } else if let Some(stmt) = block.stmts.last() {
1617 stmt.span
1619 } else {
1620 block.span
1622 }
1623 }
1624
1625 pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1628 match self.tcx.hir_node(hir_id) {
1629 hir::Node::Block(blk)
1630 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1631 self.find_block_span(blk)
1632 }
1633 hir::Node::Expr(e) => e.span,
1634 _ => DUMMY_SP,
1635 }
1636 }
1637}