filecaster_derive/lib.rs
1//! # filecaster-derive
2//!
3//! `filecaster-derive` is the procedural macro crate for `filecaster`. It provides the
4//! `#[derive(FromFile)]` macro, which automates the process of loading partial
5//! configurations from files, merging them with default values, and constructing
6//! fully-populated Rust structs.
7//!
8//! This crate significantly simplifies configuration management by generating
9//! the necessary boilerplate code for the `FromFile` trait (defined in the
10//! `filecaster` crate).
11//!
12//! ## What it does
13//!
14//! For any struct with named fields, `#[derive(FromFile)]` generates:
15//!
16//! 1. A companion "shadow" struct (e.g., `YourStructFile` for `YourStruct`)
17//! where each field is wrapped in `Option<T>`. This shadow struct is
18//! designed for deserialization from configuration files (e.g., JSON, TOML, YAML).
19//! 2. An implementation of the `FromFile` trait for your original struct. This
20//! includes the `from_file` method, which takes an `Option<YourStructFile>`
21//! and constructs your final `YourStruct`. It intelligently fills in `None`
22//! fields with either:
23//! - An expression you supply via `#[from_file(default = ...)]`.
24//! - `Default::default()` (if no `default` attribute is provided, requiring `T: Default`).
25//!
26//! ## Optional per-field defaults
27//!
28//! Use a `#[from_file(default = <expr>)]` attribute on any field to override
29//! the fallback value. You may supply any expression valid in that struct’s
30//! context. If you omit it, the macro will require the field's type to implement
31//! `Default` and will call `Default::default()`.
32//!
33//! ## Example
34//!
35//! ```rust
36//! use filecaster::FromFile;
37//! use serde::{Deserialize, Serialize};
38//!
39//! #[derive(Debug, Clone, PartialEq, FromFile, Serialize, Deserialize)]
40//! struct AppConfig {
41//! /// If the user does not specify a host, use `"127.0.0.1"`.
42//! #[from_file(default = "127.0.0.1")]
43//! host: String,
44//!
45//! /// Number of worker threads; defaults to `4`.
46//! #[from_file(default = 4)]
47//! workers: usize,
48//!
49//! /// If not set, use `false`. Requires `bool: Default`.
50//! auto_reload: bool,
51//! }
52//!
53//! fn main() {
54//! // Simulate file content (e.g., from a JSON file)
55//! let file_content = r#"{
56//! "host": "localhost",
57//! "workers": 8
58//! }"#;
59//!
60//! // The `AppConfigFile` struct is automatically generated by `#[derive(FromFile)]`.
61//! // It has all fields as `Option<T>`.
62//! let partial_config: AppConfigFile = serde_json::from_str(file_content).unwrap();
63//!
64//! // Use the generated `from_file` method to get the final config.
65//! // Default values are applied for missing fields.
66//! let config = AppConfig::from_file(Some(partial_config));
67//!
68//! assert_eq!(config.host, "localhost");
69//! assert_eq!(config.workers, 8);
70//! assert_eq!(config.auto_reload, false); // `Default::default()` for bool is `false`
71//!
72//! println!("Final Config: {:#?}", config);
73//!
74//! // Example with no file content (all defaults)
75//! let default_config = AppConfig::from_file(None);
76//! assert_eq!(default_config.host, "127.0.0.1");
77//! assert_eq!(default_config.workers, 4);
78//! assert_eq!(default_config.auto_reload, false);
79//! }
80//! ```
81//!
82//! ## Feature flags
83//!
84//! - `serde`: Enables `serde` serialization/deserialization support for the
85//! generated shadow structs. This is typically required to deserialize
86//! your configuration from file formats like JSON, TOML, or YAML.
87//! - `merge`: If enabled, the generated shadow struct will also derive
88//! `merge::Merge`. This allows you to layer multiple partial configuration
89//! files together before calling `.from_file(...)`. Any field-level
90//! `#[merge(...)]` attributes will be respected.
91//!
92//! ## Limitations
93//!
94//! - Only works on structs with _named_ fields (no tuple structs or enums).
95//! - All fields without a `#[from_file(default = ...)]` attribute must
96//! implement the `Default` trait.
97
98mod from_file;
99
100pub(crate) use from_file::impl_from_file;
101use proc_macro::TokenStream;
102use proc_macro_error2::proc_macro_error;
103use syn::{DeriveInput, parse_macro_input};
104
105/// Implements the [`FromFile`] trait.
106///
107/// This macro processes the `#[from_file]` attribute on structs to generate
108/// code for loading data from files.
109#[proc_macro_error]
110#[proc_macro_derive(FromFile, attributes(from_file))]
111pub fn derive_from_file(input: TokenStream) -> TokenStream {
112 let inp = parse_macro_input!(input as DeriveInput);
113 impl_from_file(&inp)
114 .unwrap_or_else(|e| e.to_compile_error())
115 .into()
116}