rullst-macros 12.3.0

Procedural and JSX-like compilation macros for the Rullst framework
Documentation
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#![cfg_attr(mutants, mutants::skip)]
extern crate proc_macro;

use proc_macro::TokenStream;
use syn::parse_macro_input;

#[cfg(test)]
mod billable_tests;
mod html_parser;
mod live_parser;
#[cfg(test)]
mod memoize_tests;
#[cfg(test)]
mod require_role_tests;
mod server_function;

/// A macro for writing HTML inline in Rust.
/// It compiles down to highly optimized string concatenations at compile time,
/// and automatically escapes dynamic variables to prevent XSS.
///
/// Dynamic URL attributes (`href`, `src`, `action`, …) render `#` for script or
/// non-media `data:` URLs; dynamic `style`/`on*` values are trusted-only.
///
/// # Example
///
/// This block is ignored only in the standalone proc-macro crate because the
/// expansion deliberately calls the `rullst::html` runtime and adding that
/// facade here would create a circular development dependency. The same dynamic
/// expansion is compiled and asserted in `rullst/tests/html_snapshot_tests.rs`.
///
/// ```rust,ignore
/// use rullst_macros::html;
///
/// let name = "Mundo";
/// let page = html! {
///     <div class="container">
///         <h1>"Olá, " {name} "!"</h1>
///     </div>
/// };
/// assert!(page.contains("Olá, Mundo!"));
/// ```
#[proc_macro]
pub fn html(input: TokenStream) -> TokenStream {
    let document = parse_macro_input!(input as html_parser::HtmlDocument);
    let expanded = document.to_tokens();
    expanded.into()
}

/// Proc macro attribute to define a Wasm Island client component.
///
/// It compiles dual versions depending on compilation targets:
/// - On native server compiles, it wraps the component's HTML output in a `<div data-island="..." data-props="...">`
/// - On wasm32-unknown-unknown compiles, it generates structural props parsing and registers a hydration function
///
/// Props that cannot be serialized to JSON leave `data-props` empty, so the
/// server HTML renders without hydration instead of panicking.
#[proc_macro_attribute]
#[allow(clippy::collapsible_if)]
pub fn island(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(item as syn::ItemFn);
    let vis = &input_fn.vis;
    let sig = &input_fn.sig;
    let name = &sig.ident;
    let body = &input_fn.block;

    // Extract argument names and types
    let mut arg_names = Vec::new();
    let mut arg_types = Vec::new();

    for arg in &sig.inputs {
        if let syn::FnArg::Typed(pat_type) = arg {
            if let syn::Pat::Ident(pat_ident) = &*pat_type.pat {
                arg_names.push(&pat_ident.ident);
                arg_types.push(&pat_type.ty);
            }
        }
    }

    let props_struct_name =
        syn::Ident::new(&format!("{}_Props", name), proc_macro2::Span::call_site());

    let hydrate_fn_name =
        syn::Ident::new(&format!("hydrate_{}", name), proc_macro2::Span::call_site());

    let expanded = quote::quote! {
        #[cfg(not(target_arch = "wasm32"))]
        #vis fn #name(#(#arg_names: #arg_types),*) -> String {
            let inner_html = {
                #body
            };

            // Props that cannot be represented as JSON (for example a u128
            // above u64::MAX) leave `data-props` empty, so the island renders
            // without hydration instead of panicking.
            let props_json = (|| -> ::core::result::Result<String, serde_json::Error> {
                let mut props = serde_json::Map::new();
                #(
                    props.insert(
                        stringify!(#arg_names).to_string(),
                        serde_json::to_value(&#arg_names)?,
                    );
                )*
                ::core::result::Result::Ok(serde_json::Value::Object(props).to_string())
            })()
            .unwrap_or_default();

            let escaped_props = rullst::html::escape_str(&props_json);

            format!(
                "<div data-island=\"{}\" data-props=\"{}\">{}</div>",
                stringify!(#name),
                escaped_props,
                inner_html
            )
        }

        #[cfg(target_arch = "wasm32")]
        #vis fn #name(#(#arg_names: #arg_types),*) -> String {
            let Some(element) = web_sys::window()
                .and_then(|w| w.document())
                .and_then(|d| d.create_element("div").ok())
            else {
                return String::new();
            };
            let _ = {
                #body
            };
            String::new()
        }

        #[cfg(target_arch = "wasm32")]
        #[derive(serde::Deserialize)]
        #[allow(non_camel_case_types)]
        struct #props_struct_name {
            #(#arg_names: #arg_types),*
        }

        #[cfg(target_arch = "wasm32")]
        #[wasm_bindgen::prelude::wasm_bindgen]
        #[allow(non_snake_case)]
        pub fn #hydrate_fn_name(element: web_sys::Element, props_json: &str) {
            let props: #props_struct_name = match serde_json::from_str(props_json) {
                Ok(p) => p,
                Err(_) => return,
            };

            #(let #arg_names = props.#arg_names;)*
            let element = element;

            let _ = {
                #body
            };
        }
    };

    expanded.into()
}

