1use crate::util::mir_utils;
6use rustc_abi::FieldIdx;
7use rustc_hir::def::DefKind;
8use rustc_hir::def_id::DefId;
9use rustc_middle::mir::Local;
10use rustc_middle::ty::{Ty, TyCtxt, TyKind};
11use syn::Expr;
12
13use crate::util::fn_info::{FnKind, get_type};
14use crate::util::name::{access_ident_recursive, get_adt_self_ty, parse_signature};
15
16use super::{ContractExpr, ContractPlace, ContractProjection, PlaceBase, Property, PropertyArg, PropertyKind};
17
18type PlacePath<'tcx> = (usize, Vec<usize>, Ty<'tcx>);
19
20pub(crate) fn index_access_locals(property: &Property<'_>) -> Option<(Local, Local)> {
22 let Property::Atom(atom) = property else { return None };
23 if atom.kind != PropertyKind::InBound { return None }
24 let Some(ContractExpr::IndexAccess { slice, index }) = atom.args.first().and_then(PropertyArg::expr)
25 else { return None };
26 let (ContractExpr::Place(slice), ContractExpr::Place(index)) = (slice.as_ref(), index.as_ref())
27 else { return None };
28 (slice.projections.is_empty() && index.projections.is_empty())
29 .then(|| (slice.base.to_local(), index.base.to_local()))
30}
31
32pub(crate) fn slice_offset_locals(property: &Property<'_>) -> Option<(Local, Local, Local)> {
34 let Property::Atom(atom) = property else { return None };
35 if atom.kind != PropertyKind::SliceOffset { return None }
36 let locals: Option<Vec<Local>> = atom.args.iter().map(|arg| {
37 let Some(ContractExpr::Place(place)) = arg.expr() else { return None };
38 place.projections.is_empty().then(|| place.base.to_local())
39 }).collect();
40 let locals = locals?;
41 let [dest, base, index] = locals.as_slice() else { return None };
42 Some((*dest, *base, *index))
43}
44
45pub(crate) fn bind_call_property<'tcx>(property: &mut Property<'tcx>, args: &[Option<Local>], destination: Local) -> bool {
47 let mut bound = true;
48 map_property_places(property, &mut |base| {
49 let local = match *base {
50 PlaceBase::Return | PlaceBase::Local(0) => Some(destination),
51 PlaceBase::Arg(index) => args.get(index).copied().flatten(),
52 PlaceBase::Local(index) => args.get(index - 1).copied().flatten(),
53 };
54 if let Some(local) = local {
55 *base = PlaceBase::Local(local.as_usize());
56 } else {
57 bound = false;
58 }
59 });
60 bound
61}
62
63pub(crate) fn rebind_property_place<'tcx>(property: &mut Property<'tcx>, local: Local) {
65 map_property_places(property, &mut |base| *base = PlaceBase::Local(local.as_usize()));
66}
67
68fn map_property_places<'tcx>(property: &mut Property<'tcx>, map: &mut impl FnMut(&mut PlaceBase)) {
69 match property {
70 Property::Atom(atom) => {
71 for arg in &mut atom.args {
72 match arg {
73 PropertyArg::Expr(expr) | PropertyArg::ForEach(expr) => map_expr_places(expr, map),
74 PropertyArg::Predicates(preds) => {
75 for pred in preds {
76 map_expr_places(&mut pred.lhs, map);
77 map_expr_places(&mut pred.rhs, map);
78 }
79 }
80 _ => {}
81 }
82 }
83 }
84 Property::And(and) => {
85 for conjunct in &mut and.conjuncts { map_property_places(conjunct, map) }
86 }
87 Property::Or(or) => {
88 for disjunct in &mut or.disjuncts { map_property_places(disjunct, map) }
89 }
90 }
91}
92
93fn map_expr_places<'tcx>(expr: &mut ContractExpr<'tcx>, map: &mut impl FnMut(&mut PlaceBase)) {
94 match expr {
95 ContractExpr::Place(cp) => map(&mut cp.base),
96 ContractExpr::Len(inner, _) | ContractExpr::IsEmpty(inner, _) | ContractExpr::Unary { expr: inner, .. } => {
97 map_expr_places(inner, map)
98 }
99 ContractExpr::IndexAccess { slice, index } => {
100 map_expr_places(slice, map);
101 map_expr_places(index, map);
102 }
103 ContractExpr::Binary { lhs, rhs, .. } => {
104 map_expr_places(lhs, map);
105 map_expr_places(rhs, map);
106 }
107 ContractExpr::MethodCall { receiver, args, .. } => {
108 map_expr_places(receiver, map);
109 for arg in args { map_expr_places(arg, map) }
110 }
111 ContractExpr::If { cond, then_expr, else_expr } => {
112 map_expr_places(&mut cond.lhs, map);
113 map_expr_places(&mut cond.rhs, map);
114 map_expr_places(then_expr, map);
115 map_expr_places(else_expr, map);
116 }
117 _ => {}
118 }
119}
120
121pub(crate) fn parse_contract_place<'tcx>(
122 tcx: TyCtxt<'tcx>,
123 def_id: DefId,
124 expr: &Expr,
125) -> Option<ContractPlace> {
126 if let Expr::MethodCall(expr_method) = expr
127 && (expr_method.method == "iter" || expr_method.method == "each_element")
128 && expr_method.args.is_empty()
129 {
130 let mut place = parse_contract_place(tcx, def_id, &expr_method.receiver)?;
131 place.projections.push(ContractProjection::ForEach);
132 return Some(place);
133 }
134
135 if let Expr::MethodCall(expr_method) = expr
136 && expr_method.method == "unwrap_some" && expr_method.args.is_empty()
137 && let Some((base, fields, recv_ty)) =
138 parse_expr_into_local_and_ty(tcx, def_id, &expr_method.receiver)
139 {
140 let peeled_ty = recv_ty.peel_refs();
141 if let TyKind::Adt(adt_def, _) = peeled_ty.kind()
142 && adt_def.is_enum() {
143 let some_variant =
144 adt_def.variants().iter_enumerated().find_map(|(vidx, v)| {
145 if v.name.to_string() == "Some" {
146 Some(vidx.as_usize())
147 } else {
148 None
149 }
150 });
151 if let Some(variant_index) = some_variant {
152 let mut place = ContractPlace::local(base, fields);
153 place
154 .projections
155 .push(ContractProjection::Downcast { variant_index });
156 return Some(place);
157 }
158 }
159 }
160
161 if let Some((base, fields, _ty)) = parse_expr_into_local_and_ty(tcx, def_id, expr) {
162 return Some(ContractPlace::local(base, fields));
163 }
164 parse_return_field_place(tcx, def_id, expr).or_else(|| parse_named_place(expr))
165}
166
167fn parse_return_field_place<'tcx>(
171 tcx: TyCtxt<'tcx>,
172 def_id: DefId,
173 expr: &Expr,
174) -> Option<ContractPlace> {
175 let mut field_names: Vec<String> = Vec::new();
176 let mut cur = expr;
177 loop {
178 match cur {
179 Expr::Return(expr_return) if expr_return.expr.is_none() => break,
180 Expr::Field(expr_field) => {
181 field_names.push(match &expr_field.member {
182 syn::Member::Named(ident) => ident.to_string(),
183 syn::Member::Unnamed(index) => index.index.to_string(),
184 });
185 cur = &expr_field.base;
186 }
187 _ => return None,
188 }
189 }
190 if field_names.is_empty() {
191 return None;
192 }
193 field_names.reverse();
194 let ret_ty = tcx.fn_sig(def_id).skip_binder().output().skip_binder();
195 let (field_indices, _) = walk_fields(tcx, ret_ty, Vec::new(), &field_names)?;
196 Some(ContractPlace::local(0, field_indices))
197}
198
199fn parse_named_place(expr: &Expr) -> Option<ContractPlace> {
200 if let Expr::Return(expr_return) = expr
207 && expr_return.expr.is_none()
208 {
209 return Some(ContractPlace {
210 base: PlaceBase::Return,
211 projections: Vec::new(),
212 });
213 }
214 if let Expr::Path(expr_path) = expr
215 && let Some(ident) = expr_path.path.get_ident() {
216 let s = ident.to_string();
217 if let Some(num_str) = s.strip_prefix("Arg_")
218 && let Ok(idx) = num_str.parse::<usize>() {
219 return Some(ContractPlace::arg(idx));
220 }
221 }
222 None
223}
224
225pub(crate) fn parse_expr_into_local_and_ty<'tcx>(
226 tcx: TyCtxt<'tcx>,
227 def_id: DefId,
228 expr: &Expr,
229) -> Option<PlacePath<'tcx>> {
230 if let Some((base_ident, fields)) = access_ident_recursive(expr) {
231 return resolve_place_from_ident(tcx, def_id, &base_ident, &fields);
232 }
233 None
234}
235
236pub(crate) fn resolve_place_from_ident<'tcx>(
239 tcx: TyCtxt<'tcx>,
240 def_id: DefId,
241 base_ident: &str,
242 fields: &[String],
243) -> Option<PlacePath<'tcx>> {
244 let (param_names, param_tys) = parse_signature(tcx, def_id);
245 if param_names.first().is_some_and(|name| name != "0")
246 && let Some(param_index) = param_names.iter().position(|name| name == base_ident) {
247 return resolve_projection_from_base_ident(
248 tcx,
249 fields.to_vec(),
250 param_index + 1,
251 param_tys[param_index],
252 );
253 }
254
255 if let Some(struct_ty) = get_adt_self_ty(tcx, def_id) {
256 return resolve_projection_from_struct_ident(
257 tcx,
258 def_id,
259 base_ident.to_string(),
260 fields.to_vec(),
261 struct_ty,
262 );
263 }
264 None
265}
266
267fn walk_fields<'tcx>(
269 tcx: TyCtxt<'tcx>,
270 mut current_ty: Ty<'tcx>,
271 mut field_indices: Vec<usize>,
272 fields: &[String],
273) -> Option<(Vec<usize>, Ty<'tcx>)> {
274 for field_name in fields {
275 let (field_idx, field_ty) = resolve_next_field(tcx, current_ty, field_name)?;
276 current_ty = field_ty;
277 field_indices.push(field_idx);
278 }
279 Some((field_indices, current_ty))
280}
281
282fn resolve_projection_from_base_ident<'tcx>(
283 tcx: TyCtxt<'tcx>,
284 fields: Vec<String>,
285 base_local: usize,
286 base_ty: Ty<'tcx>,
287) -> Option<PlacePath<'tcx>> {
288 let (field_indices, current_ty) = walk_fields(tcx, base_ty, Vec::new(), &fields)?;
289 Some((base_local, field_indices, current_ty))
290}
291
292fn resolve_projection_from_struct_ident<'tcx>(
293 tcx: TyCtxt<'tcx>,
294 def_id: DefId,
295 base_ident: String,
296 fields: Vec<String>,
297 struct_ty: Ty<'tcx>,
298) -> Option<PlacePath<'tcx>> {
299 let (field_idx, field_ty) = resolve_next_field(tcx, struct_ty, &base_ident)?;
300 let (mut field_indices, current_ty) = walk_fields(tcx, field_ty, vec![field_idx], &fields)?;
301
302 let base_local = if get_type(tcx, def_id) == FnKind::Constructor {
303 0
304 } else {
305 1
306 };
307
308 if base_local == 0 && crate::util::fn_info::returns_wrapped_self(tcx, def_id) {
313 field_indices.insert(0, 0);
314 }
315
316 Some((base_local, field_indices, current_ty))
317}
318
319fn resolve_next_field<'tcx>(
320 tcx: TyCtxt<'tcx>,
321 base_ty: Ty<'tcx>,
322 field_name: &str,
323) -> Option<(usize, Ty<'tcx>)> {
324 let peeled_ty = base_ty.peel_refs();
325 if let TyKind::Adt(adt_def, arg_list) = *peeled_ty.kind() {
326 if !adt_def.is_struct() && !adt_def.is_union() {
327 return None;
328 }
329 let variant = adt_def.non_enum_variant();
330 if let Ok(field_idx) = field_name.parse::<usize>()
331 && field_idx < variant.fields.len() {
332 let field_ty = mir_utils::field_ty(
333 tcx,
334 &variant.fields[FieldIdx::from_usize(field_idx)],
335 arg_list,
336 );
337 return Some((field_idx, field_ty));
338 }
339 if let Some((idx, _)) = variant
340 .fields
341 .iter()
342 .enumerate()
343 .find(|(_, f)| f.ident(tcx).name.to_string() == field_name)
344 {
345 let field_ty = mir_utils::field_ty(
346 tcx,
347 &variant.fields[FieldIdx::from_usize(idx)],
348 arg_list,
349 );
350 return Some((idx, field_ty));
351 }
352 }
353 None
354}
355
356pub(crate) fn strip_for_each<'tcx>(arg: &mut PropertyArg<'tcx>) -> bool {
358 if let PropertyArg::Expr(ContractExpr::Place(place)) = arg
359 && place
360 .projections
361 .iter()
362 .any(|p| matches!(p, ContractProjection::ForEach))
363 {
364 place
365 .projections
366 .retain(|p| !matches!(p, ContractProjection::ForEach));
367 return true;
368 }
369 false
370}
371
372pub(crate) fn is_array_for_each<'tcx>(
375 tcx: TyCtxt<'tcx>,
376 def_id: DefId,
377 expr: &Expr,
378) -> bool {
379 let Some(place) = parse_contract_place(tcx, def_id, expr) else { return false };
380 let param_idx = match place.base {
381 PlaceBase::Arg(n) => n,
382 PlaceBase::Local(n) => match n.checked_sub(1) { Some(n) => n, None => return false },
383 _ => return false,
384 };
385 let fn_sig = tcx.fn_sig(def_id).instantiate_identity().skip_binder();
386 fn_sig.inputs().get(param_idx).is_some_and(|ty| matches!(ty.kind(), TyKind::Array(..)))
387}
388
389pub(crate) fn field_name_from_place<'tcx>(
392 tcx: TyCtxt<'tcx>,
393 adt_def_id: DefId,
394 place: &ContractPlace,
395) -> Option<String> {
396 if !matches!(
399 tcx.def_kind(adt_def_id),
400 DefKind::Struct | DefKind::Enum | DefKind::Union
401 ) {
402 return None;
403 }
404 let idx = place.projections.iter().find_map(|p| match p {
405 ContractProjection::Field { index } => Some(*index),
406 _ => None,
407 })?;
408 let adt = tcx.adt_def(adt_def_id);
409 let field = adt
410 .non_enum_variant()
411 .fields
412 .get(FieldIdx::from_usize(idx))?;
413 Some(field.name.to_string())
414}
415
416pub(crate) fn field_name_from_arg<'tcx>(
419 tcx: TyCtxt<'tcx>,
420 adt_def_id: DefId,
421 arg: &PropertyArg<'tcx>,
422) -> Option<String> {
423 match arg {
424 PropertyArg::Ident(s) => Some(s.clone()),
425 PropertyArg::Expr(ContractExpr::Place(place)) | PropertyArg::ForEach(ContractExpr::Place(place)) => {
426 field_name_from_place(tcx, adt_def_id, place)
427 }
428 _ => None,
429 }
430}