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>>,
135
136 region_assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
142
143 hir_typeck_potentially_region_dependent_goals: Vec<PredicateObligation<'tcx>>,
149
150 opaque_type_storage: OpaqueTypeStorage<'tcx>,
152}
153
154impl<'tcx> InferCtxtInner<'tcx> {
155 fn new() -> InferCtxtInner<'tcx> {
156 InferCtxtInner {
157 undo_log: InferCtxtUndoLogs::default(),
158
159 projection_cache: Default::default(),
160 type_variable_storage: Default::default(),
161 const_unification_storage: Default::default(),
162 int_unification_storage: Default::default(),
163 float_unification_storage: Default::default(),
164 region_constraint_storage: Some(Default::default()),
165 region_obligations: Default::default(),
166 region_assumptions: Default::default(),
167 hir_typeck_potentially_region_dependent_goals: Default::default(),
168 opaque_type_storage: Default::default(),
169 }
170 }
171
172 #[inline]
173 pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
174 &self.region_obligations
175 }
176
177 #[inline]
178 pub fn region_assumptions(&self) -> &[ty::ArgOutlivesPredicate<'tcx>] {
179 &self.region_assumptions
180 }
181
182 #[inline]
183 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
184 self.projection_cache.with_log(&mut self.undo_log)
185 }
186
187 #[inline]
188 fn try_type_variables_probe_ref(
189 &self,
190 vid: ty::TyVid,
191 ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
192 self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
195 }
196
197 #[inline]
198 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
199 self.type_variable_storage.with_log(&mut self.undo_log)
200 }
201
202 #[inline]
203 pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
204 self.opaque_type_storage.with_log(&mut self.undo_log)
205 }
206
207 #[inline]
208 fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
209 self.int_unification_storage.with_log(&mut self.undo_log)
210 }
211
212 #[inline]
213 fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
214 self.float_unification_storage.with_log(&mut self.undo_log)
215 }
216
217 #[inline]
218 fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
219 self.const_unification_storage.with_log(&mut self.undo_log)
220 }
221
222 #[inline]
223 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
224 self.region_constraint_storage
225 .as_mut()
226 .expect("region constraints already solved")
227 .with_log(&mut self.undo_log)
228 }
229}
230
231pub struct InferCtxt<'tcx> {
232 pub tcx: TyCtxt<'tcx>,
233
234 typing_mode: TypingMode<'tcx>,
237
238 pub considering_regions: bool,
242 pub in_hir_typeck: bool,
262
263 skip_leak_check: bool,
268
269 pub inner: RefCell<InferCtxtInner<'tcx>>,
270
271 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
273
274 pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
277
278 pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
281
282 pub reported_trait_errors:
285 RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
286
287 pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
288
289 tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
297
298 universe: Cell<ty::UniverseIndex>,
308
309 next_trait_solver: bool,
310
311 pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
312}
313
314#[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
316pub enum ValuePairs<'tcx> {
317 Regions(ExpectedFound<ty::Region<'tcx>>),
318 Terms(ExpectedFound<ty::Term<'tcx>>),
319 Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
320 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
321 PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
322 ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
323 ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
324}
325
326impl<'tcx> ValuePairs<'tcx> {
327 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
328 if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
329 && let Some(expected) = expected.as_type()
330 && let Some(found) = found.as_type()
331 {
332 Some((expected, found))
333 } else {
334 None
335 }
336 }
337}
338
339#[derive(Clone, Debug)]
344pub struct TypeTrace<'tcx> {
345 pub cause: ObligationCause<'tcx>,
346 pub values: ValuePairs<'tcx>,
347}
348
349#[derive(Clone, Debug)]
353pub enum SubregionOrigin<'tcx> {
354 Subtype(Box<TypeTrace<'tcx>>),
356
357 RelateObjectBound(Span),
360
361 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
364
365 RelateRegionParamBound(Span, Option<Ty<'tcx>>),
368
369 Reborrow(Span),
371
372 ReferenceOutlivesReferent(Ty<'tcx>, Span),
374
375 CompareImplItemObligation {
378 span: Span,
379 impl_item_def_id: LocalDefId,
380 trait_item_def_id: DefId,
381 },
382
383 CheckAssociatedTypeBounds {
385 parent: Box<SubregionOrigin<'tcx>>,
386 impl_item_def_id: LocalDefId,
387 trait_item_def_id: DefId,
388 },
389
390 AscribeUserTypeProvePredicate(Span),
391}
392
393#[cfg(target_pointer_width = "64")]
395rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
396
397impl<'tcx> SubregionOrigin<'tcx> {
398 pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
399 match self {
400 Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
401 Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
402 _ => ConstraintCategory::BoringNoLocation,
403 }
404 }
405}
406
407#[derive(Clone, Copy, Debug)]
409pub enum BoundRegionConversionTime {
410 FnCall,
412
413 HigherRankedType,
415
416 AssocTypeProjection(DefId),
418}
419
420#[derive(Copy, Clone, Debug)]
424pub enum RegionVariableOrigin {
425 Misc(Span),
429
430 PatternRegion(Span),
432
433 BorrowRegion(Span),
435
436 Autoref(Span),
438
439 Coercion(Span),
441
442 RegionParameterDefinition(Span, Symbol),
447
448 BoundRegion(Span, ty::BoundRegionKind, BoundRegionConversionTime),
451
452 UpvarRegion(ty::UpvarId, Span),
453
454 Nll(NllRegionVariableOrigin),
457}
458
459#[derive(Copy, Clone, Debug)]
460pub enum NllRegionVariableOrigin {
461 FreeRegion,
465
466 Placeholder(ty::PlaceholderRegion),
469
470 Existential {
471 name: Option<Symbol>,
472 },
473}
474
475#[derive(Copy, Clone, Debug)]
476pub struct FixupError {
477 unresolved: TyOrConstInferVar,
478}
479
480impl fmt::Display for FixupError {
481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482 match self.unresolved {
483 TyOrConstInferVar::TyInt(_) => write!(
484 f,
485 "cannot determine the type of this integer; \
486 add a suffix to specify the type explicitly"
487 ),
488 TyOrConstInferVar::TyFloat(_) => write!(
489 f,
490 "cannot determine the type of this number; \
491 add a suffix to specify the type explicitly"
492 ),
493 TyOrConstInferVar::Ty(_) => write!(f, "unconstrained type"),
494 TyOrConstInferVar::Const(_) => write!(f, "unconstrained const value"),
495 }
496 }
497}
498
499#[derive(Clone, Debug)]
501pub struct TypeOutlivesConstraint<'tcx> {
502 pub sub_region: ty::Region<'tcx>,
503 pub sup_type: Ty<'tcx>,
504 pub origin: SubregionOrigin<'tcx>,
505}
506
507pub struct InferCtxtBuilder<'tcx> {
509 tcx: TyCtxt<'tcx>,
510 considering_regions: bool,
511 in_hir_typeck: bool,
512 skip_leak_check: bool,
513 next_trait_solver: bool,
516}
517
518#[extension(pub trait TyCtxtInferExt<'tcx>)]
519impl<'tcx> TyCtxt<'tcx> {
520 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
521 InferCtxtBuilder {
522 tcx: self,
523 considering_regions: true,
524 in_hir_typeck: false,
525 skip_leak_check: false,
526 next_trait_solver: self.next_trait_solver_globally(),
527 }
528 }
529}
530
531impl<'tcx> InferCtxtBuilder<'tcx> {
532 pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
533 self.next_trait_solver = next_trait_solver;
534 self
535 }
536
537 pub fn ignoring_regions(mut self) -> Self {
538 self.considering_regions = false;
539 self
540 }
541
542 pub fn in_hir_typeck(mut self) -> Self {
543 self.in_hir_typeck = true;
544 self
545 }
546
547 pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
548 self.skip_leak_check = skip_leak_check;
549 self
550 }
551
552 pub fn build_with_canonical<T>(
560 mut self,
561 span: Span,
562 input: &CanonicalQueryInput<'tcx, T>,
563 ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
564 where
565 T: TypeFoldable<TyCtxt<'tcx>>,
566 {
567 let infcx = self.build(input.typing_mode);
568 let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
569 (infcx, value, args)
570 }
571
572 pub fn build_with_typing_env(
573 mut self,
574 TypingEnv { typing_mode, param_env }: TypingEnv<'tcx>,
575 ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
576 (self.build(typing_mode), param_env)
577 }
578
579 pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
580 let InferCtxtBuilder {
581 tcx,
582 considering_regions,
583 in_hir_typeck,
584 skip_leak_check,
585 next_trait_solver,
586 } = *self;
587 InferCtxt {
588 tcx,
589 typing_mode,
590 considering_regions,
591 in_hir_typeck,
592 skip_leak_check,
593 inner: RefCell::new(InferCtxtInner::new()),
594 lexical_region_resolutions: RefCell::new(None),
595 selection_cache: Default::default(),
596 evaluation_cache: Default::default(),
597 reported_trait_errors: Default::default(),
598 reported_signature_mismatch: Default::default(),
599 tainted_by_errors: Cell::new(None),
600 universe: Cell::new(ty::UniverseIndex::ROOT),
601 next_trait_solver,
602 obligation_inspector: Cell::new(None),
603 }
604 }
605}
606
607impl<'tcx, T> InferOk<'tcx, T> {
608 pub fn into_value_registering_obligations<E: 'tcx>(
610 self,
611 infcx: &InferCtxt<'tcx>,
612 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
613 ) -> T {
614 let InferOk { value, obligations } = self;
615 fulfill_cx.register_predicate_obligations(infcx, obligations);
616 value
617 }
618}
619
620impl<'tcx> InferOk<'tcx, ()> {
621 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
622 self.obligations
623 }
624}
625
626impl<'tcx> InferCtxt<'tcx> {
627 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
628 self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
629 }
630
631 pub fn next_trait_solver(&self) -> bool {
632 self.next_trait_solver
633 }
634
635 #[inline(always)]
636 pub fn typing_mode(&self) -> TypingMode<'tcx> {
637 self.typing_mode
638 }
639
640 pub fn freshen<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> T {
641 t.fold_with(&mut self.freshener())
642 }
643
644 pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
648 self.inner.borrow_mut().type_variables().var_origin(vid)
649 }
650
651 pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
655 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
656 ConstVariableValue::Known { .. } => None,
657 ConstVariableValue::Unknown { origin, .. } => Some(origin),
658 }
659 }
660
661 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
662 freshen::TypeFreshener::new(self)
663 }
664
665 pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
666 let mut inner = self.inner.borrow_mut();
667 let mut vars: Vec<Ty<'_>> = inner
668 .type_variables()
669 .unresolved_variables()
670 .into_iter()
671 .map(|t| Ty::new_var(self.tcx, t))
672 .collect();
673 vars.extend(
674 (0..inner.int_unification_table().len())
675 .map(|i| ty::IntVid::from_usize(i))
676 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
677 .map(|v| Ty::new_int_var(self.tcx, v)),
678 );
679 vars.extend(
680 (0..inner.float_unification_table().len())
681 .map(|i| ty::FloatVid::from_usize(i))
682 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
683 .map(|v| Ty::new_float_var(self.tcx, v)),
684 );
685 vars
686 }
687
688 #[instrument(skip(self), level = "debug")]
689 pub fn sub_regions(
690 &self,
691 origin: SubregionOrigin<'tcx>,
692 a: ty::Region<'tcx>,
693 b: ty::Region<'tcx>,
694 ) {
695 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
696 }
697
698 pub fn coerce_predicate(
714 &self,
715 cause: &ObligationCause<'tcx>,
716 param_env: ty::ParamEnv<'tcx>,
717 predicate: ty::PolyCoercePredicate<'tcx>,
718 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
719 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
720 a_is_expected: false, a: p.a,
722 b: p.b,
723 });
724 self.subtype_predicate(cause, param_env, subtype_predicate)
725 }
726
727 pub fn subtype_predicate(
728 &self,
729 cause: &ObligationCause<'tcx>,
730 param_env: ty::ParamEnv<'tcx>,
731 predicate: ty::PolySubtypePredicate<'tcx>,
732 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
733 let r_a = self.shallow_resolve(predicate.skip_binder().a);
747 let r_b = self.shallow_resolve(predicate.skip_binder().b);
748 match (r_a.kind(), r_b.kind()) {
749 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
750 self.sub_unify_ty_vids_raw(a_vid, b_vid);
751 return Err((a_vid, b_vid));
752 }
753 _ => {}
754 }
755
756 self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
757 if a_is_expected {
758 Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
759 } else {
760 Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
761 }
762 })
763 }
764
765 pub fn num_ty_vars(&self) -> usize {
767 self.inner.borrow_mut().type_variables().num_vars()
768 }
769
770 pub fn next_ty_vid(&self, span: Span) -> TyVid {
771 self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
772 }
773
774 pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
775 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
776 }
777
778 pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
779 let origin = TypeVariableOrigin { span, param_def_id: None };
780 self.inner.borrow_mut().type_variables().new_var(universe, origin)
781 }
782
783 pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
784 self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
785 }
786
787 pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
788 let vid = self.next_ty_vid_with_origin(origin);
789 Ty::new_var(self.tcx, vid)
790 }
791
792 pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
793 let vid = self.next_ty_vid_in_universe(span, universe);
794 Ty::new_var(self.tcx, vid)
795 }
796
797 pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
798 self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
799 }
800
801 pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
802 let vid = self
803 .inner
804 .borrow_mut()
805 .const_unification_table()
806 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
807 .vid;
808 ty::Const::new_var(self.tcx, vid)
809 }
810
811 pub fn next_const_var_in_universe(
812 &self,
813 span: Span,
814 universe: ty::UniverseIndex,
815 ) -> ty::Const<'tcx> {
816 let origin = ConstVariableOrigin { span, param_def_id: None };
817 let vid = self
818 .inner
819 .borrow_mut()
820 .const_unification_table()
821 .new_key(ConstVariableValue::Unknown { origin, universe })
822 .vid;
823 ty::Const::new_var(self.tcx, vid)
824 }
825
826 pub fn next_int_var(&self) -> Ty<'tcx> {
827 let next_int_var_id =
828 self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
829 Ty::new_int_var(self.tcx, next_int_var_id)
830 }
831
832 pub fn next_float_var(&self) -> Ty<'tcx> {
833 let next_float_var_id =
834 self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown);
835 Ty::new_float_var(self.tcx, next_float_var_id)
836 }
837
838 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
842 self.next_region_var_in_universe(origin, self.universe())
843 }
844
845 pub fn next_region_var_in_universe(
849 &self,
850 origin: RegionVariableOrigin,
851 universe: ty::UniverseIndex,
852 ) -> ty::Region<'tcx> {
853 let region_var =
854 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
855 ty::Region::new_var(self.tcx, region_var)
856 }
857
858 pub fn next_term_var_of_kind(&self, term: ty::Term<'tcx>, span: Span) -> ty::Term<'tcx> {
859 match term.kind() {
860 ty::TermKind::Ty(_) => self.next_ty_var(span).into(),
861 ty::TermKind::Const(_) => self.next_const_var(span).into(),
862 }
863 }
864
865 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
871 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
872 }
873
874 pub fn num_region_vars(&self) -> usize {
876 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
877 }
878
879 #[instrument(skip(self), level = "debug")]
881 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
882 self.next_region_var(RegionVariableOrigin::Nll(origin))
883 }
884
885 #[instrument(skip(self), level = "debug")]
887 pub fn next_nll_region_var_in_universe(
888 &self,
889 origin: NllRegionVariableOrigin,
890 universe: ty::UniverseIndex,
891 ) -> ty::Region<'tcx> {
892 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
893 }
894
895 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
896 match param.kind {
897 GenericParamDefKind::Lifetime => {
898 self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
901 span, param.name,
902 ))
903 .into()
904 }
905 GenericParamDefKind::Type { .. } => {
906 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
915 self.universe(),
916 TypeVariableOrigin { param_def_id: Some(param.def_id), span },
917 );
918
919 Ty::new_var(self.tcx, ty_var_id).into()
920 }
921 GenericParamDefKind::Const { .. } => {
922 let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
923 let const_var_id = self
924 .inner
925 .borrow_mut()
926 .const_unification_table()
927 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
928 .vid;
929 ty::Const::new_var(self.tcx, const_var_id).into()
930 }
931 }
932 }
933
934 pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
937 GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
938 }
939
940 #[must_use = "this method does not have any side effects"]
946 pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
947 self.tainted_by_errors.get()
948 }
949
950 pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
953 debug!("set_tainted_by_errors(ErrorGuaranteed)");
954 self.tainted_by_errors.set(Some(e));
955 }
956
957 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
958 let mut inner = self.inner.borrow_mut();
959 let inner = &mut *inner;
960 inner.unwrap_region_constraints().var_origin(vid)
961 }
962
963 pub fn get_region_var_infos(&self) -> VarInfos {
966 let inner = self.inner.borrow();
967 assert!(!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log));
968 let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
969 assert!(storage.data.is_empty(), "{:#?}", storage.data);
970 storage.var_infos.clone()
974 }
975
976 pub fn has_opaque_types_in_storage(&self) -> bool {
977 !self.inner.borrow().opaque_type_storage.is_empty()
978 }
979
980 #[instrument(level = "debug", skip(self), ret)]
981 pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
982 self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
983 }
984
985 #[instrument(level = "debug", skip(self), ret)]
986 pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
987 self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
988 }
989
990 pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
991 if !self.next_trait_solver() {
992 return false;
993 }
994
995 let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
996 let inner = &mut *self.inner.borrow_mut();
997 let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
998 inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
999 if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1000 let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1001 if opaque_sub_vid == ty_sub_vid {
1002 return true;
1003 }
1004 }
1005
1006 false
1007 })
1008 }
1009
1010 pub fn opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> Vec<ty::AliasTy<'tcx>> {
1014 if !self.next_trait_solver() {
1016 return vec![];
1017 }
1018
1019 let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1020 let inner = &mut *self.inner.borrow_mut();
1021 let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1024 inner
1025 .opaque_type_storage
1026 .iter_opaque_types()
1027 .filter_map(|(key, hidden_ty)| {
1028 if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1029 let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1030 if opaque_sub_vid == ty_sub_vid {
1031 return Some(ty::AliasTy::new_from_args(
1032 self.tcx,
1033 key.def_id.into(),
1034 key.args,
1035 ));
1036 }
1037 }
1038
1039 None
1040 })
1041 .collect()
1042 }
1043
1044 #[inline(always)]
1045 pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1046 debug_assert!(!self.next_trait_solver());
1047 match self.typing_mode() {
1048 TypingMode::Analysis {
1049 defining_opaque_types_and_generators: defining_opaque_types,
1050 }
1051 | TypingMode::Borrowck { defining_opaque_types } => {
1052 id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1053 }
1054 TypingMode::Coherence
1058 | TypingMode::PostBorrowckAnalysis { .. }
1059 | TypingMode::PostAnalysis => false,
1060 }
1061 }
1062
1063 pub fn push_hir_typeck_potentially_region_dependent_goal(
1064 &self,
1065 goal: PredicateObligation<'tcx>,
1066 ) {
1067 let mut inner = self.inner.borrow_mut();
1068 inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1069 inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1070 }
1071
1072 pub fn take_hir_typeck_potentially_region_dependent_goals(
1073 &self,
1074 ) -> Vec<PredicateObligation<'tcx>> {
1075 assert!(!self.in_snapshot(), "cannot take goals in a snapshot");
1076 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1077 }
1078
1079 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1080 self.resolve_vars_if_possible(t).to_string()
1081 }
1082
1083 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1086 use self::type_variable::TypeVariableValue;
1087
1088 match self.inner.borrow_mut().type_variables().probe(vid) {
1089 TypeVariableValue::Known { value } => Ok(value),
1090 TypeVariableValue::Unknown { universe } => Err(universe),
1091 }
1092 }
1093
1094 pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1095 if let ty::Infer(v) = *ty.kind() {
1096 match v {
1097 ty::TyVar(v) => {
1098 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1111 known.map_or(ty, |t| self.shallow_resolve(t))
1112 }
1113
1114 ty::IntVar(v) => {
1115 match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1116 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1117 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1118 ty::IntVarValue::Unknown => ty,
1119 }
1120 }
1121
1122 ty::FloatVar(v) => {
1123 match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1124 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1125 ty::FloatVarValue::Unknown => ty,
1126 }
1127 }
1128
1129 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1130 }
1131 } else {
1132 ty
1133 }
1134 }
1135
1136 pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1137 match ct.kind() {
1138 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1139 InferConst::Var(vid) => self
1140 .inner
1141 .borrow_mut()
1142 .const_unification_table()
1143 .probe_value(vid)
1144 .known()
1145 .unwrap_or(ct),
1146 InferConst::Fresh(_) => ct,
1147 },
1148 ty::ConstKind::Param(_)
1149 | ty::ConstKind::Bound(_, _)
1150 | ty::ConstKind::Placeholder(_)
1151 | ty::ConstKind::Unevaluated(_)
1152 | ty::ConstKind::Value(_)
1153 | ty::ConstKind::Error(_)
1154 | ty::ConstKind::Expr(_) => ct,
1155 }
1156 }
1157
1158 pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1159 match term.kind() {
1160 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1161 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1162 }
1163 }
1164
1165 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1166 self.inner.borrow_mut().type_variables().root_var(var)
1167 }
1168
1169 pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1170 self.inner.borrow_mut().type_variables().sub_unify(a, b);
1171 }
1172
1173 pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1174 self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1175 }
1176
1177 pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1178 self.inner.borrow_mut().const_unification_table().find(var).vid
1179 }
1180
1181 pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1184 let mut inner = self.inner.borrow_mut();
1185 let value = inner.int_unification_table().probe_value(vid);
1186 match value {
1187 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1188 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1189 ty::IntVarValue::Unknown => {
1190 Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1191 }
1192 }
1193 }
1194
1195 pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1198 let mut inner = self.inner.borrow_mut();
1199 let value = inner.float_unification_table().probe_value(vid);
1200 match value {
1201 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1202 ty::FloatVarValue::Unknown => {
1203 Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1204 }
1205 }
1206 }
1207
1208 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1215 where
1216 T: TypeFoldable<TyCtxt<'tcx>>,
1217 {
1218 if let Err(guar) = value.error_reported() {
1219 self.set_tainted_by_errors(guar);
1220 }
1221 if !value.has_non_region_infer() {
1222 return value;
1223 }
1224 let mut r = resolve::OpportunisticVarResolver::new(self);
1225 value.fold_with(&mut r)
1226 }
1227
1228 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1229 where
1230 T: TypeFoldable<TyCtxt<'tcx>>,
1231 {
1232 if !value.has_infer() {
1233 return value; }
1235 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1236 value.fold_with(&mut r)
1237 }
1238
1239 pub fn probe_const_var(&self, vid: ty::ConstVid) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1240 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1241 ConstVariableValue::Known { value } => Ok(value),
1242 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1243 }
1244 }
1245
1246 pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1254 match resolve::fully_resolve(self, value) {
1255 Ok(value) => {
1256 if value.has_non_region_infer() {
1257 bug!("`{value:?}` is not fully resolved");
1258 }
1259 if value.has_infer_regions() {
1260 let guar = self.dcx().delayed_bug(format!("`{value:?}` is not fully resolved"));
1261 Ok(fold_regions(self.tcx, value, |re, _| {
1262 if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1263 }))
1264 } else {
1265 Ok(value)
1266 }
1267 }
1268 Err(e) => Err(e),
1269 }
1270 }
1271
1272 pub fn instantiate_binder_with_fresh_vars<T>(
1280 &self,
1281 span: Span,
1282 lbrct: BoundRegionConversionTime,
1283 value: ty::Binder<'tcx, T>,
1284 ) -> T
1285 where
1286 T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1287 {
1288 if let Some(inner) = value.no_bound_vars() {
1289 return inner;
1290 }
1291
1292 let bound_vars = value.bound_vars();
1293 let mut args = Vec::with_capacity(bound_vars.len());
1294
1295 for bound_var_kind in bound_vars {
1296 let arg: ty::GenericArg<'_> = match bound_var_kind {
1297 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1298 ty::BoundVariableKind::Region(br) => {
1299 self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1300 }
1301 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1302 };
1303 args.push(arg);
1304 }
1305
1306 struct ToFreshVars<'tcx> {
1307 args: Vec<ty::GenericArg<'tcx>>,
1308 }
1309
1310 impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1311 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1312 self.args[br.var.index()].expect_region()
1313 }
1314 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1315 self.args[bt.var.index()].expect_ty()
1316 }
1317 fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx> {
1318 self.args[bc.var.index()].expect_const()
1319 }
1320 }
1321 let delegate = ToFreshVars { args };
1322 self.tcx.replace_bound_vars_uncached(value, delegate)
1323 }
1324
1325 pub(crate) fn verify_generic_bound(
1327 &self,
1328 origin: SubregionOrigin<'tcx>,
1329 kind: GenericKind<'tcx>,
1330 a: ty::Region<'tcx>,
1331 bound: VerifyBound<'tcx>,
1332 ) {
1333 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1334
1335 self.inner
1336 .borrow_mut()
1337 .unwrap_region_constraints()
1338 .verify_generic_bound(origin, kind, a, bound);
1339 }
1340
1341 pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1345 let unresolved_kind_ty = match *closure_ty.kind() {
1346 ty::Closure(_, args) => args.as_closure().kind_ty(),
1347 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1348 _ => bug!("unexpected type {closure_ty}"),
1349 };
1350 let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1351 closure_kind_ty.to_opt_closure_kind()
1352 }
1353
1354 pub fn universe(&self) -> ty::UniverseIndex {
1355 self.universe.get()
1356 }
1357
1358 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1361 let u = self.universe.get().next_universe();
1362 debug!("create_next_universe {u:?}");
1363 self.universe.set(u);
1364 u
1365 }
1366
1367 pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1371 let typing_mode = match self.typing_mode() {
1372 ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1377 | ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1378 TypingMode::non_body_analysis()
1379 }
1380 mode @ (ty::TypingMode::Coherence
1381 | ty::TypingMode::PostBorrowckAnalysis { .. }
1382 | ty::TypingMode::PostAnalysis) => mode,
1383 };
1384 ty::TypingEnv { typing_mode, param_env }
1385 }
1386
1387 pub fn pseudo_canonicalize_query<V>(
1391 &self,
1392 param_env: ty::ParamEnv<'tcx>,
1393 value: V,
1394 ) -> PseudoCanonicalInput<'tcx, V>
1395 where
1396 V: TypeVisitable<TyCtxt<'tcx>>,
1397 {
1398 debug_assert!(!value.has_infer());
1399 debug_assert!(!value.has_placeholders());
1400 debug_assert!(!param_env.has_infer());
1401 debug_assert!(!param_env.has_placeholders());
1402 self.typing_env(param_env).as_query_input(value)
1403 }
1404
1405 #[inline]
1408 pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1409 let inner = self.inner.try_borrow();
1411
1412 move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1413 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1414 use self::type_variable::TypeVariableValue;
1415
1416 matches!(
1417 inner.try_type_variables_probe_ref(ty_var),
1418 Some(TypeVariableValue::Unknown { .. })
1419 )
1420 }
1421 _ => false,
1422 }
1423 }
1424
1425 #[inline(always)]
1435 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1436 match infer_var {
1437 TyOrConstInferVar::Ty(v) => {
1438 use self::type_variable::TypeVariableValue;
1439
1440 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1443 TypeVariableValue::Unknown { .. } => false,
1444 TypeVariableValue::Known { .. } => true,
1445 }
1446 }
1447
1448 TyOrConstInferVar::TyInt(v) => {
1449 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1453 }
1454
1455 TyOrConstInferVar::TyFloat(v) => {
1456 self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1461 }
1462
1463 TyOrConstInferVar::Const(v) => {
1464 match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1469 ConstVariableValue::Unknown { .. } => false,
1470 ConstVariableValue::Known { .. } => true,
1471 }
1472 }
1473 }
1474 }
1475
1476 pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1478 debug_assert!(
1479 self.obligation_inspector.get().is_none(),
1480 "shouldn't override a set obligation inspector"
1481 );
1482 self.obligation_inspector.set(Some(inspector));
1483 }
1484}
1485
1486#[derive(Copy, Clone, Debug)]
1489pub enum TyOrConstInferVar {
1490 Ty(TyVid),
1492 TyInt(IntVid),
1494 TyFloat(FloatVid),
1496
1497 Const(ConstVid),
1499}
1500
1501impl<'tcx> TyOrConstInferVar {
1502 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1506 match arg.kind() {
1507 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1508 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1509 GenericArgKind::Lifetime(_) => None,
1510 }
1511 }
1512
1513 pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1517 match term.kind() {
1518 TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1519 TermKind::Const(ct) => Self::maybe_from_const(ct),
1520 }
1521 }
1522
1523 fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1526 match *ty.kind() {
1527 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1528 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1529 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1530 _ => None,
1531 }
1532 }
1533
1534 fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1537 match ct.kind() {
1538 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1539 _ => None,
1540 }
1541 }
1542}
1543
1544struct InferenceLiteralEraser<'tcx> {
1547 tcx: TyCtxt<'tcx>,
1548}
1549
1550impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1551 fn cx(&self) -> TyCtxt<'tcx> {
1552 self.tcx
1553 }
1554
1555 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1556 match ty.kind() {
1557 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1558 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1559 _ => ty.super_fold_with(self),
1560 }
1561 }
1562}
1563
1564impl<'tcx> TypeTrace<'tcx> {
1565 pub fn span(&self) -> Span {
1566 self.cause.span
1567 }
1568
1569 pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1570 TypeTrace {
1571 cause: cause.clone(),
1572 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1573 }
1574 }
1575
1576 pub fn trait_refs(
1577 cause: &ObligationCause<'tcx>,
1578 a: ty::TraitRef<'tcx>,
1579 b: ty::TraitRef<'tcx>,
1580 ) -> TypeTrace<'tcx> {
1581 TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1582 }
1583
1584 pub fn consts(
1585 cause: &ObligationCause<'tcx>,
1586 a: ty::Const<'tcx>,
1587 b: ty::Const<'tcx>,
1588 ) -> TypeTrace<'tcx> {
1589 TypeTrace {
1590 cause: cause.clone(),
1591 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1592 }
1593 }
1594}
1595
1596impl<'tcx> SubregionOrigin<'tcx> {
1597 pub fn span(&self) -> Span {
1598 match *self {
1599 SubregionOrigin::Subtype(ref a) => a.span(),
1600 SubregionOrigin::RelateObjectBound(a) => a,
1601 SubregionOrigin::RelateParamBound(a, ..) => a,
1602 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1603 SubregionOrigin::Reborrow(a) => a,
1604 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1605 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1606 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1607 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1608 }
1609 }
1610
1611 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1612 where
1613 F: FnOnce() -> Self,
1614 {
1615 match *cause.code() {
1616 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1617 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1618 }
1619
1620 traits::ObligationCauseCode::CompareImplItem {
1621 impl_item_def_id,
1622 trait_item_def_id,
1623 kind: _,
1624 } => SubregionOrigin::CompareImplItemObligation {
1625 span: cause.span,
1626 impl_item_def_id,
1627 trait_item_def_id,
1628 },
1629
1630 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1631 impl_item_def_id,
1632 trait_item_def_id,
1633 } => SubregionOrigin::CheckAssociatedTypeBounds {
1634 impl_item_def_id,
1635 trait_item_def_id,
1636 parent: Box::new(default()),
1637 },
1638
1639 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1640 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1641 }
1642
1643 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1644 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1645 }
1646
1647 _ => default(),
1648 }
1649 }
1650}
1651
1652impl RegionVariableOrigin {
1653 pub fn span(&self) -> Span {
1654 match *self {
1655 RegionVariableOrigin::Misc(a)
1656 | RegionVariableOrigin::PatternRegion(a)
1657 | RegionVariableOrigin::BorrowRegion(a)
1658 | RegionVariableOrigin::Autoref(a)
1659 | RegionVariableOrigin::Coercion(a)
1660 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1661 | RegionVariableOrigin::BoundRegion(a, ..)
1662 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1663 RegionVariableOrigin::Nll(..) => bug!("NLL variable used with `span`"),
1664 }
1665 }
1666}
1667
1668impl<'tcx> InferCtxt<'tcx> {
1669 pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1672 let block = block.innermost_block();
1673 if let Some(expr) = &block.expr {
1674 expr.span
1675 } else if let Some(stmt) = block.stmts.last() {
1676 stmt.span
1678 } else {
1679 block.span
1681 }
1682 }
1683
1684 pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1687 match self.tcx.hir_node(hir_id) {
1688 hir::Node::Block(blk)
1689 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1690 self.find_block_span(blk)
1691 }
1692 hir::Node::Expr(e) => e.span,
1693 _ => DUMMY_SP,
1694 }
1695 }
1696}