Skip to main content

rapx/vm/
region.rs

1//! Region (lifetime) helpers shared by the VM and the property checker.
2
3use 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
12/// Whether `src` outlives `ret` (`src: ret`).
13///
14/// `'static` and reflexivity are handled structurally; declared where-clauses
15/// (`'a: 'b`) are resolved via rustc's `FreeRegionMap` (which also computes the
16/// transitive closure). Anything else is treated as *not* outlives.
17pub(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
38/// Consult the function's declared outlives constraints (where-clauses) via
39/// rustc's `FreeRegionMap`, which records `'a: 'b` bounds and their transitive
40/// closure. `sub_free_regions(r_a, r_b)` tests `r_a <= r_b` (i.e. `r_b: r_a`),
41/// so `src: ret` is `sub_free_regions(ret, src)`.
42fn 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
58/// Whether `src_region` provably outlives `demand` via the well-formedness of a
59/// reference parameter `&'r Self<'a>`: the reference requires its pointee's
60/// regions to outlive `'r` (`'a: 'r`), which the where-clause-only
61/// [`region_outlives`] cannot see.  This holds when `demand` is exactly the
62/// reference's own region `'r` and `src_region` is one of the pointee's outlives
63/// components.
64pub(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
82/// The function's signature with late-bound regions liberated to free
83/// `ReLateParam`s, so reference regions are comparable (MIR erases them to
84/// `ReErased`).
85fn 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
97/// The reference region of `def_id`'s return type (`&'r T` → `Some('r)`).
98pub(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
105/// The type of `def_id`'s argument at `index`.
106pub(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}