Skip to main content

serge_widget_codegen/
render_value.rs

1//! Fixed-signature leaf calculations accepted by the native development tool.
2//! Both the proc macro and the change classifier use this grammar.
3use syn::{BinOp, Expr, Item, ItemFn, Lit, Result, ReturnType, Stmt, Type, UnOp, spanned::Spanned};
4
5/// Verifies the signature and body, rejecting calls, attributes, captured
6/// variables, allocations and target-dependent arithmetic.
7pub fn check(f: &ItemFn) -> Result<()> {
8    let sig = &f.sig;
9    let allowed = sig.constness.is_none()
10        && sig.asyncness.is_none()
11        && sig.unsafety.is_none()
12        && sig.abi.is_none()
13        && sig.variadic.is_none()
14        && sig.inputs.is_empty()
15        && sig.generics.params.is_empty()
16        && sig.generics.where_clause.is_none()
17        && matches!(&sig.output, ReturnType::Type(_,ty) if matches!(ty.as_ref(),Type::Path(p) if p.qself.is_none() && p.path.is_ident("u32")));
18    if !allowed {
19        return Err(syn::Error::new(
20            sig.span(),
21            "render_value requires fn name() -> u32",
22        ));
23    }
24    let [Stmt::Expr(expr, None)] = &f.block.stmts[..] else {
25        return Err(syn::Error::new(
26            f.block.span(),
27            "use one u32 expression of literals and operators",
28        ));
29    };
30    fn pure(expr: &Expr) -> bool {
31        match expr {
32            Expr::Lit(e) => {
33                e.attrs.is_empty()
34                    && matches!(&e.lit,Lit::Int(i) if matches!(i.suffix(), ""|"u32") && i.base10_parse::<u32>().is_ok())
35            }
36            Expr::Paren(e) => e.attrs.is_empty() && pure(&e.expr),
37            Expr::Unary(e) => e.attrs.is_empty() && matches!(e.op, UnOp::Not(_)) && pure(&e.expr),
38            Expr::Binary(e) => {
39                e.attrs.is_empty()
40                    && matches!(
41                        e.op,
42                        BinOp::Add(_)
43                            | BinOp::Sub(_)
44                            | BinOp::Mul(_)
45                            | BinOp::BitAnd(_)
46                            | BinOp::BitOr(_)
47                            | BinOp::BitXor(_)
48                            | BinOp::Shl(_)
49                            | BinOp::Shr(_)
50                    )
51                    && pure(&e.left)
52                    && pure(&e.right)
53            }
54            _ => false,
55        }
56    }
57    if !pure(expr) {
58        return Err(syn::Error::new(
59            expr.span(),
60            "render_value accepts only u32 literals and arithmetic or bitwise operators",
61        ));
62    }
63    Ok(())
64}
65
66/// Replaces only verified function bodies with a fixed marker. All other
67/// source bytes, including signatures and attributes, remain in the identity.
68/// Only top-level, absolutely qualified attributes are eligible.
69pub fn identity(source: &str) -> Option<String> {
70    let file = syn::parse_file(source).ok()?;
71    let mut bytes = source.to_owned();
72    let mut ranges = Vec::new();
73    for item in &file.items {
74        let Item::Fn(f) = item else { continue };
75        let [attr] = f.attrs.as_slice() else { continue };
76        let p = attr.path();
77        if p.leading_colon.is_none()
78            || p.segments.len() != 2
79            || p.segments[0].ident != "serge"
80            || p.segments[1].ident != "render_value"
81        {
82            continue;
83        }
84        check(f).ok()?;
85        ranges.push(f.block.brace_token.span.join().byte_range());
86    }
87    if ranges.is_empty() {
88        return None;
89    }
90    for range in ranges.into_iter().rev() {
91        if !source.get(range.clone())?.starts_with('{') {
92            return None;
93        }
94        bytes.replace_range(range, "{<serge-render-u32>}");
95    }
96    Some(bytes)
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    #[test]
103    fn only_literal_render_bodies_share_an_identity() {
104        let s = "#[::serge::render_value]\nfn size() -> u32 { 2+3 }\nfn main() {}";
105        assert_eq!(identity(s), identity(&s.replace("2+3", "17 * 9")));
106        assert!(identity(s).is_some());
107        assert_ne!(
108            identity(s),
109            identity(&s.replace("fn main()", "async fn main()"))
110        );
111        for expr in ["SOME_STATE", "vec![1].len()", "size()", "{ unsafe { 5 } }"] {
112            assert!(identity(&s.replace("2+3", expr)).is_none());
113        }
114    }
115}