Skip to main content

rapx/contract/
resolve.rs

1//! Expression / argument resolution: `syn::Expr` → semantic values.
2//!
3//! The numeric-expression layer is parsed by the pest grammar (`pest.rs`);
4//! everything that still needs rustc's type context or `syn` structure lives
5//! here: places (via `place.rs`), const generics, builtin integer bounds, the
6//! length calls, tag argument types/targets, and `ValidNum` predicates.
7
8use crate::util::{
9    fn_info::parse_expr_into_number,
10    mir_utils,
11    name::{access_ident_recursive, match_ty_with_ident},
12};
13use quote::ToTokens;
14use rustc_hir::{def::DefKind, def_id::DefId};
15use rustc_middle::ty::{GenericParamDefKind, IntTy, Ty, TyCtxt, TyKind, UintTy};
16use syn::{Expr, Lit};
17
18use super::place;
19use super::{ContractExpr, ContractPlace, NumericPredicate, PlaceBase, PropertyArg, RelOp};
20
21pub(crate) fn parse_contract_expr<'tcx>(
22    tcx: TyCtxt<'tcx>,
23    def_id: DefId,
24    expr: &Expr,
25    sp: &str,
26) -> ContractExpr<'tcx> {
27    if let Expr::MethodCall(expr_method) = expr
28        && let Some(method) = resolve_self_method(
29            tcx,
30            def_id,
31            &expr_method.receiver,
32            &expr_method.method.to_string(),
33        )
34        && method.is_local()
35        && !tcx
36            .opt_associated_item(method)
37            .and_then(|item| item.impl_container(tcx))
38            .is_some_and(|impl_id| {
39                matches!(tcx.type_of(impl_id).skip_binder().kind(), TyKind::Slice(_))
40            })
41    {
42        return ContractExpr::MethodCall {
43            receiver: Box::new(parse_contract_expr(tcx, def_id, &expr_method.receiver, sp)),
44            method,
45            args: expr_method
46                .args
47                .iter()
48                .map(|arg| parse_contract_expr(tcx, def_id, arg, sp))
49                .collect(),
50        };
51    }
52    if let Expr::MethodCall(expr_method) = expr
53        && expr_method.method == "len"
54        && expr_method.args.is_empty()
55    {
56        return parse_len_call(tcx, def_id, &expr_method.receiver, sp);
57    }
58
59    // A place (fields, projections) or a const generic.
60    if let Some(place) = place::parse_contract_place(tcx, def_id, expr) {
61        return ContractExpr::Place(place);
62    }
63    if let Some(e) = parse_const_param(tcx, def_id, expr) {
64        return e;
65    }
66    if let Some(value) = parse_expr_into_number(expr) {
67        return ContractExpr::Const(value as u128);
68    }
69    // A `const` item (e.g. `CAPACITY` in `ValidNum(len <= CAPACITY)`).
70    if let Expr::Path(expr_path) = expr
71        && let Some(ident) = expr_path.path.get_ident()
72        && let Some(value) = mir_utils::resolve_const_item_value(tcx, &ident.to_string())
73    {
74        return ContractExpr::Const(value);
75    }
76    rap_warn!(
77        "Numeric expression in {:?} could not be resolved: {:?} (in {})",
78        sp,
79        expr,
80        tcx.def_path_str(def_id)
81    );
82    ContractExpr::Unknown
83}
84
85pub(crate) fn parse_len_call<'tcx>(
86    tcx: TyCtxt<'tcx>,
87    def_id: DefId,
88    receiver: &Expr,
89    sp: &str,
90) -> ContractExpr<'tcx> {
91    let method = resolve_self_method(tcx, def_id, receiver, "len");
92    ContractExpr::Len(
93        Box::new(parse_contract_expr(tcx, def_id, receiver, sp)),
94        method,
95    )
96}
97
98pub(crate) fn parse_is_empty_call<'tcx>(
99    tcx: TyCtxt<'tcx>,
100    def_id: DefId,
101    receiver_text: &str,
102    sp: &str,
103) -> ContractExpr<'tcx> {
104    let receiver = syn::parse_str::<Expr>(receiver_text).ok();
105    let method = receiver
106        .as_ref()
107        .and_then(|receiver| resolve_self_method(tcx, def_id, receiver, "is_empty"));
108    let inner = match receiver_text {
109        "return" => ContractExpr::Place(ContractPlace {
110            base: PlaceBase::Return,
111            projections: Vec::new(),
112        }),
113        s if s.starts_with("Arg_") => s[4..]
114            .parse::<usize>()
115            .map(|index| ContractExpr::Place(ContractPlace::arg(index)))
116            .unwrap_or(ContractExpr::Unknown),
117        _ => receiver
118            .as_ref()
119            .map(|receiver| parse_contract_expr(tcx, def_id, receiver, sp))
120            .unwrap_or(ContractExpr::Unknown),
121    };
122    ContractExpr::IsEmpty(
123        Box::new(inner),
124        method,
125    )
126}
127
128fn resolve_self_method(
129    tcx: TyCtxt<'_>,
130    def_id: DefId,
131    receiver: &Expr,
132    name: &str,
133) -> Option<DefId> {
134    if matches!(receiver, Expr::Path(path) if path.path.is_ident("self")) {
135        tcx.opt_associated_item(def_id)
136            .and_then(|assoc| assoc.impl_container(tcx))
137            .and_then(|impl_id| {
138                tcx.associated_items(impl_id)
139                    .in_definition_order()
140                    .find(|item| item.name().as_str() == name)
141                    .map(|item| item.def_id)
142            })
143    } else {
144        None
145    }
146}
147
148pub(crate) fn resolve_type_name<'tcx>(
149    tcx: TyCtxt<'tcx>,
150    def_id: DefId,
151    name: &str,
152) -> Option<Ty<'tcx>> {
153    if name == "Self" {
154        // `Self` refers to the type owning `def_id`: for an ADT (struct/enum/
155        // union) it is the type itself (`tcx.type_of`), for a function it is
156        // the receiver (the first input of the signature).
157        return match tcx.def_kind(def_id) {
158            DefKind::Struct | DefKind::Enum | DefKind::Union => {
159                Some(tcx.type_of(def_id).skip_binder())
160            }
161            _ => {
162                let sig = tcx.fn_sig(def_id).skip_binder();
163                sig.inputs().skip_binder().first().copied()
164            }
165        };
166    }
167    match_ty_with_ident(tcx, def_id, name.to_string())
168}
169
170pub(crate) fn int_type_min_max<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<(u128, u128)> {
171    let bits: u32 = match ty.kind() {
172        rustc_middle::ty::TyKind::Uint(ut) => match ut {
173            UintTy::U8 => 8,
174            UintTy::U16 => 16,
175            UintTy::U32 => 32,
176            UintTy::U64 => 64,
177            UintTy::U128 => 128,
178            UintTy::Usize => tcx.data_layout.pointer_size().bits() as u32,
179        },
180        rustc_middle::ty::TyKind::Int(it) => match it {
181            IntTy::I8 => 8,
182            IntTy::I16 => 16,
183            IntTy::I32 => 32,
184            IntTy::I64 => 64,
185            IntTy::I128 => 128,
186            IntTy::Isize => tcx.data_layout.pointer_size().bits() as u32,
187        },
188        _ => return None,
189    };
190    match ty.kind() {
191        rustc_middle::ty::TyKind::Uint(_) => {
192            let max = if bits == 128 {
193                u128::MAX
194            } else {
195                (1u128 << bits) - 1
196            };
197            Some((0, max))
198        }
199        rustc_middle::ty::TyKind::Int(_) => {
200            let max = (1u128 << (bits - 1)) - 1;
201            let min = max + 1;
202            Some((min, max))
203        }
204        _ => None,
205    }
206}
207
208fn parse_const_param<'tcx>(
209    tcx: TyCtxt<'tcx>,
210    def_id: DefId,
211    expr: &Expr,
212) -> Option<ContractExpr<'tcx>> {
213    let Expr::Path(expr_path) = expr else {
214        return None;
215    };
216    let ident = expr_path.path.get_ident()?.to_string();
217    let mut generics = Some(tcx.generics_of(def_id));
218    while let Some(current) = generics {
219        if let Some(param) = current.own_params.iter().find(|param| {
220            matches!(param.kind, GenericParamDefKind::Const { .. }) && param.name.as_str() == ident
221        }) {
222            return Some(ContractExpr::ConstParam { index: param.index, name: ident });
223        }
224        generics = current.parent.map(|parent| tcx.generics_of(parent));
225    }
226    None
227}
228
229pub(crate) fn parse_type<'tcx>(
230    tcx: TyCtxt<'tcx>,
231    def_id: DefId,
232    expr: &Expr,
233    sp: &str,
234) -> Option<Ty<'tcx>> {
235    if let Expr::Path(path) = expr
236        && path.path.segments.len() == 2
237        && path.path.segments[0].ident == "Self"
238        && path.path.segments[1].ident == "Output"
239    {
240        let output = tcx.fn_sig(def_id).skip_binder().output().skip_binder();
241        return mir_utils::pointee_ty(output);
242    }
243    if let Expr::Verbatim(ts) = expr {
244        let syn_ty = syn::parse2::<syn::Type>(ts.clone()).ok();
245        // A slice type `[T]` (e.g. `ValidTransmute([u8], str)`): resolve the
246        // element type and rebuild it as `TyKind::Slice`.
247        if let Some(syn::Type::Slice(slice)) = &syn_ty {
248            let Some(elem_name) = outermost_type_ident(&slice.elem) else {
249                rap_debug!("Incorrect expression for the type of {:?} Tag!", sp);
250                return None;
251            };
252            let Some(elem) = resolve_ty_ident(tcx, def_id, &elem_name) else {
253                rap_debug!("Cannot get type in {:?} Tag!", sp);
254                return None;
255            };
256            return Some(Ty::new_slice(tcx, elem));
257        }
258        // An array type `[T; N]` (e.g. `ValidTransmute([MaybeUninit<T>; N], [T; N])`):
259        // resolve the element type; the const length is kept symbolic (0), which
260        // `check_valid_transmute` handles by treating size 0 as "trust".
261        if let Some(syn::Type::Array(array)) = &syn_ty {
262            let Some(elem_name) = outermost_type_ident(&array.elem) else {
263                rap_debug!("Incorrect expression for the type of {:?} Tag!", sp);
264                return None;
265            };
266            let Some(elem) = resolve_ty_ident(tcx, def_id, &elem_name) else {
267                rap_debug!("Cannot get type in {:?} Tag!", sp);
268                return None;
269            };
270            return Some(Ty::new_array(tcx, elem, 0));
271        }
272        let name = syn_ty.and_then(|ty| outermost_type_ident(&ty));
273        let Some(name) = name else {
274            rap_debug!("Incorrect expression for the type of {:?} Tag!", sp);
275            return None;
276        };
277        let ty = resolve_ty_ident(tcx, def_id, &name);
278        if ty.is_none() {
279            rap_debug!("Cannot get type in {:?} Tag!", sp);
280        }
281        return ty;
282    }
283
284    if let Expr::Path(expr_path) = expr
285        && expr_path.path.segments.len() > 1
286        && let Some(last) = expr_path.path.segments.last()
287    {
288        return resolve_ty_ident(tcx, def_id, &last.ident.to_string());
289    }
290
291    let Some((ty_ident, _)) = access_ident_recursive(expr) else {
292        rap_debug!("Incorrect expression for the type of {:?} Tag!", sp);
293        return None;
294    };
295    let ty = resolve_ty_ident(tcx, def_id, &ty_ident);
296    if ty.is_none() {
297        rap_debug!("Cannot get type in {:?} Tag!", sp);
298    }
299    ty
300}
301
302/// Resolve a type identifier to a `Ty`, handling the `Self` keyword (which
303/// [`match_ty_with_ident`] does not understand) by delegating to
304/// [`resolve_type_name`].
305fn resolve_ty_ident<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, name: &str) -> Option<Ty<'tcx>> {
306    if name == "Self" {
307        resolve_type_name(tcx, def_id, name)
308    } else {
309        match_ty_with_ident(tcx, def_id, name.to_string())
310    }
311}
312
313/// Extract the outermost path segment name from a `syn::Type`, e.g. `Option`
314/// from `Option<NonZero<T>>` or `NonZero` from `NonZero<T>`.
315fn outermost_type_ident(ty: &syn::Type) -> Option<String> {
316    match ty {
317        syn::Type::Path(tp) if tp.qself.is_none() => {
318            tp.path.segments.last().map(|s| s.ident.to_string())
319        }
320        _ => None,
321    }
322}
323
324pub(crate) fn parse_target_arg<'tcx>(
325    tcx: TyCtxt<'tcx>,
326    def_id: DefId,
327    expr: &Expr,
328) -> PropertyArg<'tcx> {
329    // `return` parses as `syn::Expr::Return { expr: None }` (a bare `return`),
330    // which the place parser below does not recognise — handle it directly.
331    if matches!(expr, Expr::Return(_)) {
332        return PropertyArg::Expr(ContractExpr::Place(ContractPlace {
333            base: PlaceBase::Return,
334            projections: Vec::new(),
335        }));
336    }
337    // For simple identifiers that aren't local variables (e.g., lifetime param
338    // 'a parsed as ident `a`), store as Ident rather than Expr (which would
339    // become Unknown).
340    if let Expr::Path(expr_path) = expr
341        && let Some(ident) = expr_path.path.get_ident()
342    {
343        let s = ident.to_string();
344        if s != "return"
345            && !s.starts_with("Arg_")
346            && place::parse_expr_into_local_and_ty(tcx, def_id, expr).is_none()
347        {
348            return PropertyArg::Ident(s);
349        }
350    }
351    place::parse_contract_place(tcx, def_id, expr)
352        .map(|p| PropertyArg::Expr(ContractExpr::Place(p)))
353        .unwrap_or_else(|| PropertyArg::Expr(parse_contract_expr(tcx, def_id, expr, "target")))
354}
355
356pub(crate) fn parse_valid_num<'tcx>(
357    tcx: TyCtxt<'tcx>,
358    def_id: DefId,
359    exprs: &[Expr],
360) -> Vec<NumericPredicate<'tcx>> {
361    match exprs {
362        [] => Vec::new(),
363        [expr] => parse_numeric_predicate(tcx, def_id, expr)
364            .into_iter()
365            .collect(),
366        [value, range, ..] => {
367            if let Some(predicates) = parse_interval_predicates(tcx, def_id, value, range) {
368                predicates
369            } else {
370                parse_numeric_predicate(tcx, def_id, value)
371                    .into_iter()
372                    .collect()
373            }
374        }
375    }
376}
377
378fn parse_numeric_predicate<'tcx>(
379    tcx: TyCtxt<'tcx>,
380    def_id: DefId,
381    expr: &Expr,
382) -> Option<NumericPredicate<'tcx>> {
383    let text = expr.to_token_stream().to_string();
384    let has_method_operand = matches!(expr, Expr::Binary(binary)
385        if matches!(&*binary.left, Expr::MethodCall(_))
386            || matches!(&*binary.right, Expr::MethodCall(_)));
387    if !has_method_operand {
388        if let Some(predicate) = super::pest::parse_predicate_pest(tcx, def_id, &text) {
389            return Some(predicate);
390        }
391    }
392    let Expr::Binary(binary) = expr else {
393        return None;
394    };
395    let op = match binary.op {
396        syn::BinOp::Le(_) => RelOp::Le,
397        syn::BinOp::Lt(_) => RelOp::Lt,
398        syn::BinOp::Ge(_) => RelOp::Ge,
399        syn::BinOp::Gt(_) => RelOp::Gt,
400        syn::BinOp::Eq(_) => RelOp::Eq,
401        syn::BinOp::Ne(_) => RelOp::Ne,
402        _ => return None,
403    };
404    let parse_operand = |operand: &Expr| {
405        if matches!(operand, Expr::MethodCall(_)) {
406            parse_contract_expr(tcx, def_id, operand, "predicate")
407        } else {
408            super::pest::parse_expr_pest(tcx, def_id, &operand.to_token_stream().to_string())
409        }
410    };
411    let lhs = parse_operand(&binary.left);
412    let rhs = parse_operand(&binary.right);
413    (!matches!(lhs, ContractExpr::Unknown) && !matches!(rhs, ContractExpr::Unknown))
414        .then(|| NumericPredicate::new(lhs, op, rhs))
415}
416
417pub(crate) fn expr_to_pest<'tcx>(
418    tcx: TyCtxt<'tcx>,
419    def_id: DefId,
420    expr: &Expr,
421) -> ContractExpr<'tcx> {
422    let text = expr.to_token_stream().to_string();
423    super::pest::parse_expr_pest(tcx, def_id, &text)
424}
425
426fn parse_interval_predicates<'tcx>(
427    tcx: TyCtxt<'tcx>,
428    def_id: DefId,
429    value: &Expr,
430    range: &Expr,
431) -> Option<Vec<NumericPredicate<'tcx>>> {
432    match range {
433        Expr::Array(array) if array.elems.len() == 2 => {
434            let mut elems = array.elems.iter();
435            let lower = elems.next().unwrap();
436            let upper = elems.next().unwrap();
437            Some(build_interval_predicates(
438                tcx, def_id, value, lower, true, upper, true,
439            ))
440        }
441        Expr::Lit(expr_lit) => match &expr_lit.lit {
442            Lit::Str(range_lit) => parse_string_interval(tcx, def_id, value, &range_lit.value()),
443            Lit::Int(int_lit) => {
444                // A bare integer `ValidNum(v, n)` is shorthand for the singleton
445                // interval `[n, n]`, i.e. `v == n`.
446                let n = int_lit.base10_parse::<u64>().ok()?;
447                let n_expr = syn::parse_str::<Expr>(&n.to_string()).ok()?;
448                Some(build_interval_predicates(
449                    tcx, def_id, value, &n_expr, true, &n_expr, true,
450                ))
451            }
452            _ => None,
453        },
454        _ => None,
455    }
456}
457
458fn parse_string_interval<'tcx>(
459    tcx: TyCtxt<'tcx>,
460    def_id: DefId,
461    value: &Expr,
462    raw_range: &str,
463) -> Option<Vec<NumericPredicate<'tcx>>> {
464    let trimmed = raw_range.trim();
465    if trimmed.len() < 3 {
466        return None;
467    }
468
469    let lower_inclusive = trimmed.starts_with('[');
470    let upper_inclusive = trimmed.ends_with(']');
471    if !(lower_inclusive || trimmed.starts_with('('))
472        || !(upper_inclusive || trimmed.ends_with(')'))
473    {
474        return None;
475    }
476
477    let body = &trimmed[1..trimmed.len() - 1];
478    let (lower_raw, upper_raw) = body.split_once(',')?;
479    let lower_raw = lower_raw.trim();
480    let upper_raw = upper_raw.trim();
481
482    // An unbounded side is written as an empty bound, e.g. `[1,)` (no upper
483    // bound) or `(,5]` (no lower bound). Reject an entirely empty interval.
484    if lower_raw.is_empty() && upper_raw.is_empty() {
485        return None;
486    }
487
488    let value_expr = expr_to_pest(tcx, def_id, value);
489    let mut predicates = Vec::with_capacity(2);
490
491    if !lower_raw.is_empty() {
492        let lower = syn::parse_str::<Expr>(lower_raw).ok()?;
493        predicates.push(NumericPredicate::new(
494            expr_to_pest(tcx, def_id, &lower),
495            if lower_inclusive {
496                RelOp::Le
497            } else {
498                RelOp::Lt
499            },
500            value_expr.clone(),
501        ));
502    }
503
504    if !upper_raw.is_empty() {
505        let upper = syn::parse_str::<Expr>(upper_raw).ok()?;
506        predicates.push(NumericPredicate::new(
507            value_expr,
508            if upper_inclusive {
509                RelOp::Le
510            } else {
511                RelOp::Lt
512            },
513            expr_to_pest(tcx, def_id, &upper),
514        ));
515    }
516
517    Some(predicates)
518}
519
520fn build_interval_predicates<'tcx>(
521    tcx: TyCtxt<'tcx>,
522    def_id: DefId,
523    value: &Expr,
524    lower: &Expr,
525    lower_inclusive: bool,
526    upper: &Expr,
527    upper_inclusive: bool,
528) -> Vec<NumericPredicate<'tcx>> {
529    let value_expr = expr_to_pest(tcx, def_id, value);
530    let lower_expr = expr_to_pest(tcx, def_id, lower);
531    let upper_expr = expr_to_pest(tcx, def_id, upper);
532    vec![
533        NumericPredicate::new(
534            lower_expr,
535            if lower_inclusive {
536                RelOp::Le
537            } else {
538                RelOp::Lt
539            },
540            value_expr.clone(),
541        ),
542        NumericPredicate::new(
543            value_expr,
544            if upper_inclusive {
545                RelOp::Le
546            } else {
547                RelOp::Lt
548            },
549            upper_expr,
550        ),
551    ]
552}
553
554/// Extract the inner type from `[T]` (the `SplitTransmute([T], [U])` notation),
555/// then resolve it via `parse_type`.  The `[T]` argument arrives as either
556/// `Expr::Array` (JSON path, parsed via `syn::parse_str::<Expr>`) or
557/// `Expr::Verbatim` (source annotation path, where `parse_property_arg`'s
558/// type-first parse turns `Type::Slice` into `Verbatim`); both are unwrapped to
559/// the element type `T`.
560pub(crate) fn unwrap_array_expr<'tcx>(
561    tcx: TyCtxt<'tcx>,
562    def_id: DefId,
563    expr: &Expr,
564) -> Option<Ty<'tcx>> {
565    if let Expr::Array(arr) = expr
566        && arr.elems.len() == 1
567    {
568        return parse_type(tcx, def_id, &arr.elems[0], "SplitTransmute");
569    }
570    if let Expr::Verbatim(ts) = expr
571        && let Ok(syn::Type::Slice(slice)) = syn::parse2::<syn::Type>(ts.clone())
572        && let Some(name) = outermost_type_ident(slice.elem.as_ref())
573    {
574        return resolve_ty_ident(tcx, def_id, &name);
575    }
576    parse_type(tcx, def_id, expr, "SplitTransmute")
577}