/// Proc macro attribute to define a Live Component.
/// Automatically implements the `LiveComponent` trait and wires `#[live_event]` methods.
///
/// Only the first present `rullst_event`, `action` or `event` string field
/// selects a handler, and at most one runs per message; other payload keys
/// and values, such as form inputs, never dispatch.
#[proc_macro_attribute]
pub fn live_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = item.into();
    live_parser::parse_live_component(input).into()
}

/// Marker attribute for events handled by a Live Component.
#[proc_macro_attribute]
pub fn live_event(_attr: TokenStream, item: TokenStream) -> TokenStream {
    item
}

/// A macro for intelligent caching of component renders or database queries.
/// It wraps a function, caching the returned output based on the function's arguments.
/// If the function is called again with the same arguments, it returns the cached HTML immediately.
///
/// Cache keys identify the annotated function by `module_path!()`, its name and
/// the attribute's `file!()`/`line!()`/`column!()`, so same-named functions in
/// different modules, crates or `impl` blocks never share cached results.
///
/// Results live in the bounded process-wide `rullst::cache::memory` store
/// (4,096 entries, 32 MiB, one hour each; oldest evicted first). A call whose
/// key plus serialized result exceeds 256 KiB, or whose arguments cannot be
/// serialized to JSON (e.g. a `u128` above `u64::MAX`), runs uncached.
#[proc_macro_attribute]
pub fn memoize(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(item as syn::ItemFn);
    expand_memoize(&input_fn).into()
}

fn expand_memoize(input_fn: &syn::ItemFn) -> proc_macro2::TokenStream {
    let vis = &input_fn.vis;
    let sig = &input_fn.sig;
    let name = &sig.ident;
    let body = &input_fn.block;
    let output_type = match &sig.output {
        syn::ReturnType::Default => quote::quote!(()),
        syn::ReturnType::Type(_, ty) => quote::quote!(#ty),
    };

    // Extract argument names
    let mut arg_names = Vec::new();
    let mut arg_types = Vec::new();
    for arg in &sig.inputs {
        if let syn::FnArg::Typed(pat_type) = arg
            && let syn::Pat::Ident(pat_ident) = &*pat_type.pat
        {
            arg_names.push(&pat_ident.ident);
            arg_types.push(&pat_type.ty);
        }
    }

    quote::quote! {
        #vis fn #name(#(#arg_names: #arg_types),*) -> #output_type {
            // The key combines a per-function identity with the serialized
            // arguments. `module_path!()` separates modules and crates; the
            // attribute's location separates same-named associated functions.
            // Arguments that cannot be represented as JSON (for example a u128
            // above u64::MAX) run the body uncached instead of panicking.
            let cache_key = (|| -> ::core::result::Result<serde_json::Value, serde_json::Error> {
                ::core::result::Result::Ok(serde_json::Value::Array(vec![
                    #(serde_json::to_value(&#arg_names)?),*
                ]))
            })()
            .ok()
            .map(|arguments| {
                format!(
                    "{}:{}",
                    concat!(
                        module_path!(),
                        "::",
                        stringify!(#name),
                        "@",
                        file!(),
                        ":",
                        line!(),
                        ":",
                        column!()
                    ),
                    arguments
                )
            });

            // Check if it exists in the global Rullst memory cache
            if let Some(cache_key) = &cache_key {
                if let Some(cached) = rullst::cache::memory::get(cache_key) {
                    // If it's a String (HTML output), we can downcast or deserialize it.
                    // For simplicity, we assume String return types.
                    if let Ok(cached_str) = serde_json::from_str::<#output_type>(&cached) {
                        return cached_str;
                    }
                }
            }

            // Otherwise, execute the function
            let result: #output_type = { #body };

            // Store it in the cache
            if let Some(cache_key) = &cache_key {
                if let Ok(serialized) = serde_json::to_string(&result) {
                    rullst::cache::memory::set(cache_key, &serialized);
                }
            }

            result
        }
    }
}

