rapx 0.7.39

A static analysis platform for Rust program analysis and verification
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Expression / argument resolution: `syn::Expr` → semantic values.
//!
//! The numeric-expression layer is parsed by the pest grammar (`pest_conv.rs`);
//! everything that still needs rustc's type context or `syn` structure lives
//! here: places (via `place.rs`), const generics, builtin integer bounds, the
//! `x.len()` sugar, tag argument types/targets, and `ValidNum` predicates.

use quote::ToTokens;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::DefId;
use rustc_middle::ty::{GenericParamDefKind, Ty, TyCtxt};
use syn::{Expr, Lit};

use crate::helpers::fn_info::parse_expr_into_number;
use crate::helpers::name::{access_ident_recursive, match_ty_with_ident};

use super::place;
use super::types::{ContractExpr, ContractPlace, NumericPredicate, PlaceBase, PropertyArg, RelOp};

pub(crate) fn parse_contract_expr<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    expr: &Expr,
    sp: &str,
) -> ContractExpr<'tcx> {
    // `x.len` / `x.len()` sugar -> len(x).
    if let Expr::Field(expr_field) = expr
        && matches!(&expr_field.member, syn::Member::Named(ident) if ident == "len")
    {
        return ContractExpr::Len(Box::new(parse_contract_expr(
            tcx,
            def_id,
            &expr_field.base,
            sp,
        )));
    }
    if let Expr::MethodCall(expr_method) = expr
        && expr_method.method == "len"
        && expr_method.args.is_empty()
    {
        return ContractExpr::Len(Box::new(parse_contract_expr(
            tcx,
            def_id,
            &expr_method.receiver,
            sp,
        )));
    }

    // A place (fields, projections), a const generic, or a builtin constant.
    if let Some(place) = place::parse_contract_place(tcx, def_id, expr) {
        return ContractExpr::Place(place);
    }
    if let Some(e) = parse_const_param(tcx, def_id, expr) {
        return e;
    }
    if let Some(value) = parse_builtin_const(tcx, expr) {
        return ContractExpr::Const(value);
    }
    if let Some(value) = parse_expr_into_number(expr) {
        return ContractExpr::new_value(value);
    }
    // A `const` item (e.g. `CAPACITY` in `ValidNum(len <= CAPACITY)`).
    if let Expr::Path(expr_path) = expr
        && let Some(ident) = expr_path.path.get_ident()
        && let Some(value) = crate::helpers::mir_utils::resolve_const_item_value(
            tcx,
            &ident.to_string(),
        )
    {
        return ContractExpr::Const(value);
    }
    rap_debug!(
        "Numeric expression in {:?} could not be resolved: {:?}",
        sp,
        expr
    );
    ContractExpr::Unknown
}

pub(crate) fn resolve_type_name<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    name: &str,
) -> Option<Ty<'tcx>> {
    if name == "Self" {
        // `Self` refers to the type owning `def_id`: for an ADT (struct/enum/
        // union) it is the type itself (`tcx.type_of`), for a function it is
        // the receiver (the first input of the signature).
        return match tcx.def_kind(def_id) {
            DefKind::Struct | DefKind::Enum | DefKind::Union => {
                Some(tcx.type_of(def_id).skip_binder())
            }
            _ => {
                let sig = tcx.fn_sig(def_id).skip_binder();
                sig.inputs().skip_binder().first().copied()
            }
        };
    }
    match_ty_with_ident(tcx, def_id, name.to_string())
}

pub(crate) fn int_type_min_max<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<(u128, u128)> {
    use rustc_middle::ty::IntTy;
    use rustc_middle::ty::UintTy;
    let bits: u32 = match ty.kind() {
        rustc_middle::ty::TyKind::Uint(ut) => match ut {
            UintTy::U8 => 8,
            UintTy::U16 => 16,
            UintTy::U32 => 32,
            UintTy::U64 => 64,
            UintTy::U128 => 128,
            UintTy::Usize => tcx.data_layout.pointer_size().bits() as u32,
        },
        rustc_middle::ty::TyKind::Int(it) => match it {
            IntTy::I8 => 8,
            IntTy::I16 => 16,
            IntTy::I32 => 32,
            IntTy::I64 => 64,
            IntTy::I128 => 128,
            IntTy::Isize => tcx.data_layout.pointer_size().bits() as u32,
        },
        _ => return None,
    };
    if bits == 0 {
        return None;
    }
    match ty.kind() {
        rustc_middle::ty::TyKind::Uint(_) => {
            let max = if bits == 128 {
                u128::MAX
            } else {
                (1u128 << bits) - 1
            };
            Some((0, max))
        }
        rustc_middle::ty::TyKind::Int(_) => {
            let max = (1u128 << (bits - 1)) - 1;
            let min = max + 1;
            Some((min, max))
        }
        _ => None,
    }
}

