anvilforge-spark-derive 0.3.10

Proc macros for Spark: #[derive(Spark)], #[spark::action], #[spark::mount], #[spark::updated], #[spark::on].
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! Proc macros for Spark.
//!
//! - `#[spark_component(template = "spark/counter")]` — on a struct: emits
//!   Serialize/Deserialize/Default derives, the `Component` impl, the
//!   `DynComponent` impl, and the `inventory::submit!` for `ComponentEntry`.
//! - `#[spark_actions]` — on `impl Counter { … }`: scans the impl block for
//!   `pub async fn`s (treated as actions), `#[spark_mount]`, `#[spark_on(…)]`,
//!   `#[spark_updated(…)]`, and emits `DispatchEntry`, `ListenerEntry`,
//!   `MountEntry` submissions plus a generated dispatcher function. The original
//!   impl block is preserved (minus the marker attributes).
//! - `#[spark_mount]`, `#[spark_on("event")]`, `#[spark_updated("field")]` —
//!   marker attributes consumed by `#[spark_actions]`. On their own they
//!   compile to a no-op (so `cargo check` works even if `#[spark_actions]` is
//!   missing — the actions simply won't be registered).

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{
    parse_macro_input, parse_quote, Attribute, FnArg, ImplItem, ImplItemFn, ItemImpl, ItemStruct,
    Lit, LitStr, Meta, MetaNameValue, Pat, Token, Type,
};

// ─── #[spark_component(template = "spark/foo")] ────────────────────────────

struct ComponentArgs {
    template: String,
}

impl Parse for ComponentArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let pairs: Punctuated<MetaNameValue, Token![,]> = Punctuated::parse_terminated(input)?;
        let mut template = None;
        for nv in pairs {
            if nv.path.is_ident("template") {
                if let syn::Expr::Lit(expr_lit) = &nv.value {
                    if let Lit::Str(s) = &expr_lit.lit {
                        template = Some(s.value());
                    }
                }
            }
        }
        Ok(ComponentArgs {
            template: template
                .ok_or_else(|| syn::Error::new(input.span(), "expected `template = \"...\"`"))?,
        })
    }
}