/// Legacy compatibility marker that preserves the annotated function unchanged.
///
/// Route registration is defined by the `routes!` macro in `rullst-core`. This attribute never
/// implemented path registration or content negotiation and is retained for one compatibility
/// cycle so existing code does not have its function signature rewritten unexpectedly.
#[deprecated(
    since = "12.0.0",
    note = "use rullst::routes! for route registration; this legacy marker will be removed"
)]
#[proc_macro_attribute]
pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {
    if attr.is_empty() {
        item
    } else {
        syn::Error::new(
            proc_macro2::Span::call_site(),
            "#[route] does not register paths; use rullst::routes! instead",
        )
        .into_compile_error()
        .into()
    }
}

/// Defines a bounded, dual-target Rullst server function.
///
/// The annotated item must be a concrete async free function with at most 16
/// identifier parameters and a `rullst::rpc::RpcResult<T>` return type. Native
/// builds retain its body and generate `<name>_rpc_router()`. Wasm builds
/// serialize the arguments into the versioned `rullst.client` envelope and call
/// the exact generated endpoint.
///
/// `path = "/api/rpc/..."` is optional; otherwise the final path segment is the
/// function name. Mount the generated router before applying Rullst's
/// production security and application identity/authorization layers.
#[proc_macro_attribute]
pub fn server_function(attr: TokenStream, item: TokenStream) -> TokenStream {
    match server_function::expand(attr.into(), item.into()) {
        Ok(expanded) => expanded.into(),
        Err(error) => error.into_compile_error().into(),
    }
}

#[proc_macro_attribute]
pub fn require_role(attr: TokenStream, item: TokenStream) -> TokenStream {
    let role = parse_macro_input!(attr as syn::LitStr);
    let input_fn = parse_macro_input!(item as syn::ItemFn);
    match expand_require_role(&role, &input_fn) {
        Ok(expanded) => expanded.into(),
        Err(error) => error.to_compile_error().into(),
    }
}

fn expand_require_role(
    role: &syn::LitStr,
    input_fn: &syn::ItemFn,
) -> Result<proc_macro2::TokenStream, syn::Error> {
    if input_fn.sig.asyncness.is_none() {
        return Err(syn::Error::new_spanned(
            input_fn.sig.fn_token,
            "#[require_role] supports async handlers only",
        ));
    }
    let role_value = role.value();
    if role_value.trim().is_empty()
        || role_value.chars().count() > 128
        || role_value.chars().any(char::is_control)
    {
        return Err(syn::Error::new_spanned(
            role,
            "#[require_role] needs a non-empty role of at most 128 characters without controls",
        ));
    }
    let has_user = input_fn.sig.inputs.iter().any(|argument| match argument {
        syn::FnArg::Receiver(_) => false,
        syn::FnArg::Typed(argument) => pattern_binds_user(&argument.pat),
    });
    if !has_user {
        return Err(syn::Error::new_spanned(
            &input_fn.sig.inputs,
            "#[require_role] requires a handler parameter that binds an authenticated `user`",
        ));
    }

    let attributes = &input_fn.attrs;
    let vis = &input_fn.vis;
    let mut signature = input_fn.sig.clone();
    signature.output = syn::parse_quote!(-> rullst::response::Response);
    let body = &input_fn.block;

    let expanded = quote::quote! {
        #(#attributes)*
        #vis #signature {
            if !rullst::auth::HasRole::has_role(&user, #role) {
                return rullst::response::IntoResponse::into_response((
                    rullst::http::StatusCode::FORBIDDEN,
                    "Forbidden: Insufficient privileges",
                ));
            }

            let result = async move { #body }.await;
            rullst::response::IntoResponse::into_response(result)
        }
    };
    Ok(expanded)
}

