1use rustc_data_structures::{fx::FxHashSet, smallvec::SmallVec};
4use rustc_hir::{def::DefKind, def_id::DefId};
5use rustc_infer::infer::outlives::env::OutlivesEnvironment;
6use rustc_middle::ty::{
7 Region, RegionKind, Ty, TyCtxt, TyKind,
8 outlives::{Component, push_outlives_components},
9};
10
11
12pub(crate) fn region_outlives<'tcx>(
18 tcx: TyCtxt<'tcx>,
19 def_id: DefId,
20 src: Region<'tcx>,
21 ret: Region<'tcx>,
22) -> bool {
23 match (src.kind(), ret.kind()) {
24 (RegionKind::ReStatic, _) => true,
25 (_, RegionKind::ReStatic) => false,
26 _ => {
27 if src == ret {
28 return true;
29 }
30 if !src.is_free() || !ret.is_free() {
31 return false;
32 }
33 free_region_outlives(tcx, def_id, src, ret)
34 }
35 }
36}
37
38fn free_region_outlives<'tcx>(
43 tcx: TyCtxt<'tcx>,
44 def_id: DefId,
45 src: Region<'tcx>,
46 ret: Region<'tcx>,
47) -> bool {
48 let param_env = tcx.param_env(def_id);
49 let env = OutlivesEnvironment::from_normalized_bounds(
50 param_env,
51 Vec::new(),
52 std::iter::empty(),
53 FxHashSet::default(),
54 );
55 env.free_region_map().sub_free_regions(tcx, ret, src)
56}
57
58pub(crate) fn region_outlives_implied<'tcx>(
65 tcx: TyCtxt<'tcx>,
66 src_region: Region<'tcx>,
67 self_ty: Ty<'tcx>,
68 demand: Region<'tcx>,
69) -> bool {
70 let TyKind::Ref(ref_region, pointee, _) = self_ty.kind() else {
71 return false;
72 };
73 if *ref_region != demand {
74 return false;
75 }
76 let mut out: SmallVec<[Component<TyCtxt<'tcx>>; 4]> = SmallVec::new();
77 push_outlives_components(tcx, *pointee, &mut out);
78 out.iter()
79 .any(|c| matches!(c, Component::Region(r) if *r == src_region))
80}
81
82fn liberate_fn_sig<'tcx>(
86 tcx: TyCtxt<'tcx>,
87 def_id: DefId,
88) -> Option<rustc_middle::ty::FnSig<'tcx>> {
89 if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
90 return None;
91 }
92 let fn_sig = tcx.fn_sig(def_id).instantiate_identity();
93 let fn_sig = fn_sig.skip_norm_wip();
94 Some(tcx.liberate_late_bound_regions(def_id, fn_sig))
95}
96
97pub(crate) fn fn_return_region<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Region<'tcx>> {
99 match liberate_fn_sig(tcx, def_id)?.output().kind() {
100 TyKind::Ref(region, _, _) => Some(*region),
101 _ => None,
102 }
103}
104
105pub(crate) fn fn_arg_ty<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, index: usize) -> Option<Ty<'tcx>> {
107 liberate_fn_sig(tcx, def_id)?.inputs().get(index).copied()
108}