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, OpaqueTypeKey, ProvisionalHiddenType,
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<'tcx> {
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<'tcx>),
457}
458
459#[derive(Copy, Clone, Debug)]
460pub enum NllRegionVariableOrigin<'tcx> {
461 FreeRegion,
465
466 Placeholder(ty::PlaceholderRegion<'tcx>),
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 type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
644 self.inner.borrow_mut().type_variables().var_origin(vid)
645 }
646
647 pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
651 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
652 ConstVariableValue::Known { .. } => None,
653 ConstVariableValue::Unknown { origin, .. } => Some(origin),
654 }
655 }
656
657 pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
658 let mut inner = self.inner.borrow_mut();
659 let mut vars: Vec<Ty<'_>> = inner
660 .type_variables()
661 .unresolved_variables()
662 .into_iter()
663 .map(|t| Ty::new_var(self.tcx, t))
664 .collect();
665 vars.extend(
666 (0..inner.int_unification_table().len())
667 .map(|i| ty::IntVid::from_usize(i))
668 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
669 .map(|v| Ty::new_int_var(self.tcx, v)),
670 );
671 vars.extend(
672 (0..inner.float_unification_table().len())
673 .map(|i| ty::FloatVid::from_usize(i))
674 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
675 .map(|v| Ty::new_float_var(self.tcx, v)),
676 );
677 vars
678 }
679
680 #[instrument(skip(self), level = "debug")]
681 pub fn sub_regions(
682 &self,
683 origin: SubregionOrigin<'tcx>,
684 a: ty::Region<'tcx>,
685 b: ty::Region<'tcx>,
686 ) {
687 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
688 }
689
690 pub fn coerce_predicate(
706 &self,
707 cause: &ObligationCause<'tcx>,
708 param_env: ty::ParamEnv<'tcx>,
709 predicate: ty::PolyCoercePredicate<'tcx>,
710 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
711 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
712 a_is_expected: false, a: p.a,
714 b: p.b,
715 });
716 self.subtype_predicate(cause, param_env, subtype_predicate)
717 }
718
719 pub fn subtype_predicate(
720 &self,
721 cause: &ObligationCause<'tcx>,
722 param_env: ty::ParamEnv<'tcx>,
723 predicate: ty::PolySubtypePredicate<'tcx>,
724 ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
725 let r_a = self.shallow_resolve(predicate.skip_binder().a);
739 let r_b = self.shallow_resolve(predicate.skip_binder().b);
740 match (r_a.kind(), r_b.kind()) {
741 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
742 self.sub_unify_ty_vids_raw(a_vid, b_vid);
743 return Err((a_vid, b_vid));
744 }
745 _ => {}
746 }
747
748 self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
749 if a_is_expected {
750 Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
751 } else {
752 Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
753 }
754 })
755 }
756
757 pub fn num_ty_vars(&self) -> usize {
759 self.inner.borrow_mut().type_variables().num_vars()
760 }
761
762 pub fn next_ty_vid(&self, span: Span) -> TyVid {
763 self.next_ty_vid_with_origin(TypeVariableOrigin { span, param_def_id: None })
764 }
765
766 pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid {
767 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
768 }
769
770 pub fn next_ty_vid_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
771 let origin = TypeVariableOrigin { span, param_def_id: None };
772 self.inner.borrow_mut().type_variables().new_var(universe, origin)
773 }
774
775 pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
776 self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
777 }
778
779 pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
780 let vid = self.next_ty_vid_with_origin(origin);
781 Ty::new_var(self.tcx, vid)
782 }
783
784 pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
785 let vid = self.next_ty_vid_in_universe(span, universe);
786 Ty::new_var(self.tcx, vid)
787 }
788
789 pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
790 self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
791 }
792
793 pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
794 let vid = self
795 .inner
796 .borrow_mut()
797 .const_unification_table()
798 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
799 .vid;
800 ty::Const::new_var(self.tcx, vid)
801 }
802
803 pub fn next_const_var_in_universe(
804 &self,
805 span: Span,
806 universe: ty::UniverseIndex,
807 ) -> ty::Const<'tcx> {
808 let origin = ConstVariableOrigin { span, param_def_id: None };
809 let vid = self
810 .inner
811 .borrow_mut()
812 .const_unification_table()
813 .new_key(ConstVariableValue::Unknown { origin, universe })
814 .vid;
815 ty::Const::new_var(self.tcx, vid)
816 }
817
818 pub fn next_int_var(&self) -> Ty<'tcx> {
819 let next_int_var_id =
820 self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
821 Ty::new_int_var(self.tcx, next_int_var_id)
822 }
823
824 pub fn next_float_var(&self) -> Ty<'tcx> {
825 let next_float_var_id =
826 self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown);
827 Ty::new_float_var(self.tcx, next_float_var_id)
828 }
829
830 pub fn next_region_var(&self, origin: RegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
834 self.next_region_var_in_universe(origin, self.universe())
835 }
836
837 pub fn next_region_var_in_universe(
841 &self,
842 origin: RegionVariableOrigin<'tcx>,
843 universe: ty::UniverseIndex,
844 ) -> ty::Region<'tcx> {
845 let region_var =
846 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
847 ty::Region::new_var(self.tcx, region_var)
848 }
849
850 pub fn next_term_var_of_kind(&self, term: ty::Term<'tcx>, span: Span) -> ty::Term<'tcx> {
851 match term.kind() {
852 ty::TermKind::Ty(_) => self.next_ty_var(span).into(),
853 ty::TermKind::Const(_) => self.next_const_var(span).into(),
854 }
855 }
856
857 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
863 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
864 }
865
866 pub fn num_region_vars(&self) -> usize {
868 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
869 }
870
871 #[instrument(skip(self), level = "debug")]
873 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin<'tcx>) -> ty::Region<'tcx> {
874 self.next_region_var(RegionVariableOrigin::Nll(origin))
875 }
876
877 #[instrument(skip(self), level = "debug")]
879 pub fn next_nll_region_var_in_universe(
880 &self,
881 origin: NllRegionVariableOrigin<'tcx>,
882 universe: ty::UniverseIndex,
883 ) -> ty::Region<'tcx> {
884 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
885 }
886
887 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
888 match param.kind {
889 GenericParamDefKind::Lifetime => {
890 self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
893 span, param.name,
894 ))
895 .into()
896 }
897 GenericParamDefKind::Type { .. } => {
898 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
907 self.universe(),
908 TypeVariableOrigin { param_def_id: Some(param.def_id), span },
909 );
910
911 Ty::new_var(self.tcx, ty_var_id).into()
912 }
913 GenericParamDefKind::Const { .. } => {
914 let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
915 let const_var_id = self
916 .inner
917 .borrow_mut()
918 .const_unification_table()
919 .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
920 .vid;
921 ty::Const::new_var(self.tcx, const_var_id).into()
922 }
923 }
924 }
925
926 pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
929 GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
930 }
931
932 #[must_use = "this method does not have any side effects"]
938 pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
939 self.tainted_by_errors.get()
940 }
941
942 pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
945 debug!("set_tainted_by_errors(ErrorGuaranteed)");
946 self.tainted_by_errors.set(Some(e));
947 }
948
949 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin<'tcx> {
950 let mut inner = self.inner.borrow_mut();
951 let inner = &mut *inner;
952 inner.unwrap_region_constraints().var_origin(vid)
953 }
954
955 pub fn get_region_var_infos(&self) -> VarInfos<'tcx> {
958 let inner = self.inner.borrow();
959 assert!(!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log));
960 let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
961 assert!(storage.data.is_empty(), "{:#?}", storage.data);
962 storage.var_infos.clone()
966 }
967
968 pub fn has_opaque_types_in_storage(&self) -> bool {
969 !self.inner.borrow().opaque_type_storage.is_empty()
970 }
971
972 #[instrument(level = "debug", skip(self), ret)]
973 pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
974 self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
975 }
976
977 #[instrument(level = "debug", skip(self), ret)]
978 pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, ProvisionalHiddenType<'tcx>)> {
979 self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
980 }
981
982 pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool {
983 if !self.next_trait_solver() {
984 return false;
985 }
986
987 let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
988 let inner = &mut *self.inner.borrow_mut();
989 let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
990 inner.opaque_type_storage.iter_opaque_types().any(|(_, hidden_ty)| {
991 if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
992 let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
993 if opaque_sub_vid == ty_sub_vid {
994 return true;
995 }
996 }
997
998 false
999 })
1000 }
1001
1002 pub fn opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> Vec<ty::AliasTy<'tcx>> {
1006 if !self.next_trait_solver() {
1008 return vec![];
1009 }
1010
1011 let ty_sub_vid = self.sub_unification_table_root_var(ty_vid);
1012 let inner = &mut *self.inner.borrow_mut();
1013 let mut type_variables = inner.type_variable_storage.with_log(&mut inner.undo_log);
1016 inner
1017 .opaque_type_storage
1018 .iter_opaque_types()
1019 .filter_map(|(key, hidden_ty)| {
1020 if let ty::Infer(ty::TyVar(hidden_vid)) = *hidden_ty.ty.kind() {
1021 let opaque_sub_vid = type_variables.sub_unification_table_root_var(hidden_vid);
1022 if opaque_sub_vid == ty_sub_vid {
1023 return Some(ty::AliasTy::new_from_args(
1024 self.tcx,
1025 key.def_id.into(),
1026 key.args,
1027 ));
1028 }
1029 }
1030
1031 None
1032 })
1033 .collect()
1034 }
1035
1036 #[inline(always)]
1037 pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
1038 debug_assert!(!self.next_trait_solver());
1039 match self.typing_mode() {
1040 TypingMode::Analysis {
1041 defining_opaque_types_and_generators: defining_opaque_types,
1042 }
1043 | TypingMode::Borrowck { defining_opaque_types } => {
1044 id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
1045 }
1046 TypingMode::Coherence
1050 | TypingMode::PostBorrowckAnalysis { .. }
1051 | TypingMode::PostAnalysis => false,
1052 }
1053 }
1054
1055 pub fn push_hir_typeck_potentially_region_dependent_goal(
1056 &self,
1057 goal: PredicateObligation<'tcx>,
1058 ) {
1059 let mut inner = self.inner.borrow_mut();
1060 inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal);
1061 inner.hir_typeck_potentially_region_dependent_goals.push(goal);
1062 }
1063
1064 pub fn take_hir_typeck_potentially_region_dependent_goals(
1065 &self,
1066 ) -> Vec<PredicateObligation<'tcx>> {
1067 assert!(!self.in_snapshot(), "cannot take goals in a snapshot");
1068 std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals)
1069 }
1070
1071 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1072 self.resolve_vars_if_possible(t).to_string()
1073 }
1074
1075 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1078 use self::type_variable::TypeVariableValue;
1079
1080 match self.inner.borrow_mut().type_variables().probe(vid) {
1081 TypeVariableValue::Known { value } => Ok(value),
1082 TypeVariableValue::Unknown { universe } => Err(universe),
1083 }
1084 }
1085
1086 pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1087 if let ty::Infer(v) = *ty.kind() {
1088 match v {
1089 ty::TyVar(v) => {
1090 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1103 known.map_or(ty, |t| self.shallow_resolve(t))
1104 }
1105
1106 ty::IntVar(v) => {
1107 match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1108 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1109 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1110 ty::IntVarValue::Unknown => ty,
1111 }
1112 }
1113
1114 ty::FloatVar(v) => {
1115 match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1116 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1117 ty::FloatVarValue::Unknown => ty,
1118 }
1119 }
1120
1121 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1122 }
1123 } else {
1124 ty
1125 }
1126 }
1127
1128 pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1129 match ct.kind() {
1130 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1131 InferConst::Var(vid) => self
1132 .inner
1133 .borrow_mut()
1134 .const_unification_table()
1135 .probe_value(vid)
1136 .known()
1137 .unwrap_or(ct),
1138 InferConst::Fresh(_) => ct,
1139 },
1140 ty::ConstKind::Param(_)
1141 | ty::ConstKind::Bound(_, _)
1142 | ty::ConstKind::Placeholder(_)
1143 | ty::ConstKind::Unevaluated(_)
1144 | ty::ConstKind::Value(_)
1145 | ty::ConstKind::Error(_)
1146 | ty::ConstKind::Expr(_) => ct,
1147 }
1148 }
1149
1150 pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1151 match term.kind() {
1152 ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1153 ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1154 }
1155 }
1156
1157 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1158 self.inner.borrow_mut().type_variables().root_var(var)
1159 }
1160
1161 pub fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1162 self.inner.borrow_mut().type_variables().sub_unify(a, b);
1163 }
1164
1165 pub fn sub_unification_table_root_var(&self, var: ty::TyVid) -> ty::TyVid {
1166 self.inner.borrow_mut().type_variables().sub_unification_table_root_var(var)
1167 }
1168
1169 pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1170 self.inner.borrow_mut().const_unification_table().find(var).vid
1171 }
1172
1173 pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1176 let mut inner = self.inner.borrow_mut();
1177 let value = inner.int_unification_table().probe_value(vid);
1178 match value {
1179 ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1180 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1181 ty::IntVarValue::Unknown => {
1182 Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1183 }
1184 }
1185 }
1186
1187 pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1190 let mut inner = self.inner.borrow_mut();
1191 let value = inner.float_unification_table().probe_value(vid);
1192 match value {
1193 ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1194 ty::FloatVarValue::Unknown => {
1195 Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1196 }
1197 }
1198 }
1199
1200 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1207 where
1208 T: TypeFoldable<TyCtxt<'tcx>>,
1209 {
1210 if let Err(guar) = value.error_reported() {
1211 self.set_tainted_by_errors(guar);
1212 }
1213 if !value.has_non_region_infer() {
1214 return value;
1215 }
1216 let mut r = resolve::OpportunisticVarResolver::new(self);
1217 value.fold_with(&mut r)
1218 }
1219
1220 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1221 where
1222 T: TypeFoldable<TyCtxt<'tcx>>,
1223 {
1224 if !value.has_infer() {
1225 return value; }
1227 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1228 value.fold_with(&mut r)
1229 }
1230
1231 pub fn probe_const_var(&self, vid: ty::ConstVid) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1232 match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1233 ConstVariableValue::Known { value } => Ok(value),
1234 ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1235 }
1236 }
1237
1238 pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1246 match resolve::fully_resolve(self, value) {
1247 Ok(value) => {
1248 if value.has_non_region_infer() {
1249 bug!("`{value:?}` is not fully resolved");
1250 }
1251 if value.has_infer_regions() {
1252 let guar = self.dcx().delayed_bug(format!("`{value:?}` is not fully resolved"));
1253 Ok(fold_regions(self.tcx, value, |re, _| {
1254 if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1255 }))
1256 } else {
1257 Ok(value)
1258 }
1259 }
1260 Err(e) => Err(e),
1261 }
1262 }
1263
1264 pub fn instantiate_binder_with_fresh_vars<T>(
1272 &self,
1273 span: Span,
1274 lbrct: BoundRegionConversionTime,
1275 value: ty::Binder<'tcx, T>,
1276 ) -> T
1277 where
1278 T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1279 {
1280 if let Some(inner) = value.no_bound_vars() {
1281 return inner;
1282 }
1283
1284 let bound_vars = value.bound_vars();
1285 let mut args = Vec::with_capacity(bound_vars.len());
1286
1287 for bound_var_kind in bound_vars {
1288 let arg: ty::GenericArg<'_> = match bound_var_kind {
1289 ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1290 ty::BoundVariableKind::Region(br) => {
1291 self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1292 }
1293 ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1294 };
1295 args.push(arg);
1296 }
1297
1298 struct ToFreshVars<'tcx> {
1299 args: Vec<ty::GenericArg<'tcx>>,
1300 }
1301
1302 impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1303 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1304 self.args[br.var.index()].expect_region()
1305 }
1306 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1307 self.args[bt.var.index()].expect_ty()
1308 }
1309 fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx> {
1310 self.args[bc.var.index()].expect_const()
1311 }
1312 }
1313 let delegate = ToFreshVars { args };
1314 self.tcx.replace_bound_vars_uncached(value, delegate)
1315 }
1316
1317 pub(crate) fn verify_generic_bound(
1319 &self,
1320 origin: SubregionOrigin<'tcx>,
1321 kind: GenericKind<'tcx>,
1322 a: ty::Region<'tcx>,
1323 bound: VerifyBound<'tcx>,
1324 ) {
1325 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1326
1327 self.inner
1328 .borrow_mut()
1329 .unwrap_region_constraints()
1330 .verify_generic_bound(origin, kind, a, bound);
1331 }
1332
1333 pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1337 let unresolved_kind_ty = match *closure_ty.kind() {
1338 ty::Closure(_, args) => args.as_closure().kind_ty(),
1339 ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1340 _ => bug!("unexpected type {closure_ty}"),
1341 };
1342 let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1343 closure_kind_ty.to_opt_closure_kind()
1344 }
1345
1346 pub fn universe(&self) -> ty::UniverseIndex {
1347 self.universe.get()
1348 }
1349
1350 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1353 let u = self.universe.get().next_universe();
1354 debug!("create_next_universe {u:?}");
1355 self.universe.set(u);
1356 u
1357 }
1358
1359 pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1363 let typing_mode = match self.typing_mode() {
1364 ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1369 | ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1370 TypingMode::non_body_analysis()
1371 }
1372 mode @ (ty::TypingMode::Coherence
1373 | ty::TypingMode::PostBorrowckAnalysis { .. }
1374 | ty::TypingMode::PostAnalysis) => mode,
1375 };
1376 ty::TypingEnv { typing_mode, param_env }
1377 }
1378
1379 pub fn pseudo_canonicalize_query<V>(
1383 &self,
1384 param_env: ty::ParamEnv<'tcx>,
1385 value: V,
1386 ) -> PseudoCanonicalInput<'tcx, V>
1387 where
1388 V: TypeVisitable<TyCtxt<'tcx>>,
1389 {
1390 debug_assert!(!value.has_infer());
1391 debug_assert!(!value.has_placeholders());
1392 debug_assert!(!param_env.has_infer());
1393 debug_assert!(!param_env.has_placeholders());
1394 self.typing_env(param_env).as_query_input(value)
1395 }
1396
1397 #[inline]
1400 pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1401 let inner = self.inner.try_borrow();
1403
1404 move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1405 (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1406 use self::type_variable::TypeVariableValue;
1407
1408 matches!(
1409 inner.try_type_variables_probe_ref(ty_var),
1410 Some(TypeVariableValue::Unknown { .. })
1411 )
1412 }
1413 _ => false,
1414 }
1415 }
1416
1417 #[inline(always)]
1427 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1428 match infer_var {
1429 TyOrConstInferVar::Ty(v) => {
1430 use self::type_variable::TypeVariableValue;
1431
1432 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1435 TypeVariableValue::Unknown { .. } => false,
1436 TypeVariableValue::Known { .. } => true,
1437 }
1438 }
1439
1440 TyOrConstInferVar::TyInt(v) => {
1441 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1445 }
1446
1447 TyOrConstInferVar::TyFloat(v) => {
1448 self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1453 }
1454
1455 TyOrConstInferVar::Const(v) => {
1456 match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1461 ConstVariableValue::Unknown { .. } => false,
1462 ConstVariableValue::Known { .. } => true,
1463 }
1464 }
1465 }
1466 }
1467
1468 pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1470 debug_assert!(
1471 self.obligation_inspector.get().is_none(),
1472 "shouldn't override a set obligation inspector"
1473 );
1474 self.obligation_inspector.set(Some(inspector));
1475 }
1476}
1477
1478#[derive(Copy, Clone, Debug)]
1481pub enum TyOrConstInferVar {
1482 Ty(TyVid),
1484 TyInt(IntVid),
1486 TyFloat(FloatVid),
1488
1489 Const(ConstVid),
1491}
1492
1493impl<'tcx> TyOrConstInferVar {
1494 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1498 match arg.kind() {
1499 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1500 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1501 GenericArgKind::Lifetime(_) => None,
1502 }
1503 }
1504
1505 pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1509 match term.kind() {
1510 TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1511 TermKind::Const(ct) => Self::maybe_from_const(ct),
1512 }
1513 }
1514
1515 fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1518 match *ty.kind() {
1519 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1520 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1521 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1522 _ => None,
1523 }
1524 }
1525
1526 fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1529 match ct.kind() {
1530 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1531 _ => None,
1532 }
1533 }
1534}
1535
1536struct InferenceLiteralEraser<'tcx> {
1539 tcx: TyCtxt<'tcx>,
1540}
1541
1542impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1543 fn cx(&self) -> TyCtxt<'tcx> {
1544 self.tcx
1545 }
1546
1547 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1548 match ty.kind() {
1549 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1550 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1551 _ => ty.super_fold_with(self),
1552 }
1553 }
1554}
1555
1556impl<'tcx> TypeTrace<'tcx> {
1557 pub fn span(&self) -> Span {
1558 self.cause.span
1559 }
1560
1561 pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1562 TypeTrace {
1563 cause: cause.clone(),
1564 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1565 }
1566 }
1567
1568 pub fn trait_refs(
1569 cause: &ObligationCause<'tcx>,
1570 a: ty::TraitRef<'tcx>,
1571 b: ty::TraitRef<'tcx>,
1572 ) -> TypeTrace<'tcx> {
1573 TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1574 }
1575
1576 pub fn consts(
1577 cause: &ObligationCause<'tcx>,
1578 a: ty::Const<'tcx>,
1579 b: ty::Const<'tcx>,
1580 ) -> TypeTrace<'tcx> {
1581 TypeTrace {
1582 cause: cause.clone(),
1583 values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1584 }
1585 }
1586}
1587
1588impl<'tcx> SubregionOrigin<'tcx> {
1589 pub fn span(&self) -> Span {
1590 match *self {
1591 SubregionOrigin::Subtype(ref a) => a.span(),
1592 SubregionOrigin::RelateObjectBound(a) => a,
1593 SubregionOrigin::RelateParamBound(a, ..) => a,
1594 SubregionOrigin::RelateRegionParamBound(a, _) => a,
1595 SubregionOrigin::Reborrow(a) => a,
1596 SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1597 SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1598 SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1599 SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1600 }
1601 }
1602
1603 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1604 where
1605 F: FnOnce() -> Self,
1606 {
1607 match *cause.code() {
1608 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1609 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1610 }
1611
1612 traits::ObligationCauseCode::CompareImplItem {
1613 impl_item_def_id,
1614 trait_item_def_id,
1615 kind: _,
1616 } => SubregionOrigin::CompareImplItemObligation {
1617 span: cause.span,
1618 impl_item_def_id,
1619 trait_item_def_id,
1620 },
1621
1622 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1623 impl_item_def_id,
1624 trait_item_def_id,
1625 } => SubregionOrigin::CheckAssociatedTypeBounds {
1626 impl_item_def_id,
1627 trait_item_def_id,
1628 parent: Box::new(default()),
1629 },
1630
1631 traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1632 SubregionOrigin::AscribeUserTypeProvePredicate(span)
1633 }
1634
1635 traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1636 SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1637 }
1638
1639 _ => default(),
1640 }
1641 }
1642}
1643
1644impl<'tcx> RegionVariableOrigin<'tcx> {
1645 pub fn span(&self) -> Span {
1646 match *self {
1647 RegionVariableOrigin::Misc(a)
1648 | RegionVariableOrigin::PatternRegion(a)
1649 | RegionVariableOrigin::BorrowRegion(a)
1650 | RegionVariableOrigin::Autoref(a)
1651 | RegionVariableOrigin::Coercion(a)
1652 | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1653 | RegionVariableOrigin::BoundRegion(a, ..)
1654 | RegionVariableOrigin::UpvarRegion(_, a) => a,
1655 RegionVariableOrigin::Nll(..) => bug!("NLL variable used with `span`"),
1656 }
1657 }
1658}
1659
1660impl<'tcx> InferCtxt<'tcx> {
1661 pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1664 let block = block.innermost_block();
1665 if let Some(expr) = &block.expr {
1666 expr.span
1667 } else if let Some(stmt) = block.stmts.last() {
1668 stmt.span
1670 } else {
1671 block.span
1673 }
1674 }
1675
1676 pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1679 match self.tcx.hir_node(hir_id) {
1680 hir::Node::Block(blk)
1681 | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1682 self.find_block_span(blk)
1683 }
1684 hir::Node::Expr(e) => e.span,
1685 _ => DUMMY_SP,
1686 }
1687 }
1688}