mecha10-macros 4.2.9

Procedural macros for the Mecha10 robotics 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
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
//! Mecha10 Procedural Macros
//!
//! This crate provides derive macros to reduce boilerplate in Mecha10 configuration structs.

use darling::FromDeriveInput;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput, Fields, Meta};

/// Derive macro for automatic config defaults
///
/// This macro eliminates the need for manual `default_*()` functions and
/// manual `Default` implementation.
///
/// # Attributes
///
/// - `#[config(default = value)]` - Specifies the default value for a field
/// - Fields without `#[config(default)]` will use `Default::default()` or `None` for Option types
///
/// # Example
///
/// ## Before (Manual approach):
///
/// ```ignore
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// pub struct CameraConfig {
///     #[serde(default = "default_fps")]
///     pub fps: f32,
///
///     #[serde(default = "default_width")]
///     pub width: u32,
///
///     pub device: Option<String>,
/// }
///
/// fn default_fps() -> f32 { 30.0 }
/// fn default_width() -> u32 { 640 }
///
/// impl Default for CameraConfig {
///     fn default() -> Self {
///         Self {
///             fps: default_fps(),
///             width: default_width(),
///             device: None,
///         }
///     }
/// }
/// ```
///
/// ## After (Using ConfigDefaults):
///
/// ```ignore
/// use mecha10_macros::ConfigDefaults;
///
/// #[derive(Debug, Clone, Serialize, Deserialize, ConfigDefaults)]
/// #[config_defaults]
/// pub struct CameraConfig {
///     #[serde(default = "CameraConfig::default_fps")]
///     #[config(default = 30.0)]
///     pub fps: f32,
///
///     #[serde(default = "CameraConfig::default_width")]
///     #[config(default = 640)]
///     pub width: u32,
///
///     pub device: Option<String>,
/// }
/// ```
///
/// This generates:
/// - Associated functions `default_fps()`, `default_width()` in the `impl` block
/// - A `Default` trait implementation
///
/// You still need the `#[serde(default = "TypeName::default_field")]` attribute,
/// but the actual default functions and Default impl are generated for you.
#[proc_macro_derive(ConfigDefaults, attributes(config))]
pub fn derive_config_defaults(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;

    let fields = match &input.data {
        Data::Struct(data) => match &data.fields {
            Fields::Named(fields) => &fields.named,
            _ => {
                return syn::Error::new_spanned(&input, "ConfigDefaults only supports structs with named fields")
                    .to_compile_error()
                    .into();
            }
        },
        _ => {
            return syn::Error::new_spanned(&input, "ConfigDefaults only supports structs")
                .to_compile_error()
                .into();
        }
    };

    let mut default_fns = Vec::new();
    let mut field_inits = Vec::new();

    for field in fields {
        let field_name = field.ident.as_ref().unwrap();
        let field_type = &field.ty;

        let default_value = field.attrs.iter().find_map(|attr| {
            if !attr.path().is_ident("config") {
                return None;
            }

            attr.parse_args::<Meta>().ok().and_then(|meta| match meta {
                Meta::NameValue(nv) if nv.path.is_ident("default") => Some(nv.value),
                _ => None,
            })
        });

        if let Some(default_val) = default_value {
            let default_fn_name = syn::Ident::new(&format!("default_{}", field_name), field_name.span());

            default_fns.push(quote! {
                pub fn #default_fn_name() -> #field_type {
                    #default_val
                }
            });

            field_inits.push(quote! {
                #field_name: Self::#default_fn_name()
            });
        } else {
            let is_option = is_option_type(field_type);

            if is_option {
                field_inits.push(quote! {
                    #field_name: None
                });
            } else {
                field_inits.push(quote! {
                    #field_name: Default::default()
                });
            }
        }
    }

    let expanded = quote! {
        impl #name {
            #(#default_fns)*
        }

        impl Default for #name {
            fn default() -> Self {
                Self {
                    #(#field_inits),*
                }
            }
        }
    };

    TokenStream::from(expanded)
}

/// Check if a type is Option<T>
fn is_option_type(ty: &syn::Type) -> bool {
    if let syn::Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            return segment.ident == "Option";
        }
    }
    false
}

