1use proc_macro::TokenStream;
2use quote::{format_ident, quote};
3use syn::{parse_macro_input, Data, DataStruct, DeriveInput, Expr, Field, Fields, Type};
4
5enum FieldStrategy {
6 None,
7 Literal(Expr),
8 Expression(Expr),
9 Nest,
10}
11
12struct FieldLogic {
13 partial_field: proc_macro2::TokenStream,
14 inherit: proc_macro2::TokenStream,
15 simplify: proc_macro2::TokenStream,
16 build: proc_macro2::TokenStream,
17 default: proc_macro2::TokenStream,
18 from_full: proc_macro2::TokenStream,
19}
20
21struct ParsedFieldConfig {
22 strategy: FieldStrategy,
23 partial_attrs: Vec<proc_macro2::TokenStream>,
24}
25
26#[proc_macro_derive(InheritConfig, attributes(config))]
35pub fn inherit_config_derive(input: TokenStream) -> TokenStream {
36 let ast = parse_macro_input!(input as DeriveInput);
37
38 let Data::Struct(DataStruct {
39 fields: Fields::Named(fields),
40 ..
41 }) = &ast.data
42 else {
43 return syn::Error::new_spanned(
44 ast.ident,
45 "InheritConfig macro only supports structs with named fields",
46 )
47 .to_compile_error()
48 .into();
49 };
50
51 let mut struct_partial_attrs = Vec::new();
53 for attr in &ast.attrs {
54 if attr.path().is_ident("config") {
55 if let Err(e) = attr.parse_nested_meta(|meta| {
56 if meta.path.is_ident("partial_attr") {
57 let content;
58 syn::parenthesized!(content in meta.input);
59 let tokens: proc_macro2::TokenStream = content.parse()?;
60 struct_partial_attrs.push(tokens);
61 }
62 Ok(())
63 }) {
64 return e.to_compile_error().into();
65 }
66 }
67 }
68
69 let mut partial_fields = Vec::new();
70 let mut inherit_logic = Vec::new();
71 let mut simplify_logic = Vec::new();
72 let mut build_logic = Vec::new();
73 let mut default_logic = Vec::new();
74 let mut from_full_logic = Vec::new();
75
76 for field in &fields.named {
77 match process_field(field) {
78 Ok(logic) => {
79 partial_fields.push(logic.partial_field);
80 inherit_logic.push(logic.inherit);
81 simplify_logic.push(logic.simplify);
82 build_logic.push(logic.build);
83 default_logic.push(logic.default);
84 from_full_logic.push(logic.from_full);
85 }
86 Err(e) => return e.to_compile_error().into(),
87 }
88 }
89
90 generate_final_code(
91 &ast.ident,
92 &ast.vis,
93 &struct_partial_attrs,
94 &partial_fields,
95 &inherit_logic,
96 &simplify_logic,
97 &build_logic,
98 &default_logic,
99 &from_full_logic,
100 )
101}
102
103#[allow(clippy::too_many_lines)]
105fn process_field(field: &Field) -> syn::Result<FieldLogic> {
106 let f_name = field
107 .ident
108 .as_ref()
109 .ok_or_else(|| syn::Error::new_spanned(field, "Field must have a name"))?;
110 let f_ty = &field.ty;
111
112 let parsed = parse_field_config(&field.attrs)?;
113 let strategy = parsed.strategy;
114 let p_attrs = parsed.partial_attrs;
115
116 let mut doc_attrs = Vec::new();
118 for attr in &field.attrs {
119 if attr.path().is_ident("doc") {
120 doc_attrs.push(attr.clone());
121 }
122 }
123
124 let partial_field = if matches!(strategy, FieldStrategy::Nest) {
125 let partial_ty = to_partial_type(f_ty);
126 quote! {
127 #(#doc_attrs)*
128 #( #[#p_attrs] )*
129 #[serde(skip_serializing_if = "Option::is_none")]
130 pub #f_name: Option<#partial_ty>
131 }
132 } else {
133 quote! {
134 #(#doc_attrs)*
135 #( #[#p_attrs] )*
136 #[serde(skip_serializing_if = "Option::is_none")]
137 pub #f_name: Option<#f_ty>
138 }
139 };
140
141 let from_full = if matches!(strategy, FieldStrategy::Nest) {
142 let partial_ty = to_partial_type(f_ty);
143 quote! { #f_name: Some(#partial_ty::from_full(full.#f_name)) }
144 } else {
145 quote! { #f_name: Some(full.#f_name) }
146 };
147
148 let (inherit, simplify, build, default) = match strategy {
149 FieldStrategy::Nest => (
150 quote! {
151 match (&mut self.#f_name, &parent.#f_name) {
152 (Some(s), Some(p)) => s.inherit_from(p),
153 (None, Some(p)) => self.#f_name = Some(p.clone()),
154 _ => {}
155 }
156 },
157 quote! {
158 if let (Some(s), Some(p)) = (&mut self.#f_name, &parent.#f_name) {
159 s.simplify_from(p);
160 } else if let Some(s) = &mut self.#f_name {
161 s.simplify_from(&Default::default());
162 }
163 if self.#f_name == parent.#f_name || self.#f_name == Some(Default::default()) {
164 self.#f_name = None;
165 }
166 },
167 quote! { #f_name: self.#f_name.map(|c| c.build()).unwrap_or_else(|| Default::default()) },
168 quote! { #f_name: Default::default() },
169 ),
170 FieldStrategy::Literal(ref expr) => (
171 quote! { if self.#f_name.is_none() { self.#f_name = parent.#f_name.clone(); } },
172 quote! {
173 if self.#f_name == parent.#f_name
174 || (parent.#f_name.is_none() && self.#f_name == Some(#expr))
175 {
176 self.#f_name = None;
177 }
178 },
179 quote! { #f_name: self.#f_name.unwrap_or(#expr) },
180 quote! { #f_name: #expr },
181 ),
182 FieldStrategy::Expression(ref expr) => (
183 quote! { if self.#f_name.is_none() { self.#f_name = parent.#f_name.clone(); } },
184 quote! {
185 if self.#f_name == parent.#f_name
186 || (parent.#f_name.is_none() && self.#f_name == Some(#expr))
187 {
188 self.#f_name = None;
189 }
190 },
191 quote! { #f_name: self.#f_name.unwrap_or_else(|| #expr) },
192 quote! { #f_name: #expr },
193 ),
194 FieldStrategy::None => (
195 quote! { if self.#f_name.is_none() { self.#f_name = parent.#f_name.clone(); } },
196 quote! {
197 if self.#f_name == parent.#f_name
198 || (parent.#f_name.is_none() && self.#f_name == Some(Default::default()))
199 {
200 self.#f_name = None;
201 }
202 },
203 quote! { #f_name: self.#f_name.unwrap_or_default() },
204 quote! { #f_name: Default::default() },
205 ),
206 };
207
208 Ok(FieldLogic {
209 partial_field,
210 inherit,
211 simplify,
212 build,
213 default,
214 from_full,
215 })
216}
217
218fn parse_field_config(attrs: &[syn::Attribute]) -> syn::Result<ParsedFieldConfig> {
220 let mut strategy = FieldStrategy::None;
221 let mut partial_attrs = Vec::new();
222
223 for attr in attrs {
224 if !attr.path().is_ident("config") {
225 continue;
226 }
227 attr.parse_nested_meta(|meta| {
228 if meta.path.is_ident("default") {
229 let expr: Expr = meta.value()?.parse()?;
230 strategy = FieldStrategy::Literal(expr);
231 } else if meta.path.is_ident("default_t") {
232 let expr: Expr = meta.value()?.parse()?;
233 strategy = FieldStrategy::Expression(expr);
234 } else if meta.path.is_ident("nest") {
235 strategy = FieldStrategy::Nest;
236 } else if meta.path.is_ident("partial_attr") {
237 let content;
238 syn::parenthesized!(content in meta.input);
239 let tokens: proc_macro2::TokenStream = content.parse()?;
240 partial_attrs.push(tokens);
241 }
242 Ok(())
243 })?;
244 }
245 Ok(ParsedFieldConfig {
246 strategy,
247 partial_attrs,
248 })
249}
250
251#[allow(clippy::too_many_arguments)]
253fn generate_final_code(
254 name: &syn::Ident,
255 vis: &syn::Visibility,
256 struct_partial_attrs: &[proc_macro2::TokenStream],
257 partial_fields: &[proc_macro2::TokenStream],
258 inherit_logic: &[proc_macro2::TokenStream],
259 simplify_logic: &[proc_macro2::TokenStream],
260 build_logic: &[proc_macro2::TokenStream],
261 default_logic: &[proc_macro2::TokenStream],
262 from_full_logic: &[proc_macro2::TokenStream],
263) -> TokenStream {
264 let partial_name = format_ident!("Partial{}", name);
265
266 let expanded = quote! {
267 impl Default for #name {
269 fn default() -> Self {
270 Self { #(#default_logic),* }
271 }
272 }
273
274 #[allow(clippy::derive_partial_eq_without_eq)]
276 #[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
277 #( #[#struct_partial_attrs] )*
278 #vis struct #partial_name {
279 #(#partial_fields),*
280 }
281
282 impl ::inherit_config::ConfigLayer for #partial_name {
284 type Full = #name;
285
286 fn inherit_from(&mut self, parent: &Self) {
287 #(#inherit_logic)*
288 }
289
290 fn simplify_from(&mut self, parent: &Self) {
291 #(#simplify_logic)*
292 }
293
294 fn build(self) -> Self::Full {
295 #name {
296 #(#build_logic),*
297 }
298 }
299
300 fn from_full(full: Self::Full) -> Self {
301 Self {
302 #(#from_full_logic),*
303 }
304 }
305 }
306
307 impl From<#name> for #partial_name {
308 fn from(full: #name) -> Self {
309 <Self as ::inherit_config::ConfigLayer>::from_full(full)
310 }
311 }
312 };
313
314 expanded.into()
315}
316
317fn to_partial_type(ty: &Type) -> Type {
319 let mut new_ty = ty.clone();
320 if let Type::Path(type_path) = &mut new_ty {
321 if let Some(segment) = type_path.path.segments.last_mut() {
322 segment.ident = format_ident!("Partial{}", segment.ident);
323 }
324 }
325 new_ty
326}