Skip to main content

rapx/util/
fn_info.rs

1use rustc_hir::{Safety, def::DefKind, def_id::DefId};
2use rustc_middle::{
3    mir::{ProjectionElem, StatementKind},
4    ty::{self, AssocKind, Mutability, TyCtxt, TyKind},
5};
6use rustc_public::{CrateDef, rustc_internal};
7use rustc_span::{kw, sym};
8use std::{collections::HashSet, fmt::Debug, hash::Hash};
9use syn::Expr;
10
11pub use super::mir_scan::get_fn_safety;
12
13#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
14pub enum FnKind {
15    Fn,
16    Method,
17    Constructor,
18    Intrinsic,
19}
20
21#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
22pub struct FnInfo {
23    pub def_id: DefId,
24    pub fn_safety: Safety,
25    pub fn_kind: FnKind,
26}
27
28impl FnInfo {
29    pub fn new(def_id: DefId, fn_safety: Safety, fn_kind: FnKind) -> Self {
30        FnInfo {
31            def_id,
32            fn_safety,
33            fn_kind,
34        }
35    }
36}
37
38#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
39pub struct AdtInfo {
40    pub def_id: DefId,
41    pub literal_cons_enabled: bool,
42}
43
44impl AdtInfo {
45    pub fn new(def_id: DefId, literal_cons_enabled: bool) -> Self {
46        AdtInfo {
47            def_id,
48            literal_cons_enabled,
49        }
50    }
51}
52
53pub fn check_visibility(tcx: TyCtxt, func_defid: DefId) -> bool {
54    tcx.visibility(func_defid).is_public()
55}
56
57/// Returns true when `ty` denotes `Self`: either the generic `Self` param
58/// (`ty.is_param(0)`) or a type equal to the impl's self type.
59fn is_self_ty<'tcx>(tcx: TyCtxt<'tcx>, assoc_item: &ty::AssocItem, ty: ty::Ty<'tcx>) -> bool {
60    if ty.is_param(0) {
61        return true;
62    }
63    assoc_item
64        .impl_container(tcx)
65        .is_some_and(|impl_id| ty == tcx.type_of(impl_id).skip_binder())
66}
67
68pub fn get_type(tcx: TyCtxt<'_>, def_id: DefId) -> FnKind {
69    let Some(assoc_item) = tcx.opt_associated_item(def_id) else {
70        return FnKind::Fn;
71    };
72    let AssocKind::Fn { has_self, .. } = assoc_item.kind else {
73        return FnKind::Fn;
74    };
75    if has_self {
76        return FnKind::Method;
77    }
78    let output = tcx.fn_sig(def_id).skip_binder().output().skip_binder();
79    if is_self_ty(tcx, &assoc_item, output) {
80        return FnKind::Constructor;
81    }
82    match output.kind() {
83        TyKind::Ref(_, ref_ty, _) => {
84            if is_self_ty(tcx, &assoc_item, *ref_ty) {
85                return FnKind::Constructor;
86            }
87        }
88        TyKind::Adt(adt_def, substs)
89            if adt_def.is_enum()
90                && (tcx.is_diagnostic_item(sym::Option, adt_def.did())
91                    || tcx.is_diagnostic_item(sym::Result, adt_def.did())
92                    || tcx.is_diagnostic_item(kw::Box, adt_def.did()))
93            && is_self_ty(tcx, &assoc_item, substs.type_at(0)) => {
94                return FnKind::Constructor;
95            }
96        _ => {}
97    }
98    FnKind::Fn
99}
100
101/// Returns true when the function is a "wrapped" constructor that returns
102/// `Option<Self>` / `Result<Self, _>` rather than a bare `Self`.
103///
104/// `get_type` classifies these as [`FnKind::Constructor`], but for the wrapped
105/// forms the `None`/`Err` paths do not produce a `Self`. Contract place
106/// resolution uses this to select the `Some`/`Ok` field of the return value.
107/// (`Box<Self>` is intentionally *not* included: every path still produces a
108/// `Self` behind the pointer.)
109pub fn returns_wrapped_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
110    let Some(assoc_item) = tcx.opt_associated_item(def_id) else {
111        return false;
112    };
113    if !matches!(
114        assoc_item.kind,
115        AssocKind::Fn {
116            has_self: false,
117            ..
118        }
119    ) {
120        return false;
121    }
122    let fn_sig = tcx.fn_sig(def_id).skip_binder();
123    let output = fn_sig.output().skip_binder();
124    let TyKind::Adt(adt_def, substs) = output.kind() else {
125        return false;
126    };
127    if !(adt_def.is_enum()
128        && (tcx.is_diagnostic_item(sym::Option, adt_def.did())
129            || tcx.is_diagnostic_item(sym::Result, adt_def.did())))
130    {
131        return false;
132    }
133    is_self_ty(tcx, &assoc_item, substs.type_at(0))
134}
135
136/// The `AdtDef` that `def_id`'s impl block is implemented for, if any.
137fn self_adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::AdtDef<'_>> {
138    let assoc_item = tcx.opt_associated_item(def_id)?;
139    let impl_id = assoc_item.impl_container(tcx)?;
140    tcx.type_of(impl_id).skip_binder().ty_adt_def()
141}
142
143// result: adt_def_id, is_literal
144pub fn get_adt_via_method(tcx: TyCtxt<'_>, method_def_id: DefId) -> Option<AdtInfo> {
145    let adt_def = self_adt_def(tcx, method_def_id)?;
146    let adt_def_id = adt_def.did();
147
148    let total_count = adt_def.all_fields().count();
149
150    if total_count == 0 {
151        return Some(AdtInfo::new(adt_def_id, true));
152    }
153
154    let pub_count = public_field_indices(tcx, adt_def).len();
155
156    if pub_count == 0 {
157        return None;
158    }
159    Some(AdtInfo::new(adt_def_id, pub_count == total_count))
160}
161pub fn get_adt_def_id_by_adt_method(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
162    self_adt_def(tcx, def_id).map(|adt_def| adt_def.did())
163}
164
165/// Returns true when `def_id` is a method taking `&mut self` (a mutator).
166///
167/// Detection is based on the method signature rather than MIR, so it also
168/// works for foreign (e.g. std) functions whose MIR is unavailable.
169fn is_mut_self_method(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
170    let Some(assoc) = tcx.opt_associated_item(def_id) else {
171        return false;
172    };
173    if !matches!(assoc.kind, AssocKind::Fn { has_self: true, .. }) {
174        return false;
175    }
176    let fn_sig = tcx.fn_sig(def_id).instantiate_identity().skip_binder();
177    let Some(first) = fn_sig.inputs_and_output.first().copied() else {
178        return false;
179    };
180    matches!(first.kind(), TyKind::Ref(_, _, Mutability::Mut))
181}
182
183// Check each field's visibility, return the public fields vec
184fn public_field_indices(tcx: TyCtxt<'_>, adt_def: ty::AdtDef<'_>) -> HashSet<usize> {
185    adt_def
186        .all_fields()
187        .enumerate()
188        .filter_map(|(index, field_def)| tcx.visibility(field_def.did).is_public().then_some(index))
189        .collect()
190}
191
192/// parse expr into number.
193pub fn parse_expr_into_number(expr: &Expr) -> Option<usize> {
194    if let Expr::Lit(expr_lit) = expr
195        && let syn::Lit::Int(lit_int) = &expr_lit.lit {
196            return lit_int.base10_parse::<usize>().ok();
197        }
198    None
199}
200
201pub fn get_all_std_fns_by_rustc_public(tcx: TyCtxt) -> Vec<DefId> {
202    let mut all_std_fn_def = Vec::new();
203    let mut results = Vec::new();
204    let mut core_fn_def: Vec<_> = rustc_public::find_crates("core")
205        .iter()
206        .flat_map(|krate| krate.fn_defs())
207        .collect();
208    let mut std_fn_def: Vec<_> = rustc_public::find_crates("std")
209        .iter()
210        .flat_map(|krate| krate.fn_defs())
211        .collect();
212    let mut alloc_fn_def: Vec<_> = rustc_public::find_crates("alloc")
213        .iter()
214        .flat_map(|krate| krate.fn_defs())
215        .collect();
216    all_std_fn_def.append(&mut core_fn_def);
217    all_std_fn_def.append(&mut std_fn_def);
218    all_std_fn_def.append(&mut alloc_fn_def);
219
220    for fn_def in &all_std_fn_def {
221        let def_id = rustc_internal::internal(tcx, fn_def.def_id());
222        results.push(def_id);
223    }
224    results
225}
226
227/// Find `&mut self` methods (mutators) on the same struct as `src_def_id`.
228///
229/// For std types the mutators are located among the std library's public
230/// functions; for user types they are the struct's inherent `&mut self` methods.
231pub fn get_all_mutable_methods(tcx: TyCtxt, src_def_id: DefId) -> HashSet<DefId> {
232    if get_type(tcx, src_def_id) == FnKind::Constructor {
233        return HashSet::new();
234    }
235    let target_adt_def = get_adt_def_id_by_adt_method(tcx, src_def_id);
236    let mut mutators = HashSet::new();
237    let mut is_std = false;
238    for def_id in get_all_std_fns_by_rustc_public(tcx) {
239        let adt_def = get_adt_def_id_by_adt_method(tcx, def_id);
240        if adt_def.is_some() && adt_def == target_adt_def && src_def_id != def_id {
241            if is_mut_self_method(tcx, def_id) {
242                mutators.insert(def_id);
243            }
244            is_std = true;
245        }
246    }
247    if is_std {
248        return mutators;
249    }
250    mutators.extend(get_muts(tcx, src_def_id));
251    mutators
252}
253
254/// Associated function `DefId`s (inherent impls only) on the struct that
255/// `def_id`'s impl block is implemented for.
256fn assoc_fns_of_self(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<DefId> {
257    let Some(adt_def) = self_adt_def(tcx, def_id) else {
258        return Vec::new();
259    };
260    let mut fns = Vec::new();
261    for impl_def_id in tcx.inherent_impls(adt_def.did()) {
262        for item in tcx.associated_item_def_ids(*impl_def_id) {
263            if matches!(tcx.def_kind(*item), DefKind::Fn | DefKind::AssocFn) {
264                fns.push(*item);
265            }
266        }
267    }
268    fns
269}
270
271pub fn get_cons(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<DefId> {
272    if tcx.def_kind(def_id) == DefKind::Fn || get_type(tcx, def_id) == FnKind::Constructor {
273        return Vec::new();
274    }
275    assoc_fns_of_self(tcx, def_id)
276        .into_iter()
277        .filter(|&item| get_type(tcx, item) == FnKind::Constructor)
278        .collect()
279}
280
281/// Find `&mut self` methods (mutators) on the same struct as `def_id`.
282///
283/// A mutator is a method whose first parameter is a mutable reference to Self.
284/// These methods can change struct fields and affect subsequent invariant checks.
285pub fn get_muts(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<DefId> {
286    assoc_fns_of_self(tcx, def_id)
287        .into_iter()
288        .filter(|&item| is_mut_self_method(tcx, item))
289        .collect()
290}
291
292pub fn append_fn_with_types(tcx: TyCtxt, def_id: DefId) -> FnInfo {
293    FnInfo::new(def_id, get_fn_safety(tcx, def_id), get_type(tcx, def_id))
294}
295
296pub fn get_ptr_deref_dummy_def_id(tcx: TyCtxt<'_>) -> Option<DefId> {
297    tcx.hir_crate_items(()).free_items().find_map(|item_id| {
298        let def_id = item_id.owner_id.to_def_id();
299        let name = tcx.opt_item_name(def_id)?;
300
301        (name.as_str() == "__raw_ptr_deref_dummy").then_some(def_id)
302    })
303}
304
305/// Return field indices that a `&mut self` method writes to.
306///
307/// Scans the MIR body for assignments to `(*self).field_n` and returns the
308/// set of field indices that are modified.  Used by --no-invariant-target mode to know which
309/// constructor-inherited invariants are invalidated by a mutator.
310pub fn get_mutated_fields(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<usize> {
311    let body = tcx.optimized_mir(def_id);
312    let mut fields = Vec::new();
313
314    for data in body.basic_blocks.iter() {
315        for statement in &data.statements {
316            if let StatementKind::Assign(assign) = &statement.kind {
317                let (place, _) = &**assign;
318                if place.local.as_usize() != 1 {
319                    continue;
320                }
321                let mut saw_deref = false;
322                for proj in place.projection.iter() {
323                    match proj {
324                        ProjectionElem::Deref => {
325                            saw_deref = true;
326                        }
327                        ProjectionElem::Field(index, _) if saw_deref => {
328                            let idx = index.as_usize();
329                            if !fields.contains(&idx) {
330                                fields.push(idx);
331                            }
332                        }
333                        _ => {}
334                    }
335                }
336            }
337        }
338    }
339
340    fields
341}
342
343pub fn is_externally_reachable(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
344    let Some(local) = def_id.as_local() else {
345        return true;
346    };
347    tcx.effective_visibilities(()).is_reachable(local)
348}