Skip to main content

rapx/contract/
compound.rs

1//! User-defined compound-contract layer.
2//!
3//! Users (downloading a prebuilt `rapx` binary) can define *new* named safety
4//! contracts as boolean combinations of the primitive safety properties, and
5//! reference them from `#[rapx::requires(MyTag(...))]` — without recompiling
6//! `rapx`.
7//!
8//! A compound property is a DNF macro over primitive property calls:
9//!
10//! ```text
11//! MySafeRead(p: Ptr, T: Ty, n: Expr) {
12//!     NonNull(p) && Align(p, T) && Allocated(p, T, n)
13//! }
14//!
15//! StrOrBytes(s: Ptr, T: Ty, n: Expr) {
16//!     ValidCStr(s, n) || (Allocated(s, T, n) && Init(s, T, n))
17//! }
18//! ```
19//!
20//! The DSL only *composes* existing primitives; it cannot invent new primitive
21//! semantics (those live in `property_checker.rs`).  Expansion is a pure
22//! front-end that produces ordinary `Property` values consumed by the existing
23//! checker.
24
25use std::{
26    collections::{HashMap, HashSet},
27    sync::{OnceLock, RwLock},
28};
29
30#[cfg(rapx_has_attr_ir)]
31use rustc_attr_ir::Attribute;
32#[cfg(not(rapx_has_attr_ir))]
33use rustc_hir::Attribute;
34use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
35use rustc_span::Symbol;
36use syn::{
37    Expr,
38    visit_mut::{self, VisitMut},
39};
40
41use super::spec::ArgKind;
42use super::{AtomProperty, ContractExpr, ContractKind, Property, PropertyArg, PropertyKind};
43
44/// A single argument in a compound body: a reference to a formal parameter, or a
45/// literal (kept as source text, re-parsed as `syn::Expr` at expansion time).
46#[derive(Debug, Clone, PartialEq, Eq, Hash)]
47pub(crate) enum CompoundArg {
48    Param(usize),
49    Lit(String),
50}
51
52/// The body of a compound property: a boolean tree over primitive-property
53/// calls (`Call` leaves), freely nested via `And`/`Or`.  The DSL `&&`/`||`
54/// grammar permits arbitrary nesting (an `And` may contain an `Or` and vice
55/// versa), so this is *not* constrained to DNF; `expand_compound_body`
56/// recurses over whatever shape was parsed.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub(crate) enum CompoundBody {
59    And(Vec<CompoundBody>),
60    Or(Vec<CompoundBody>),
61    Call { tag: String, args: Vec<CompoundArg> },
62}
63
64/// A parsed compound-property declaration.
65#[derive(Debug, Clone)]
66pub(crate) struct CompoundSpec {
67    pub name: String,
68    pub params: Vec<String>,
69    pub param_tys: Vec<String>,
70    /// Number of leading required parameters; the rest are optional.
71    pub required: usize,
72    pub body: CompoundBody,
73    pub doc: Vec<String>,
74}
75
76/// Parse a source fragment containing block-shaped contract definitions
77/// (`Name(params) { body }`) into a list of `CompoundSpec`s.
78///
79/// This is the format produced by the `pred!` macro and used by the bundled
80/// `assets/*-compound-properties.rs` files:
81///
82/// ```text
83/// MySafeRead(p: Ptr, T: Ty, n: Expr) { NonNull(p) && Align(p, T) && Allocated(p, T, n) }
84/// ```
85///
86/// Each compound may be preceded by `///` doc lines (shown as the human-readable
87/// meaning in reports); `//` comments and blank lines are skipped.  The body
88/// supports `&&` (conjunction) and `||` (disjunction) of `Tag(arg, ...)` calls,
89/// plus `( ... )` grouping for a conjunction used as a single disjunct.
90pub(crate) fn parse_compounds(source: &str) -> Vec<CompoundSpec> {
91    let mut compounds = Vec::new();
92    let mut doc: Vec<String> = Vec::new();
93
94    let mut s = source.trim_start();
95    loop {
96        loop {
97            if let Some(r) = s.strip_prefix("///") {
98                let end = r.find('\n').unwrap_or(r.len());
99                doc.push(r[..end].trim().to_string());
100                s = r[end..].trim_start();
101            } else if let Some(r) = s.strip_prefix("//") {
102                let end = r.find('\n').unwrap_or(r.len());
103                s = r[end..].trim_start();
104            } else {
105                break;
106            }
107        }
108        if s.is_empty() {
109            break;
110        }
111
112        let (Some(mut compound), consumed) = parse_one_compound_block(s) else {
113            let preview: String = s.chars().take(80).collect();
114            rap_error!("failed to parse contract compound near: {preview}");
115            break;
116        };
117        compound.doc = std::mem::take(&mut doc);
118        compounds.push(compound);
119        s = s[consumed..].trim_start();
120    }
121
122    compounds
123}
124
125/// Parse a single leading `Name(p: Ptr, T: Ty, ...) { body }` block from `s`.
126/// Returns the `CompoundSpec` (without doc) and the number of bytes consumed through
127/// the closing `}`.
128///
129/// The block is emitted by the `pred!` proc-macro as a single line of
130/// space-separated tokens, so parameter names and role annotations (`Ptr`,
131/// `Ty`, `Expr`, `Ident`) are split on `:` and `,` after trimming whitespace.
132/// The braces delimit the body, so nested `==`/`<=` inside a `ValidNum`
133/// predicate cannot be confused with a definition separator.
134fn parse_one_compound_block(s: &str) -> (Option<CompoundSpec>, usize) {
135    let Some(open) = s.find('(') else {
136        return (None, 0);
137    };
138    let name = s[..open].trim().to_string();
139    if name.is_empty() {
140        return (None, 0);
141    }
142
143    // Params: match the first `)` — parameter annotations are `ident: ident`,
144    // so they never contain nested parens.
145    let Some(rel_close) = s[open + 1..].find(')') else {
146        return (None, 0);
147    };
148    let close = open + 1 + rel_close;
149    let params_str = &s[open + 1..close];
150
151    let after = s[close + 1..].trim_start();
152    if !after.starts_with('{') {
153        return (None, 0);
154    }
155    let brace_open = s.len() - after.len();
156    let body_start = brace_open + 1;
157
158    let bytes = s.as_bytes();
159    let mut depth = 1usize;
160    let mut j = body_start;
161    while j < bytes.len() {
162        match bytes[j] {
163            b'{' => depth += 1,
164            b'}' => {
165                depth -= 1;
166                if depth == 0 {
167                    break;
168                }
169            }
170            _ => {}
171        }
172        j += 1;
173    }
174    if depth != 0 {
175        return (None, 0);
176    }
177    let body = s[body_start..j].trim();
178
179    let (params, param_tys, required) = parse_equation_params(params_str);
180    let Some(body_ast) = super::pest::parse_compound_body(body, &params) else {
181        return (None, 0);
182    };
183
184    let compound = CompoundSpec {
185        name,
186        params,
187        param_tys,
188        required,
189        body: body_ast,
190        doc: Vec::new(),
191    };
192    (Some(compound), j + 1)
193}
194
195fn parse_equation_params(params_str: &str) -> (Vec<String>, Vec<String>, usize) {
196    let mut params = Vec::new();
197    let mut param_tys = Vec::new();
198    let mut required = 0usize;
199    let mut seen_optional = false;
200    for seg in params_str.split(',') {
201        let seg = seg.trim();
202        if seg.is_empty() {
203            continue;
204        }
205        let (name, ty) = match seg.split_once(':') {
206            Some((p, ty)) => (p.trim().to_string(), ty.trim().to_string()),
207            None => (seg.to_string(), String::new()),
208        };
209        let (ty, optional) = match ty.strip_suffix('?') {
210            Some(stripped) => (stripped.to_string(), true),
211            None => (ty, false),
212        };
213        if optional {
214            seen_optional = true;
215        } else if !seen_optional {
216            required += 1;
217        }
218        params.push(name);
219        param_tys.push(ty);
220    }
221    (params, param_tys, required)
222}
223
224/// Render a `syn::Expr` back to source-like text.  `proc_macro2` stringifies
225/// tokens space-separated (`self . 0`, `size_of (T)`), so collapse the spaces
226/// around punctuation for a readable form.
227fn render_expr_src(e: &Expr) -> String {
228    quote::ToTokens::to_token_stream(e)
229        .to_string()
230        .replace(" . ", ".")
231        .replace(" ,", ",")
232        .replace(" (", "(")
233        .replace(" :: ", "::")
234}
235
236/// Resolve a call-site argument expression to its display form, following the
237/// compound parameter's declared role so internal placeholders (e.g. `Arg_0` from a
238/// JSON contract) render as the actual parameter name.
239fn resolve_arg_string<'tcx>(
240    tcx: rustc_middle::ty::TyCtxt<'tcx>,
241    def_id: rustc_hir::def_id::DefId,
242    param_ty: &str,
243    expr: &Expr,
244) -> String {
245    match param_ty {
246        "Ptr" => {
247            let arg = super::resolve::parse_target_arg(tcx, def_id, expr);
248            // For a resolved field place, show the field name (e.g. `ptr` in
249            // `self.ptr`) rather than the internal `arg1.0` form.
250            if let Some(ContractExpr::Place(place)) = arg.expr()
251                && let Some(name) = super::place::field_name_from_place(tcx, def_id, place)
252            {
253                return name;
254            }
255            arg.display_for_report(tcx, None, Some(def_id))
256        }
257        "Ty" => super::resolve::parse_type(tcx, def_id, expr, "compound")
258            .map(|ty| ty.to_string())
259            .unwrap_or_else(|| render_expr_src(expr)),
260        "Expr" => {
261            let ce = super::resolve::expr_to_pest(tcx, def_id, expr);
262            super::render::display_expr_user_friendly(&ce, tcx, None, Some(def_id))
263        }
264        _ => render_expr_src(expr),
265    }
266}
267
268/// Substitute compound formal parameters with the concrete call-site arguments inside
269/// a literal expression (e.g. turn `size_of(T) * n` into `size_of(u32) * len`,
270/// or `p.unwrap_some()` into `head.unwrap_some()`).
271///
272/// Only a bare single-segment path that exactly matches a formal parameter name
273/// is replaced, so builtin function names (`size_of`), method names
274/// (`unwrap_some`) and field names are never rewritten.
275struct Subst<'a> {
276    params: &'a [String],
277    args: &'a [Expr],
278}
279
280impl VisitMut for Subst<'_> {
281    fn visit_expr_mut(&mut self, node: &mut Expr) {
282        if let Expr::Path(path) = node
283            && path.qself.is_none()
284                && path.path.leading_colon.is_none()
285                && path.path.segments.len() == 1
286            {
287                let ident = path.path.segments[0].ident.to_string();
288                if let Some(i) = self.params.iter().position(|n| *n == ident)
289                    && let Some(arg) = self.args.get(i) {
290                        // The substituted argument comes from the call site and
291                        // never refers to this compound's formals, so stop recursing.
292                        *node = arg.clone();
293                        return;
294                    }
295            }
296        visit_mut::visit_expr_mut(self, node);
297    }
298}
299
300/// Whether a compound parameter annotation matches a primitive argument role.
301fn compound_param_ty_matches_arg_kind(def_ty: &str, kind: super::spec::ArgKind) -> bool {
302    matches!(
303        (def_ty, kind),
304        ("Ptr", ArgKind::Target)
305            | ("Ty", ArgKind::Ty)
306            | ("Expr", ArgKind::Expr)
307            | ("Ident", ArgKind::Ident)
308    )
309}
310
311/// Expand a `CompoundBody` into the property list it denotes.
312///
313/// `and` produces multiple `Property` values (the caller's `requires` list is
314/// already a conjunction); `or` produces a single `Property::Or` property
315/// whose `groups` encode the DNF groups.
316fn expand_compound_body<'tcx>(
317    tcx: rustc_middle::ty::TyCtxt<'tcx>,
318    def_id: rustc_hir::def_id::DefId,
319    body: &CompoundBody,
320    exprs: &[Expr],
321    params: &[String],
322    param_tys: &[String],
323) -> Vec<Property<'tcx>> {
324    match body {
325        CompoundBody::And(parts) => parts
326            .iter()
327            .flat_map(|p| expand_compound_body(tcx, def_id, p, exprs, params, param_tys))
328            .collect(),
329        CompoundBody::Or(parts) => {
330            let mut disjuncts: Vec<Property<'tcx>> = Vec::new();
331            for part in parts {
332                let conjuncts = expand_compound_body(tcx, def_id, part, exprs, params, param_tys);
333                if !conjuncts.is_empty() {
334                    disjuncts.push(Property::conjunction(conjuncts));
335                }
336            }
337            vec![Property::new_or(disjuncts)]
338        }
339        CompoundBody::Call { tag, args } => {
340            // Validate the compound's parameter annotations against the primitive's
341            // declared argument roles (e.g. a `Ptr` param used in a `Ty` slot).
342            if let Some(spec) = super::spec::find_spec(tag) {
343                match spec.kind {
344                    PropertyKind::Alias | PropertyKind::Alive => {
345                        for (pos, a) in args.iter().enumerate() {
346                            if let CompoundArg::Param(i) = a
347                                && let Some(def_ty) = param_tys.get(*i)
348                                && !compound_param_ty_matches_arg_kind(
349                                    def_ty,
350                                    super::spec::ArgKind::Target,
351                                )
352                            {
353                                let pname = params.get(*i).map(String::as_str).unwrap_or("?");
354                                rap_warn!(
355                                    "contract compound type mismatch: `{tag}` arg {pos} expects \
356                                     {:?}, but param `{pname}` is annotated `{def_ty}`",
357                                    super::spec::ArgKind::Target
358                                );
359                            }
360                        }
361                    }
362                    PropertyKind::Unknown => {}
363                    // Fixed-arity tag: match a form by call arity, then check each
364                    // positional parameter annotation against the declared role.
365                    _ => {
366                        if let Some(form) = spec.forms.iter().find(|f| f.len() == args.len()) {
367                            for (pos, a) in args.iter().enumerate() {
368                                if let CompoundArg::Param(i) = a
369                                    && let (Some(def_ty), Some(&arg_kind)) =
370                                        (param_tys.get(*i), form.get(pos))
371                                    && !compound_param_ty_matches_arg_kind(def_ty, arg_kind)
372                                {
373                                    let pname = params.get(*i).map(String::as_str).unwrap_or("?");
374                                    rap_warn!(
375                                        "contract compound type mismatch: `{tag}` arg {pos} expects \
376                                         {:?}, but param `{pname}` is annotated `{def_ty}`",
377                                        arg_kind
378                                    );
379                                }
380                            }
381                        }
382                    }
383                }
384            }
385
386            let mut resolved: Vec<Expr> = Vec::with_capacity(args.len());
387            for (idx, a) in args.iter().enumerate() {
388                match a {
389                    CompoundArg::Param(i) => {
390                        match exprs.get(*i) {
391                            Some(e) => resolved.push(e.clone()),
392                            None => {
393                                // Omitted trailing optional parameter. Truncate
394                                // the call only when the remaining args are all
395                                // params too; a literal after the omitted param
396                                // (e.g. `Size(T, 0)` with `T` omitted) has no
397                                // sensible partial form — drop the whole call.
398                                if args[idx..]
399                                    .iter()
400                                    .any(|a| matches!(a, CompoundArg::Lit(_)))
401                                {
402                                    return Vec::new();
403                                }
404                                break;
405                            }
406                        }
407                    }
408                    CompoundArg::Lit(s) => {
409                        let Ok(mut e) = syn::parse_str::<Expr>(s) else {
410                            return vec![unknown_property()];
411                        };
412                        Subst {
413                            params,
414                            args: exprs,
415                        }
416                        .visit_expr_mut(&mut e);
417                        resolved.push(e);
418                    }
419                }
420            }
421            // Recurse through the normal property parser so nested compounds and
422            // primitives are handled uniformly.
423            Property::parse_list(tcx, def_id, tag, &resolved)
424        }
425    }
426}
427
428fn unknown_property<'tcx>() -> Property<'tcx> {
429    Property::new_atom(PropertyKind::Unknown, Vec::new())
430}
431
432// ── Subsumption (one-way weakening) ───────────────────────────
433
434/// Cached builtin subsumption map (see [`subsumption_closure`]).
435fn builtin_subsumptions_map() -> &'static HashMap<String, CompoundSpec> {
436    static BUILTIN: OnceLock<HashMap<String, CompoundSpec>> = OnceLock::new();
437    BUILTIN.get_or_init(|| {
438        parse_compounds(include_str!("assets/std-subsumption.rs"))
439            .into_iter()
440            .map(|c| (c.name.clone(), c))
441            .collect()
442    })
443}
444
445/// Apply the builtin subsumption rules to an asserted fact: a stronger
446/// primitive also asserts its weaker consequences — a one-way weakening, unlike
447/// the `≡` compound equivalences above.  The rules are declared declaratively
448/// in `std-subsumption.rs` with the same `Name(params) { body }` syntax; the
449/// head is an existing primitive tag and the body a pure conjunction of weaker
450/// primitive calls whose parameters map positionally to the head's arguments
451/// (e.g. `Init(p, T, n) ⇒ Typed(p, T)`).  Pointer-validity primitives
452/// (`NonNull`/`Allocated`/`InBound`) are deliberately *not* implied: they are
453/// orthogonal requirements stated explicitly by contracts.
454///
455/// Returns the *transitive closure* of the subsumption relation applied to
456/// `atom`, deduplicated: each weaker consequence appears exactly once.
457pub(crate) fn subsumption_closure<'tcx>(atom: &AtomProperty<'tcx>) -> Vec<AtomProperty<'tcx>> {
458    let Some(head_tag) = super::spec::tag_name_for_kind(atom.kind) else {
459        return Vec::new();
460    };
461
462    // BFS over the subsumption graph, tracking `(tag, args)` pairs at the
463    // declared level, where `args` stay positionally relative to the original
464    // `atom` (substitution keeps them as `Param(i)`/`Lit`).  `CompoundArg` is
465    // `Eq + Hash`, so the pair is a valid dedup key.
466    let mut out: Vec<AtomProperty<'tcx>> = Vec::new();
467    let mut seen: HashSet<(String, Vec<CompoundArg>)> = HashSet::new();
468    let mut queue: Vec<(String, Vec<CompoundArg>)> = Vec::new();
469    if let Some(spec) = builtin_subsumptions_map().get(head_tag) {
470        queue.extend(flatten_subsumption_body(&spec.body));
471    }
472    let mut cursor = 0;
473    while cursor < queue.len() {
474        let (tag, args) = queue[cursor].clone();
475        cursor += 1;
476        if !seen.insert((tag.clone(), args.clone())) {
477            continue;
478        }
479        if let Some(kind) = super::spec::find_spec(&tag).map(|s| s.kind)
480            && let Some(resolved) = resolve_subsumption_args(&args, atom) {
481                out.push(AtomProperty {
482                    kind,
483                    args: resolved,
484                    contract_kind: ContractKind::Precond,
485                    origin: None,
486                });
487            }
488        // Enqueue this tag's own consequences, substituting its params with the
489        // actual `args` passed to it (kept relative to `atom`).
490        if let Some(spec) = builtin_subsumptions_map().get(&tag) {
491            for (child_tag, child_args) in flatten_subsumption_body(&spec.body) {
492                let substituted: Vec<CompoundArg> = child_args
493                    .into_iter()
494                    .map(|a| match a {
495                        CompoundArg::Param(j) => args
496                            .get(j)
497                            .cloned()
498                            .unwrap_or(CompoundArg::Lit(String::new())),
499                        lit @ CompoundArg::Lit(_) => lit,
500                    })
501                    .collect();
502                queue.push((child_tag, substituted));
503            }
504        }
505    }
506    out
507}
508
509/// Resolve a subsumption body's `(tag, args)` — whose `args` are `Param(i)`
510/// indices into `atom`'s own arguments — into concrete `PropertyArg`s.
511fn resolve_subsumption_args<'tcx>(
512    args: &[CompoundArg],
513    atom: &AtomProperty<'tcx>,
514) -> Option<Vec<PropertyArg<'tcx>>> {
515    let mut resolved: Vec<PropertyArg<'tcx>> = Vec::with_capacity(args.len());
516    for a in args {
517        match a {
518            CompoundArg::Param(i) => {
519                let pa = atom.args.get(*i)?;
520                resolved.push(pa.clone())
521            }
522            CompoundArg::Lit(s) => {
523                rap_warn!("subsumption body literal `{s}` unsupported; skipping");
524                return None;
525            }
526        }
527    }
528    Some(resolved)
529}
530
531/// Flatten a subsumption body (a pure conjunction of primitive calls) into a
532/// list of `(tag, args)` pairs.
533fn flatten_subsumption_body(body: &CompoundBody) -> Vec<(String, Vec<CompoundArg>)> {
534    match body {
535        CompoundBody::And(parts) => parts.iter().flat_map(flatten_subsumption_body).collect(),
536        CompoundBody::Call { tag, args } => vec![(tag.clone(), args.clone())],
537        CompoundBody::Or(_) => {
538            rap_warn!("subsumption body must be a conjunction (no `||`); ignoring disjunction");
539            Vec::new()
540        }
541    }
542}
543
544// ── Registry ───────────────────────────────────────────────────
545
546/// Cached, shared builtin compound map (see [`builtin_compounds`]).
547fn builtin_compounds_map() -> &'static HashMap<String, CompoundSpec> {
548    static BUILTIN: OnceLock<HashMap<String, CompoundSpec>> = OnceLock::new();
549    BUILTIN.get_or_init(builtin_compounds)
550}
551
552/// Per-crate user compounds, registered from `#[rapx::def_property]` attributes.
553///
554/// Keyed by `CrateNum` so that compounds defined in one crate cannot leak into (or
555/// collide with) another crate analyzed in the same process.  A crate's own
556/// compounds shadow builtin compounds of the same name.
557fn user_compounds_map() -> &'static RwLock<HashMap<CrateNum, HashMap<String, CompoundSpec>>> {
558    static USER: OnceLock<RwLock<HashMap<CrateNum, HashMap<String, CompoundSpec>>>> =
559        OnceLock::new();
560    USER.get_or_init(|| RwLock::new(HashMap::new()))
561}
562
563/// Builtin compounds shipped with `rapx`: the standard compound safety properties
564/// (`std-compound-properties.rs`) plus user extensions
565/// (`user-compound-properties.rs`).
566fn builtin_compounds() -> HashMap<String, CompoundSpec> {
567    let mut map = HashMap::new();
568    for compound in parse_compounds(include_str!("assets/std-compound-properties.rs")) {
569        map.insert(compound.name.clone(), compound);
570    }
571    for compound in parse_compounds(include_str!("assets/user-compound-properties.rs")) {
572        map.insert(compound.name.clone(), compound);
573    }
574    map
575}
576
577/// Look up a compound property by name, in the given crate's namespace first,
578/// then the builtin namespace.
579pub(crate) fn find_compound(krate: CrateNum, name: &str) -> Option<CompoundSpec> {
580    if let Some(d) = user_compounds_map()
581        .read()
582        .ok()
583        .and_then(|t| t.get(&krate).and_then(|m| m.get(name).cloned()))
584    {
585        return Some(d);
586    }
587    builtin_compounds_map().get(name).cloned()
588}
589
590/// Expand a named compound against concrete argument expressions.
591pub(crate) fn expand_compound<'tcx>(
592    tcx: rustc_middle::ty::TyCtxt<'tcx>,
593    def_id: rustc_hir::def_id::DefId,
594    name: &str,
595    exprs: &[Expr],
596) -> Option<Vec<Property<'tcx>>> {
597    let compound = find_compound(def_id.krate, name)?;
598    if exprs.len() < compound.required || exprs.len() > compound.params.len() {
599        let expected = if compound.required == compound.params.len() {
600            compound.params.len().to_string()
601        } else {
602            format!("{}-{}", compound.required, compound.params.len())
603        };
604        rap_warn!(
605            "contract compound `{name}` expects {expected} argument(s), got {}",
606            exprs.len()
607        );
608        return None;
609    }
610    // Guard against self-referential compounds (direct or mutual) before recursing;
611    // otherwise `expand_compound_body` → `Property::parse_list` → `expand_compound` would
612    // recurse forever and overflow the stack.
613    if let Some(cycle) = find_compound_cycle(def_id.krate, name) {
614        rap_error!("contract compound cycle detected: {}", cycle.join(" -> "));
615        return None;
616    }
617    let mut props = expand_compound_body(
618        tcx,
619        def_id,
620        &compound.body,
621        exprs,
622        &compound.params,
623        &compound.param_tys,
624    );
625    // Tag expanded properties with the compound name, its full call-site arguments,
626    // and its doc-derived meaning so reports can show the compound as a single
627    // entry instead of the underlying primitives.
628    let arg_strings: Vec<String> = exprs
629        .iter()
630        .enumerate()
631        .map(|(i, e)| {
632            let param_ty = compound.param_tys.get(i).map(|s| s.as_str()).unwrap_or("");
633            resolve_arg_string(tcx, def_id, param_ty, e)
634        })
635        .collect();
636    let meaning = if compound.doc.is_empty() {
637        None
638    } else {
639        Some(compound.doc.join(" "))
640    };
641    for p in &mut props {
642        p.set_origin(name.to_string(), arg_strings.clone(), meaning.clone());
643    }
644    Some(props)
645}
646
647/// Return a cycle path (e.g. `["A", "B", "A"]`) if expanding `start` can reach
648/// itself again through compound-to-compound references, `None` otherwise.
649///
650/// Only edges that resolve to another registered compound are followed; calls to
651/// primitives (`Allocated`, `Align`, ...) terminate the walk.  The crate's own
652/// compounds are overlaid on the builtin namespace.
653pub(crate) fn find_compound_cycle(krate: CrateNum, start: &str) -> Option<Vec<String>> {
654    let mut combined = builtin_compounds_map().clone();
655    if let Ok(user) = user_compounds_map().read()
656        && let Some(crate_defs) = user.get(&krate)
657    {
658        for (name, compound) in crate_defs {
659            combined.insert(name.clone(), compound.clone());
660        }
661    }
662    find_cycle_in(start, &combined)
663}
664
665fn find_cycle_in(start: &str, table: &HashMap<String, CompoundSpec>) -> Option<Vec<String>> {
666    fn dfs(
667        name: &str,
668        table: &HashMap<String, CompoundSpec>,
669        path: &mut Vec<String>,
670        done: &mut HashSet<String>,
671    ) -> Option<Vec<String>> {
672        if let Some(pos) = path.iter().position(|n| n == name) {
673            let mut cycle: Vec<String> = path[pos..].to_vec();
674            cycle.push(name.to_string());
675            return Some(cycle);
676        }
677        if done.contains(name) {
678            return None;
679        }
680        let compound = table.get(name)?;
681        path.push(name.to_string());
682        for tag in compound_refs(&compound.body) {
683            if let Some(cycle) = dfs(&tag, table, path, done) {
684                return Some(cycle);
685            }
686        }
687        path.pop();
688        done.insert(name.to_string());
689        None
690    }
691
692    let mut path = Vec::new();
693    let mut done = HashSet::new();
694    dfs(start, table, &mut path, &mut done)
695}
696
697/// Collect the tag names referenced by a `CompoundBody`, in left-to-right order.
698fn compound_refs(body: &CompoundBody) -> Vec<String> {
699    let mut out = Vec::new();
700    collect_compound_refs(body, &mut out);
701    out
702}
703
704fn collect_compound_refs(body: &CompoundBody, out: &mut Vec<String>) {
705    match body {
706        CompoundBody::And(parts) | CompoundBody::Or(parts) => {
707            for part in parts {
708                collect_compound_refs(part, out);
709            }
710        }
711        CompoundBody::Call { tag, .. } => out.push(tag.clone()),
712    }
713}
714
715// ── Registration of user-defined compounds ─────────────────────────
716
717/// Parse compound-property declarations from `source` and insert them into the
718/// given crate's namespace.  Returns the number of compounds registered.
719pub(crate) fn register_compounds_from_source(krate: CrateNum, source: &str) -> usize {
720    let compounds = parse_compounds(source);
721    let n = compounds.len();
722    if n == 0 {
723        return 0;
724    }
725    let mut table = user_compounds_map()
726        .write()
727        .expect("compound table poisoned");
728    let entry = table.entry(krate).or_default();
729    for compound in compounds {
730        entry.insert(compound.name.clone(), compound);
731    }
732    n
733}
734
735// ── Procedural-macro contract definitions ─────────────────────
736
737/// Scan the local crate for `#[rapx::def_property("...")]` tool attributes
738/// (emitted by the `rapx_macros::pred` proc-macro) and register each embedded
739/// compound-property string.  Returns the number of compounds registered.
740pub(crate) fn register_compound_properties(tcx: rustc_middle::ty::TyCtxt<'_>) -> usize {
741    struct Visitor<'tcx> {
742        tcx: rustc_middle::ty::TyCtxt<'tcx>,
743        count: usize,
744    }
745
746    impl<'tcx> rustc_hir::intravisit::Visitor<'tcx> for Visitor<'tcx> {
747        fn visit_item(&mut self, item: &'tcx rustc_hir::Item<'tcx>) {
748            let attrs = self.tcx.hir_attrs(item.hir_id());
749            for attr in attrs {
750                if !is_def_property_attr(self.tcx, attr) {
751                    continue;
752                }
753                let attr_str = crate::compat::attribute_to_string(self.tcx, attr);
754                if let Some(def_str) = extract_def_property_string(&attr_str) {
755                    let n = register_compounds_from_source(LOCAL_CRATE, &def_str);
756                    if n > 0 {
757                        rap_info!(
758                            "rapx: registered {n} contract compound(s) from #[rapx::def_property]"
759                        );
760                    }
761                    self.count += n;
762                }
763            }
764            rustc_hir::intravisit::walk_item(self, item);
765        }
766    }
767
768    let mut v = Visitor { tcx, count: 0 };
769    tcx.hir_visit_all_item_likes_in_crate(&mut v);
770    v.count
771}
772
773/// Whether an attribute path is `rapx::def_property` (or the bare form with the
774/// tool prefix stripped).
775fn is_def_property_attr(tcx: rustc_middle::ty::TyCtxt<'_>, attr: &Attribute) -> bool {
776    let name = Symbol::intern("def_property");
777    crate::compat::attribute_path_matches(tcx, attr, &[Symbol::intern("rapx"), name])
778        || crate::compat::attribute_path_matches(tcx, attr, &[name])
779}
780
781/// Extract the string literal from a `#[rapx::def_property("compound ...")]`
782/// attribute's textual representation.
783fn extract_def_property_string(attr_str: &str) -> Option<String> {
784    let attr = syn::parse::Parser::parse_str(super::attr::parse_outer_attr, attr_str).ok()?;
785    let syn::Meta::List(list) = attr.meta else {
786        return None;
787    };
788    let lit: syn::LitStr = syn::parse2(list.tokens).ok()?;
789    Some(lit.value())
790}