Skip to main content

spark_derive/
lib.rs

1//! Proc macros for Spark.
2//!
3//! - `#[spark_component(template = "spark/counter")]` — on a struct: emits
4//!   Serialize/Deserialize/Default derives, the `Component` impl, the
5//!   `DynComponent` impl, and the `inventory::submit!` for `ComponentEntry`.
6//! - `#[spark_actions]` — on `impl Counter { … }`: scans the impl block for
7//!   `pub async fn`s (treated as actions), `#[spark_mount]`, `#[spark_on(…)]`,
8//!   `#[spark_updated(…)]`, and emits `DispatchEntry`, `ListenerEntry`,
9//!   `MountEntry` submissions plus a generated dispatcher function. The original
10//!   impl block is preserved (minus the marker attributes).
11//! - `#[spark_mount]`, `#[spark_on("event")]`, `#[spark_updated("field")]` —
12//!   marker attributes consumed by `#[spark_actions]`. On their own they
13//!   compile to a no-op (so `cargo check` works even if `#[spark_actions]` is
14//!   missing — the actions simply won't be registered).
15
16use proc_macro::TokenStream;
17use proc_macro2::TokenStream as TokenStream2;
18use quote::{format_ident, quote};
19use syn::parse::{Parse, ParseStream};
20use syn::punctuated::Punctuated;
21use syn::{
22    parse_macro_input, parse_quote, Attribute, FnArg, ImplItem, ImplItemFn, ItemImpl, ItemStruct,
23    Lit, LitStr, Meta, MetaNameValue, Pat, Token, Type,
24};
25
26// ─── #[spark_component(template = "spark/foo")] ────────────────────────────
27
28struct ComponentArgs {
29    template: String,
30}
31
32impl Parse for ComponentArgs {
33    fn parse(input: ParseStream) -> syn::Result<Self> {
34        let pairs: Punctuated<MetaNameValue, Token![,]> = Punctuated::parse_terminated(input)?;
35        let mut template = None;
36        for nv in pairs {
37            if nv.path.is_ident("template") {
38                if let syn::Expr::Lit(expr_lit) = &nv.value {
39                    if let Lit::Str(s) = &expr_lit.lit {
40                        template = Some(s.value());
41                    }
42                }
43            }
44        }
45        Ok(ComponentArgs {
46            template: template
47                .ok_or_else(|| syn::Error::new(input.span(), "expected `template = \"...\"`"))?,
48        })
49    }
50}
51
52#[proc_macro_attribute]
53pub fn component(args: TokenStream, input: TokenStream) -> TokenStream {
54    let args = parse_macro_input!(args as ComponentArgs);
55    let mut input = parse_macro_input!(input as ItemStruct);
56
57    // Collect field metadata before we strip Spark attributes.
58    let mut model_fields: Vec<(syn::Ident, Type)> = Vec::new();
59    let mut data_fields: Vec<syn::Ident> = Vec::new();
60    let mut skip_fields: Vec<syn::Ident> = Vec::new();
61
62    if let syn::Fields::Named(fields_named) = &mut input.fields {
63        for field in &mut fields_named.named {
64            let ident = field.ident.clone().expect("named field");
65            let ty = field.ty.clone();
66            let mut is_skip = false;
67            let mut is_model = false;
68            // Walk + strip #[spark(...)] attributes.
69            field.attrs.retain(|attr| {
70                if !attr.path().is_ident("spark") {
71                    return true;
72                }
73                if let Meta::List(list) = &attr.meta {
74                    let tokens: TokenStream2 = list.tokens.clone();
75                    let str = tokens.to_string();
76                    if str.contains("model") {
77                        is_model = true;
78                    }
79                    if str.contains("skip") {
80                        is_skip = true;
81                    }
82                }
83                false
84            });
85            if is_skip {
86                skip_fields.push(ident.clone());
87                // Ensure serde skips it too.
88                field.attrs.push(parse_quote!(#[serde(skip)]));
89            } else {
90                data_fields.push(ident.clone());
91            }
92            if is_model {
93                model_fields.push((ident.clone(), ty.clone()));
94            }
95        }
96    }
97
98    let struct_ident = input.ident.clone();
99    let template_path = args.template.clone();
100
101    // Inject `derive(Serialize, Deserialize, Default, Clone)` if not present.
102    let needed_derives = needed_derives(&input.attrs);
103    if !needed_derives.is_empty() {
104        let combined: TokenStream2 = needed_derives.iter().map(|p| quote!(#p,)).collect();
105        input.attrs.push(parse_quote!(#[derive(#combined)]));
106    }
107
108    let _ = data_fields;
109    let _ = skip_fields;
110
111    let model_arms: Vec<TokenStream2> = model_fields
112        .iter()
113        .map(|(name, ty)| {
114            let name_s = name.to_string();
115            quote! {
116                #name_s => {
117                    self.#name = ::spark::serde_json::from_value::<#ty>(write.value.clone())
118                        .map_err(|e| ::spark::Error::InvalidArguments {
119                            method: "apply_writes".into(),
120                            message: format!("field {}: {}", #name_s, e),
121                        })?;
122                }
123            }
124        })
125        .collect();
126
127    let class_name_literal = quote! {
128        ::std::concat!(::std::module_path!(), "::", ::std::stringify!(#struct_ident))
129    };
130
131    let dyn_impl = quote! {
132        impl ::spark::registry::DynComponent for #struct_ident {
133            fn as_any_mut(&mut self) -> &mut (dyn ::std::any::Any + ::std::marker::Send + ::std::marker::Sync) {
134                self
135            }
136
137            fn snapshot_data(&self) -> ::spark::serde_json::Value {
138                ::spark::serde_json::to_value(self).unwrap_or(::spark::serde_json::Value::Null)
139            }
140
141            fn render(&self) -> ::spark::Result<String> {
142                <Self as ::spark::Component>::render(self)
143            }
144
145            fn apply_writes<'a>(
146                &'a mut self,
147                writes: &'a [::spark::PropertyWrite],
148                ctx: &'a mut ::spark::Ctx,
149            ) -> ::std::pin::Pin<Box<dyn ::spark::futures::Future<Output = ::spark::Result<()>> + ::std::marker::Send + 'a>> {
150                Box::pin(<Self as ::spark::Component>::apply_writes(self, writes, ctx))
151            }
152
153            fn dispatch_call<'a>(
154                &'a mut self,
155                method: &'a str,
156                args: ::std::vec::Vec<::spark::serde_json::Value>,
157                ctx: &'a mut ::spark::Ctx,
158            ) -> ::std::pin::Pin<Box<dyn ::spark::futures::Future<Output = ::spark::Result<()>> + ::std::marker::Send + 'a>> {
159                Box::pin(<Self as ::spark::Component>::dispatch_call(self, method, args, ctx))
160            }
161        }
162    };
163
164    let component_impl = quote! {
165        #[::spark::async_trait::async_trait]
166        impl ::spark::Component for #struct_ident {
167            fn class_name() -> &'static str { #class_name_literal }
168            fn view_path() -> &'static str { #template_path }
169
170            fn listeners() -> ::std::vec::Vec<String> {
171                ::spark::registry::listeners_for(<Self as ::spark::Component>::class_name())
172            }
173
174            fn snapshot_data(&self) -> ::spark::serde_json::Value {
175                ::spark::serde_json::to_value(self).unwrap_or(::spark::serde_json::Value::Null)
176            }
177
178            fn load_snapshot(data: &::spark::serde_json::Value) -> ::spark::Result<Self> {
179                ::spark::serde_json::from_value::<Self>(data.clone())
180                    .map_err(|e| ::spark::Error::SnapshotDecode(format!("load_snapshot: {e}")))
181            }
182
183            fn mount(props: ::spark::MountProps) -> Self {
184                Self::default_then_props(props)
185            }
186
187            async fn apply_writes(
188                &mut self,
189                writes: &[::spark::PropertyWrite],
190                _ctx: &mut ::spark::Ctx,
191            ) -> ::spark::Result<()> {
192                for write in writes {
193                    match write.name.as_str() {
194                        #(#model_arms)*
195                        other => {
196                            ::tracing::debug!(
197                                field = other,
198                                class = <Self as ::spark::Component>::class_name(),
199                                "ignored property write for non-#[spark(model)] field"
200                            );
201                        }
202                    }
203                }
204                Ok(())
205            }
206
207            async fn dispatch_call(
208                &mut self,
209                method: &str,
210                args: ::std::vec::Vec<::spark::serde_json::Value>,
211                ctx: &mut ::spark::Ctx,
212            ) -> ::spark::Result<()> {
213                let class = <Self as ::spark::Component>::class_name();
214                if let Some(entry) = ::spark::registry::dispatcher_for(class) {
215                    let any: &mut (dyn ::std::any::Any + ::std::marker::Send + ::std::marker::Sync) = self;
216                    return (entry.dispatch)(any, method, args, ctx).await;
217                }
218                Err(::spark::Error::UnknownMethod {
219                    class: class.into(),
220                    method: method.into(),
221                })
222            }
223        }
224
225        impl #struct_ident {
226            #[doc(hidden)]
227            fn default_then_props(props: ::spark::MountProps) -> Self {
228                let class = <Self as ::spark::Component>::class_name();
229                if let Some(factory) = ::spark::registry::mount_factory_for(class) {
230                    let any_boxed: Box<dyn ::std::any::Any + ::std::marker::Send> = (factory)(props);
231                    match any_boxed.downcast::<Self>() {
232                        Ok(this) => return *this,
233                        Err(_) => return Self::default(),
234                    }
235                }
236                let _ = props;
237                Self::default()
238            }
239        }
240    };
241
242    let const_class = quote! {
243        ::std::concat!(::std::module_path!(), "::", ::std::stringify!(#struct_ident))
244    };
245    let const_view = LitStr::new(&template_path, proc_macro2::Span::call_site());
246
247    let component_entry = quote! {
248        fn __spark_mount_thunk(props: ::spark::MountProps) -> ::spark::BoxedComponent {
249            let inst: #struct_ident = <#struct_ident as ::spark::Component>::mount(props);
250            ::spark::BoxedComponent {
251                class: #const_class,
252                view: #const_view,
253                state: Box::new(inst),
254            }
255        }
256        fn __spark_load_thunk(data: &::spark::serde_json::Value) -> ::spark::Result<::spark::BoxedComponent> {
257            let inst = <#struct_ident as ::spark::Component>::load_snapshot(data)?;
258            Ok(::spark::BoxedComponent {
259                class: #const_class,
260                view: #const_view,
261                state: Box::new(inst),
262            })
263        }
264        fn __spark_listeners_thunk() -> ::std::vec::Vec<String> {
265            ::spark::registry::listeners_for(#const_class)
266        }
267        ::spark::inventory::submit! {
268            ::spark::registry::ComponentEntry {
269                class: #const_class,
270                view: #const_view,
271                listeners: __spark_listeners_thunk,
272                mount: __spark_mount_thunk,
273                load: __spark_load_thunk,
274            }
275        }
276    };
277
278    let expanded = quote! {
279        #input
280
281        #dyn_impl
282
283        #component_impl
284
285        const _: () = {
286            #component_entry
287        };
288    };
289
290    expanded.into()
291}
292
293fn needed_derives(attrs: &[Attribute]) -> Vec<syn::Path> {
294    let mut has_serialize = false;
295    let mut has_deserialize = false;
296    let mut has_default = false;
297    let mut has_clone = false;
298
299    for attr in attrs {
300        if attr.path().is_ident("derive") {
301            if let Meta::List(list) = &attr.meta {
302                let s = list.tokens.to_string();
303                if s.contains("Serialize") {
304                    has_serialize = true;
305                }
306                if s.contains("Deserialize") {
307                    has_deserialize = true;
308                }
309                if s.contains("Default") {
310                    has_default = true;
311                }
312                if s.contains("Clone") {
313                    has_clone = true;
314                }
315            }
316        }
317    }
318
319    let mut needed: Vec<syn::Path> = Vec::new();
320    if !has_serialize {
321        needed.push(parse_quote!(::spark::serde::Serialize));
322    }
323    if !has_deserialize {
324        needed.push(parse_quote!(::spark::serde::Deserialize));
325    }
326    if !has_default {
327        needed.push(parse_quote!(::std::default::Default));
328    }
329    if !has_clone {
330        needed.push(parse_quote!(::std::clone::Clone));
331    }
332    needed
333}
334
335// ─── #[spark_actions] on impl block ────────────────────────────────────────
336
337#[proc_macro_attribute]
338pub fn actions(_args: TokenStream, input: TokenStream) -> TokenStream {
339    let mut input = parse_macro_input!(input as ItemImpl);
340
341    let self_ty = match &*input.self_ty {
342        Type::Path(p) => p.path.clone(),
343        _ => {
344            return syn::Error::new_spanned(
345                &input.self_ty,
346                "#[spark_actions] requires a path self type, e.g. `impl Counter { ... }`",
347            )
348            .to_compile_error()
349            .into();
350        }
351    };
352    let struct_ident = match self_ty.segments.last() {
353        Some(seg) => seg.ident.clone(),
354        None => {
355            return syn::Error::new_spanned(
356                &input.self_ty,
357                "#[spark_actions] could not extract struct ident",
358            )
359            .to_compile_error()
360            .into();
361        }
362    };
363
364    // Walk the methods, classifying them.
365    let mut action_methods: Vec<ImplItemFn> = Vec::new();
366    let mut mount_method: Option<ImplItemFn> = None;
367    let mut on_methods: Vec<(String, ImplItemFn)> = Vec::new();
368    let mut updated_methods: Vec<(String, ImplItemFn)> = Vec::new();
369
370    for item in input.items.iter_mut() {
371        let ImplItem::Fn(method) = item else { continue };
372
373        let mut is_mount = false;
374        let mut on_event: Option<String> = None;
375        let mut updated_field: Option<String> = None;
376
377        // Strip marker attributes, recording what we saw. We accept either bare
378        // attribute names (`#[spark_mount]`) or qualified paths
379        // (`#[spark_derive::mount]`, `#[crate::spark_mount]`), keying on the
380        // *last* path segment.
381        method.attrs.retain(|attr| {
382            let last_seg = attr
383                .path()
384                .segments
385                .last()
386                .map(|s| s.ident.to_string())
387                .unwrap_or_default();
388            match last_seg.as_str() {
389                "spark_mount" | "mount" => {
390                    is_mount = true;
391                    false
392                }
393                "spark_on" | "on" => {
394                    if let Ok(s) = attr.parse_args::<LitStr>() {
395                        on_event = Some(s.value());
396                    }
397                    false
398                }
399                "spark_updated" | "updated" => {
400                    if let Ok(s) = attr.parse_args::<LitStr>() {
401                        updated_field = Some(s.value());
402                    }
403                    false
404                }
405                _ => true,
406            }
407        });
408
409        if is_mount {
410            mount_method = Some(method.clone());
411            continue;
412        }
413        if let Some(event) = on_event.clone() {
414            on_methods.push((event, method.clone()));
415            // Also expose as a regular action so the on_broadcast handler can route to it.
416            action_methods.push(method.clone());
417            continue;
418        }
419        if let Some(field) = updated_field.clone() {
420            updated_methods.push((field, method.clone()));
421            continue;
422        }
423
424        // Anything else that's `async fn name(&mut self, ...)` is an action.
425        if method.sig.asyncness.is_some() {
426            if let Some(FnArg::Receiver(rec)) = method.sig.inputs.first() {
427                if rec.mutability.is_some() {
428                    action_methods.push(method.clone());
429                }
430            }
431        }
432    }
433
434    // Build the dispatch function body.
435    let dispatch_arms: Vec<TokenStream2> = action_methods.iter().map(dispatch_arm_for).collect();
436
437    let on_arms: Vec<TokenStream2> = on_methods
438        .iter()
439        .map(|(event, m)| {
440            let method_ident = &m.sig.ident;
441            let event_lit = LitStr::new(event, proc_macro2::Span::call_site());
442            quote! {
443                #event_lit => {
444                    let _ = this.#method_ident().await;
445                }
446            }
447        })
448        .collect();
449
450    let on_events: Vec<String> = on_methods.iter().map(|(e, _)| e.clone()).collect();
451    let on_events_count = on_events.len();
452    let on_event_literals: Vec<LitStr> = on_events
453        .iter()
454        .map(|e| LitStr::new(e, proc_macro2::Span::call_site()))
455        .collect();
456
457    let updated_arms: Vec<TokenStream2> = updated_methods
458        .iter()
459        .map(|(field, m)| {
460            let method_ident = &m.sig.ident;
461            let field_lit = LitStr::new(field, proc_macro2::Span::call_site());
462            quote! {
463                if write_name == #field_lit {
464                    let this = any.downcast_mut::<#struct_ident>().expect("downcast");
465                    this.#method_ident();
466                }
467            }
468        })
469        .collect();
470
471    let _ = updated_arms; // currently unused; planned for v1.1.
472
473    let dispatch_fn_ident = format_ident!("__spark_dispatch_{}", struct_ident);
474    let listeners_fn_ident = format_ident!("__spark_listeners_{}", struct_ident);
475    let mount_fn_ident = format_ident!("__spark_mount_{}", struct_ident);
476
477    // Class name as a literal — must be evaluable in a `static` initializer.
478    let class_path = quote! {
479        ::std::concat!(::std::module_path!(), "::", ::std::stringify!(#struct_ident))
480    };
481
482    let dispatcher_block = quote! {
483        #[allow(non_camel_case_types)]
484        type __SparkSelfTy = #self_ty;
485
486        #[allow(non_snake_case)]
487        fn #dispatch_fn_ident<'a>(
488            any: &'a mut (dyn ::std::any::Any + ::std::marker::Send + ::std::marker::Sync),
489            method: &'a str,
490            args: ::std::vec::Vec<::spark::serde_json::Value>,
491            ctx: &'a mut ::spark::Ctx,
492        ) -> ::std::pin::Pin<Box<dyn ::spark::futures::Future<Output = ::spark::Result<()>> + ::std::marker::Send + 'a>>
493        {
494            Box::pin(async move {
495                let _ = ctx;
496                let _ = &args;
497                if method == "__on_broadcast" {
498                    let event_name: String = args.get(0)
499                        .and_then(|v| v.as_str())
500                        .map(String::from)
501                        .unwrap_or_default();
502                    let this = any.downcast_mut::<__SparkSelfTy>().expect("downcast");
503                    let _ = this;
504                    match event_name.as_str() {
505                        #(#on_arms)*
506                        _ => {}
507                    }
508                    return Ok(());
509                }
510                match method {
511                    #(#dispatch_arms)*
512                    other => {
513                        return Err(::spark::Error::UnknownMethod {
514                            class: #class_path.into(),
515                            method: other.into(),
516                        });
517                    }
518                }
519            })
520        }
521
522        #[inline]
523        fn __spark_into_err(e: ::spark::Error) -> ::spark::Error { e }
524
525        ::spark::inventory::submit! {
526            ::spark::registry::DispatchEntry {
527                class: #class_path,
528                dispatch: #dispatch_fn_ident,
529            }
530        }
531    };
532
533    let listeners_block = if on_events_count > 0 {
534        quote! {
535            #[allow(non_snake_case)]
536            fn #listeners_fn_ident() -> ::std::vec::Vec<String> {
537                vec![#(String::from(#on_event_literals)),*]
538            }
539            ::spark::inventory::submit! {
540                ::spark::registry::ListenerEntry {
541                    class: #class_path,
542                    events: #listeners_fn_ident,
543                }
544            }
545        }
546    } else {
547        quote! {}
548    };
549
550    let mount_block = if let Some(mount_method) = mount_method {
551        let method_ident = &mount_method.sig.ident;
552        quote! {
553            #[allow(non_snake_case)]
554            fn #mount_fn_ident(props: ::spark::MountProps) -> Box<dyn ::std::any::Any + ::std::marker::Send> {
555                let inst: #self_ty = #self_ty::#method_ident(props);
556                Box::new(inst)
557            }
558            ::spark::inventory::submit! {
559                ::spark::registry::MountEntry {
560                    class: #class_path,
561                    mount: #mount_fn_ident,
562                }
563            }
564        }
565    } else {
566        quote! {}
567    };
568
569    let expanded = quote! {
570        #input
571
572        const _: () = {
573            #dispatcher_block
574            #listeners_block
575            #mount_block
576        };
577    };
578
579    expanded.into()
580}
581
582fn dispatch_arm_for(method: &ImplItemFn) -> TokenStream2 {
583    let method_ident = &method.sig.ident;
584    let method_name = method_ident.to_string();
585    let method_name_lit = LitStr::new(&method_name, proc_macro2::Span::call_site());
586
587    // Extract non-receiver, non-Ctx params.
588    let mut typed_args: Vec<(syn::Ident, Type)> = Vec::new();
589    let mut takes_ctx = false;
590    for arg in method.sig.inputs.iter().skip(1) {
591        let FnArg::Typed(typed) = arg else { continue };
592        let ty = (*typed.ty).clone();
593        let Pat::Ident(ident_pat) = &*typed.pat else {
594            continue;
595        };
596        // Detect `ctx: &mut Ctx`.
597        if is_ctx_type(&ty) {
598            takes_ctx = true;
599            continue;
600        }
601        typed_args.push((ident_pat.ident.clone(), ty));
602    }
603
604    let arg_extractions: Vec<TokenStream2> = typed_args
605        .iter()
606        .enumerate()
607        .map(|(i, (name, ty))| {
608            let idx = i;
609            let name_str = name.to_string();
610            quote! {
611                let #name: #ty = match args.get(#idx) {
612                    Some(v) => ::spark::serde_json::from_value::<#ty>(v.clone())
613                        .map_err(|e| ::spark::Error::InvalidArguments {
614                            method: #method_name_lit.into(),
615                            message: format!("arg {}: {}", #name_str, e),
616                        })?,
617                    None => return Err(::spark::Error::InvalidArguments {
618                        method: #method_name_lit.into(),
619                        message: format!("missing arg {}", #name_str),
620                    }),
621                };
622            }
623        })
624        .collect();
625
626    let arg_names: Vec<TokenStream2> = typed_args.iter().map(|(n, _)| quote!(#n)).collect();
627
628    let call = if takes_ctx {
629        quote! { this.#method_ident(#(#arg_names,)* ctx).await }
630    } else {
631        quote! { this.#method_ident(#(#arg_names),*).await }
632    };
633
634    quote! {
635        #method_name_lit => {
636            let this = any.downcast_mut::<__SparkSelfTy>().expect("downcast");
637            #(#arg_extractions)*
638            let _ = ctx; // suppress unused
639            #call.map_err(__spark_into_err)?;
640            return Ok(());
641        }
642    }
643}
644
645fn is_ctx_type(ty: &Type) -> bool {
646    let s = quote!(#ty).to_string();
647    s.contains("Ctx")
648}
649
650// ─── Marker attributes (no-ops on their own) ───────────────────────────────
651
652#[proc_macro_attribute]
653pub fn mount(_args: TokenStream, input: TokenStream) -> TokenStream {
654    input
655}
656
657#[proc_macro_attribute]
658pub fn on(_args: TokenStream, input: TokenStream) -> TokenStream {
659    input
660}
661
662#[proc_macro_attribute]
663pub fn updated(_args: TokenStream, input: TokenStream) -> TokenStream {
664    input
665}