fn pattern_binds_user(pattern: &syn::Pat) -> bool {
    match pattern {
        syn::Pat::Ident(binding) => {
            binding.ident == "user"
                || binding
                    .subpat
                    .as_ref()
                    .is_some_and(|(_, pattern)| pattern_binds_user(pattern))
        }
        syn::Pat::Or(pattern) => pattern.cases.iter().any(pattern_binds_user),
        syn::Pat::Paren(pattern) => pattern_binds_user(&pattern.pat),
        syn::Pat::Reference(pattern) => pattern_binds_user(&pattern.pat),
        syn::Pat::Slice(pattern) => pattern.elems.iter().any(pattern_binds_user),
        syn::Pat::Struct(pattern) => pattern
            .fields
            .iter()
            .any(|field| pattern_binds_user(&field.pat)),
        syn::Pat::Tuple(pattern) => pattern.elems.iter().any(pattern_binds_user),
        syn::Pat::TupleStruct(pattern) => pattern.elems.iter().any(pattern_binds_user),
        syn::Pat::Type(pattern) => pattern_binds_user(&pattern.pat),
        _ => false,
    }
}

#[proc_macro_derive(Billable)]
pub fn derive_billable(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as syn::DeriveInput);
    match expand_billable(&input) {
        Ok(expanded) => expanded.into(),
        Err(error) => error.into_compile_error().into(),
    }
}

fn expand_billable(input: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let name = &input.ident;
    let syn::Data::Struct(data_struct) = &input.data else {
        return Err(syn::Error::new_spanned(
            input,
            "Billable can only be derived for a struct with named fields",
        ));
    };
    let syn::Fields::Named(fields) = &data_struct.fields else {
        return Err(syn::Error::new_spanned(
            &data_struct.fields,
            "Billable requires a struct with a named `email: String` field",
        ));
    };
    let has_field = |expected: &str| {
        fields
            .named
            .iter()
            .any(|field| field.ident.as_ref().is_some_and(|ident| ident == expected))
    };
    if !has_field("email") {
        return Err(syn::Error::new_spanned(
            fields,
            "Billable requires a named `email: String` field",
        ));
    }

    let sub_id_fn = if has_field("subscription_id") {
        quote::quote! {
            fn subscription_id(&self) -> Option<String> {
                self.subscription_id.clone()
            }
        }
    } else {
        quote::quote! {}
    };

    let tier_fn = if has_field("tier") {
        quote::quote! {
            fn tier(&self) -> Option<String> {
                self.tier.clone()
            }
        }
    } else {
        quote::quote! {}
    };

    let has_grace_start = has_field("grace_period_starts_at");
    let has_grace_end = has_field("grace_period_ends_at");
    if has_grace_start != has_grace_end {
        return Err(syn::Error::new_spanned(
            fields,
            "Billable grace periods require both `grace_period_starts_at: Option<i64>` and `grace_period_ends_at: Option<i64>`",
        ));
    }
    let grace_period_fn = if has_grace_start {
        quote::quote! {
            fn grace_period(
                &self,
            ) -> Result<Option<rullst::capital::GracePeriod>, rullst::capital::CapitalError> {
                match (self.grace_period_starts_at, self.grace_period_ends_at) {
                    (Some(starts_at), Some(ends_at)) => {
                        rullst::capital::GracePeriod::new(starts_at, ends_at).map(Some)
                    }
                    (None, None) => Ok(None),
                    _ => Err(rullst::capital::CapitalError::SubscriptionError(
                        "grace period requires both start and end timestamps".to_string(),
                    )),
                }
            }
        }
    } else {
        quote::quote! {}
    };

    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
    Ok(quote::quote! {
        impl #impl_generics rullst::capital::Billable for #name #type_generics #where_clause {
            fn email(&self) -> String {
                self.email.clone()
            }

            #sub_id_fn
            #tier_fn
            #grace_period_fn
        }
    })
}