/// Derive macro for automatic configuration loading
///
/// This macro generates methods to load configuration from files or environment
/// variables with minimal boilerplate. Each generated method resolves from exactly
/// one declared source and fails loudly (no silent fallthrough to another source or
/// to a built-in default) when that source doesn't resolve.
///
/// # Attributes
///
/// - `#[config(path = "path/to/config.yaml")]` - Default config file path
/// - `#[config(env_prefix = "MYAPP")]` - Environment variable prefix for loading from env
/// - `#[config(env_var = "MYAPP_CONFIG")]` - Environment variable for config file path override
///
/// # Example
///
/// ```ignore
/// use mecha10_macros::Config;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Clone, Serialize, Deserialize, Config)]
/// #[config(
///     path = "config/camera.yaml",
///     env_prefix = "CAMERA",
///     env_var = "CAMERA_CONFIG"
/// )]
/// pub struct CameraConfig {
///     pub fps: f32,
///     pub width: u32,
///     pub device: Option<String>,
/// }
///
/// // Generated methods:
/// // - CameraConfig::load() -> Result<Self>
/// // - CameraConfig::load_from_file(path: &str) -> Result<Self>
/// // - CameraConfig::load_from_env() -> Result<Self>
/// ```
///
/// ## Usage:
///
/// ```ignore
/// // Load from env var CAMERA_CONFIG if set, else the default path
/// // (config/camera.yaml). Errors immediately if neither resolves -- it does
/// // not fall through to environment-variable overrides or a built-in default.
/// let config = CameraConfig::load()?;
///
/// // Load from specific file
/// let config = CameraConfig::load_from_file("custom.yaml")?;
///
/// // Load from environment variables (CAMERA_FPS, CAMERA_WIDTH, CAMERA_DEVICE)
/// let config = CameraConfig::load_from_env()?;
/// ```
#[proc_macro_derive(Config, attributes(config))]
pub fn derive_config(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;

    let mut default_path = None;
    let mut env_prefix = None;
    let mut env_var = None;

    for attr in &input.attrs {
        if !attr.path().is_ident("config") {
            continue;
        }

        if let Ok(Meta::List(meta_list)) = attr.parse_args::<Meta>() {
            let nested = meta_list.tokens.to_string();

            for item in nested.split(',') {
                let item = item.trim();
                if let Some(value) = item.strip_prefix("path = ") {
                    default_path = Some(value.trim_matches('"').to_string());
                } else if let Some(value) = item.strip_prefix("env_prefix = ") {
                    env_prefix = Some(value.trim_matches('"').to_string());
                } else if let Some(value) = item.strip_prefix("env_var = ") {
                    env_var = Some(value.trim_matches('"').to_string());
                }
            }
        }
    }

    let default_path = default_path.unwrap_or_else(|| format!("config/{}.yaml", name.to_string().to_lowercase()));
    let env_prefix = env_prefix.unwrap_or_else(|| name.to_string().to_uppercase());
    let env_var = env_var.unwrap_or_else(|| format!("{}_CONFIG", name.to_string().to_uppercase()));

    let expanded = quote! {
        impl #name {
            /// Load configuration using the default strategy:
            /// 1. Try environment variable for config file path
            /// 2. Try default config file path
            /// 3. Return error if neither exists
            pub fn load() -> ::mecha10_core::Result<Self> {
                use ::mecha10_core::config::load_config;
                use std::env;
                use std::path::Path;

                if let Ok(path) = env::var(#env_var) {
                    return load_config(&path);
                }

                if Path::new(#default_path).exists() {
                    return load_config(#default_path);
                }

                Err(::mecha10_core::Mecha10Error::Configuration(format!(
                    "No configuration found for {}. Tried: env var {}, file {}",
                    stringify!(#name),
                    #env_var,
                    #default_path
                )))
            }

            /// Load configuration from a specific file path
            ///
            /// Supports JSON, YAML, and TOML files based on extension.
            /// Environment variable substitution is supported with `${VAR_NAME}` syntax.
            pub fn load_from_file(path: &str) -> ::mecha10_core::Result<Self> {
                ::mecha10_core::config::load_config(path)
            }

            /// Load configuration from environment variables
            ///
            /// Uses the configured prefix to find environment variables.
            /// For example, with prefix "CAMERA", looks for CAMERA_FPS, CAMERA_WIDTH, etc.
            pub fn load_from_env() -> ::mecha10_core::Result<Self> {
                ::mecha10_core::config::load_config_from_env(#env_prefix)
            }

            /// Get the default configuration file path
            pub fn default_config_path() -> &'static str {
                #default_path
            }

            /// Get the environment variable name for config file override
            pub fn config_env_var() -> &'static str {
                #env_var
            }

            /// Get the environment variable prefix for loading from env
            pub fn env_prefix() -> &'static str {
                #env_prefix
            }
        }
    };

    TokenStream::from(expanded)
}

