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::region_constraints::UndoLog;
41use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
42use crate::traits::{
43    self, ObligationCause, ObligationInspector, PredicateObligations, TraitEngine,
44};
45
46pub mod at;
47pub mod canonical;
48mod context;
49mod free_regions;
50mod freshen;
51mod lexical_region_resolve;
52mod opaque_types;
53pub mod outlives;
54mod projection;
55pub mod region_constraints;
56pub mod relate;
57pub mod resolve;
58pub(crate) mod snapshot;
59mod type_variable;
60mod unify_key;
61
62#[must_use]
70#[derive(Debug)]
71pub struct InferOk<'tcx, T> {
72    pub value: T,
73    pub obligations: PredicateObligations<'tcx>,
74}
75pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
76
77pub(crate) type FixupResult<T> = Result<T, FixupError>; pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
80    ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
81>;
82
83#[derive(Clone)]
88pub struct InferCtxtInner<'tcx> {
89    undo_log: InferCtxtUndoLogs<'tcx>,
90
91    projection_cache: traits::ProjectionCacheStorage<'tcx>,
95
96    type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
100
101    const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
103
104    int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
106
107    float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
109
110    region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
117
118    region_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
151
152    region_assumptions: Vec<ty::ArgOutlivesPredicate<'tcx>>,
158
159    opaque_type_storage: OpaqueTypeStorage<'tcx>,
161}
162
163impl<'tcx> InferCtxtInner<'tcx> {
164    fn new() -> InferCtxtInner<'tcx> {
165        InferCtxtInner {
166            undo_log: InferCtxtUndoLogs::default(),
167
168            projection_cache: Default::default(),
169            type_variable_storage: Default::default(),
170            const_unification_storage: Default::default(),
171            int_unification_storage: Default::default(),
172            float_unification_storage: Default::default(),
173            region_constraint_storage: Some(Default::default()),
174            region_obligations: Default::default(),
175            region_assumptions: Default::default(),
176            opaque_type_storage: Default::default(),
177        }
178    }
179
180    #[inline]
181    pub fn region_obligations(&self) -> &[TypeOutlivesConstraint<'tcx>] {
182        &self.region_obligations
183    }
184
185    #[inline]
186    pub fn region_assumptions(&self) -> &[ty::ArgOutlivesPredicate<'tcx>] {
187        &self.region_assumptions
188    }
189
190    #[inline]
191    pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
192        self.projection_cache.with_log(&mut self.undo_log)
193    }
194
195    #[inline]
196    fn try_type_variables_probe_ref(
197        &self,
198        vid: ty::TyVid,
199    ) -> Option<&type_variable::TypeVariableValue<'tcx>> {
200        self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
203    }
204
205    #[inline]
206    fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
207        self.type_variable_storage.with_log(&mut self.undo_log)
208    }
209
210    #[inline]
211    pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
212        self.opaque_type_storage.with_log(&mut self.undo_log)
213    }
214
215    #[inline]
216    fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
217        self.int_unification_storage.with_log(&mut self.undo_log)
218    }
219
220    #[inline]
221    fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
222        self.float_unification_storage.with_log(&mut self.undo_log)
223    }
224
225    #[inline]
226    fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
227        self.const_unification_storage.with_log(&mut self.undo_log)
228    }
229
230    #[inline]
231    pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
232        self.region_constraint_storage
233            .as_mut()
234            .expect("region constraints already solved")
235            .with_log(&mut self.undo_log)
236    }
237}
238
239pub struct InferCtxt<'tcx> {
240    pub tcx: TyCtxt<'tcx>,
241
242    typing_mode: TypingMode<'tcx>,
245
246    pub considering_regions: bool,
250
251    skip_leak_check: bool,
256
257    pub inner: RefCell<InferCtxtInner<'tcx>>,
258
259    lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
261
262    pub selection_cache: select::SelectionCache<'tcx, ty::ParamEnv<'tcx>>,
265
266    pub evaluation_cache: select::EvaluationCache<'tcx, ty::ParamEnv<'tcx>>,
269
270    pub reported_trait_errors:
273        RefCell<FxIndexMap<Span, (Vec<Goal<'tcx, ty::Predicate<'tcx>>>, ErrorGuaranteed)>>,
274
275    pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
276
277    tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
285
286    universe: Cell<ty::UniverseIndex>,
296
297    next_trait_solver: bool,
298
299    pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
300}
301
302#[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
304pub enum ValuePairs<'tcx> {
305    Regions(ExpectedFound<ty::Region<'tcx>>),
306    Terms(ExpectedFound<ty::Term<'tcx>>),
307    Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
308    TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
309    PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
310    ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
311    ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
312}
313
314impl<'tcx> ValuePairs<'tcx> {
315    pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
316        if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
317            && let Some(expected) = expected.as_type()
318            && let Some(found) = found.as_type()
319        {
320            Some((expected, found))
321        } else {
322            None
323        }
324    }
325}
326
327#[derive(Clone, Debug)]
332pub struct TypeTrace<'tcx> {
333    pub cause: ObligationCause<'tcx>,
334    pub values: ValuePairs<'tcx>,
335}
336
337#[derive(Clone, Debug)]
341pub enum SubregionOrigin<'tcx> {
342    Subtype(Box<TypeTrace<'tcx>>),
344
345    RelateObjectBound(Span),
348
349    RelateParamBound(Span, Ty<'tcx>, Option<Span>),
352
353    RelateRegionParamBound(Span, Option<Ty<'tcx>>),
356
357    Reborrow(Span),
359
360    ReferenceOutlivesReferent(Ty<'tcx>, Span),
362
363    CompareImplItemObligation {
366        span: Span,
367        impl_item_def_id: LocalDefId,
368        trait_item_def_id: DefId,
369    },
370
371    CheckAssociatedTypeBounds {
373        parent: Box<SubregionOrigin<'tcx>>,
374        impl_item_def_id: LocalDefId,
375        trait_item_def_id: DefId,
376    },
377
378    AscribeUserTypeProvePredicate(Span),
379}
380
381#[cfg(target_pointer_width = "64")]
383rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
384
385impl<'tcx> SubregionOrigin<'tcx> {
386    pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
387        match self {
388            Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
389            Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
390            _ => ConstraintCategory::BoringNoLocation,
391        }
392    }
393}
394
395#[derive(Clone, Copy, Debug)]
397pub enum BoundRegionConversionTime {
398    FnCall,
400
401    HigherRankedType,
403
404    AssocTypeProjection(DefId),
406}
407
408#[derive(Copy, Clone, Debug)]
412pub enum RegionVariableOrigin {
413    Misc(Span),
417
418    PatternRegion(Span),
420
421    BorrowRegion(Span),
423
424    Autoref(Span),
426
427    Coercion(Span),
429
430    RegionParameterDefinition(Span, Symbol),
435
436    BoundRegion(Span, ty::BoundRegionKind, BoundRegionConversionTime),
439
440    UpvarRegion(ty::UpvarId, Span),
441
442    Nll(NllRegionVariableOrigin),
445}
446
447#[derive(Copy, Clone, Debug)]
448pub enum NllRegionVariableOrigin {
449    FreeRegion,
453
454    Placeholder(ty::PlaceholderRegion),
457
458    Existential {
459        from_forall: bool,
470    },
471}
472
473#[derive(Copy, Clone, Debug)]
474pub struct FixupError {
475    unresolved: TyOrConstInferVar,
476}
477
478impl fmt::Display for FixupError {
479    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480        match self.unresolved {
481            TyOrConstInferVar::TyInt(_) => write!(
482                f,
483                "cannot determine the type of this integer; \
484                 add a suffix to specify the type explicitly"
485            ),
486            TyOrConstInferVar::TyFloat(_) => write!(
487                f,
488                "cannot determine the type of this number; \
489                 add a suffix to specify the type explicitly"
490            ),
491            TyOrConstInferVar::Ty(_) => write!(f, "unconstrained type"),
492            TyOrConstInferVar::Const(_) => write!(f, "unconstrained const value"),
493        }
494    }
495}
496
497#[derive(Clone, Debug)]
499pub struct TypeOutlivesConstraint<'tcx> {
500    pub sub_region: ty::Region<'tcx>,
501    pub sup_type: Ty<'tcx>,
502    pub origin: SubregionOrigin<'tcx>,
503}
504
505pub struct InferCtxtBuilder<'tcx> {
507    tcx: TyCtxt<'tcx>,
508    considering_regions: bool,
509    skip_leak_check: bool,
510    next_trait_solver: bool,
513}
514
515#[extension(pub trait TyCtxtInferExt<'tcx>)]
516impl<'tcx> TyCtxt<'tcx> {
517    fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
518        InferCtxtBuilder {
519            tcx: self,
520            considering_regions: true,
521            skip_leak_check: false,
522            next_trait_solver: self.next_trait_solver_globally(),
523        }
524    }
525}
526
527impl<'tcx> InferCtxtBuilder<'tcx> {
528    pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
529        self.next_trait_solver = next_trait_solver;
530        self
531    }
532
533    pub fn ignoring_regions(mut self) -> Self {
534        self.considering_regions = false;
535        self
536    }
537
538    pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
539        self.skip_leak_check = skip_leak_check;
540        self
541    }
542
543    pub fn build_with_canonical<T>(
551        mut self,
552        span: Span,
553        input: &CanonicalQueryInput<'tcx, T>,
554    ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
555    where
556        T: TypeFoldable<TyCtxt<'tcx>>,
557    {
558        let infcx = self.build(input.typing_mode);
559        let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
560        (infcx, value, args)
561    }
562
563    pub fn build_with_typing_env(
564        mut self,
565        TypingEnv { typing_mode, param_env }: TypingEnv<'tcx>,
566    ) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
567        (self.build(typing_mode), param_env)
568    }
569
570    pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
571        let InferCtxtBuilder { tcx, considering_regions, skip_leak_check, next_trait_solver } =
572            *self;
573        InferCtxt {
574            tcx,
575            typing_mode,
576            considering_regions,
577            skip_leak_check,
578            inner: RefCell::new(InferCtxtInner::new()),
579            lexical_region_resolutions: RefCell::new(None),
580            selection_cache: Default::default(),
581            evaluation_cache: Default::default(),
582            reported_trait_errors: Default::default(),
583            reported_signature_mismatch: Default::default(),
584            tainted_by_errors: Cell::new(None),
585            universe: Cell::new(ty::UniverseIndex::ROOT),
586            next_trait_solver,
587            obligation_inspector: Cell::new(None),
588        }
589    }
590}
591
592impl<'tcx, T> InferOk<'tcx, T> {
593    pub fn into_value_registering_obligations<E: 'tcx>(
595        self,
596        infcx: &InferCtxt<'tcx>,
597        fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
598    ) -> T {
599        let InferOk { value, obligations } = self;
600        fulfill_cx.register_predicate_obligations(infcx, obligations);
601        value
602    }
603}
604
605impl<'tcx> InferOk<'tcx, ()> {
606    pub fn into_obligations(self) -> PredicateObligations<'tcx> {
607        self.obligations
608    }
609}
610
611impl<'tcx> InferCtxt<'tcx> {
612    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
613        self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
614    }
615
616    pub fn next_trait_solver(&self) -> bool {
617        self.next_trait_solver
618    }
619
620    #[inline(always)]
621    pub fn typing_mode(&self) -> TypingMode<'tcx> {
622        self.typing_mode
623    }
624
625    pub fn freshen<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> T {
626        t.fold_with(&mut self.freshener())
627    }
628
629    pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
633        self.inner.borrow_mut().type_variables().var_origin(vid)
634    }
635
636    pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
640        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
641            ConstVariableValue::Known { .. } => None,
642            ConstVariableValue::Unknown { origin, .. } => Some(origin),
643        }
644    }
645
646    pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
647        freshen::TypeFreshener::new(self)
648    }
649
650    pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
651        let mut inner = self.inner.borrow_mut();
652        let mut vars: Vec<Ty<'_>> = inner
653            .type_variables()
654            .unresolved_variables()
655            .into_iter()
656            .map(|t| Ty::new_var(self.tcx, t))
657            .collect();
658        vars.extend(
659            (0..inner.int_unification_table().len())
660                .map(|i| ty::IntVid::from_usize(i))
661                .filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
662                .map(|v| Ty::new_int_var(self.tcx, v)),
663        );
664        vars.extend(
665            (0..inner.float_unification_table().len())
666                .map(|i| ty::FloatVid::from_usize(i))
667                .filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
668                .map(|v| Ty::new_float_var(self.tcx, v)),
669        );
670        vars
671    }
672
673    #[instrument(skip(self), level = "debug")]
674    pub fn sub_regions(
675        &self,
676        origin: SubregionOrigin<'tcx>,
677        a: ty::Region<'tcx>,
678        b: ty::Region<'tcx>,
679    ) {
680        self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
681    }
682
683    pub fn coerce_predicate(
699        &self,
700        cause: &ObligationCause<'tcx>,
701        param_env: ty::ParamEnv<'tcx>,
702        predicate: ty::PolyCoercePredicate<'tcx>,
703    ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
704        let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
705            a_is_expected: false, a: p.a,
707            b: p.b,
708        });
709        self.subtype_predicate(cause, param_env, subtype_predicate)
710    }
711
712    pub fn subtype_predicate(
713        &self,
714        cause: &ObligationCause<'tcx>,
715        param_env: ty::ParamEnv<'tcx>,
716        predicate: ty::PolySubtypePredicate<'tcx>,
717    ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
718        let r_a = self.shallow_resolve(predicate.skip_binder().a);
732        let r_b = self.shallow_resolve(predicate.skip_binder().b);
733        match (r_a.kind(), r_b.kind()) {
734            (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
735                return Err((a_vid, b_vid));
736            }
737            _ => {}
738        }
739
740        self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
741            if a_is_expected {
742                Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
743            } else {
744                Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
745            }
746        })
747    }
748
749    pub fn num_ty_vars(&self) -> usize {
751        self.inner.borrow_mut().type_variables().num_vars()
752    }
753
754    pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
755        self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
756    }
757
758    pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
759        let vid = self.inner.borrow_mut().type_variables().new_var(self.universe(), origin);
760        Ty::new_var(self.tcx, vid)
761    }
762
763    pub fn next_ty_var_id_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
764        let origin = TypeVariableOrigin { span, param_def_id: None };
765        self.inner.borrow_mut().type_variables().new_var(universe, origin)
766    }
767
768    pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
769        let vid = self.next_ty_var_id_in_universe(span, universe);
770        Ty::new_var(self.tcx, vid)
771    }
772
773    pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
774        self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
775    }
776
777    pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
778        let vid = self
779            .inner
780            .borrow_mut()
781            .const_unification_table()
782            .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
783            .vid;
784        ty::Const::new_var(self.tcx, vid)
785    }
786
787    pub fn next_const_var_in_universe(
788        &self,
789        span: Span,
790        universe: ty::UniverseIndex,
791    ) -> ty::Const<'tcx> {
792        let origin = ConstVariableOrigin { span, param_def_id: None };
793        let vid = self
794            .inner
795            .borrow_mut()
796            .const_unification_table()
797            .new_key(ConstVariableValue::Unknown { origin, universe })
798            .vid;
799        ty::Const::new_var(self.tcx, vid)
800    }
801
802    pub fn next_int_var(&self) -> Ty<'tcx> {
803        let next_int_var_id =
804            self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
805        Ty::new_int_var(self.tcx, next_int_var_id)
806    }
807
808    pub fn next_float_var(&self) -> Ty<'tcx> {
809        let next_float_var_id =
810            self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown);
811        Ty::new_float_var(self.tcx, next_float_var_id)
812    }
813
814    pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
818        self.next_region_var_in_universe(origin, self.universe())
819    }
820
821    pub fn next_region_var_in_universe(
825        &self,
826        origin: RegionVariableOrigin,
827        universe: ty::UniverseIndex,
828    ) -> ty::Region<'tcx> {
829        let region_var =
830            self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
831        ty::Region::new_var(self.tcx, region_var)
832    }
833
834    pub fn next_term_var_of_kind(&self, term: ty::Term<'tcx>, span: Span) -> ty::Term<'tcx> {
835        match term.kind() {
836            ty::TermKind::Ty(_) => self.next_ty_var(span).into(),
837            ty::TermKind::Const(_) => self.next_const_var(span).into(),
838        }
839    }
840
841    pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
847        self.inner.borrow_mut().unwrap_region_constraints().universe(r)
848    }
849
850    pub fn num_region_vars(&self) -> usize {
852        self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
853    }
854
855    #[instrument(skip(self), level = "debug")]
857    pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
858        self.next_region_var(RegionVariableOrigin::Nll(origin))
859    }
860
861    #[instrument(skip(self), level = "debug")]
863    pub fn next_nll_region_var_in_universe(
864        &self,
865        origin: NllRegionVariableOrigin,
866        universe: ty::UniverseIndex,
867    ) -> ty::Region<'tcx> {
868        self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
869    }
870
871    pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
872        match param.kind {
873            GenericParamDefKind::Lifetime => {
874                self.next_region_var(RegionVariableOrigin::RegionParameterDefinition(
877                    span, param.name,
878                ))
879                .into()
880            }
881            GenericParamDefKind::Type { .. } => {
882                let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
891                    self.universe(),
892                    TypeVariableOrigin { param_def_id: Some(param.def_id), span },
893                );
894
895                Ty::new_var(self.tcx, ty_var_id).into()
896            }
897            GenericParamDefKind::Const { .. } => {
898                let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
899                let const_var_id = self
900                    .inner
901                    .borrow_mut()
902                    .const_unification_table()
903                    .new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
904                    .vid;
905                ty::Const::new_var(self.tcx, const_var_id).into()
906            }
907        }
908    }
909
910    pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
913        GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
914    }
915
916    #[must_use = "this method does not have any side effects"]
922    pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
923        self.tainted_by_errors.get()
924    }
925
926    pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
929        debug!("set_tainted_by_errors(ErrorGuaranteed)");
930        self.tainted_by_errors.set(Some(e));
931    }
932
933    pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
934        let mut inner = self.inner.borrow_mut();
935        let inner = &mut *inner;
936        inner.unwrap_region_constraints().var_origin(vid)
937    }
938
939    pub fn get_region_var_infos(&self) -> VarInfos {
942        let inner = self.inner.borrow();
943        assert!(!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log));
944        let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
945        assert!(storage.data.is_empty(), "{:#?}", storage.data);
946        storage.var_infos.clone()
950    }
951
952    #[instrument(level = "debug", skip(self), ret)]
953    pub fn take_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
954        self.inner.borrow_mut().opaque_type_storage.take_opaque_types().collect()
955    }
956
957    #[instrument(level = "debug", skip(self), ret)]
958    pub fn clone_opaque_types(&self) -> Vec<(OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>)> {
959        self.inner.borrow_mut().opaque_type_storage.iter_opaque_types().collect()
960    }
961
962    #[inline(always)]
963    pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool {
964        debug_assert!(!self.next_trait_solver());
965        match self.typing_mode() {
966            TypingMode::Analysis {
967                defining_opaque_types_and_generators: defining_opaque_types,
968            }
969            | TypingMode::Borrowck { defining_opaque_types } => {
970                id.into().as_local().is_some_and(|def_id| defining_opaque_types.contains(&def_id))
971            }
972            TypingMode::Coherence
976            | TypingMode::PostBorrowckAnalysis { .. }
977            | TypingMode::PostAnalysis => false,
978        }
979    }
980
981    pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
982        self.resolve_vars_if_possible(t).to_string()
983    }
984
985    pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
988        use self::type_variable::TypeVariableValue;
989
990        match self.inner.borrow_mut().type_variables().probe(vid) {
991            TypeVariableValue::Known { value } => Ok(value),
992            TypeVariableValue::Unknown { universe } => Err(universe),
993        }
994    }
995
996    pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
997        if let ty::Infer(v) = *ty.kind() {
998            match v {
999                ty::TyVar(v) => {
1000                    let known = self.inner.borrow_mut().type_variables().probe(v).known();
1013                    known.map_or(ty, |t| self.shallow_resolve(t))
1014                }
1015
1016                ty::IntVar(v) => {
1017                    match self.inner.borrow_mut().int_unification_table().probe_value(v) {
1018                        ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1019                        ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1020                        ty::IntVarValue::Unknown => ty,
1021                    }
1022                }
1023
1024                ty::FloatVar(v) => {
1025                    match self.inner.borrow_mut().float_unification_table().probe_value(v) {
1026                        ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1027                        ty::FloatVarValue::Unknown => ty,
1028                    }
1029                }
1030
1031                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => ty,
1032            }
1033        } else {
1034            ty
1035        }
1036    }
1037
1038    pub fn shallow_resolve_const(&self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1039        match ct.kind() {
1040            ty::ConstKind::Infer(infer_ct) => match infer_ct {
1041                InferConst::Var(vid) => self
1042                    .inner
1043                    .borrow_mut()
1044                    .const_unification_table()
1045                    .probe_value(vid)
1046                    .known()
1047                    .unwrap_or(ct),
1048                InferConst::Fresh(_) => ct,
1049            },
1050            ty::ConstKind::Param(_)
1051            | ty::ConstKind::Bound(_, _)
1052            | ty::ConstKind::Placeholder(_)
1053            | ty::ConstKind::Unevaluated(_)
1054            | ty::ConstKind::Value(_)
1055            | ty::ConstKind::Error(_)
1056            | ty::ConstKind::Expr(_) => ct,
1057        }
1058    }
1059
1060    pub fn shallow_resolve_term(&self, term: ty::Term<'tcx>) -> ty::Term<'tcx> {
1061        match term.kind() {
1062            ty::TermKind::Ty(ty) => self.shallow_resolve(ty).into(),
1063            ty::TermKind::Const(ct) => self.shallow_resolve_const(ct).into(),
1064        }
1065    }
1066
1067    pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1068        self.inner.borrow_mut().type_variables().root_var(var)
1069    }
1070
1071    pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
1072        self.inner.borrow_mut().const_unification_table().find(var).vid
1073    }
1074
1075    pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> {
1078        let mut inner = self.inner.borrow_mut();
1079        let value = inner.int_unification_table().probe_value(vid);
1080        match value {
1081            ty::IntVarValue::IntType(ty) => Ty::new_int(self.tcx, ty),
1082            ty::IntVarValue::UintType(ty) => Ty::new_uint(self.tcx, ty),
1083            ty::IntVarValue::Unknown => {
1084                Ty::new_int_var(self.tcx, inner.int_unification_table().find(vid))
1085            }
1086        }
1087    }
1088
1089    pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> {
1092        let mut inner = self.inner.borrow_mut();
1093        let value = inner.float_unification_table().probe_value(vid);
1094        match value {
1095            ty::FloatVarValue::Known(ty) => Ty::new_float(self.tcx, ty),
1096            ty::FloatVarValue::Unknown => {
1097                Ty::new_float_var(self.tcx, inner.float_unification_table().find(vid))
1098            }
1099        }
1100    }
1101
1102    pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1109    where
1110        T: TypeFoldable<TyCtxt<'tcx>>,
1111    {
1112        if let Err(guar) = value.error_reported() {
1113            self.set_tainted_by_errors(guar);
1114        }
1115        if !value.has_non_region_infer() {
1116            return value;
1117        }
1118        let mut r = resolve::OpportunisticVarResolver::new(self);
1119        value.fold_with(&mut r)
1120    }
1121
1122    pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1123    where
1124        T: TypeFoldable<TyCtxt<'tcx>>,
1125    {
1126        if !value.has_infer() {
1127            return value; }
1129        let mut r = InferenceLiteralEraser { tcx: self.tcx };
1130        value.fold_with(&mut r)
1131    }
1132
1133    pub fn probe_const_var(&self, vid: ty::ConstVid) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1134        match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
1135            ConstVariableValue::Known { value } => Ok(value),
1136            ConstVariableValue::Unknown { origin: _, universe } => Err(universe),
1137        }
1138    }
1139
1140    pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<T> {
1148        match resolve::fully_resolve(self, value) {
1149            Ok(value) => {
1150                if value.has_non_region_infer() {
1151                    bug!("`{value:?}` is not fully resolved");
1152                }
1153                if value.has_infer_regions() {
1154                    let guar = self.dcx().delayed_bug(format!("`{value:?}` is not fully resolved"));
1155                    Ok(fold_regions(self.tcx, value, |re, _| {
1156                        if re.is_var() { ty::Region::new_error(self.tcx, guar) } else { re }
1157                    }))
1158                } else {
1159                    Ok(value)
1160                }
1161            }
1162            Err(e) => Err(e),
1163        }
1164    }
1165
1166    pub fn instantiate_binder_with_fresh_vars<T>(
1174        &self,
1175        span: Span,
1176        lbrct: BoundRegionConversionTime,
1177        value: ty::Binder<'tcx, T>,
1178    ) -> T
1179    where
1180        T: TypeFoldable<TyCtxt<'tcx>> + Copy,
1181    {
1182        if let Some(inner) = value.no_bound_vars() {
1183            return inner;
1184        }
1185
1186        let bound_vars = value.bound_vars();
1187        let mut args = Vec::with_capacity(bound_vars.len());
1188
1189        for bound_var_kind in bound_vars {
1190            let arg: ty::GenericArg<'_> = match bound_var_kind {
1191                ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(),
1192                ty::BoundVariableKind::Region(br) => {
1193                    self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into()
1194                }
1195                ty::BoundVariableKind::Const => self.next_const_var(span).into(),
1196            };
1197            args.push(arg);
1198        }
1199
1200        struct ToFreshVars<'tcx> {
1201            args: Vec<ty::GenericArg<'tcx>>,
1202        }
1203
1204        impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> {
1205            fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
1206                self.args[br.var.index()].expect_region()
1207            }
1208            fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
1209                self.args[bt.var.index()].expect_ty()
1210            }
1211            fn replace_const(&mut self, bv: ty::BoundVar) -> ty::Const<'tcx> {
1212                self.args[bv.index()].expect_const()
1213            }
1214        }
1215        let delegate = ToFreshVars { args };
1216        self.tcx.replace_bound_vars_uncached(value, delegate)
1217    }
1218
1219    pub(crate) fn verify_generic_bound(
1221        &self,
1222        origin: SubregionOrigin<'tcx>,
1223        kind: GenericKind<'tcx>,
1224        a: ty::Region<'tcx>,
1225        bound: VerifyBound<'tcx>,
1226    ) {
1227        debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1228
1229        self.inner
1230            .borrow_mut()
1231            .unwrap_region_constraints()
1232            .verify_generic_bound(origin, kind, a, bound);
1233    }
1234
1235    pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ty::ClosureKind> {
1239        let unresolved_kind_ty = match *closure_ty.kind() {
1240            ty::Closure(_, args) => args.as_closure().kind_ty(),
1241            ty::CoroutineClosure(_, args) => args.as_coroutine_closure().kind_ty(),
1242            _ => bug!("unexpected type {closure_ty}"),
1243        };
1244        let closure_kind_ty = self.shallow_resolve(unresolved_kind_ty);
1245        closure_kind_ty.to_opt_closure_kind()
1246    }
1247
1248    pub fn universe(&self) -> ty::UniverseIndex {
1249        self.universe.get()
1250    }
1251
1252    pub fn create_next_universe(&self) -> ty::UniverseIndex {
1255        let u = self.universe.get().next_universe();
1256        debug!("create_next_universe {u:?}");
1257        self.universe.set(u);
1258        u
1259    }
1260
1261    pub fn typing_env(&self, param_env: ty::ParamEnv<'tcx>) -> ty::TypingEnv<'tcx> {
1265        let typing_mode = match self.typing_mode() {
1266            ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1271            | ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1272                TypingMode::non_body_analysis()
1273            }
1274            mode @ (ty::TypingMode::Coherence
1275            | ty::TypingMode::PostBorrowckAnalysis { .. }
1276            | ty::TypingMode::PostAnalysis) => mode,
1277        };
1278        ty::TypingEnv { typing_mode, param_env }
1279    }
1280
1281    pub fn pseudo_canonicalize_query<V>(
1285        &self,
1286        param_env: ty::ParamEnv<'tcx>,
1287        value: V,
1288    ) -> PseudoCanonicalInput<'tcx, V>
1289    where
1290        V: TypeVisitable<TyCtxt<'tcx>>,
1291    {
1292        debug_assert!(!value.has_infer());
1293        debug_assert!(!value.has_placeholders());
1294        debug_assert!(!param_env.has_infer());
1295        debug_assert!(!param_env.has_placeholders());
1296        self.typing_env(param_env).as_query_input(value)
1297    }
1298
1299    #[inline]
1302    pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool {
1303        let inner = self.inner.try_borrow();
1305
1306        move |infer_var: TyOrConstInferVar| match (infer_var, &inner) {
1307            (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => {
1308                use self::type_variable::TypeVariableValue;
1309
1310                matches!(
1311                    inner.try_type_variables_probe_ref(ty_var),
1312                    Some(TypeVariableValue::Unknown { .. })
1313                )
1314            }
1315            _ => false,
1316        }
1317    }
1318
1319    #[inline(always)]
1329    pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar) -> bool {
1330        match infer_var {
1331            TyOrConstInferVar::Ty(v) => {
1332                use self::type_variable::TypeVariableValue;
1333
1334                match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1337                    TypeVariableValue::Unknown { .. } => false,
1338                    TypeVariableValue::Known { .. } => true,
1339                }
1340            }
1341
1342            TyOrConstInferVar::TyInt(v) => {
1343                self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_known()
1347            }
1348
1349            TyOrConstInferVar::TyFloat(v) => {
1350                self.inner.borrow_mut().float_unification_table().probe_value(v).is_known()
1355            }
1356
1357            TyOrConstInferVar::Const(v) => {
1358                match self.inner.borrow_mut().const_unification_table().probe_value(v) {
1363                    ConstVariableValue::Unknown { .. } => false,
1364                    ConstVariableValue::Known { .. } => true,
1365                }
1366            }
1367        }
1368    }
1369
1370    pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
1372        debug_assert!(
1373            self.obligation_inspector.get().is_none(),
1374            "shouldn't override a set obligation inspector"
1375        );
1376        self.obligation_inspector.set(Some(inspector));
1377    }
1378}
1379
1380#[derive(Copy, Clone, Debug)]
1383pub enum TyOrConstInferVar {
1384    Ty(TyVid),
1386    TyInt(IntVid),
1388    TyFloat(FloatVid),
1390
1391    Const(ConstVid),
1393}
1394
1395impl<'tcx> TyOrConstInferVar {
1396    pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1400        match arg.kind() {
1401            GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1402            GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1403            GenericArgKind::Lifetime(_) => None,
1404        }
1405    }
1406
1407    pub fn maybe_from_term(term: Term<'tcx>) -> Option<Self> {
1411        match term.kind() {
1412            TermKind::Ty(ty) => Self::maybe_from_ty(ty),
1413            TermKind::Const(ct) => Self::maybe_from_const(ct),
1414        }
1415    }
1416
1417    fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1420        match *ty.kind() {
1421            ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1422            ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1423            ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1424            _ => None,
1425        }
1426    }
1427
1428    fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1431        match ct.kind() {
1432            ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1433            _ => None,
1434        }
1435    }
1436}
1437
1438struct InferenceLiteralEraser<'tcx> {
1441    tcx: TyCtxt<'tcx>,
1442}
1443
1444impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> {
1445    fn cx(&self) -> TyCtxt<'tcx> {
1446        self.tcx
1447    }
1448
1449    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1450        match ty.kind() {
1451            ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1452            ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1453            _ => ty.super_fold_with(self),
1454        }
1455    }
1456}
1457
1458impl<'tcx> TypeTrace<'tcx> {
1459    pub fn span(&self) -> Span {
1460        self.cause.span
1461    }
1462
1463    pub fn types(cause: &ObligationCause<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> TypeTrace<'tcx> {
1464        TypeTrace {
1465            cause: cause.clone(),
1466            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1467        }
1468    }
1469
1470    pub fn trait_refs(
1471        cause: &ObligationCause<'tcx>,
1472        a: ty::TraitRef<'tcx>,
1473        b: ty::TraitRef<'tcx>,
1474    ) -> TypeTrace<'tcx> {
1475        TypeTrace { cause: cause.clone(), values: ValuePairs::TraitRefs(ExpectedFound::new(a, b)) }
1476    }
1477
1478    pub fn consts(
1479        cause: &ObligationCause<'tcx>,
1480        a: ty::Const<'tcx>,
1481        b: ty::Const<'tcx>,
1482    ) -> TypeTrace<'tcx> {
1483        TypeTrace {
1484            cause: cause.clone(),
1485            values: ValuePairs::Terms(ExpectedFound::new(a.into(), b.into())),
1486        }
1487    }
1488}
1489
1490impl<'tcx> SubregionOrigin<'tcx> {
1491    pub fn span(&self) -> Span {
1492        match *self {
1493            SubregionOrigin::Subtype(ref a) => a.span(),
1494            SubregionOrigin::RelateObjectBound(a) => a,
1495            SubregionOrigin::RelateParamBound(a, ..) => a,
1496            SubregionOrigin::RelateRegionParamBound(a, _) => a,
1497            SubregionOrigin::Reborrow(a) => a,
1498            SubregionOrigin::ReferenceOutlivesReferent(_, a) => a,
1499            SubregionOrigin::CompareImplItemObligation { span, .. } => span,
1500            SubregionOrigin::AscribeUserTypeProvePredicate(span) => span,
1501            SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1502        }
1503    }
1504
1505    pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1506    where
1507        F: FnOnce() -> Self,
1508    {
1509        match *cause.code() {
1510            traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1511                SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1512            }
1513
1514            traits::ObligationCauseCode::CompareImplItem {
1515                impl_item_def_id,
1516                trait_item_def_id,
1517                kind: _,
1518            } => SubregionOrigin::CompareImplItemObligation {
1519                span: cause.span,
1520                impl_item_def_id,
1521                trait_item_def_id,
1522            },
1523
1524            traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1525                impl_item_def_id,
1526                trait_item_def_id,
1527            } => SubregionOrigin::CheckAssociatedTypeBounds {
1528                impl_item_def_id,
1529                trait_item_def_id,
1530                parent: Box::new(default()),
1531            },
1532
1533            traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
1534                SubregionOrigin::AscribeUserTypeProvePredicate(span)
1535            }
1536
1537            traits::ObligationCauseCode::ObjectTypeBound(ty, _reg) => {
1538                SubregionOrigin::RelateRegionParamBound(cause.span, Some(ty))
1539            }
1540
1541            _ => default(),
1542        }
1543    }
1544}
1545
1546impl RegionVariableOrigin {
1547    pub fn span(&self) -> Span {
1548        match *self {
1549            RegionVariableOrigin::Misc(a)
1550            | RegionVariableOrigin::PatternRegion(a)
1551            | RegionVariableOrigin::BorrowRegion(a)
1552            | RegionVariableOrigin::Autoref(a)
1553            | RegionVariableOrigin::Coercion(a)
1554            | RegionVariableOrigin::RegionParameterDefinition(a, ..)
1555            | RegionVariableOrigin::BoundRegion(a, ..)
1556            | RegionVariableOrigin::UpvarRegion(_, a) => a,
1557            RegionVariableOrigin::Nll(..) => bug!("NLL variable used with `span`"),
1558        }
1559    }
1560}
1561
1562impl<'tcx> InferCtxt<'tcx> {
1563    pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
1566        let block = block.innermost_block();
1567        if let Some(expr) = &block.expr {
1568            expr.span
1569        } else if let Some(stmt) = block.stmts.last() {
1570            stmt.span
1572        } else {
1573            block.span
1575        }
1576    }
1577
1578    pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
1581        match self.tcx.hir_node(hir_id) {
1582            hir::Node::Block(blk)
1583            | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => {
1584                self.find_block_span(blk)
1585            }
1586            hir::Node::Expr(e) => e.span,
1587            _ => DUMMY_SP,
1588        }
1589    }
1590}