rapx/analysis/dataflow/call_summary/
function_var.rs1use rustc_hir::def_id::DefId;
9use rustc_middle::{
10 mir::{Body, Operand},
11 ty::{Mutability, Ty, TyCtxt, TyKind},
12};
13
14use crate::def_ids::type_ids;
15use crate::analysis::dataflow::call::CallDependencies;
16use crate::compat::Spanned;
17use crate::def_ids::lang_api;
18
19pub(crate) fn supports_result(ty: Ty<'_>) -> bool {
20 matches!(ty.kind(), TyKind::Bool)
21 || matches!(ty.kind(), TyKind::Adt(def, _) if type_ids::is_std_ordering(def.did()))
22}
23
24pub(super) fn estimate<'tcx>(
25 tcx: TyCtxt<'tcx>,
26 callee: DefId,
27 args: &[Spanned<Operand<'tcx>>],
28 body: &Body<'tcx>,
29) -> Option<CallDependencies> {
30 if tcx.is_mir_available(callee) {
31 return None;
32 }
33 let trait_id = tcx.trait_of_assoc(callee)?;
34 if !lang_api::is_fn_trait(tcx, trait_id) {
35 return None;
36 }
37
38 let write_args: Vec<_> = args
43 .iter()
44 .enumerate()
45 .filter_map(|(index, arg)| {
46 (index == 0 || operand_ty(tcx, body, &arg.node).is_none_or(may_write_reachable))
47 .then_some(index)
48 })
49 .collect();
50 let all_args: Vec<_> = (0..args.len()).collect();
51 Some(CallDependencies {
52 return_depends_on_args: all_args.clone(),
53 write_args,
54 write_inputs: all_args,
55 })
56}
57
58fn operand_ty<'tcx>(
59 tcx: TyCtxt<'tcx>,
60 body: &Body<'tcx>,
61 operand: &Operand<'tcx>,
62) -> Option<Ty<'tcx>> {
63 match operand {
64 Operand::Copy(place) | Operand::Move(place) => Some(place.ty(&body.local_decls, tcx).ty),
65 Operand::Constant(constant) => Some(constant.const_.ty()),
66 Operand::RuntimeChecks(_) => None,
67 }
68}
69
70fn may_write_reachable(ty: Ty<'_>) -> bool {
71 match ty.kind() {
72 TyKind::Ref(_, _, Mutability::Mut) | TyKind::RawPtr(..) => true,
73 TyKind::Ref(_, inner, Mutability::Not) => may_contain_interior_mutability(*inner),
74 TyKind::Tuple(fields) => fields.iter().any(may_write_reachable),
75 TyKind::Array(inner, _) | TyKind::Slice(inner) => may_write_reachable(*inner),
76 TyKind::Bool | TyKind::Char | TyKind::Int(_) | TyKind::Uint(_) | TyKind::Float(_)
77 | TyKind::Never | TyKind::Str => false,
78 _ => true,
80 }
81}
82
83fn may_contain_interior_mutability(ty: Ty<'_>) -> bool {
84 match ty.kind() {
85 TyKind::Bool | TyKind::Char | TyKind::Int(_) | TyKind::Uint(_) | TyKind::Float(_)
86 | TyKind::Never | TyKind::Str => false,
87 TyKind::Tuple(fields) => fields.iter().any(may_contain_interior_mutability),
88 TyKind::Array(inner, _) | TyKind::Slice(inner) => may_contain_interior_mutability(*inner),
89 TyKind::Ref(_, inner, Mutability::Not) => may_contain_interior_mutability(*inner),
90 _ => true,
92 }
93}