#[proc_macro_attribute]
pub fn component(args: TokenStream, input: TokenStream) -> TokenStream {
    let args = parse_macro_input!(args as ComponentArgs);
    let mut input = parse_macro_input!(input as ItemStruct);

    // Collect field metadata before we strip Spark attributes.
    let mut model_fields: Vec<(syn::Ident, Type)> = Vec::new();
    let mut data_fields: Vec<syn::Ident> = Vec::new();
    let mut skip_fields: Vec<syn::Ident> = Vec::new();

    if let syn::Fields::Named(fields_named) = &mut input.fields {
        for field in &mut fields_named.named {
            let ident = field.ident.clone().expect("named field");
            let ty = field.ty.clone();
            let mut is_skip = false;
            let mut is_model = false;
            // Walk + strip #[spark(...)] attributes.
            field.attrs.retain(|attr| {
                if !attr.path().is_ident("spark") {
                    return true;
                }
                if let Meta::List(list) = &attr.meta {
                    let tokens: TokenStream2 = list.tokens.clone();
                    let str = tokens.to_string();
                    if str.contains("model") {
                        is_model = true;
                    }
                    if str.contains("skip") {
                        is_skip = true;
                    }
                }
                false
            });
            if is_skip {
                skip_fields.push(ident.clone());
                // Ensure serde skips it too.
                field.attrs.push(parse_quote!(#[serde(skip)]));
            } else {
                data_fields.push(ident.clone());
            }
            if is_model {
                model_fields.push((ident.clone(), ty.clone()));
            }
        }
    }

    let struct_ident = input.ident.clone();
    let template_path = args.template.clone();

    // Inject `derive(Serialize, Deserialize, Default, Clone)` if not present.
    let needed_derives = needed_derives(&input.attrs);
    if !needed_derives.is_empty() {
        let combined: TokenStream2 = needed_derives.iter().map(|p| quote!(#p,)).collect();
        input.attrs.push(parse_quote!(#[derive(#combined)]));
    }

    let _ = data_fields;
    let _ = skip_fields;

    let model_arms: Vec<TokenStream2> = model_fields
        .iter()
        .map(|(name, ty)| {
            let name_s = name.to_string();
            quote! {
                #name_s => {
                    self.#name = ::spark::serde_json::from_value::<#ty>(write.value.clone())
                        .map_err(|e| ::spark::Error::InvalidArguments {
                            method: "apply_writes".into(),
                            message: format!("field {}: {}", #name_s, e),
                        })?;
                }
            }
        })
        .collect();

    let class_name_literal = quote! {
        ::std::concat!(::std::module_path!(), "::", ::std::stringify!(#struct_ident))
    };

    let dyn_impl = quote! {
        impl ::spark::registry::DynComponent for #struct_ident {
            fn as_any_mut(&mut self) -> &mut (dyn ::std::any::Any + ::std::marker::Send + ::std::marker::Sync) {
                self
            }

            fn snapshot_data(&self) -> ::spark::serde_json::Value {
                ::spark::serde_json::to_value(self).unwrap_or(::spark::serde_json::Value::Null)
            }

            fn render(&self) -> ::spark::Result<String> {
                <Self as ::spark::Component>::render(self)
            }

            fn apply_writes<'a>(
                &'a mut self,
                writes: &'a [::spark::PropertyWrite],
                ctx: &'a mut ::spark::Ctx,
            ) -> ::std::pin::Pin<Box<dyn ::spark::futures::Future<Output = ::spark::Result<()>> + ::std::marker::Send + 'a>> {
                Box::pin(<Self as ::spark::Component>::apply_writes(self, writes, ctx))
            }

            fn dispatch_call<'a>(
                &'a mut self,
                method: &'a str,
                args: ::std::vec::Vec<::spark::serde_json::Value>,
                ctx: &'a mut ::spark::Ctx,
            ) -> ::std::pin::Pin<Box<dyn ::spark::futures::Future<Output = ::spark::Result<()>> + ::std::marker::Send + 'a>> {
                Box::pin(<Self as ::spark::Component>::dispatch_call(self, method, args, ctx))
            }
        }
    };

    let component_impl = quote! {
        #[::spark::async_trait::async_trait]
        impl ::spark::Component for #struct_ident {
            fn class_name() -> &'static str { #class_name_literal }
            fn view_path() -> &'static str { #template_path }

            fn listeners() -> ::std::vec::Vec<String> {
                ::spark::registry::listeners_for(<Self as ::spark::Component>::class_name())
            }

            fn snapshot_data(&self) -> ::spark::serde_json::Value {
                ::spark::serde_json::to_value(self).unwrap_or(::spark::serde_json::Value::Null)
            }

            fn load_snapshot(data: &::spark::serde_json::Value) -> ::spark::Result<Self> {
                ::spark::serde_json::from_value::<Self>(data.clone())
                    .map_err(|e| ::spark::Error::SnapshotDecode(format!("load_snapshot: {e}")))
            }

            fn mount(props: ::spark::MountProps) -> Self {
                Self::default_then_props(props)
            }

            async fn apply_writes(
                &mut self,
                writes: &[::spark::PropertyWrite],
                _ctx: &mut ::spark::Ctx,
            ) -> ::spark::Result<()> {
                for write in writes {
                    match write.name.as_str() {
                        #(#model_arms)*
                        other => {
                            ::tracing::debug!(
                                field = other,
                                class = <Self as ::spark::Component>::class_name(),
                                "ignored property write for non-#[spark(model)] field"
                            );
                        }
                    }
                }
                Ok(())
            }

            async fn dispatch_call(
                &mut self,
                method: &str,
                args: ::std::vec::Vec<::spark::serde_json::Value>,
                ctx: &mut ::spark::Ctx,
            ) -> ::spark::Result<()> {
                let class = <Self as ::spark::Component>::class_name();
                if let Some(entry) = ::spark::registry::dispatcher_for(class) {
                    let any: &mut (dyn ::std::any::Any + ::std::marker::Send + ::std::marker::Sync) = self;
                    return (entry.dispatch)(any, method, args, ctx).await;
                }
                Err(::spark::Error::UnknownMethod {
                    class: class.into(),
                    method: method.into(),
                })
            }
        }

        impl #struct_ident {
            #[doc(hidden)]
            fn default_then_props(props: ::spark::MountProps) -> Self {
                let class = <Self as ::spark::Component>::class_name();
                if let Some(factory) = ::spark::registry::mount_factory_for(class) {
                    let any_boxed: Box<dyn ::std::any::Any + ::std::marker::Send> = (factory)(props);
                    match any_boxed.downcast::<Self>() {
                        Ok(this) => return *this,
                        Err(_) => return Self::default(),
                    }
                }
                let _ = props;
                Self::default()
            }
        }
    };

    let const_class = quote! {
        ::std::concat!(::std::module_path!(), "::", ::std::stringify!(#struct_ident))
    };
    let const_view = LitStr::new(&template_path, proc_macro2::Span::call_site());

    let component_entry = quote! {
        fn __spark_mount_thunk(props: ::spark::MountProps) -> ::spark::BoxedComponent {
            let inst: #struct_ident = <#struct_ident as ::spark::Component>::mount(props);
            ::spark::BoxedComponent {
                class: #const_class,
                view: #const_view,
                state: Box::new(inst),
            }
        }
        fn __spark_load_thunk(data: &::spark::serde_json::Value) -> ::spark::Result<::spark::BoxedComponent> {
            let inst = <#struct_ident as ::spark::Component>::load_snapshot(data)?;
            Ok(::spark::BoxedComponent {
                class: #const_class,
                view: #const_view,
                state: Box::new(inst),
            })
        }
        fn __spark_listeners_thunk() -> ::std::vec::Vec<String> {
            ::spark::registry::listeners_for(#const_class)
        }
        ::spark::inventory::submit! {
            ::spark::registry::ComponentEntry {
                class: #const_class,
                view: #const_view,
                listeners: __spark_listeners_thunk,
                mount: __spark_mount_thunk,
                load: __spark_load_thunk,
            }
        }
    };

    let expanded = quote! {
        #input

        #dyn_impl

        #component_impl

        const _: () = {
            #component_entry
        };
    };

    expanded.into()
}

fn needed_derives(attrs: &[Attribute]) -> Vec<syn::Path> {
    let mut has_serialize = false;
    let mut has_deserialize = false;
    let mut has_default = false;
    let mut has_clone = false;

    for attr in attrs {
        if attr.path().is_ident("derive") {
            if let Meta::List(list) = &attr.meta {
                let s = list.tokens.to_string();
                if s.contains("Serialize") {
                    has_serialize = true;
                }
                if s.contains("Deserialize") {
                    has_deserialize = true;
                }
                if s.contains("Default") {
                    has_default = true;
                }
                if s.contains("Clone") {
                    has_clone = true;
                }
            }
        }
    }

    let mut needed: Vec<syn::Path> = Vec::new();
    if !has_serialize {
        needed.push(parse_quote!(::spark::serde::Serialize));
    }
    if !has_deserialize {
        needed.push(parse_quote!(::spark::serde::Deserialize));
    }
    if !has_default {
        needed.push(parse_quote!(::std::default::Default));
    }
    if !has_clone {
        needed.push(parse_quote!(::std::clone::Clone));
    }
    needed
}

// ─── #[spark_actions] on impl block ────────────────────────────────────────

#[proc_macro_attribute]
pub fn actions(_args: TokenStream, input: TokenStream) -> TokenStream {
    let mut input = parse_macro_input!(input as ItemImpl);

    let self_ty = match &*input.self_ty {
        Type::Path(p) => p.path.clone(),
        _ => {
            return syn::Error::new_spanned(
                &input.self_ty,
                "#[spark_actions] requires a path self type, e.g. `impl Counter { ... }`",
            )
            .to_compile_error()
            .into();
        }
    };
    let struct_ident = match self_ty.segments.last() {
        Some(seg) => seg.ident.clone(),
        None => {
            return syn::Error::new_spanned(
                &input.self_ty,
                "#[spark_actions] could not extract struct ident",
            )
            .to_compile_error()
            .into();
        }
    };

    // Walk the methods, classifying them.
    let mut action_methods: Vec<ImplItemFn> = Vec::new();
    let mut mount_method: Option<ImplItemFn> = None;
    let mut on_methods: Vec<(String, ImplItemFn)> = Vec::new();
    let mut updated_methods: Vec<(String, ImplItemFn)> = Vec::new();

    for item in input.items.iter_mut() {
        let ImplItem::Fn(method) = item else { continue };

        let mut is_mount = false;
        let mut on_event: Option<String> = None;
        let mut updated_field: Option<String> = None;

        // Strip marker attributes, recording what we saw. We accept either bare
        // attribute names (`#[spark_mount]`) or qualified paths
        // (`#[spark_derive::mount]`, `#[crate::spark_mount]`), keying on the
        // *last* path segment.
        method.attrs.retain(|attr| {
            let last_seg = attr
                .path()
                .segments
                .last()
                .map(|s| s.ident.to_string())
                .unwrap_or_default();
            match last_seg.as_str() {
                "spark_mount" | "mount" => {
                    is_mount = true;
                    false
                }
                "spark_on" | "on" => {
                    if let Ok(s) = attr.parse_args::<LitStr>() {
                        on_event = Some(s.value());
                    }
                    false
                }
                "spark_updated" | "updated" => {
                    if let Ok(s) = attr.parse_args::<LitStr>() {
                        updated_field = Some(s.value());
                    }
                    false
                }
                _ => true,
            }
        });

        if is_mount {
            mount_method = Some(method.clone());
            continue;
        }
        if let Some(event) = on_event.clone() {
            on_methods.push((event, method.clone()));
            // Also expose as a regular action so the on_broadcast handler can route to it.
            action_methods.push(method.clone());
            continue;
        }
        if let Some(field) = updated_field.clone() {
            updated_methods.push((field, method.clone()));
            continue;
        }

        // Anything else that's `async fn name(&mut self, ...)` is an action.
        if method.sig.asyncness.is_some() {
            if let Some(FnArg::Receiver(rec)) = method.sig.inputs.first() {
                if rec.mutability.is_some() {
                    action_methods.push(method.clone());
                }
            }
        }
    }

    // Build the dispatch function body.
    let dispatch_arms: Vec<TokenStream2> = action_methods.iter().map(dispatch_arm_for).collect();

    let on_arms: Vec<TokenStream2> = on_methods
        .iter()
        .map(|(event, m)| {
            let method_ident = &m.sig.ident;
            let event_lit = LitStr::new(event, proc_macro2::Span::call_site());
            quote! {
                #event_lit => {
                    let _ = this.#method_ident().await;
                }
            }
        })
        .collect();

    let on_events: Vec<String> = on_methods.iter().map(|(e, _)| e.clone()).collect();
    let on_events_count = on_events.len();
    let on_event_literals: Vec<LitStr> = on_events
        .iter()
        .map(|e| LitStr::new(e, proc_macro2::Span::call_site()))
        .collect();

    let updated_arms: Vec<TokenStream2> = updated_methods
        .iter()
        .map(|(field, m)| {
            let method_ident = &m.sig.ident;
            let field_lit = LitStr::new(field, proc_macro2::Span::call_site());
            quote! {
                if write_name == #field_lit {
                    let this = any.downcast_mut::<#struct_ident>().expect("downcast");
                    this.#method_ident();
                }
            }
        })
        .collect();

    let _ = updated_arms; // currently unused; planned for v1.1.

    let dispatch_fn_ident = format_ident!("__spark_dispatch_{}", struct_ident);
    let listeners_fn_ident = format_ident!("__spark_listeners_{}", struct_ident);
    let mount_fn_ident = format_ident!("__spark_mount_{}", struct_ident);

    // Class name as a literal — must be evaluable in a `static` initializer.
    let class_path = quote! {
        ::std::concat!(::std::module_path!(), "::", ::std::stringify!(#struct_ident))
    };

    let dispatcher_block = quote! {
        #[allow(non_camel_case_types)]
        type __SparkSelfTy = #self_ty;

        #[allow(non_snake_case)]
        fn #dispatch_fn_ident<'a>(
            any: &'a mut (dyn ::std::any::Any + ::std::marker::Send + ::std::marker::Sync),
            method: &'a str,
            args: ::std::vec::Vec<::spark::serde_json::Value>,
            ctx: &'a mut ::spark::Ctx,
        ) -> ::std::pin::Pin<Box<dyn ::spark::futures::Future<Output = ::spark::Result<()>> + ::std::marker::Send + 'a>>
        {
            Box::pin(async move {
                let _ = ctx;
                let _ = &args;
                if method == "__on_broadcast" {
                    let event_name: String = args.get(0)
                        .and_then(|v| v.as_str())
                        .map(String::from)
                        .unwrap_or_default();
                    let this = any.downcast_mut::<__SparkSelfTy>().expect("downcast");
                    let _ = this;
                    match event_name.as_str() {
                        #(#on_arms)*
                        _ => {}
                    }
                    return Ok(());
                }
                match method {
                    #(#dispatch_arms)*
                    other => {
                        return Err(::spark::Error::UnknownMethod {
                            class: #class_path.into(),
                            method: other.into(),
                        });
                    }
                }
            })
        }

        #[inline]
        fn __spark_into_err(e: ::spark::Error) -> ::spark::Error { e }

        ::spark::inventory::submit! {
            ::spark::registry::DispatchEntry {
                class: #class_path,
                dispatch: #dispatch_fn_ident,
            }
        }
    };

    let listeners_block = if on_events_count > 0 {
        quote! {
            #[allow(non_snake_case)]
            fn #listeners_fn_ident() -> ::std::vec::Vec<String> {
                vec![#(String::from(#on_event_literals)),*]
            }
            ::spark::inventory::submit! {
                ::spark::registry::ListenerEntry {
                    class: #class_path,
                    events: #listeners_fn_ident,
                }
            }
        }
    } else {
        quote! {}
    };

    let mount_block = if let Some(mount_method) = mount_method {
        let method_ident = &mount_method.sig.ident;
        quote! {
            #[allow(non_snake_case)]
            fn #mount_fn_ident(props: ::spark::MountProps) -> Box<dyn ::std::any::Any + ::std::marker::Send> {
                let inst: #self_ty = #self_ty::#method_ident(props);
                Box::new(inst)
            }
            ::spark::inventory::submit! {
                ::spark::registry::MountEntry {
                    class: #class_path,
                    mount: #mount_fn_ident,
                }
            }
        }
    } else {
        quote! {}
    };

    let expanded = quote! {
        #input

        const _: () = {
            #dispatcher_block
            #listeners_block
            #mount_block
        };
    };

    expanded.into()
}

fn dispatch_arm_for(method: &ImplItemFn) -> TokenStream2 {
    let method_ident = &method.sig.ident;
    let method_name = method_ident.to_string();
    let method_name_lit = LitStr::new(&method_name, proc_macro2::Span::call_site());

    // Extract non-receiver, non-Ctx params.
    let mut typed_args: Vec<(syn::Ident, Type)> = Vec::new();
    let mut takes_ctx = false;
    for arg in method.sig.inputs.iter().skip(1) {
        let FnArg::Typed(typed) = arg else { continue };
        let ty = (*typed.ty).clone();
        let Pat::Ident(ident_pat) = &*typed.pat else {
            continue;
        };
        // Detect `ctx: &mut Ctx`.
        if is_ctx_type(&ty) {
            takes_ctx = true;
            continue;
        }
        typed_args.push((ident_pat.ident.clone(), ty));
    }

    let arg_extractions: Vec<TokenStream2> = typed_args
        .iter()
        .enumerate()
        .map(|(i, (name, ty))| {
            let idx = i;
            let name_str = name.to_string();
            quote! {
                let #name: #ty = match args.get(#idx) {
                    Some(v) => ::spark::serde_json::from_value::<#ty>(v.clone())
                        .map_err(|e| ::spark::Error::InvalidArguments {
                            method: #method_name_lit.into(),
                            message: format!("arg {}: {}", #name_str, e),
                        })?,
                    None => return Err(::spark::Error::InvalidArguments {
                        method: #method_name_lit.into(),
                        message: format!("missing arg {}", #name_str),
                    }),
                };
            }
        })
        .collect();

    let arg_names: Vec<TokenStream2> = typed_args.iter().map(|(n, _)| quote!(#n)).collect();

    let call = if takes_ctx {
        quote! { this.#method_ident(#(#arg_names,)* ctx).await }
    } else {
        quote! { this.#method_ident(#(#arg_names),*).await }
    };

    quote! {
        #method_name_lit => {
            let this = any.downcast_mut::<__SparkSelfTy>().expect("downcast");
            #(#arg_extractions)*
            let _ = ctx; // suppress unused
            #call.map_err(__spark_into_err)?;
            return Ok(());
        }
    }
}

fn is_ctx_type(ty: &Type) -> bool {
    let s = quote!(#ty).to_string();
    s.contains("Ctx")
}

// ─── Marker attributes (no-ops on their own) ───────────────────────────────

#[proc_macro_attribute]
pub fn mount(_args: TokenStream, input: TokenStream) -> TokenStream {
    input
}

#[proc_macro_attribute]
pub fn on(_args: TokenStream, input: TokenStream) -> TokenStream {
    input
}

#[proc_macro_attribute]
pub fn updated(_args: TokenStream, input: TokenStream) -> TokenStream {
    input
}