Skip to main content

ortho_config_macros/
lib.rs

1//! Procedural macros for `ortho_config`.
2//!
3//! The current implementation of the [`OrthoConfig`] derive provides a basic
4//! `load` method that layers configuration from a `config.toml` file,
5//! environment variables, and now command-line arguments via `clap`. CLI flag
6//! names are automatically generated from `snake_case` field names by replacing
7//! underscores with hyphens. Generated long flags therefore never include
8//! underscores; supply `cli_long` to specify them.
9
10use proc_macro::TokenStream;
11use quote::quote;
12use syn::{DeriveInput, parse_macro_input};
13
14mod derive {
15    //! Implementation modules for the `OrthoConfig` derive macro.
16
17    pub(crate) mod build;
18    pub(crate) mod crate_path;
19    pub(crate) mod generate;
20    pub(crate) mod load_impl;
21    pub(crate) mod parse;
22    pub(crate) mod policy_impl;
23}
24mod components;
25pub(crate) use components::MacroComponents;
26use components::{MacroComponentArgs, build_macro_components};
27mod selected_subcommand_merge;
28mod subcommand_docs;
29
30use derive::generate::declarative::generate_declarative_impl;
31use derive::generate::docs::{DocsArgs, generate_docs_impl};
32use derive::generate::localization::{
33    emit_identifier_artefact, emit_localization_impl, generate_localization_ids,
34};
35use derive::generate::ortho_impl::generate_trait_implementation;
36use derive::parse::{parse_input, serde_rename_all};
37
38/// Derive macro for the
39/// [`OrthoConfig`](https://docs.rs/ortho_config/latest/ortho_config/trait.OrthoConfig.html)
40/// trait.
41///
42/// # Errors
43///
44/// Returns a compile-time error if invoked on a struct that contains unnamed fields.
45#[proc_macro_derive(OrthoConfig, attributes(ortho_config))]
46pub fn derive_ortho_config(input_tokens: TokenStream) -> TokenStream {
47    let derive_input = parse_macro_input!(input_tokens as DeriveInput);
48    let (ident, fields, struct_attrs, field_attrs) = match parse_input(&derive_input) {
49        Ok(v) => v,
50        Err(e) => return e.to_compile_error().into(),
51    };
52
53    let serde_rename_all = match serde_rename_all(&derive_input.attrs) {
54        Ok(v) => v,
55        Err(e) => return e.to_compile_error().into(),
56    };
57
58    let krate = derive::crate_path::resolve(struct_attrs.crate_path.as_ref());
59
60    let component_args = MacroComponentArgs {
61        ident: &ident,
62        fields: &fields,
63        struct_attrs: &struct_attrs,
64        field_attrs: &field_attrs,
65        serde_rename_all,
66        krate: &krate,
67    };
68
69    let components = match build_macro_components(&component_args) {
70        Ok(v) => v,
71        Err(e) => return e.to_compile_error().into(),
72    };
73
74    let core_tokens = generate_trait_implementation(&ident, &components, &krate);
75    let declarative_impl = generate_declarative_impl(
76        &ident,
77        &components.collection_strategies,
78        components.post_merge_hook,
79        &krate,
80    );
81    let localization_ids =
82        match generate_localization_ids(&struct_attrs, &ident, &fields, &field_attrs) {
83            Ok(model) => model,
84            Err(err) => return err.to_compile_error().into(),
85        };
86    let docs_impl = match generate_docs_impl(&DocsArgs {
87        ident: &ident,
88        fields: &fields,
89        field_attrs: &field_attrs,
90        struct_attrs: &struct_attrs,
91        serde_rename_all,
92        cli_fields: &components.cli_field_metadata,
93        localization_ids: &localization_ids,
94        krate: &krate,
95    }) {
96        Ok(tokens) => tokens,
97        Err(err) => return err.to_compile_error().into(),
98    };
99    if let Err(err) = emit_identifier_artefact(&localization_ids, &ident) {
100        return err.to_compile_error().into();
101    }
102    let localization_impl = emit_localization_impl(&localization_ids, &ident, &krate);
103    let expanded = quote! {
104        #core_tokens
105        #declarative_impl
106        #docs_impl
107        #localization_impl
108    };
109
110    TokenStream::from(expanded)
111}
112
113/// Derive macro for the `ortho_config::SelectedSubcommandMerge` trait.
114///
115/// Apply this derive to a `clap::Subcommand` enum to generate a
116/// `load_and_merge_selected` method that merges configuration defaults for the
117/// selected variant.
118///
119/// Variants can opt into `ArgMatches`-aware merging (required for
120/// `cli_default_as_absent` support) using `#[ortho_subcommand(with_matches)]`.
121#[proc_macro_derive(SelectedSubcommandMerge, attributes(ortho_subcommand, ortho_config))]
122pub fn derive_selected_subcommand_merge(input_tokens: TokenStream) -> TokenStream {
123    let derive_input = parse_macro_input!(input_tokens as DeriveInput);
124    match selected_subcommand_merge::derive_selected_subcommand_merge(derive_input) {
125        Ok(tokens) => tokens.into(),
126        Err(err) => err.to_compile_error().into(),
127    }
128}
129
130/// Derive macro for the `ortho_config::docs::OrthoConfigSubcommandDocs` trait.
131///
132/// Apply this derive to a `clap::Subcommand` enum whose variants each wrap a
133/// single argument struct that implements `OrthoConfigDocs`.
134#[proc_macro_derive(OrthoConfigSubcommandDocs, attributes(ortho_config))]
135pub fn derive_subcommand_docs(input_tokens: TokenStream) -> TokenStream {
136    let derive_input = parse_macro_input!(input_tokens as DeriveInput);
137    match subcommand_docs::derive_subcommand_docs(derive_input) {
138        Ok(tokens) => tokens.into(),
139        Err(err) => err.to_compile_error().into(),
140    }
141}
142
143/// Metadata about a field used for `CliValueExtractor` generation.
144#[derive(Clone)]
145pub(crate) struct CliFieldInfo {
146    /// The field name used by serde during serialization.
147    ///
148    /// This respects `#[serde(rename = "...")]` and `#[serde(rename_all = "...")]`
149    /// so `CliValueExtractor` can reliably map values from `serde_json::to_value(self)`.
150    pub serialized_key: String,
151    /// The clap argument ID used with `ArgMatches::value_source()`.
152    ///
153    /// This is the `id = "..."` override from `#[arg(...)]`/`#[clap(...)]` when
154    /// present, otherwise the field identifier (`snake_case`).
155    pub arg_id: String,
156    /// Whether the field's declared type is `bool` (or `Option<bool>`).
157    ///
158    /// Selects optional boolean-value parsing: absence remains `None`, a bare
159    /// flag means `true`, and an explicit `=false` remains user input. Layer
160    /// builders also use this classification to prune actual clap defaults
161    /// without mistaking an explicit `false` for an absent value.
162    pub is_bool: bool,
163    /// Whether this field has the `cli_default_as_absent` attribute.
164    pub is_default_as_absent: bool,
165}
166
167#[cfg(test)]
168mod tests;