Skip to main content

rapx/contract/
attr.rs

1//! Parsing utilities for RAPx contract attributes.
2//!
3//! Parses raw `#[rapx::<name>(...)]` attributes (`requires` / `invariant` /
4//! `ensures`) and resolves their properties for verification.
5//!
6//! The supported shape is:
7//!
8//! ```text
9//! #[rapx::<name>(property_call, kind = "...")]
10//! ```
11//!
12//! where `kind = "..."` (a string literal) applies to the property in the same
13//! attribute.
14
15use syn::{
16    Expr, Lit, Result as SynResult, Token, Type,
17    parse::{Parse, ParseStream},
18};
19
20use quote::ToTokens;
21
22#[cfg(rapx_has_attr_ir)]
23use rustc_attr_ir::Attribute;
24#[cfg(not(rapx_has_attr_ir))]
25use rustc_hir::Attribute;
26use rustc_hir::def_id::DefId;
27use rustc_middle::ty::TyCtxt;
28use rustc_span::Symbol;
29
30use super::Property;
31
32/// The raw syntactic form of a property call `tag(arg0, arg1, ...)` parsed
33/// from an attribute — the *unevaluated* stage, before semantic resolution
34/// into a [`Property`](crate::contract::Property).
35#[derive(Debug, Clone)]
36pub(crate) struct AttrProperty {
37    /// The property name extracted from the call target.
38    pub tag: String,
39    /// The positional arguments passed to the property call.
40    pub args: Vec<Expr>,
41    /// Optional `kind` metadata associated with this property.
42    pub kind: Option<String>,
43}
44
45impl Parse for AttrProperty {
46    /// Parse a single property item from an attribute argument list.
47    ///
48    /// Supported forms:
49    /// - `NonNull(x)`
50    /// - `NonNull(x), kind = "precond"`
51    fn parse(input: ParseStream<'_>) -> SynResult<Self> {
52        let mut property = parse_property_head(input)?;
53
54        if input.peek(Token![,]) {
55            let fork = input.fork();
56            let _: Token![,] = fork.parse()?;
57            if fork.peek(syn::Ident) && fork.peek2(Token![=]) {
58                let _: Token![,] = input.parse()?;
59                let ident: syn::Ident = input.parse()?;
60                let _: Token![=] = input.parse()?;
61                let value: Expr = input.parse()?;
62
63                if ident == "kind" {
64                    if let Expr::Lit(ref expr_lit) = value
65                        && let Lit::Str(ref kind) = expr_lit.lit
66                    {
67                        property.kind = Some(kind.value());
68                    } else {
69                        return Err(syn::Error::new_spanned(
70                            value,
71                            "RAPx requires attribute kind must be a string literal",
72                        ));
73                    }
74                } else {
75                    return Err(syn::Error::new(
76                        ident.span(),
77                        "unsupported named RAPx requires attribute argument",
78                    ));
79                }
80            }
81        }
82
83        Ok(property)
84    }
85}
86
87pub(crate) fn parse_outer_attr(input: ParseStream<'_>) -> SynResult<syn::Attribute> {
88    input
89        .call(syn::Attribute::parse_outer)?
90        .into_iter()
91        .next()
92        .ok_or_else(|| input.error("expected an outer attribute"))
93}
94
95/// Parse a raw attribute string into a structured `requires` property.
96///
97/// Returns `Ok(None)` when the attribute does not match `rapx::<expected_name>`
98/// or when it is not a list attribute.
99pub(crate) fn parse_rapx_attr(
100    attr_str: &str,
101    expected_name: &str,
102) -> SynResult<Option<AttrProperty>> {
103    let attr_str = strip_lifetime_ticks(attr_str);
104    let attr = syn::parse::Parser::parse_str(parse_outer_attr, &attr_str)?;
105    if !is_expected_syn_rapx_attr(&attr, expected_name) {
106        return Ok(None);
107    }
108
109    let syn::Meta::List(meta_list) = &attr.meta else {
110        return Ok(None);
111    };
112
113    let property = meta_list.parse_args::<AttrProperty>()?;
114    Ok(Some(property))
115}
116
117/// Check whether an attribute path is exactly `rapx::<expected_name>`.
118fn is_expected_syn_rapx_attr(attr: &syn::Attribute, expected_name: &str) -> bool {
119    let mut segments = attr.path().segments.iter();
120    matches!(
121        (segments.next(), segments.next(), segments.next()),
122        (Some(first), Some(second), None)
123            if first.ident == "rapx" && second.ident == expected_name
124    )
125}
126
127/// Parse a property call head `tag(arg0, arg1, ...)`.
128///
129/// The argument list is parsed position-by-position rather than as a single
130/// `Expr::Call`, because property arguments may be generic *types* (e.g.
131/// `ValidTransmute(T, Option<NonZero<T>>)`) that `syn` cannot parse as value
132/// expressions.
133fn parse_property_head(input: ParseStream<'_>) -> SynResult<AttrProperty> {
134    let path: syn::Path = input.parse()?;
135    let tag = path
136        .segments
137        .last()
138        .map(|seg| seg.ident.to_string())
139        .ok_or_else(|| syn::Error::new_spanned(&path, "missing property name"))?;
140
141    let content;
142    syn::parenthesized!(content in input);
143
144    let mut args: Vec<Expr> = Vec::new();
145    while !content.is_empty() {
146        args.push(parse_property_arg(&content)?);
147        if content.is_empty() {
148            break;
149        }
150        content.parse::<Token![,]>()?;
151    }
152
153    Ok(AttrProperty {
154        tag,
155        args,
156        kind: None,
157    })
158}
159
160/// Parse a single property argument as an `Expr`.
161///
162/// Arguments are usually types (`Option<NonZero<T>>`, `[T; N]`, `T`), which
163/// `syn` cannot parse as value expressions (it would read `<`/`>` as comparison
164/// operators), so we try `Type` first and wrap its token stream as
165/// `Expr::Verbatim`.  Plain path types (single- or multi-segment identifiers
166/// without generics) are kept as `Expr::Path` so downstream place/ident
167/// resolution still recognises them.  Arguments that are genuine expressions
168/// (`0`, `x + 1`, `ptr.0`) fail type parsing and fall back to `Expr`.
169fn parse_property_arg(input: ParseStream<'_>) -> SynResult<Expr> {
170    // Arguments that begin with a parenthesised group are tuple/parenthesised
171    // expressions (e.g. the disjunctive grouping `(Align(head, T), ValidPtr(...))`
172    // inside `any`), never types.  syn's `Type` parser is fooled by these: it
173    // parses `(Align(head, T))` as a `Type::Paren` around just `Align` and
174    // silently leaves the rest of the group unparsed, which then surfaces as a
175    // spurious `unexpected token, expected `)`` error.  Parse them directly as
176    // expressions instead.
177    if input.peek(syn::token::Paren) {
178        return input.parse::<Expr>();
179    }
180
181    let fork = input.fork();
182    if fork.parse::<Type>().is_ok() && (fork.is_empty() || fork.peek(Token![,])) {
183        let ty: Type = input.parse()?;
184        return Ok(type_to_arg_expr(ty));
185    }
186    input.parse::<Expr>()
187}
188
189/// Convert a parsed argument `Type` back into the `Expr` form expected by the
190/// property builder: plain paths stay `Expr::Path`, everything else (generics,
191/// arrays, tuples, references) becomes `Expr::Verbatim`.
192fn type_to_arg_expr(ty: Type) -> Expr {
193    if let Type::Path(type_path) = &ty
194        && type_path.qself.is_none()
195        && type_path
196            .path
197            .segments
198            .iter()
199            .all(|s| matches!(s.arguments, syn::PathArguments::None))
200    {
201        return Expr::Path(syn::ExprPath {
202            attrs: Vec::new(),
203            qself: None,
204            path: type_path.path.clone(),
205        });
206    }
207    Expr::Verbatim(ty.to_token_stream())
208}
209
210/// Strips the leading `'` from Rust lifetime tokens so that `syn` can
211/// parse them as regular identifier expressions inside attribute arguments.
212/// For example, `'a` becomes `a`, `'static` becomes `static_lifetime`.
213///
214/// String literals (`"..."`) and char literals (`'x'`) are copied verbatim so
215/// their contents are never altered.
216fn strip_lifetime_ticks(s: &str) -> String {
217    let chars: Vec<char> = s.chars().collect();
218    let mut out = String::with_capacity(s.len());
219    let mut i = 0;
220    while i < chars.len() {
221        match chars[i] {
222            '"' => {
223                out.push('"');
224                i += 1;
225                while i < chars.len() {
226                    let c = chars[i];
227                    out.push(c);
228                    i += 1;
229                    if c == '\\' && i < chars.len() {
230                        out.push(chars[i]);
231                        i += 1;
232                    } else if c == '"' {
233                        break;
234                    }
235                }
236            }
237            '\'' => {
238                // `'static` is a Rust keyword, so it cannot be parsed as a
239                // plain ident after the tick is stripped. Map it to a
240                // non-keyword token that `resolve_region_name` recognises.
241                let rest: String = chars[i + 1..].iter().collect();
242                if rest.starts_with("static")
243                    && chars.get(i + 1 + "static".len()).is_none_or(|&c| !c.is_ascii_alphanumeric() && c != '_')
244                {
245                    out.push_str(super::STATIC_LIFETIME_IDENT);
246                    i += 1 + "static".len();
247                    continue;
248                }
249                let len = match chars.get(i + 1) {
250                    Some('\\') if chars.get(i + 3) == Some(&'\'') => 4,
251                    Some(_) if chars.get(i + 2) == Some(&'\'') => 3,
252                    _ => 0,
253                };
254                if len > 0 {
255                    out.extend(&chars[i..i + len]);
256                    i += len;
257                } else {
258                    i += 1;
259                }
260            }
261            c => {
262                out.push(c);
263                i += 1;
264            }
265        }
266    }
267    out
268}
269
270pub(crate) fn is_rapx_named_attr(tcx: TyCtxt<'_>, attr: &Attribute, name: &str) -> bool {
271    let name = Symbol::intern(name);
272    crate::compat::attribute_path_matches(tcx, attr, &[Symbol::intern("rapx"), name])
273        || crate::compat::attribute_path_matches(tcx, attr, &[name])
274}
275
276pub(crate) fn collect_properties_from_named_attrs<'tcx>(
277    tcx: TyCtxt<'tcx>,
278    attrs: impl IntoIterator<Item = &'tcx Attribute>,
279    property_def_id: DefId,
280    parse_error_label: &str,
281    attr_name: &str,
282) -> Vec<Property<'tcx>> {
283    let mut results = Vec::new();
284
285    for attr in attrs {
286        if !is_rapx_named_attr(tcx, attr, attr_name) {
287            continue;
288        }
289
290        let attr_str = crate::compat::attribute_to_string(tcx, attr);
291        let parsed = match parse_rapx_attr(attr_str.as_str(), attr_name) {
292            Ok(parsed) => parsed,
293            Err(err) => {
294                rap_error!(
295                    "Failed to parse RAPx {} attr '{}': {}",
296                    parse_error_label,
297                    attr_str,
298                    err
299                );
300                continue;
301            }
302        };
303
304        let Some(property) = parsed else { continue };
305        results.extend(
306            Property::parse_list(tcx, property_def_id, property.tag.as_str(), &property.args)
307                .into_iter()
308                .map(move |mut p| {
309                    p.apply_kind(property.kind.as_deref());
310                    p
311                }),
312        );
313    }
314
315    results
316}