Skip to main content

rapx/contract/
builder.rs

1//! Assemble a safety tag into a [`Property`] via the declarative spec table.
2//!
3//! `Property::new` looks up `spec::SPECS`, dispatches on the tag's
4//! `PropertyKind`, and resolves arguments positionally. `Property::parse_list`
5//! is the shared entry point for all front-ends, including the `any(...)`
6//! combinator.
7
8use rustc_hir::def_id::DefId;
9use rustc_middle::ty::TyCtxt;
10use syn::Expr;
11
12use crate::util::name::access_ident_recursive;
13
14use super::spec;
15use super::*;
16
17impl<'tcx> Property<'tcx> {
18    /// Parse a property from the declaration table, dispatching on the tag's
19    /// `PropertyKind`.
20    fn parse_from_spec(
21        tcx: TyCtxt<'tcx>,
22        def_id: DefId,
23        spec: &spec::PropertySpec,
24        exprs: &[Expr],
25    ) -> Self {
26        let mut prop = match spec.kind {
27            PropertyKind::Size => Self::build_size(tcx, def_id, exprs),
28            PropertyKind::Allocated => Self::build_allocated(tcx, def_id, exprs),
29            PropertyKind::InBound => Self::build_inbound(tcx, def_id, exprs),
30            PropertyKind::Init
31            | PropertyKind::Typed
32            | PropertyKind::NonVolatile
33            | PropertyKind::Owning
34            | PropertyKind::RefCountShare => Self::build_target_ty_count(spec, tcx, def_id, exprs),
35            PropertyKind::NonOverlap => Self::build_nonoverlap(tcx, def_id, exprs),
36            PropertyKind::ValidNum => Self::build_validnum(tcx, def_id, exprs),
37            PropertyKind::Pinned => Self::build_pinned(tcx, def_id, exprs),
38            PropertyKind::SplitTransmute => Self::build_split_transmute(tcx, def_id, exprs),
39            PropertyKind::Alias | PropertyKind::Alive => {
40                Self::build_targets(spec, tcx, def_id, exprs)
41            }
42            PropertyKind::ContainNoType => Self::build_contain_no_type(tcx, def_id, exprs),
43            PropertyKind::Unknown => Self::new_simple(PropertyKind::Unknown),
44            _ => Self::build_uniform(tcx, def_id, spec, exprs),
45        };
46        // Apply the spec-declared `ContractKind` centrally, so `Hazard` /
47        // `Option_` tags keep their kind regardless of how they're built.
48        prop.set_contract_kind(spec.contract_kind);
49        prop
50    }
51
52    /// Resolve a single positional argument according to its declared role.
53    ///
54    /// Returns `None` when a `Ty` argument cannot be resolved, so the caller
55    /// degrades the whole property to `Unknown` instead of silently
56    /// substituting the `never` type (which would make `Align`/`Typed` trivially
57    /// provable).
58    fn resolve_arg(
59        tcx: TyCtxt<'tcx>,
60        def_id: DefId,
61        tag: &str,
62        arg_kind: spec::ArgKind,
63        expr: &Expr,
64    ) -> Option<PropertyArg<'tcx>> {
65        match arg_kind {
66            spec::ArgKind::Target => Some(super::resolve::parse_target_arg(tcx, def_id, expr)),
67            spec::ArgKind::Ty => {
68                super::resolve::parse_type(tcx, def_id, expr, tag).map(PropertyArg::Ty)
69            }
70            spec::ArgKind::Expr => Some(PropertyArg::Expr(super::resolve::expr_to_pest(
71                tcx, def_id, expr,
72            ))),
73            spec::ArgKind::Ident => {
74                let s = access_ident_recursive(expr).map(|(name, _)| name)?;
75                Some(PropertyArg::Ident(s))
76            }
77        }
78    }
79
80    /// Positional resolution over one of the spec's accepted forms.
81    fn build_uniform(
82        tcx: TyCtxt<'tcx>,
83        def_id: DefId,
84        spec: &spec::PropertySpec,
85        exprs: &[Expr],
86    ) -> Self {
87        let Some(form) = spec.forms.iter().find(|f| f.len() == exprs.len()) else {
88            let expected: Vec<usize> = spec.forms.iter().map(|f| f.len()).collect();
89            rap_error!(
90                "Wrong args length for {} Tag! expected one of {expected:?}, got {}",
91                spec.tag,
92                exprs.len()
93            );
94            return Self::new_simple(PropertyKind::Unknown);
95        };
96        let mut args: Vec<PropertyArg<'tcx>> = Vec::with_capacity(exprs.len());
97        for (expr, &arg_kind) in exprs.iter().zip(form.iter()) {
98            let Some(arg) = Self::resolve_arg(tcx, def_id, spec.tag, arg_kind, expr) else {
99                return Self::new_simple(PropertyKind::Unknown);
100            };
101            args.push(arg);
102        }
103        Self::new_atom(spec.kind, args)
104    }
105
106    pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: DefId, name: &str, exprs: &[Expr]) -> Self {
107        match spec::find_spec(name) {
108            Some(spec) => Self::parse_from_spec(tcx, def_id, spec, exprs),
109            None => Self::new_simple(PropertyKind::Unknown),
110        }
111    }
112
113    fn build_size(tcx: TyCtxt<'tcx>, def_id: DefId, exprs: &[Expr]) -> Self {
114        match exprs {
115            [ty_expr, const_expr] => {
116                let Some(ty) = super::resolve::parse_type(tcx, def_id, ty_expr, "Size") else {
117                    return Self::new_simple(PropertyKind::Unknown);
118                };
119                if let Some((ident, _)) = access_ident_recursive(const_expr)
120                    && (ident == "sized" || ident == "unsized") {
121                        return Self::new_atom(
122                            PropertyKind::Size,
123                            vec![PropertyArg::Ty(ty), PropertyArg::Ident(ident)],
124                        );
125                    }
126                let c = super::resolve::expr_to_pest(tcx, def_id, const_expr);
127                Self::new_atom(
128                    PropertyKind::Size,
129                    vec![PropertyArg::Ty(ty), PropertyArg::Expr(c)],
130                )
131            }
132            _ => {
133                rap_error!(
134                    "Wrong args length for Size Tag! expected 2, got {}",
135                    exprs.len()
136                );
137                Self::new_simple(PropertyKind::Unknown)
138            }
139        }
140    }
141
142    fn build_allocated(tcx: TyCtxt<'tcx>, def_id: DefId, exprs: &[Expr]) -> Self {
143        match exprs {
144            [target] => Self::new_atom(
145                PropertyKind::Allocated,
146                vec![super::resolve::parse_target_arg(tcx, def_id, target)],
147            ),
148            [target_expr, ty_expr] => {
149                let target = super::resolve::parse_target_arg(tcx, def_id, target_expr);
150                let Some(ty) = super::resolve::parse_type(tcx, def_id, ty_expr, "Allocated") else {
151                    return Self::new_simple(PropertyKind::Unknown);
152                };
153                Self::new_atom(
154                    PropertyKind::Allocated,
155                    vec![target, PropertyArg::Ty(ty)],
156                )
157            }
158            [target_expr, ty_expr, len_expr] => {
159                let target = super::resolve::parse_target_arg(tcx, def_id, target_expr);
160                let Some(ty) = super::resolve::parse_type(tcx, def_id, ty_expr, "Allocated") else {
161                    return Self::new_simple(PropertyKind::Unknown);
162                };
163                if let Expr::Assign(assign) = len_expr
164                    && let Some((name, fields)) = access_ident_recursive(&assign.left)
165                    && name == "allocator"
166                    && fields.is_empty()
167                {
168                    let Some((allocator, fields)) = access_ident_recursive(&assign.right) else {
169                        return Self::new_simple(PropertyKind::Unknown);
170                    };
171                    if !fields.is_empty() {
172                        return Self::new_simple(PropertyKind::Unknown);
173                    }
174                    return Self::new_atom(
175                        PropertyKind::Allocated,
176                        vec![
177                            target,
178                            PropertyArg::Ty(ty),
179                            PropertyArg::Expr(ContractExpr::Const(1)),
180                            PropertyArg::Ident(allocator),
181                        ],
182                    );
183                }
184                let length = super::resolve::expr_to_pest(tcx, def_id, len_expr);
185                Self::new_atom(
186                    PropertyKind::Allocated,
187                    vec![target, PropertyArg::Ty(ty), PropertyArg::Expr(length)],
188                )
189            }
190            [target_expr, ty_expr, len_expr, allocator_expr] => {
191                let target = super::resolve::parse_target_arg(tcx, def_id, target_expr);
192                let Some(ty) = super::resolve::parse_type(tcx, def_id, ty_expr, "Allocated") else {
193                    return Self::new_simple(PropertyKind::Unknown);
194                };
195                let length = super::resolve::expr_to_pest(tcx, def_id, len_expr);
196                let allocator = access_ident_recursive(allocator_expr)
197                    .map(|(name, _)| name)
198                    .unwrap_or_else(|| "Global".to_string());
199                Self::new_atom(
200                    PropertyKind::Allocated,
201                    vec![
202                        target,
203                        PropertyArg::Ty(ty),
204                        PropertyArg::Expr(length),
205                        PropertyArg::Ident(allocator),
206                    ],
207                )
208            }
209            _ => {
210                rap_error!(
211                    "Wrong args length for Allocated Tag! expected 1, 2, 3 or 4, got {}",
212                    exprs.len()
213                );
214                Self::new_simple(PropertyKind::Unknown)
215            }
216        }
217    }
218
219    fn build_inbound(tcx: TyCtxt<'tcx>, def_id: DefId, exprs: &[Expr]) -> Self {
220        match exprs {
221            [target_expr, ty_expr, len_expr] => {
222                let target = super::resolve::parse_target_arg(tcx, def_id, target_expr);
223                let Some(ty) = super::resolve::parse_type(tcx, def_id, ty_expr, "InBound") else {
224                    return Self::new_simple(PropertyKind::Unknown);
225                };
226                let length = super::resolve::expr_to_pest(tcx, def_id, len_expr);
227                Self::new_atom(
228                    PropertyKind::InBound,
229                    vec![target, PropertyArg::Ty(ty), PropertyArg::Expr(length)],
230                )
231            }
232            [target_expr, second_expr] => {
233                if let Some(ty) = super::resolve::parse_type(tcx, def_id, second_expr, "InBound") {
234                    let target = super::resolve::parse_target_arg(tcx, def_id, target_expr);
235                    return Self::new_atom(
236                        PropertyKind::InBound,
237                        vec![target, PropertyArg::Ty(ty)],
238                    );
239                }
240                if let Some((_, _, ty)) =
241                    super::place::parse_expr_into_local_and_ty(tcx, def_id, target_expr)
242                    && !matches!(
243                        ty.peel_refs().kind(),
244                        rustc_middle::ty::TyKind::Slice(..)
245                            | rustc_middle::ty::TyKind::Array(..)
246                    )
247                {
248                    rap_error!(
249                        "InBound(slice, index): first argument must be a slice or array, got `{ty}`"
250                    );
251                    return Self::new_simple(PropertyKind::Unknown);
252                }
253                let slice = super::resolve::expr_to_pest(tcx, def_id, target_expr);
254                let index = super::resolve::expr_to_pest(tcx, def_id, second_expr);
255                if matches!(slice, ContractExpr::Unknown) || matches!(index, ContractExpr::Unknown)
256                {
257                    return Self::new_simple(PropertyKind::Unknown);
258                }
259                let for_each = super::place::is_array_for_each(tcx, def_id, second_expr);
260                let expr = ContractExpr::IndexAccess { slice: Box::new(slice), index: Box::new(index) };
261                let arg = if for_each { PropertyArg::ForEach(expr) } else { PropertyArg::Expr(expr) };
262                Self::new_atom(PropertyKind::InBound, vec![arg])
263            }
264            [target_expr] => {
265                let target = super::resolve::parse_target_arg(tcx, def_id, target_expr);
266                Self::new_atom(PropertyKind::InBound, vec![target])
267            }
268            _ => {
269                rap_error!(
270                    "Wrong args length for InBound Tag! expected 1, 2 or 3, got {}",
271                    exprs.len()
272                );
273                Self::new_simple(PropertyKind::Unknown)
274            }
275        }
276    }
277
278    fn build_target_ty_count(
279        spec: &spec::PropertySpec,
280        tcx: TyCtxt<'tcx>,
281        def_id: DefId,
282        exprs: &[Expr],
283    ) -> Self {
284        match exprs {
285            [target_expr, ty_expr, count_expr] => {
286                let target = super::resolve::parse_target_arg(tcx, def_id, target_expr);
287                let Some(ty) = super::resolve::parse_type(tcx, def_id, ty_expr, spec.tag) else {
288                    return Self::new_simple(PropertyKind::Unknown);
289                };
290                let count = super::resolve::expr_to_pest(tcx, def_id, count_expr);
291                Self::new_atom(
292                    spec.kind,
293                    vec![target, PropertyArg::Ty(ty), PropertyArg::Expr(count)],
294                )
295            }
296            [target_expr, ty_expr] => {
297                let target = super::resolve::parse_target_arg(tcx, def_id, target_expr);
298                let Some(ty) = super::resolve::parse_type(tcx, def_id, ty_expr, spec.tag) else {
299                    return Self::new_simple(PropertyKind::Unknown);
300                };
301                Self::new_atom(spec.kind, vec![target, PropertyArg::Ty(ty)])
302            }
303            [target_expr] => {
304                let target = super::resolve::parse_target_arg(tcx, def_id, target_expr);
305                Self::new_atom(spec.kind, vec![target])
306            }
307            _ => {
308                rap_error!(
309                    "Wrong args length for {} Tag! expected 1, 2 or 3, got {}",
310                    spec.tag,
311                    exprs.len()
312                );
313                Self::new_simple(PropertyKind::Unknown)
314            }
315        }
316    }
317
318    fn build_nonoverlap(tcx: TyCtxt<'tcx>, def_id: DefId, exprs: &[Expr]) -> Self {
319        match exprs {
320            [indices] => {
321                let target = super::resolve::parse_target_arg(tcx, def_id, indices);
322                Self::new_atom(PropertyKind::NonOverlap, vec![target])
323            }
324            [a, b, ty_expr, count_expr] => {
325                let Some(ty) = super::resolve::parse_type(tcx, def_id, ty_expr, "NonOverlap")
326                else {
327                    return Self::new_simple(PropertyKind::Unknown);
328                };
329                let left = super::resolve::parse_target_arg(tcx, def_id, a);
330                let right = super::resolve::parse_target_arg(tcx, def_id, b);
331                let count = super::resolve::expr_to_pest(tcx, def_id, count_expr);
332                Self::new_atom(
333                    PropertyKind::NonOverlap,
334                    vec![left, right, PropertyArg::Ty(ty), PropertyArg::Expr(count)],
335                )
336            }
337            [a, b, ty_expr] => {
338                let Some(ty) = super::resolve::parse_type(tcx, def_id, ty_expr, "NonOverlap")
339                else {
340                    return Self::new_simple(PropertyKind::Unknown);
341                };
342                let left = super::resolve::parse_target_arg(tcx, def_id, a);
343                let right = super::resolve::parse_target_arg(tcx, def_id, b);
344                Self::new_atom(PropertyKind::NonOverlap, vec![left, right, PropertyArg::Ty(ty)])
345            }
346            [a, b] => {
347                let left = super::resolve::parse_target_arg(tcx, def_id, a);
348                let right = super::resolve::parse_target_arg(tcx, def_id, b);
349                let ta = super::place::parse_expr_into_local_and_ty(tcx, def_id, a)
350                    .and_then(|(_, _, ty)| crate::util::mir_utils::pointee_ty(ty));
351                let tb = super::place::parse_expr_into_local_and_ty(tcx, def_id, b)
352                    .and_then(|(_, _, ty)| crate::util::mir_utils::pointee_ty(ty));
353                match (ta, tb) {
354                    (Some(ta), Some(tb)) if ta == tb => Self::new_atom(
355                        PropertyKind::NonOverlap,
356                        vec![left, right, PropertyArg::Ty(ta)],
357                    ),
358                    (Some(_), Some(_)) => {
359                        rap_error!(
360                            "NonOverlap(a, b): `a` and `b` have different pointee types; specify `T` explicitly"
361                        );
362                        Self::new_simple(PropertyKind::Unknown)
363                    }
364                    _ => Self::new_atom(PropertyKind::NonOverlap, vec![left, right]),
365                }
366            }
367            _ => {
368                rap_error!(
369                    "Wrong args length for NonOverlap Tag! expected 1, 2, 3 or 4, got {}",
370                    exprs.len()
371                );
372                Self::new_simple(PropertyKind::Unknown)
373            }
374        }
375    }
376
377    fn build_validnum(tcx: TyCtxt<'tcx>, def_id: DefId, exprs: &[Expr]) -> Self {
378        let predicates = super::resolve::parse_valid_num(tcx, def_id, exprs);
379        if predicates.is_empty() {
380            Self::new_simple(PropertyKind::Unknown)
381        } else {
382            Self::new_atom(
383                PropertyKind::ValidNum,
384                vec![PropertyArg::Predicates(predicates)],
385            )
386        }
387    }
388
389    fn build_targets(
390        spec: &spec::PropertySpec,
391        tcx: TyCtxt<'tcx>,
392        def_id: DefId,
393        exprs: &[Expr],
394    ) -> Self {
395        let args = exprs
396            .iter()
397            .map(|expr| super::resolve::parse_target_arg(tcx, def_id, expr))
398            .collect();
399        Self::new_atom(spec.kind, args)
400    }
401
402    fn build_pinned(tcx: TyCtxt<'tcx>, def_id: DefId, exprs: &[Expr]) -> Self {
403        match exprs {
404            [ptr_expr, lifetime_expr] => {
405                let target = super::resolve::parse_target_arg(tcx, def_id, ptr_expr);
406                let Some((lifetime, _)) = access_ident_recursive(lifetime_expr) else {
407                    return Self::new_simple(PropertyKind::Unknown);
408                };
409                Self::new_atom(
410                    PropertyKind::Pinned,
411                    vec![target, PropertyArg::Ident(lifetime)],
412                )
413            }
414            _ => {
415                rap_error!(
416                    "Wrong args length for Pinned Tag! expected 2, got {}",
417                    exprs.len()
418                );
419                Self::new_simple(PropertyKind::Unknown)
420            }
421        }
422    }
423
424    fn build_split_transmute(tcx: TyCtxt<'tcx>, def_id: DefId, exprs: &[Expr]) -> Self {
425        if exprs.len() != 2 {
426            rap_error!(
427                "Wrong args length for SplitTransmute Tag! expected 2, got {}",
428                exprs.len()
429            );
430            return Self::new_simple(PropertyKind::Unknown);
431        }
432        let src_elem = super::resolve::unwrap_array_expr(tcx, def_id, &exprs[0]);
433        let dst_elem = super::resolve::unwrap_array_expr(tcx, def_id, &exprs[1]);
434        let (Some(src_elem), Some(dst_elem)) = (src_elem, dst_elem) else {
435            return Self::new_simple(PropertyKind::Unknown);
436        };
437        Self::new_atom(
438            PropertyKind::SplitTransmute,
439            vec![PropertyArg::Ty(src_elem), PropertyArg::Ty(dst_elem)],
440        )
441    }
442
443    fn build_contain_no_type(tcx: TyCtxt<'tcx>, def_id: DefId, exprs: &[Expr]) -> Self {
444        if exprs.len() < 2 {
445            rap_error!(
446                "Wrong args length for ContainNoType Tag! expected at least 2 (ty, ident...), got {}",
447                exprs.len()
448            );
449            return Self::new_simple(PropertyKind::Unknown);
450        }
451        let Some(ty) = super::resolve::parse_type(tcx, def_id, &exprs[0], "ContainNoType") else {
452            return Self::new_simple(PropertyKind::Unknown);
453        };
454        let mut args = vec![PropertyArg::Ty(ty)];
455        for expr in &exprs[1..] {
456            let Some((name, _)) = access_ident_recursive(expr) else {
457                return Self::new_simple(PropertyKind::Unknown);
458            };
459            args.push(PropertyArg::Ident(name));
460        }
461        Self::new_atom(PropertyKind::ContainNoType, args)
462    }
463
464    fn new_simple(kind: PropertyKind) -> Self {
465        Self::new_atom(kind, Vec::new())
466    }
467
468    /// Parse one annotation entry into the properties it denotes.
469    ///
470    /// Plain entries (`Align(p, T)`, `Owning(p)`, ...) yield one property.
471    /// The `any(...)` combinator may expand to several: see [`Self::parse_any`].
472    pub(crate) fn parse_list(
473        tcx: TyCtxt<'tcx>,
474        def_id: DefId,
475        name: &str,
476        exprs: &[Expr],
477    ) -> Vec<Self> {
478        // User-defined / compound property macro expansion takes precedence, so
479        // `#[rapx::requires(MyTag(...))]` can reference DSL-defined contracts.
480        if let Some(props) = super::compound::expand_compound(tcx, def_id, name, exprs) {
481            return props;
482        }
483        let mut props = if name == "any" {
484            Self::parse_any(tcx, def_id, exprs)
485        } else {
486            vec![Self::new(tcx, def_id, name, exprs)]
487        };
488        for prop in &mut props {
489            if let Property::Atom(atom) = prop
490                && !atom.args.iter().any(|arg| matches!(arg, PropertyArg::ForEach(_))) {
491                    for arg in &mut atom.args {
492                        if super::place::strip_for_each(arg)
493                            && let PropertyArg::Expr(expr) = arg {
494                            *arg = PropertyArg::ForEach(expr.clone());
495                            break;
496                        }
497                    }
498                }
499        }
500        props
501    }
502
503    /// Parse the disjunctive combinator `any(D1, D2, ...)` written in DNF:
504    /// `any` means logical OR between disjuncts, and commas inside a
505    /// parenthesised disjunct mean logical AND:
506    ///
507    /// ```text
508    /// any(Null(p), (P1(p, ...), P2(p, ...), ...))
509    /// any(Trait(T, Copy), Trait(T, TrivialClone), ...)
510    /// ```
511    ///
512    /// A disjunct is either a single property application `P(...)` or a
513    /// parenthesised conjunction `(P1(...), ..., Pn(...))`.  Any number (≥ 2)
514    /// of disjuncts is accepted; each is expanded into its constituent
515    /// properties, producing a single `Property::Or` whose disjuncts are atoms
516    /// or `And` nodes.
517    fn parse_any(tcx: TyCtxt<'tcx>, def_id: DefId, exprs: &[Expr]) -> Vec<Self> {
518        if exprs.len() < 2 {
519            rap_error!(
520                "any(...) requires at least 2 disjuncts, got {}",
521                exprs.len()
522            );
523            return vec![Self::new_simple(PropertyKind::Unknown)];
524        }
525
526        let mut disjuncts: Vec<Vec<(String, Vec<Expr>)>> = Vec::with_capacity(exprs.len());
527        for expr in exprs {
528            let Some(parts) = Self::disjunct_parts(expr) else {
529                rap_error!(
530                    "any(...) disjuncts must be property applications or (P1, P2, ...) groups"
531                );
532                return vec![Self::new_simple(PropertyKind::Unknown)];
533            };
534            disjuncts.push(parts);
535        }
536
537        let mut or_disjuncts: Vec<Self> = Vec::with_capacity(disjuncts.len());
538        for parts in disjuncts {
539            let mut conjuncts: Vec<Self> = Vec::new();
540            for (name, args) in parts {
541                conjuncts.extend(Self::parse_list(tcx, def_id, &name, &args));
542            }
543            or_disjuncts.push(Self::conjunction(conjuncts));
544        }
545        vec![Self::new_or(or_disjuncts)]
546    }
547
548    /// Split one disjunct into its conjunct calls: a `(P1, P2, ...)` tuple, a
549    /// parenthesised single property `(P)`, or a bare property application.
550    fn disjunct_parts(expr: &Expr) -> Option<Vec<(String, Vec<Expr>)>> {
551        match expr {
552            Expr::Tuple(tuple) => tuple.elems.iter().map(Self::call_parts).collect(),
553            Expr::Paren(paren) => Self::call_parts(&paren.expr).map(|parts| vec![parts]),
554            _ => Self::call_parts(expr).map(|parts| vec![parts]),
555        }
556    }
557
558    /// Split a `Name(arg, ...)` call expression into its name and arguments.
559    fn call_parts(expr: &Expr) -> Option<(String, Vec<Expr>)> {
560        let Expr::Call(call) = expr else {
561            return None;
562        };
563        let Expr::Path(path) = call.func.as_ref() else {
564            return None;
565        };
566        let name = path.path.get_ident()?.to_string();
567        Some((name, call.args.iter().cloned().collect()))
568    }
569}