/// Derive macro for automatic node boilerplate generation
///
/// This macro generates a `run()` function that handles:
/// - Configuration loading with fallback
/// - Context creation
/// - Instance support (optional)
/// - Health reporting configuration with priority levels
///
/// # Attributes
///
/// - `#[node(name = "node_name")]` - Node name (required)
/// - `#[node(instance_env = "NODE_INSTANCE")]` - Environment variable for instance name (optional, enables multi-instance support)
/// - `#[node(health_priority = "normal")]` - Health reporting priority (optional, defaults to "normal")
///   - `"critical"` - 1s interval, 5s TTL (motor-controller, estop, safety nodes)
///   - `"normal"` - 5s interval, 60s TTL (default, sensors, AI nodes)
///   - `"background"` - 30s interval, 120s TTL (logging, diagnostics)
///
/// # Example - Simple Node
///
/// ```ignore
/// use mecha10::prelude::*;
///
/// #[derive(Debug, Node)]
/// #[node(name = "camera")]
/// pub struct CameraNode {
///     config: CameraConfig,
/// }
///
/// #[derive(Debug, Clone, Serialize, Deserialize, Default)]
/// pub struct CameraConfig {
///     pub fps: f32,
/// }
///
/// #[async_trait]
/// impl NodeImpl for CameraNode {
///     type Config = CameraConfig;
///
///     async fn init(config: Self::Config) -> Result<Self> {
///         Ok(Self { config })
///     }
///
///     async fn run(&mut self, ctx: &Context) -> Result<()> {
///         // Node logic here
///         Ok(())
///     }
/// }
///
/// // The macro generates:
/// // pub async fn run() -> ::mecha10_core::Result<()> { ... }
/// ```
///
/// # Example - Critical Node (Safety-Critical)
///
/// ```ignore
/// use mecha10::prelude::*;
///
/// #[derive(Debug, Node)]
/// #[node(
///     name = "motor-controller",
///     health_priority = "critical"  // 1s heartbeat for safety nodes
/// )]
/// pub struct MotorControllerNode { ... }
/// ```
///
/// # Example - Background Node (Auxiliary)
///
/// ```ignore
/// use mecha10::prelude::*;
///
/// #[derive(Debug, Node)]
/// #[node(
///     name = "diagnostics",
///     health_priority = "background"  // 30s heartbeat for background nodes
/// )]
/// pub struct DiagnosticsNode { ... }
/// ```
///
/// # Example - Multi-Instance Node
///
/// ```ignore
/// use mecha10::prelude::*;
///
/// #[derive(Debug, Node)]
/// #[node(
///     name = "camera",
///     instance_env = "CAMERA_INSTANCE"  // Enables multi-instance support
/// )]
/// pub struct CameraNode { ... }
///
/// // Run with: CAMERA_INSTANCE=left ./camera
/// // Creates node "camera/left" with instance-scoped topics
/// ```
///
/// # Generated Code
///
/// The macro generates a `run()` function that:
/// 1. Loads config using the V2 config system with environment-aware fallback
/// 2. Creates a Context with the node name
/// 3. Optionally applies instance name from environment variable
/// 4. Calls `run_node()` with configured health reporting priority
///
/// This eliminates 15-20 lines of boilerplate per node.
#[proc_macro_derive(Node, attributes(node))]
pub fn derive_node(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let opts = match NodeOpts::from_derive_input(&input) {
        Ok(opts) => opts,
        Err(e) => return e.write_errors().into(),
    };

    let node_type = &input.ident;
    let node_name = &opts.name;

    let health_config = match opts.health_priority.as_deref() {
        Some("critical") => quote! {
            ::mecha10_core::node::HealthReportingConfig::critical()
        },
        Some("background") => quote! {
            ::mecha10_core::node::HealthReportingConfig::background()
        },
        Some("normal") | None => quote! {
            ::mecha10_core::node::HealthReportingConfig::default()
        },
        Some(other) => {
            return syn::Error::new_spanned(
                &input,
                format!(
                    "Invalid health_priority '{}'. Valid values: 'critical', 'normal', 'background'",
                    other
                ),
            )
            .to_compile_error()
            .into();
        }
    };

    let run_fn = if let Some(instance_env) = opts.instance_env {
        quote! {
            /// Run this node with multi-instance support
            ///
            /// This function is auto-generated by the `#[derive(Node)]` macro.
            ///
            /// # Configuration
            ///
            /// Configuration is loaded with the following fallback chain:
            /// 1. File path from environment variable: `#config_env`
            /// 2. Default file path: `#config_path`
            /// 3. Environment variables with prefix: `#env_prefix`
            /// 4. Default configuration
            ///
            /// # Instance Support
            ///
            /// Instance name is read from environment variable: `#instance_env`
            ///
            /// If set, the node will run with instance-scoped topics and the instance
            /// name will be appended to the node ID (e.g., "camera_fake/left").
            ///
            /// # Examples
            ///
            /// ```bash
            /// # Run single instance
            /// ./camera_fake
            ///
            /// # Run with instance name
            /// CAMERA_INSTANCE=left ./camera_fake
            ///
            /// # Run with custom config
            /// CAMERA_CONFIG=custom.yaml CAMERA_INSTANCE=left ./camera_fake
            /// ```
            pub async fn run() -> ::mecha10_core::Result<()> {
                let mut ctx = ::mecha10_core::context::Context::new(#node_name).await?;

                if let Ok(instance) = std::env::var(#instance_env) {
                    ctx = ctx.with_instance(&instance);
                    ::mecha10_core::prelude::info!(
                        "Running node '{}' with instance '{}'",
                        #node_name,
                        instance
                    );
                } else {
                    ::mecha10_core::prelude::info!(
                        "Running node '{}' (no instance)",
                        #node_name
                    );
                }

                let config: <#node_type as ::mecha10_core::node::NodeImpl>::Config =
                    ctx.load_and_validate_node_config(#node_name).await?;

                ::mecha10_core::node::run_node::<#node_type>(
                    config,
                    ctx,
                    #health_config
                ).await
            }
        }
    } else {
        quote! {
            /// Run this node
            ///
            /// This function is auto-generated by the `#[derive(Node)]` macro.
            ///
            /// # Configuration
            ///
            /// Configuration is loaded with the following fallback chain:
            /// 1. File path from environment variable: `#config_env`
            /// 2. Default file path: `#config_path`
            /// 3. Environment variables with prefix: `#env_prefix`
            /// 4. Default configuration
            ///
            /// # Examples
            ///
            /// ```bash
            /// # Run with default config
            /// ./my_node
            ///
            /// # Run with custom config file
            /// MY_NODE_CONFIG=custom.yaml ./my_node
            ///
            /// # Run with environment variable overrides
            /// MY_NODE_FPS=60 ./my_node
            /// ```
            pub async fn run() -> ::mecha10_core::Result<()> {
                let ctx = ::mecha10_core::context::Context::new(#node_name).await?;

                let config: <#node_type as ::mecha10_core::node::NodeImpl>::Config =
                    ctx.load_and_validate_node_config(#node_name).await?;

                ::mecha10_core::node::run_node::<#node_type>(
                    config,
                    ctx,
                    #health_config
                ).await
            }
        }
    };

    let register = quote! {
        ::mecha10_core::register_node!(#node_type);
    };

    let expanded = quote! {
        #register
        #run_fn
    };

    TokenStream::from(expanded)
}

#[derive(Debug, FromDeriveInput)]
#[darling(attributes(node), supports(struct_named))]
struct NodeOpts {
    name: String,

    instance_env: Option<String>,

    #[darling(default)]
    health_priority: Option<String>,
}