fn parse_builtin_const<'tcx>(tcx: TyCtxt<'tcx>, expr: &Expr) -> Option<u128> {
    let Expr::Path(expr_path) = expr else {
        return None;
    };
    let mut segments = expr_path.path.segments.iter();
    let first = segments.next()?.ident.to_string();
    let second = segments.next()?.ident.to_string();
    if segments.next().is_some() || second != "MAX" {
        return None;
    }

    let pointer_bits = tcx.data_layout.pointer_size().bits();
    match first.as_str() {
        "isize" => Some((1_u128 << (pointer_bits - 1)) - 1),
        "usize" => Some((1_u128 << pointer_bits) - 1),
        _ => None,
    }
}

fn parse_const_param<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    expr: &Expr,
) -> Option<ContractExpr<'tcx>> {
    let Expr::Path(expr_path) = expr else {
        return None;
    };
    let ident = expr_path.path.get_ident()?.to_string();
    let mut generics = Some(tcx.generics_of(def_id));
    while let Some(current) = generics {
        if let Some(param) = current.own_params.iter().find(|param| {
            matches!(param.kind, GenericParamDefKind::Const { .. }) && param.name.as_str() == ident
        }) {
            return Some(ContractExpr::ConstParam {
                index: param.index,
                name: ident,
            });
        }
        generics = current.parent.map(|parent| tcx.generics_of(parent));
    }
    None
}

pub(crate) fn parse_type<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    expr: &Expr,
    sp: &str,
) -> Option<Ty<'tcx>> {
    // A generic type argument (`Option<NonZero<T>>`, `NonZero<T>`) is wrapped as
    // `Expr::Verbatim` by the attribute parser. Extract the outermost type name
    // and resolve it like a plain identifier.
    if let Expr::Verbatim(ts) = expr {
        let name = syn::parse2::<syn::Type>(ts.clone())
            .ok()
            .and_then(|ty| outermost_type_ident(&ty));
        let Some(name) = name else {
            rap_debug!("Incorrect expression for the type of {:?} Tag!", sp);
            return None;
        };
        let ty = resolve_ty_ident(tcx, def_id, &name);
        if ty.is_none() {
            rap_debug!("Cannot get type in {:?} Tag!", sp);
        }
        return ty;
    }

    let ty_ident_full = access_ident_recursive(expr);
    if ty_ident_full.is_none() {
        rap_debug!("Incorrect expression for the type of {:?} Tag!", sp);
        return None;
    }
    let ty_ident = ty_ident_full.unwrap().0;
    let ty = resolve_ty_ident(tcx, def_id, &ty_ident);
    if ty.is_none() {
        rap_debug!("Cannot get type in {:?} Tag!", sp);
    }
    ty
}

/// Resolve a type identifier to a `Ty`, handling the `Self` keyword (which
/// [`match_ty_with_ident`] does not understand) by delegating to
/// [`resolve_type_name`].
fn resolve_ty_ident<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, name: &str) -> Option<Ty<'tcx>> {
    if name == "Self" {
        resolve_type_name(tcx, def_id, name)
    } else {
        match_ty_with_ident(tcx, def_id, name.to_string())
    }
}

/// Extract the outermost path segment name from a `syn::Type`, e.g. `Option`
/// from `Option<NonZero<T>>` or `NonZero` from `NonZero<T>`.
fn outermost_type_ident(ty: &syn::Type) -> Option<String> {
    match ty {
        syn::Type::Path(tp) if tp.qself.is_none() => {
            tp.path.segments.last().map(|s| s.ident.to_string())
        }
        _ => None,
    }
}

pub(crate) fn parse_target_arg<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    expr: &Expr,
) -> PropertyArg<'tcx> {
    // `return` parses as `syn::Expr::Return { expr: None }` (a bare `return`),
    // which the place parser below does not recognise — handle it directly.
    if matches!(expr, Expr::Return(_)) {
        return PropertyArg::Expr(ContractExpr::Place(ContractPlace {
            base: PlaceBase::Return,
            projections: Vec::new(),
        }));
    }
    // For simple identifiers that aren't local variables (e.g., lifetime param
    // 'a parsed as ident `a`), store as Ident rather than Expr (which would
    // become Unknown).
    if let Expr::Path(expr_path) = expr {
        if let Some(ident) = expr_path.path.get_ident() {
            let s = ident.to_string();
            if s != "return"
                && !s.starts_with("Arg_")
                && place::parse_expr_into_local_and_ty(tcx, def_id, expr).is_none()
            {
                return PropertyArg::Ident(s);
            }
        }
    }
    place::parse_contract_place(tcx, def_id, expr)
        .map(|p| PropertyArg::Expr(ContractExpr::Place(p)))
        .unwrap_or_else(|| PropertyArg::Expr(parse_contract_expr(tcx, def_id, expr, "target")))
}

pub(crate) fn parse_valid_num<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    exprs: &[Expr],
) -> Vec<NumericPredicate<'tcx>> {
    match exprs {
        [] => Vec::new(),
        [expr] => parse_numeric_predicate(tcx, def_id, expr)
            .into_iter()
            .collect(),
        [value, range, ..] => {
            if let Some(predicates) = parse_interval_predicates(tcx, def_id, value, range) {
                predicates
            } else {
                parse_numeric_predicate(tcx, def_id, value)
                    .into_iter()
                    .collect()
            }
        }
    }
}

