rok-config-macros 0.6.0

Proc-macro internals for rok-config (#[derive(Config)])
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
//! Proc-macro internals for `rok-core::config`.
//!
//! Do not use this crate directly — import `rok-core` with `features = ["config"]` instead.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input, Attribute, Data, DeriveInput, Fields, Ident, Lit, LitStr, Meta, Token, Type,
};

// ── field type classification ─────────────────────────────────────────────────

#[derive(Debug, Clone)]
enum FieldKind {
    Str,
    Bool,
    Num(proc_macro2::TokenStream), // token stream of the type for parse::<T>()
    OptStr,
    OptBool,
    OptNum(proc_macro2::TokenStream),
    Other,
}

fn classify(ty: &Type) -> FieldKind {
    let Type::Path(tp) = ty else {
        return FieldKind::Other;
    };
    let segs = &tp.path.segments;
    if segs.is_empty() {
        return FieldKind::Other;
    }
    let last = segs.last().unwrap();
    let name = last.ident.to_string();

    match name.as_str() {
        "String" => FieldKind::Str,
        "bool" => FieldKind::Bool,
        n @ ("u8" | "u16" | "u32" | "u64" | "u128" | "i8" | "i16" | "i32" | "i64" | "i128"
        | "f32" | "f64" | "usize" | "isize") => {
            let ident = Ident::new(n, proc_macro2::Span::call_site());
            FieldKind::Num(quote! { #ident })
        }
        "Option" => {
            if let syn::PathArguments::AngleBracketed(ab) = &last.arguments {
                if let Some(syn::GenericArgument::Type(inner)) = ab.args.first() {
                    return match classify(inner) {
                        FieldKind::Str => FieldKind::OptStr,
                        FieldKind::Bool => FieldKind::OptBool,
                        FieldKind::Num(t) => FieldKind::OptNum(t),
                        _ => FieldKind::Other,
                    };
                }
            }
            FieldKind::Other
        }
        _ => FieldKind::Other,
    }
}

// ── #[env("VAR", default = value)] attribute ──────────────────────────────────

struct EnvAttr {
    var_name: LitStr,
    default: Option<Lit>,
}

impl Parse for EnvAttr {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let var_name: LitStr = input.parse()?;
        let default = if input.peek(Token![,]) {
            input.parse::<Token![,]>()?;
            let key: Ident = input.parse()?;
            if key != "default" {
                return Err(syn::Error::new(key.span(), "expected `default`"));
            }
            input.parse::<Token![=]>()?;
            Some(input.parse::<Lit>()?)
        } else {
            None
        };
        Ok(EnvAttr { var_name, default })
    }
}

// ── derive entry point ────────────────────────────────────────────────────────

/// Derive `rok_config::FromEnv` for a struct, reading each field from an
/// environment variable declared with `#[env("VAR_NAME")]` or
/// `#[env("VAR_NAME", default = value)]`.
///
/// Fields without a default **must** be set in the environment or the binary
/// panics with a clear message at startup.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Config)]
/// pub struct AppConfig {
///     #[env("APP_NAME", default = "rok-app")]
///     pub name: String,
///
///     #[env("APP_DEBUG", default = false)]
///     pub debug: bool,
///
///     #[env("JWT_SECRET")]    // required — no default
///     pub jwt_secret: String,
///
///     #[env("REDIS_URL")]     // optional Option<String>
///     pub redis_url: Option<String>,
/// }
/// ```
#[proc_macro_derive(Config, attributes(env))]
pub fn derive_config(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_config(input).unwrap_or_else(|e| e.to_compile_error().into())
}

fn expand_config(input: DeriveInput) -> syn::Result<TokenStream> {
    let name = &input.ident;

    let Data::Struct(data) = &input.data else {
        return Err(syn::Error::new_spanned(
            &input.ident,
            "#[derive(Config)] only supports structs",
        ));
    };
    let Fields::Named(fields) = &data.fields else {
        return Err(syn::Error::new_spanned(
            &input.ident,
            "#[derive(Config)] only supports structs with named fields",
        ));
    };

    let mut field_inits: Vec<TokenStream2> = Vec::new();

    for field in &fields.named {
        let field_ident = field.ident.as_ref().unwrap();
        let kind = classify(&field.ty);

        // Find the #[env(...)] attribute.
        let env_attr = field
            .attrs
            .iter()
            .find(|a| a.path().is_ident("env"))
            .ok_or_else(|| {
                syn::Error::new_spanned(
                    field_ident,
                    "each field must have an #[env(\"VAR_NAME\")] attribute",
                )
            })?;

        let parsed: EnvAttr = env_attr.parse_args()?;
        let var_name = &parsed.var_name;
        let var_str = var_name.value();

        let init = match kind {
            FieldKind::Str => match &parsed.default {
                Some(Lit::Str(default)) => quote! {
                    #field_ident: ::std::env::var(#var_name).unwrap_or_else(|_| #default.to_string()),
                },
                None => {
                    let msg = format!(
                        "required env var `{var_str}` is not set — add it to .env or the environment"
                    );
                    quote! {
                        #field_ident: ::std::env::var(#var_name).unwrap_or_else(|_| panic!(#msg)),
                    }
                }
                Some(other) => {
                    return Err(syn::Error::new_spanned(
                        other,
                        "default for a String field must be a string literal",
                    ))
                }
            },

            FieldKind::Bool => {
                let default_val = match &parsed.default {
                    Some(Lit::Bool(b)) => b.value,
                    None => false,
                    Some(other) => {
                        return Err(syn::Error::new_spanned(
                            other,
                            "default for a bool field must be `true` or `false`",
                        ))
                    }
                };
                quote! {
                    #field_ident: ::std::env::var(#var_name)
                        .ok()
                        .and_then(|v| match v.to_lowercase().as_str() {
                            "true" | "1" | "yes" | "on"  => ::std::option::Option::Some(true),
                            "false" | "0" | "no" | "off" => ::std::option::Option::Some(false),
                            _ => ::std::option::Option::None,
                        })
                        .unwrap_or(#default_val),
                }
            }

            FieldKind::Num(ref ty_tokens) => match &parsed.default {
                Some(Lit::Int(n)) => quote! {
                    #field_ident: ::std::env::var(#var_name)
                        .ok()
                        .and_then(|v| v.parse::<#ty_tokens>().ok())
                        .unwrap_or(#n as #ty_tokens),
                },
                Some(Lit::Float(f)) => quote! {
                    #field_ident: ::std::env::var(#var_name)
                        .ok()
                        .and_then(|v| v.parse::<#ty_tokens>().ok())
                        .unwrap_or(#f as #ty_tokens),
                },
                None => {
                    let msg = format!(
                        "required env var `{var_str}` is not set — add it to .env or the environment"
                    );
                    let bad_msg = format!("env var `{var_str}` must be a valid number");
                    quote! {
                        #field_ident: {
                            let __raw = ::std::env::var(#var_name).unwrap_or_else(|_| panic!(#msg));
                            __raw.parse::<#ty_tokens>().unwrap_or_else(|_| panic!(#bad_msg))
                        },
                    }
                }
                Some(other) => {
                    return Err(syn::Error::new_spanned(
                        other,
                        "default for a numeric field must be a numeric literal",
                    ))
                }
            },

            FieldKind::OptStr => quote! {
                #field_ident: ::std::env::var(#var_name).ok(),
            },

            FieldKind::OptBool => quote! {
                #field_ident: ::std::env::var(#var_name)
                    .ok()
                    .and_then(|v| match v.to_lowercase().as_str() {
                        "true" | "1" | "yes" | "on"  => ::std::option::Option::Some(true),
                        "false" | "0" | "no" | "off" => ::std::option::Option::Some(false),
                        _ => ::std::option::Option::None,
                    }),
            },

            FieldKind::OptNum(ref ty_tokens) => quote! {
                #field_ident: ::std::env::var(#var_name)
                    .ok()
                    .and_then(|v| v.parse::<#ty_tokens>().ok()),
            },

            FieldKind::Other => {
                return Err(syn::Error::new_spanned(
                    &field.ty,
                    "#[derive(Config)] supports String, bool, numeric types, and their Option<T> wrappers",
                ))
            }
        };

        field_inits.push(init);
    }

    let expanded = quote! {
        impl ::rok_core::config::FromEnv for #name {
            fn from_env() -> Self {
                Self {
                    #(#field_inits)*
                }
            }
        }

        impl #name {
            /// Load this config from environment variables (reads `.env` automatically).
            pub fn load() -> Self {
                ::rok_core::config::Config::load::<Self>()
            }
        }
    };

    Ok(expanded.into())
}

// ── config attribute helpers ──────────────────────────────────────────────────

/// Parse `#[config(prefix = "app")]` from struct-level attributes.
fn extract_prefix(attrs: &[Attribute]) -> syn::Result<String> {
    for attr in attrs {
        if attr.path().is_ident("config") {
            let meta: Meta = attr.parse_args()?;
            match &meta {
                Meta::NameValue(nv) if nv.path.is_ident("prefix") => {
                    if let syn::Expr::Lit(expr_lit) = &nv.value {
                        if let Lit::Str(s) = &expr_lit.lit {
                            return Ok(s.value());
                        }
                    }
                }
                _ => {
                    return Err(syn::Error::new_spanned(
                        &meta,
                        "expected `#[config(prefix = \"...\")]`",
                    ))
                }
            }
        }
    }
    Err(syn::Error::new(
        proc_macro2::Span::call_site(),
        "missing `#[config(prefix = \"app\")]` attribute",
    ))
}

// ── RokConfig derive ──────────────────────────────────────────────────────────

/// Derive `rok_core::config::Configurable` for a struct, combining
/// environment-variable loading (like `#[derive(Config)]`) with a
/// config-key prefix for file-based discovery.
///
/// # Attributes
///
/// | Level   | Attribute | Description |
/// |---------|-----------|-------------|
/// | Struct  | `#[config(prefix = "app")]` | Config key for `config/app.toml` |
/// | Field   | `#[env("VAR", default = val)]` | Same as `#[derive(Config)]` |
///
/// # Generated
///
/// - `impl Configurable` (with `key()` returning the prefix)
/// - `impl FromEnv` (same as `#[derive(Config)]`)
/// - `fn load()` — tries `load_config` first, falls back to env
///
/// # Example
///
/// ```rust,ignore
/// #[derive(RokConfig)]
/// #[config(prefix = "auth")]
/// pub struct AuthConfig {
///     #[env("JWT_SECRET")]
///     pub jwt_secret: String,
///
///     #[env("JWT_TTL", default = 3600)]
///     pub jwt_ttl: u64,
/// }
/// ```
#[proc_macro_derive(RokConfig, attributes(config, env))]
pub fn derive_rok_config(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_rok_config(input).unwrap_or_else(|e| e.to_compile_error().into())
}

fn expand_rok_config(input: DeriveInput) -> syn::Result<TokenStream> {
    let prefix = extract_prefix(&input.attrs)?;
    let name = &input.ident;
    let prefix_str = prefix.clone();

    // Reuse the same field-expansion logic as Config
    let Data::Struct(data) = &input.data else {
        return Err(syn::Error::new_spanned(
            &input.ident,
            "#[derive(RokConfig)] only supports structs",
        ));
    };
    let Fields::Named(fields) = &data.fields else {
        return Err(syn::Error::new_spanned(
            &input.ident,
            "#[derive(RokConfig)] only supports structs with named fields",
        ));
    };

    let mut field_inits: Vec<TokenStream2> = Vec::new();

    for field in &fields.named {
        let field_ident = field.ident.as_ref().unwrap();
        let kind = classify(&field.ty);

        let env_attr = field
            .attrs
            .iter()
            .find(|a| a.path().is_ident("env"))
            .ok_or_else(|| {
                syn::Error::new_spanned(
                    field_ident,
                    "each field must have an #[env(\"VAR_NAME\")] attribute",
                )
            })?;

        let parsed: EnvAttr = env_attr.parse_args()?;
        let var_name = &parsed.var_name;
        let var_str = var_name.value();

        let init = match kind {
            FieldKind::Str => match &parsed.default {
                Some(Lit::Str(default)) => quote! {
                    #field_ident: ::std::env::var(#var_name).unwrap_or_else(|_| #default.to_string()),
                },
                None => {
                    let msg = format!(
                        "required env var `{var_str}` is not set — add it to .env or the environment"
                    );
                    quote! {
                        #field_ident: ::std::env::var(#var_name).unwrap_or_else(|_| panic!(#msg)),
                    }
                }
                Some(other) => {
                    return Err(syn::Error::new_spanned(
                        other,
                        "default for a String field must be a string literal",
                    ))
                }
            },

            FieldKind::Bool => {
                let default_val = match &parsed.default {
                    Some(Lit::Bool(b)) => b.value,
                    None => false,
                    Some(other) => {
                        return Err(syn::Error::new_spanned(
                            other,
                            "default for a bool field must be `true` or `false`",
                        ))
                    }
                };
                quote! {
                    #field_ident: ::std::env::var(#var_name)
                        .ok()
                        .and_then(|v| match v.to_lowercase().as_str() {
                            "true" | "1" | "yes" | "on"  => ::std::option::Option::Some(true),
                            "false" | "0" | "no" | "off" => ::std::option::Option::Some(false),
                            _ => ::std::option::Option::None,
                        })
                        .unwrap_or(#default_val),
                }
            }

            FieldKind::Num(ref ty_tokens) => match &parsed.default {
                Some(Lit::Int(n)) => quote! {
                    #field_ident: ::std::env::var(#var_name)
                        .ok()
                        .and_then(|v| v.parse::<#ty_tokens>().ok())
                        .unwrap_or(#n as #ty_tokens),
                },
                Some(Lit::Float(f)) => quote! {
                    #field_ident: ::std::env::var(#var_name)
                        .ok()
                        .and_then(|v| v.parse::<#ty_tokens>().ok())
                        .unwrap_or(#f as #ty_tokens),
                },
                None => {
                    let msg = format!(
                        "required env var `{var_str}` is not set — add it to .env or the environment"
                    );
                    let bad_msg = format!("env var `{var_str}` must be a valid number");
                    quote! {
                        #field_ident: {
                            let __raw = ::std::env::var(#var_name).unwrap_or_else(|_| panic!(#msg));
                            __raw.parse::<#ty_tokens>().unwrap_or_else(|_| panic!(#bad_msg))
                        },
                    }
                }
                Some(other) => {
                    return Err(syn::Error::new_spanned(
                        other,
                        "default for a numeric field must be a numeric literal",
                    ))
                }
            },

            FieldKind::OptStr => quote! {
                #field_ident: ::std::env::var(#var_name).ok(),
            },

            FieldKind::OptBool => quote! {
                #field_ident: ::std::env::var(#var_name)
                    .ok()
                    .and_then(|v| match v.to_lowercase().as_str() {
                        "true" | "1" | "yes" | "on"  => ::std::option::Option::Some(true),
                        "false" | "0" | "no" | "off" => ::std::option::Option::Some(false),
                        _ => ::std::option::Option::None,
                    }),
            },

            FieldKind::OptNum(ref ty_tokens) => quote! {
                #field_ident: ::std::env::var(#var_name)
                    .ok()
                    .and_then(|v| v.parse::<#ty_tokens>().ok()),
            },

            FieldKind::Other => {
                return Err(syn::Error::new_spanned(
                    &field.ty,
                    "#[derive(RokConfig)] supports String, bool, numeric types, and their Option<T> wrappers",
                ))
            }
        };

        field_inits.push(init);
    }

    let expanded = quote! {
        impl ::rok_core::config::Configurable for #name {
            fn key() -> &'static str {
                #prefix_str
            }
        }

        impl ::rok_core::config::FromEnv for #name {
            fn from_env() -> Self {
                Self {
                    #(#field_inits)*
                }
            }
        }

        impl #name {
            /// Load this config — tries `config/{key}.toml` first,
            /// then falls back to environment variables.
            pub fn load() -> Self {
                ::rok_core::config::load_config::<Self>()
                    .unwrap_or_else(|| ::rok_core::config::Config::load::<Self>())
            }
        }
    };

    Ok(expanded.into())
}