Skip to main content

xerv_macros/
lib.rs

1//! Procedural macros for XERV.
2//!
3//! This crate provides the following macros:
4//! - `#[xerv::node]` - Define a node with namespace and name
5//! - `#[xerv::schema]` - Derive schema metadata with stable layout
6//! - `#[xerv::pipeline]` - Define a pipeline controller
7
8use proc_macro::TokenStream;
9use proc_macro2::TokenStream as TokenStream2;
10use quote::{format_ident, quote};
11use syn::{Data, DeriveInput, Fields, Ident, ItemFn, LitStr, parse_macro_input};
12
13/// Marks a function as a XERV node.
14///
15/// # Attributes
16/// - `namespace`: The node namespace (e.g., "std", "plugins")
17/// - `name`: The node name (e.g., "switch", "fraud_model")
18///
19/// # Example
20///
21/// ```ignore
22/// #[xerv::node(namespace = "std", name = "slack_post")]
23/// pub async fn run(
24///     ctx: Context,
25///     cfg: SlackConfig,
26///     input: AlertInput
27/// ) -> Result<NodeOutput> {
28///     // Node logic here
29///     Ok(NodeOutput::out(ptr))
30/// }
31/// ```
32#[proc_macro_attribute]
33pub fn node(attr: TokenStream, item: TokenStream) -> TokenStream {
34    let args = parse_macro_input!(attr as NodeArgs);
35    let input_fn = parse_macro_input!(item as ItemFn);
36
37    let expanded = expand_node(args, input_fn);
38    TokenStream::from(expanded)
39}
40
41/// Derives schema metadata for a struct.
42///
43/// This macro:
44/// - Adds `#[repr(C)]` for stable memory layout
45/// - Generates compile-time offset constants
46/// - Implements the `Schema` trait
47/// - Registers the schema in the global registry
48///
49/// # Attributes
50/// - `version`: Schema version string (default: "v1")
51///
52/// # Example
53///
54/// ```ignore
55/// #[xerv::schema(version = "v1")]
56/// #[derive(Archive, Serialize, Deserialize)]
57/// pub struct FraudResult {
58///     pub score: f32,
59///     pub risk_level: u8,
60///     pub flags: u32,
61/// }
62/// ```
63#[proc_macro_attribute]
64pub fn schema(attr: TokenStream, item: TokenStream) -> TokenStream {
65    let args = parse_macro_input!(attr as SchemaArgs);
66    let input = parse_macro_input!(item as DeriveInput);
67
68    let expanded = expand_schema(args, input);
69    TokenStream::from(expanded)
70}
71
72/// Marks a struct as a XERV pipeline controller.
73///
74/// # Attributes
75/// - `name`: The pipeline name (e.g., "order_processor_v1")
76///
77/// # Example
78///
79/// ```ignore
80/// #[xerv::pipeline(name = "order_processor_v1")]
81/// pub struct OrderPipeline {
82///     config: ECommerceConfig,
83///     state: PipelineState,
84/// }
85/// ```
86#[proc_macro_attribute]
87pub fn pipeline(attr: TokenStream, item: TokenStream) -> TokenStream {
88    let args = parse_macro_input!(attr as PipelineArgs);
89    let input = parse_macro_input!(item as DeriveInput);
90
91    let expanded = expand_pipeline(args, input);
92    TokenStream::from(expanded)
93}
94
95// =============================================================================
96// Node Macro Implementation
97// =============================================================================
98
99struct NodeArgs {
100    namespace: String,
101    name: String,
102}
103
104impl syn::parse::Parse for NodeArgs {
105    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
106        let mut namespace = String::from("custom");
107        let mut name = String::new();
108
109        while !input.is_empty() {
110            let ident: Ident = input.parse()?;
111            input.parse::<syn::Token![=]>()?;
112
113            match ident.to_string().as_str() {
114                "namespace" => {
115                    let lit: LitStr = input.parse()?;
116                    namespace = lit.value();
117                }
118                "name" => {
119                    let lit: LitStr = input.parse()?;
120                    name = lit.value();
121                }
122                other => {
123                    return Err(syn::Error::new(
124                        ident.span(),
125                        format!("unknown attribute: {}", other),
126                    ));
127                }
128            }
129
130            if !input.is_empty() {
131                input.parse::<syn::Token![,]>()?;
132            }
133        }
134
135        if name.is_empty() {
136            return Err(syn::Error::new(
137                proc_macro2::Span::call_site(),
138                "missing required attribute: name",
139            ));
140        }
141
142        Ok(NodeArgs { namespace, name })
143    }
144}
145
146fn expand_node(args: NodeArgs, input_fn: ItemFn) -> TokenStream2 {
147    let _fn_name = &input_fn.sig.ident;
148    let fn_vis = &input_fn.vis;
149    let fn_block = &input_fn.block;
150    let fn_attrs = &input_fn.attrs;
151
152    let struct_name = format_ident!("{}Node", to_pascal_case(&args.name));
153    let factory_name = format_ident!("{}Factory", to_pascal_case(&args.name));
154    let namespace = &args.namespace;
155    let name = &args.name;
156    let full_name = format!("{}::{}", namespace, name);
157
158    // Extract parameter types from the function signature
159    let params: Vec<_> = input_fn.sig.inputs.iter().collect();
160
161    // We expect: (ctx: Context, cfg: ConfigType, input: InputType)
162    let (config_type, input_type) = if params.len() >= 3 {
163        let cfg_param = &params[1];
164        let input_param = &params[2];
165
166        let cfg_ty = extract_type(cfg_param);
167        let input_ty = extract_type(input_param);
168
169        (cfg_ty, input_ty)
170    } else {
171        (quote!(serde_yaml::Value), quote!(()))
172    };
173
174    quote! {
175        #(#fn_attrs)*
176        #fn_vis struct #struct_name {
177            config: #config_type,
178        }
179
180        impl #struct_name {
181            /// Create a new node instance with the given configuration.
182            pub fn new(config: #config_type) -> Self {
183                Self { config }
184            }
185        }
186
187        impl xerv_core::traits::Node for #struct_name {
188            fn info(&self) -> xerv_core::traits::NodeInfo {
189                xerv_core::traits::NodeInfo::new(#namespace, #name)
190                    .with_description(concat!("Node: ", #full_name))
191            }
192
193            fn execute<'a>(
194                &'a self,
195                ctx: xerv_core::traits::Context,
196                inputs: std::collections::HashMap<String, xerv_core::types::RelPtr<()>>,
197            ) -> xerv_core::traits::NodeFuture<'a> {
198                Box::pin(async move {
199                    let cfg = &self.config;
200                    let input = inputs.get("in").cloned().unwrap_or_else(|| {
201                        xerv_core::types::RelPtr::null()
202                    });
203
204                    // User's node logic
205                    let inner_fn = |ctx: xerv_core::traits::Context,
206                                    cfg: &#config_type,
207                                    input: xerv_core::types::RelPtr<#input_type>|
208                                    #fn_block;
209
210                    inner_fn(ctx, cfg, input.cast())
211                })
212            }
213        }
214
215        /// Factory for creating #struct_name instances.
216        #fn_vis struct #factory_name;
217
218        impl xerv_core::traits::NodeFactory for #factory_name {
219            fn node_type(&self) -> &str {
220                #full_name
221            }
222
223            fn create(&self, config: &serde_yaml::Value) -> xerv_core::error::Result<Box<dyn xerv_core::traits::Node>> {
224                let cfg: #config_type = serde_yaml::from_value(config.clone())
225                    .map_err(|e| xerv_core::error::XervError::ConfigValue {
226                        field: "config".to_string(),
227                        cause: e.to_string(),
228                    })?;
229                Ok(Box::new(#struct_name::new(cfg)))
230            }
231        }
232    }
233}
234
235fn extract_type(param: &syn::FnArg) -> TokenStream2 {
236    match param {
237        syn::FnArg::Typed(pat_type) => {
238            let ty = &pat_type.ty;
239            quote!(#ty)
240        }
241        _ => quote!(()),
242    }
243}
244
245fn to_pascal_case(s: &str) -> String {
246    s.split('_')
247        .map(|word| {
248            let mut chars = word.chars();
249            match chars.next() {
250                Some(first) => first.to_uppercase().chain(chars).collect(),
251                None => String::new(),
252            }
253        })
254        .collect()
255}
256
257// =============================================================================
258// Schema Macro Implementation
259// =============================================================================
260
261struct SchemaArgs {
262    version: String,
263}
264
265impl syn::parse::Parse for SchemaArgs {
266    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
267        let mut version = String::from("v1");
268
269        while !input.is_empty() {
270            let ident: Ident = input.parse()?;
271            input.parse::<syn::Token![=]>()?;
272
273            match ident.to_string().as_str() {
274                "version" => {
275                    let lit: LitStr = input.parse()?;
276                    version = lit.value();
277                }
278                other => {
279                    return Err(syn::Error::new(
280                        ident.span(),
281                        format!("unknown attribute: {}", other),
282                    ));
283                }
284            }
285
286            if !input.is_empty() {
287                input.parse::<syn::Token![,]>()?;
288            }
289        }
290
291        Ok(SchemaArgs { version })
292    }
293}
294
295fn expand_schema(args: SchemaArgs, mut input: DeriveInput) -> TokenStream2 {
296    let name = &input.ident;
297    let version = &args.version;
298    let version_num: u32 = version.trim_start_matches('v').parse().unwrap_or(1);
299    let hash_input = format!("{}@{}", name, version);
300
301    // Add #[repr(C)] attribute
302    let repr_c = syn::parse_quote!(#[repr(C)]);
303    input.attrs.push(repr_c);
304
305    // Extract field information
306    let fields = match &input.data {
307        Data::Struct(data_struct) => match &data_struct.fields {
308            Fields::Named(fields) => &fields.named,
309            _ => {
310                return syn::Error::new_spanned(
311                    &input,
312                    "xerv::schema only supports structs with named fields",
313                )
314                .to_compile_error();
315            }
316        },
317        _ => {
318            return syn::Error::new_spanned(&input, "xerv::schema only supports structs")
319                .to_compile_error();
320        }
321    };
322
323    // Generate offset constants
324    let offset_consts: Vec<_> = fields
325        .iter()
326        .map(|field| {
327            let field_name = field.ident.as_ref().unwrap();
328            let const_name = format_ident!("OFFSET_{}", field_name.to_string().to_uppercase());
329
330            quote! {
331                /// Byte offset of the `#field_name` field.
332                pub const #const_name: usize = std::mem::offset_of!(#name, #field_name);
333            }
334        })
335        .collect();
336
337    // Generate field info for Schema trait
338    let field_infos: Vec<_> = fields
339        .iter()
340        .map(|field| {
341            let field_name = field.ident.as_ref().unwrap().to_string();
342            let field_type = &field.ty;
343            let type_name = quote!(#field_type).to_string();
344
345            quote! {
346                xerv_core::traits::FieldInfo::new(#field_name, #type_name)
347                    .with_offset(std::mem::offset_of!(#name, #field_name))
348                    .with_size(std::mem::size_of::<#field_type>())
349            }
350        })
351        .collect();
352
353    let vis = &input.vis;
354    let attrs = &input.attrs;
355    let generics = &input.generics;
356    let data = &input.data;
357
358    // Reconstruct the struct with repr(C)
359    let struct_def = match data {
360        Data::Struct(data_struct) => {
361            let fields = &data_struct.fields;
362            quote! {
363                #(#attrs)*
364                #vis struct #name #generics #fields
365            }
366        }
367        _ => unreachable!(),
368    };
369
370    // Generate a hash from the struct name and version
371    let hash_value = simple_hash(&hash_input);
372
373    quote! {
374        #struct_def
375
376        impl #name {
377            #(#offset_consts)*
378        }
379
380        impl xerv_core::traits::Schema for #name {
381            fn type_info() -> xerv_core::traits::TypeInfo {
382                xerv_core::traits::TypeInfo::new(stringify!(#name), #version_num)
383                    .with_hash(#hash_value)
384                    .with_size(std::mem::size_of::<#name>())
385                    .with_alignment(std::mem::align_of::<#name>())
386                    .with_fields(vec![#(#field_infos),*])
387                    .stable()
388            }
389        }
390    }
391}
392
393/// Simple FNV-1a hash for generating schema hashes at compile time.
394fn simple_hash(s: &str) -> u64 {
395    const FNV_OFFSET: u64 = 0xcbf29ce484222325;
396    const FNV_PRIME: u64 = 0x100000001b3;
397
398    let mut hash = FNV_OFFSET;
399    for byte in s.bytes() {
400        hash ^= byte as u64;
401        hash = hash.wrapping_mul(FNV_PRIME);
402    }
403    hash
404}
405
406// =============================================================================
407// Pipeline Macro Implementation
408// =============================================================================
409
410struct PipelineArgs {
411    name: String,
412}
413
414impl syn::parse::Parse for PipelineArgs {
415    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
416        let mut name = String::new();
417
418        while !input.is_empty() {
419            let ident: Ident = input.parse()?;
420            input.parse::<syn::Token![=]>()?;
421
422            match ident.to_string().as_str() {
423                "name" => {
424                    let lit: LitStr = input.parse()?;
425                    name = lit.value();
426                }
427                other => {
428                    return Err(syn::Error::new(
429                        ident.span(),
430                        format!("unknown attribute: {}", other),
431                    ));
432                }
433            }
434
435            if !input.is_empty() {
436                input.parse::<syn::Token![,]>()?;
437            }
438        }
439
440        if name.is_empty() {
441            return Err(syn::Error::new(
442                proc_macro2::Span::call_site(),
443                "missing required attribute: name",
444            ));
445        }
446
447        Ok(PipelineArgs { name })
448    }
449}
450
451fn expand_pipeline(args: PipelineArgs, input: DeriveInput) -> TokenStream2 {
452    let struct_name = &input.ident;
453    let pipeline_name = &args.name;
454    let vis = &input.vis;
455    let attrs = &input.attrs;
456    let generics = &input.generics;
457
458    let fields = match &input.data {
459        Data::Struct(data_struct) => match &data_struct.fields {
460            Fields::Named(fields) => &fields.named,
461            _ => {
462                return syn::Error::new_spanned(
463                    &input,
464                    "xerv::pipeline only supports structs with named fields",
465                )
466                .to_compile_error();
467            }
468        },
469        _ => {
470            return syn::Error::new_spanned(&input, "xerv::pipeline only supports structs")
471                .to_compile_error();
472        }
473    };
474
475    // Look for config and state fields
476    let has_config = fields
477        .iter()
478        .any(|f| f.ident.as_ref().is_some_and(|i| i == "config"));
479    let has_state = fields
480        .iter()
481        .any(|f| f.ident.as_ref().is_some_and(|i| i == "state"));
482
483    let config_accessor = if has_config {
484        quote! {
485            /// Get a reference to the pipeline configuration.
486            pub fn config(&self) -> &impl std::any::Any {
487                &self.config
488            }
489        }
490    } else {
491        quote!()
492    };
493
494    let state_accessor = if has_state {
495        quote! {
496            /// Get the current pipeline state.
497            pub fn state(&self) -> &xerv_core::traits::PipelineState {
498                &self.state
499            }
500
501            /// Set the pipeline state.
502            pub fn set_state(&mut self, state: xerv_core::traits::PipelineState) {
503                self.state = state;
504            }
505        }
506    } else {
507        quote!()
508    };
509
510    quote! {
511        #(#attrs)*
512        #vis struct #struct_name #generics {
513            #fields
514        }
515
516        impl #struct_name {
517            /// Get the pipeline name.
518            pub const fn pipeline_name() -> &'static str {
519                #pipeline_name
520            }
521
522            #config_accessor
523            #state_accessor
524        }
525    }
526}