fn parse_numeric_predicate<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    expr: &Expr,
) -> Option<NumericPredicate<'tcx>> {
    let text = expr.to_token_stream().to_string();
    super::pest_conv::parse_predicate_pest(tcx, def_id, &text)
}

pub(crate) fn expr_to_pest<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    expr: &Expr,
) -> ContractExpr<'tcx> {
    let text = expr.to_token_stream().to_string();
    super::pest_conv::parse_expr_pest(tcx, def_id, &text)
}

fn parse_interval_predicates<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    value: &Expr,
    range: &Expr,
) -> Option<Vec<NumericPredicate<'tcx>>> {
    match range {
        Expr::Array(array) if array.elems.len() == 2 => {
            let mut elems = array.elems.iter();
            let lower = elems.next().unwrap();
            let upper = elems.next().unwrap();
            Some(build_interval_predicates(
                tcx, def_id, value, lower, true, upper, true,
            ))
        }
        Expr::Lit(expr_lit) => match &expr_lit.lit {
            Lit::Str(range_lit) => {
                parse_string_interval(tcx, def_id, value, &range_lit.value())
            }
            Lit::Int(int_lit) => {
                // A bare integer `ValidNum(v, n)` is shorthand for the singleton
                // interval `[n, n]`, i.e. `v == n`.
                let n = int_lit.base10_parse::<u64>().ok()?;
                let n_expr = syn::parse_str::<Expr>(&n.to_string()).ok()?;
                Some(build_interval_predicates(
                    tcx, def_id, value, &n_expr, true, &n_expr, true,
                ))
            }
            _ => None,
        },
        _ => None,
    }
}

fn parse_string_interval<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    value: &Expr,
    raw_range: &str,
) -> Option<Vec<NumericPredicate<'tcx>>> {
    let trimmed = raw_range.trim();
    if trimmed.len() < 3 {
        return None;
    }

    let lower_inclusive = trimmed.starts_with('[');
    let upper_inclusive = trimmed.ends_with(']');
    if !(lower_inclusive || trimmed.starts_with('('))
        || !(upper_inclusive || trimmed.ends_with(')'))
    {
        return None;
    }

    let body = &trimmed[1..trimmed.len() - 1];
    let (lower_raw, upper_raw) = body.split_once(',')?;
    let lower_raw = lower_raw.trim();
    let upper_raw = upper_raw.trim();

    // An unbounded side is written as an empty bound, e.g. `[1,)` (no upper
    // bound) or `(,5]` (no lower bound). Reject an entirely empty interval.
    if lower_raw.is_empty() && upper_raw.is_empty() {
        return None;
    }

    let value_expr = expr_to_pest(tcx, def_id, value);
    let mut predicates = Vec::with_capacity(2);

    if !lower_raw.is_empty() {
        let lower = syn::parse_str::<Expr>(lower_raw).ok()?;
        predicates.push(NumericPredicate::new(
            expr_to_pest(tcx, def_id, &lower),
            if lower_inclusive { RelOp::Le } else { RelOp::Lt },
            value_expr.clone(),
        ));
    }

    if !upper_raw.is_empty() {
        let upper = syn::parse_str::<Expr>(upper_raw).ok()?;
        predicates.push(NumericPredicate::new(
            value_expr,
            if upper_inclusive { RelOp::Le } else { RelOp::Lt },
            expr_to_pest(tcx, def_id, &upper),
        ));
    }

    Some(predicates)
}

fn build_interval_predicates<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    value: &Expr,
    lower: &Expr,
    lower_inclusive: bool,
    upper: &Expr,
    upper_inclusive: bool,
) -> Vec<NumericPredicate<'tcx>> {
    let value_expr = expr_to_pest(tcx, def_id, value);
    let lower_expr = expr_to_pest(tcx, def_id, lower);
    let upper_expr = expr_to_pest(tcx, def_id, upper);
    vec![
        NumericPredicate::new(
            lower_expr,
            if lower_inclusive {
                RelOp::Le
            } else {
                RelOp::Lt
            },
            value_expr.clone(),
        ),
        NumericPredicate::new(
            value_expr,
            if upper_inclusive {
                RelOp::Le
            } else {
                RelOp::Lt
            },
            upper_expr,
        ),
    ]
}

/// Extract the inner type from an `Expr::Array` (the `[T]` notation in
/// `SplitTransmute([T], [U])`), then resolve it via `parse_type`.
pub(crate) fn unwrap_array_expr<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    expr: &Expr,
) -> Option<Ty<'tcx>> {
    if let Expr::Array(arr) = expr
        && arr.elems.len() == 1
    {
        return parse_type(tcx, def_id, &arr.elems[0], "SplitTransmute");
    }
    parse_type(tcx, def_id, expr, "SplitTransmute")
}