Skip to main content

yaml_rt_derive/
lib.rs

1//! Derive macro entry point for typed YAML round-trip overlays.
2//!
3//! The derive supports named mapping structs, transparent single-field tuple
4//! structs, positional tuple structs, unit structs, and every enum variant
5//! shape. It generates document- and
6//! node-level overlay implementations that retain the lossless YAML document
7//! as the source of truth.
8
9use std::collections::BTreeMap;
10
11use proc_macro::TokenStream;
12use proc_macro2::TokenStream as TokenStream2;
13use quote::quote;
14use syn::{
15    Attribute, Data, DeriveInput, Fields, LitStr, Meta, Path, WherePredicate, parse_macro_input,
16};
17
18/// Derives typed YAML round-trip overlay implementations.
19///
20/// Named structs overlay YAML mappings. A tuple struct with exactly one field
21/// is transparent and delegates directly to that field. Multi-field tuple
22/// structs overlay YAML sequences, and unit structs overlay YAML null values.
23///
24/// Enum unit variants are represented as scalar strings. Newtype, tuple, and
25/// struct variants use local YAML tags:
26///
27/// ```text
28/// Unit
29/// !Newtype 42
30/// !Tuple [1, true]
31/// !Struct {host: api}
32/// ```
33///
34/// Struct- and enum-level `rename_all` accepts `lowercase`, `snake_case`,
35/// `kebab-case`, `SCREAMING_SNAKE_CASE`, `camelCase`, and `PascalCase`.
36/// Variants accept `rename`, repeated `alias`, and `rename_all` for named
37/// payload fields. Unnamed newtype and tuple payload fields accept `with`.
38///
39/// Supported field attributes:
40///
41/// - `#[yaml(rename = "yaml-key")]`
42/// - `#[yaml(default)]`
43/// - `#[yaml(default = expression)]`
44/// - `#[yaml(comment = "Comment for inserted entries.")]`
45/// - `#[yaml(alias = "legacy-key")]` for read/update fallback keys
46/// - `#[yaml(skip)]` to ignore a field and fill it with `Default::default()`
47/// - `#[yaml(skip_serializing_if = "path::to::predicate")]` to remove or omit
48///   the field when the predicate returns `true`
49/// - `#[yaml(flatten)]` to overlay a nested round-trip struct on the same root
50///   mapping or capture unmodeled entries in a string-keyed `BTreeMap` or
51///   `HashMap`
52/// - `#[yaml(with = "module::path")]` to convert through the module's `Repr`
53///   type and `from_yaml`/`to_yaml` functions
54/// - Rust doc comments as insertion comments when `yaml(comment = ...)` is not
55///   present
56///
57/// Adapter modules use this contract:
58///
59/// ```text
60/// type Repr;
61///
62/// fn from_yaml(value: Repr) -> Result<FieldType, yaml_rt::YamlError>;
63/// fn to_yaml(value: &FieldType) -> Result<Repr, yaml_rt::YamlError>;
64/// ```
65///
66/// `Repr` must implement `YamlValue` and `ToYamlFragment`. The usual field
67/// attributes are applied outside the conversion. `with` cannot be combined
68/// with `skip` or `flatten`.
69///
70/// A recursively flattened mapping graph may contain one catch-all map. Its
71/// entries exclude canonical field names, aliases, skipped fields, and keys
72/// modeled by nested flattened structs. Applying the overlay synchronizes the
73/// catch-all entries exactly; inserting a modeled key into the map is an error.
74///
75/// Supported struct attributes:
76///
77/// - `#[yaml(rename_all = "camelCase")]` transforms fields without an explicit
78///   `rename`
79/// - `#[yaml(preserve_unknown_fields)]` keeps unknown mapping entries, which is
80///   the default behavior
81/// - `#[yaml(prune_unknown_fields)]` removes root mapping entries that are not
82///   known fields or aliases after writing typed fields
83/// - `#[yaml(insert_order = "append")]` appends missing fields, which is the
84///   default behavior
85/// - `#[yaml(insert_order = "struct")]` inserts missing fields before the next
86///   existing field in declaration order when possible
87///
88/// Same-variant enum writes patch payloads incrementally. Variant switches
89/// replace the enum node while retaining its anchor and surrounding entry
90/// comment. Enum data variants intentionally support only the local-tag
91/// representation; internally tagged, adjacently tagged, externally mapped,
92/// and untagged representations are outside this derive's current contract.
93#[proc_macro_derive(YamlRt, attributes(yaml))]
94pub fn derive_yaml_rt(input: TokenStream) -> TokenStream {
95    let input = parse_macro_input!(input as DeriveInput);
96
97    expand_yaml_rt(input)
98        .unwrap_or_else(syn::Error::into_compile_error)
99        .into()
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
103enum UnknownFieldPolicy {
104    #[default]
105    Preserve,
106    Prune,
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
110enum InsertOrder {
111    #[default]
112    Append,
113    Struct,
114}
115
116#[derive(Default)]
117struct StructOptions {
118    unknown_field_policy: UnknownFieldPolicy,
119    insert_order: InsertOrder,
120    rename_all: Option<RenameRule>,
121}
122
123#[derive(Debug, Clone, Copy)]
124enum RenameRule {
125    Lowercase,
126    SnakeCase,
127    KebabCase,
128    ScreamingSnakeCase,
129    CamelCase,
130    PascalCase,
131}
132
133#[derive(Default)]
134struct EnumOptions {
135    rename_all: Option<RenameRule>,
136}
137
138#[derive(Default)]
139struct VariantOptions {
140    rename: Option<String>,
141    aliases: Vec<String>,
142    rename_all: Option<RenameRule>,
143}
144
145#[derive(Default)]
146struct FieldOptions {
147    rename: Option<String>,
148    aliases: Vec<String>,
149    default: Option<TokenStream2>,
150    comment: Option<String>,
151    doc_comment: Option<String>,
152    skip: bool,
153    skip_serializing_if: Option<Path>,
154    flatten: bool,
155    with: Option<Path>,
156}
157
158#[derive(Default)]
159struct FieldExpansion {
160    reads: Vec<TokenStream2>,
161    writes: Vec<TokenStream2>,
162    known_keys: Vec<String>,
163    flatten_types: Vec<syn::Type>,
164    flatten_values: Vec<TokenStream2>,
165    has_flatten: bool,
166    read_bounds: Vec<WherePredicate>,
167    write_bounds: Vec<WherePredicate>,
168}
169
170#[derive(Clone, Copy)]
171enum FieldAccess {
172    SelfFields,
173    Bindings,
174}
175
176fn expand_yaml_rt(input: DeriveInput) -> syn::Result<TokenStream2> {
177    let DeriveInput {
178        attrs,
179        ident: name,
180        generics,
181        data,
182        ..
183    } = input;
184    match data {
185        Data::Struct(struct_data) => match struct_data.fields {
186            Fields::Named(fields) => expand_named_struct(&attrs, &name, generics, fields.named),
187            Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
188                let field = fields
189                    .unnamed
190                    .into_iter()
191                    .next()
192                    .expect("one unnamed field was checked");
193                expand_newtype_struct(&attrs, &name, generics, field)
194            }
195            Fields::Unnamed(fields) => expand_tuple_struct(&attrs, &name, generics, fields.unnamed),
196            Fields::Unit => expand_unit_struct(&attrs, &name, generics),
197        },
198        Data::Enum(data) => expand_enum(&attrs, &name, generics, data.variants),
199        Data::Union(data) => Err(syn::Error::new_spanned(
200            data.union_token,
201            "YamlRt cannot be derived for unions",
202        )),
203    }
204}
205
206fn expand_named_struct(
207    attrs: &[Attribute],
208    name: &syn::Ident,
209    generics: syn::Generics,
210    fields: syn::punctuated::Punctuated<syn::Field, syn::token::Comma>,
211) -> syn::Result<TokenStream2> {
212    let struct_options = parse_struct_options(attrs)?;
213    let fields = expand_fields(
214        fields,
215        struct_options.insert_order,
216        FieldAccess::SelfFields,
217        struct_options.rename_all,
218    )?;
219    validate_struct_options(name, &struct_options, fields.has_flatten)?;
220
221    let ordered_keys_binding = match struct_options.insert_order {
222        InsertOrder::Append => quote! {},
223        InsertOrder::Struct => {
224            let known_keys = &fields.known_keys;
225            quote! {
226                let __yaml_rt_ordered_keys = &[#(#known_keys),*];
227            }
228        }
229    };
230
231    let prune_unknown_fields = match struct_options.unknown_field_policy {
232        UnknownFieldPolicy::Preserve => quote! {},
233        UnknownFieldPolicy::Prune => {
234            quote! {
235                doc.retain_mapping_entries(root, &__yaml_rt_claimed_keys)?;
236            }
237        }
238    };
239
240    let field_reads = &fields.reads;
241    let field_writes = &fields.writes;
242    let catch_all_count = flatten_catch_all_count(&fields);
243    let direct_claimed_keys = flatten_claimed_keys_binding(&fields, quote! { &[] });
244    let outer_claimed_keys =
245        flatten_claimed_keys_binding(&fields, quote! { __yaml_rt_outer_claimed_keys });
246    let flatten_validations = flatten_validation_tokens(&fields);
247    let flatten_key_metadata = flatten_key_metadata(&fields);
248    let mut read_generics = generics.clone();
249    read_generics
250        .make_where_clause()
251        .predicates
252        .extend(fields.read_bounds.iter().cloned());
253    let mut write_generics = generics.clone();
254    write_generics
255        .make_where_clause()
256        .predicates
257        .extend(fields.write_bounds.iter().cloned());
258    let mut combined_generics = generics;
259    combined_generics
260        .make_where_clause()
261        .predicates
262        .extend(fields.read_bounds.iter().cloned());
263    combined_generics
264        .make_where_clause()
265        .predicates
266        .extend(fields.write_bounds.iter().cloned());
267    let (read_impl_generics, read_type_generics, read_where_clause) =
268        read_generics.split_for_impl();
269    let (write_impl_generics, write_type_generics, write_where_clause) =
270        write_generics.split_for_impl();
271    let (combined_impl_generics, combined_type_generics, combined_where_clause) =
272        combined_generics.split_for_impl();
273
274    Ok(quote! {
275        impl #read_impl_generics ::yaml_rt::FromYamlDoc for #name #read_type_generics #read_where_clause {
276            fn from_yaml_doc(doc: &::yaml_rt::YamlDoc) -> Result<Self, ::yaml_rt::YamlError> {
277                ::yaml_rt::__validate_yaml_flatten_layout(doc, #catch_all_count)?;
278                #direct_claimed_keys
279                Ok(Self {
280                    #(#field_reads,)*
281                })
282            }
283        }
284
285        impl #write_impl_generics ::yaml_rt::ToYamlDoc for #name #write_type_generics #write_where_clause {
286            fn apply_to_yaml_doc(&self, doc: &mut ::yaml_rt::YamlDoc) -> Result<(), ::yaml_rt::YamlError> {
287                ::yaml_rt::__validate_yaml_flatten_layout(doc, #catch_all_count)?;
288                #direct_claimed_keys
289                #(#flatten_validations)*
290                let root = doc.root_mapping()?;
291                #ordered_keys_binding
292                #(#field_writes)*
293                #prune_unknown_fields
294                Ok(())
295            }
296        }
297
298        impl #combined_impl_generics ::yaml_rt::YamlFlatten for #name #combined_type_generics #combined_where_clause {
299            fn yaml_flatten_keys() -> ::std::vec::Vec<&'static str> {
300                #flatten_key_metadata
301            }
302
303            fn yaml_flatten_catch_all_count() -> usize {
304                #catch_all_count
305            }
306
307            fn from_yaml_flattened(
308                doc: &::yaml_rt::YamlDoc,
309                __yaml_rt_outer_claimed_keys: &[&str],
310            ) -> Result<Self, ::yaml_rt::YamlError> {
311                ::yaml_rt::__validate_yaml_flatten_layout(doc, #catch_all_count)?;
312                #outer_claimed_keys
313                Ok(Self {
314                    #(#field_reads,)*
315                })
316            }
317
318            fn validate_yaml_flattened(
319                &self,
320                doc: &::yaml_rt::YamlDoc,
321                __yaml_rt_outer_claimed_keys: &[&str],
322            ) -> Result<(), ::yaml_rt::YamlError> {
323                ::yaml_rt::__validate_yaml_flatten_layout(doc, #catch_all_count)?;
324                #outer_claimed_keys
325                #(#flatten_validations)*
326                Ok(())
327            }
328
329            fn apply_to_yaml_flattened(
330                &self,
331                doc: &mut ::yaml_rt::YamlDoc,
332                __yaml_rt_outer_claimed_keys: &[&str],
333            ) -> Result<(), ::yaml_rt::YamlError> {
334                <Self as ::yaml_rt::YamlFlatten>::validate_yaml_flattened(
335                    self,
336                    doc,
337                    __yaml_rt_outer_claimed_keys,
338                )?;
339                #outer_claimed_keys
340                let root = doc.root_mapping()?;
341                #ordered_keys_binding
342                #(#field_writes)*
343                #prune_unknown_fields
344                Ok(())
345            }
346        }
347
348        impl #combined_impl_generics ::yaml_rt::YamlValue for #name #combined_type_generics #combined_where_clause {
349            fn read_yaml(
350                doc: &::yaml_rt::YamlDoc,
351                node: ::yaml_rt::NodeId,
352            ) -> Result<Self, ::yaml_rt::YamlError> {
353                ::yaml_rt::__read_mapping_overlay(doc, node)
354            }
355
356            fn write_yaml(
357                &self,
358                doc: &mut ::yaml_rt::YamlDoc,
359                node: Option<::yaml_rt::NodeId>,
360            ) -> Result<::yaml_rt::NodeId, ::yaml_rt::YamlError> {
361                ::yaml_rt::__write_mapping_overlay(self, doc, node)
362            }
363        }
364
365        impl #write_impl_generics ::yaml_rt::ToYamlFragment for #name #write_type_generics #write_where_clause {
366            fn to_yaml_fragment(
367                &self,
368                indent: usize,
369                line_ending: &str,
370            ) -> Result<String, ::yaml_rt::YamlError> {
371                ::yaml_rt::__mapping_overlay_to_yaml_fragment(self, indent, line_ending)
372            }
373        }
374    })
375}
376
377fn flatten_catch_all_count(fields: &FieldExpansion) -> TokenStream2 {
378    let counts = fields.flatten_types.iter().map(|field_type| {
379        quote! { <#field_type as ::yaml_rt::YamlFlatten>::yaml_flatten_catch_all_count() }
380    });
381    quote! { 0usize #(+ #counts)* }
382}
383
384fn flatten_claimed_keys_binding(
385    fields: &FieldExpansion,
386    outer_claimed_keys: TokenStream2,
387) -> TokenStream2 {
388    let known_keys = &fields.known_keys;
389    let nested_keys = fields.flatten_types.iter().map(|field_type| {
390        quote! {
391            for __yaml_rt_key in
392                <#field_type as ::yaml_rt::YamlFlatten>::yaml_flatten_keys()
393            {
394                if !__yaml_rt_claimed_keys.contains(&__yaml_rt_key) {
395                    __yaml_rt_claimed_keys.push(__yaml_rt_key);
396                }
397            }
398        }
399    });
400    quote! {
401        let mut __yaml_rt_claimed_keys: ::std::vec::Vec<&str> =
402            (#outer_claimed_keys).to_vec();
403        #(
404            if !__yaml_rt_claimed_keys.contains(&#known_keys) {
405                __yaml_rt_claimed_keys.push(#known_keys);
406            }
407        )*
408        #(#nested_keys)*
409    }
410}
411
412fn flatten_key_metadata(fields: &FieldExpansion) -> TokenStream2 {
413    let known_keys = &fields.known_keys;
414    let nested_keys = fields.flatten_types.iter().map(|field_type| {
415        quote! {
416            for __yaml_rt_key in
417                <#field_type as ::yaml_rt::YamlFlatten>::yaml_flatten_keys()
418            {
419                if !__yaml_rt_keys.contains(&__yaml_rt_key) {
420                    __yaml_rt_keys.push(__yaml_rt_key);
421                }
422            }
423        }
424    });
425    quote! {
426        let mut __yaml_rt_keys = ::std::vec::Vec::new();
427        #(
428            if !__yaml_rt_keys.contains(&#known_keys) {
429                __yaml_rt_keys.push(#known_keys);
430            }
431        )*
432        #(#nested_keys)*
433        __yaml_rt_keys
434    }
435}
436
437fn flatten_validation_tokens(fields: &FieldExpansion) -> Vec<TokenStream2> {
438    fields
439        .flatten_types
440        .iter()
441        .zip(&fields.flatten_values)
442        .map(|(field_type, field_value)| {
443            quote! {
444                <#field_type as ::yaml_rt::YamlFlatten>::validate_yaml_flattened(
445                    #field_value,
446                    doc,
447                    &__yaml_rt_claimed_keys,
448                )?;
449            }
450        })
451        .collect()
452}
453
454#[expect(
455    clippy::too_many_lines,
456    reason = "the generated trait implementations share validated newtype metadata"
457)]
458fn expand_newtype_struct(
459    attrs: &[Attribute],
460    name: &syn::Ident,
461    generics: syn::Generics,
462    field: syn::Field,
463) -> syn::Result<TokenStream2> {
464    if let Some(attr) = attrs.iter().find(|attr| attr.path().is_ident("yaml")) {
465        return Err(syn::Error::new_spanned(
466            attr,
467            "transparent newtype structs do not support container-level yaml attributes",
468        ));
469    }
470    let options = parse_field_options(&field.attrs)?;
471    if options.rename.is_some()
472        || !options.aliases.is_empty()
473        || options.default.is_some()
474        || options.comment.is_some()
475        || options.skip
476        || options.skip_serializing_if.is_some()
477        || options.flatten
478    {
479        return Err(syn::Error::new_spanned(
480            field,
481            "transparent newtype fields support only yaml(with)",
482        ));
483    }
484    let field_type = field.ty;
485    let (read_value, read_document_value, write_value, fragment_value, read_bound, write_bound) =
486        if let Some(with) = options.with {
487            (
488                quote! {
489                    {
490                        let __yaml_rt_repr =
491                            <#with::Repr as ::yaml_rt::YamlValue>::read_yaml(doc, node)?;
492                        #with::from_yaml(__yaml_rt_repr)?
493                    }
494                },
495                quote! {
496                    {
497                        let __yaml_rt_repr =
498                            ::yaml_rt::__read_yaml_document::<#with::Repr>(doc)?;
499                        #with::from_yaml(__yaml_rt_repr)?
500                    }
501                },
502                quote! {
503                    let __yaml_rt_repr = #with::to_yaml(&self.0)?;
504                    <#with::Repr as ::yaml_rt::YamlValue>::write_yaml(
505                        &__yaml_rt_repr,
506                        doc,
507                        node,
508                    )
509                },
510                quote! {
511                    let __yaml_rt_repr = #with::to_yaml(&self.0)?;
512                    <#with::Repr as ::yaml_rt::ToYamlFragment>::to_yaml_fragment(
513                        &__yaml_rt_repr,
514                        indent,
515                        line_ending,
516                    )
517                },
518                syn::parse_quote! {
519                    #with::Repr: ::yaml_rt::YamlValue
520                },
521                syn::parse_quote! {
522                    #with::Repr: ::yaml_rt::YamlValue + ::yaml_rt::ToYamlFragment
523                },
524            )
525        } else {
526            (
527                quote! {
528                    <#field_type as ::yaml_rt::YamlValue>::read_yaml(doc, node)?
529                },
530                quote! {
531                    ::yaml_rt::__read_yaml_document::<#field_type>(doc)?
532                },
533                quote! {
534                    <#field_type as ::yaml_rt::YamlValue>::write_yaml(&self.0, doc, node)
535                },
536                quote! {
537                    <#field_type as ::yaml_rt::ToYamlFragment>::to_yaml_fragment(
538                        &self.0,
539                        indent,
540                        line_ending,
541                    )
542                },
543                syn::parse_quote! {
544                    #field_type: ::yaml_rt::YamlValue
545                },
546                syn::parse_quote! {
547                    #field_type: ::yaml_rt::YamlValue + ::yaml_rt::ToYamlFragment
548                },
549            )
550        };
551
552    let mut read_generics = generics.clone();
553    read_generics
554        .make_where_clause()
555        .predicates
556        .push(read_bound);
557    let mut write_generics = generics;
558    write_generics
559        .make_where_clause()
560        .predicates
561        .push(write_bound);
562    let (read_impl_generics, read_type_generics, read_where_clause) =
563        read_generics.split_for_impl();
564    let (write_impl_generics, write_type_generics, write_where_clause) =
565        write_generics.split_for_impl();
566
567    Ok(quote! {
568        impl #read_impl_generics ::yaml_rt::FromYamlDoc for #name #read_type_generics #read_where_clause {
569            fn from_yaml_doc(doc: &::yaml_rt::YamlDoc) -> Result<Self, ::yaml_rt::YamlError> {
570                Ok(Self(#read_document_value))
571            }
572        }
573
574        impl #write_impl_generics ::yaml_rt::ToYamlDoc for #name #write_type_generics #write_where_clause {
575            fn apply_to_yaml_doc(&self, doc: &mut ::yaml_rt::YamlDoc) -> Result<(), ::yaml_rt::YamlError> {
576                ::yaml_rt::__write_yaml_document(self, doc)
577            }
578        }
579
580        impl #write_impl_generics ::yaml_rt::YamlValue for #name #write_type_generics #write_where_clause {
581            fn read_yaml(
582                doc: &::yaml_rt::YamlDoc,
583                node: ::yaml_rt::NodeId,
584            ) -> Result<Self, ::yaml_rt::YamlError> {
585                Ok(Self(#read_value))
586            }
587
588            fn write_yaml(
589                &self,
590                doc: &mut ::yaml_rt::YamlDoc,
591                node: Option<::yaml_rt::NodeId>,
592            ) -> Result<::yaml_rt::NodeId, ::yaml_rt::YamlError> {
593                #write_value
594            }
595        }
596
597        impl #write_impl_generics ::yaml_rt::ToYamlFragment for #name #write_type_generics #write_where_clause {
598            fn to_yaml_fragment(
599                &self,
600                indent: usize,
601                line_ending: &str,
602            ) -> Result<String, ::yaml_rt::YamlError> {
603                #fragment_value
604            }
605        }
606    })
607}
608
609fn reject_tuple_container_attributes(attrs: &[Attribute], kind: &str) -> syn::Result<()> {
610    if let Some(attr) = attrs.iter().find(|attr| attr.path().is_ident("yaml")) {
611        return Err(syn::Error::new_spanned(
612            attr,
613            format!("{kind} do not support container-level yaml attributes"),
614        ));
615    }
616    Ok(())
617}
618
619fn expand_unit_struct(
620    attrs: &[Attribute],
621    name: &syn::Ident,
622    generics: syn::Generics,
623) -> syn::Result<TokenStream2> {
624    reject_tuple_container_attributes(attrs, "unit structs")?;
625    let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
626
627    Ok(quote! {
628        impl #impl_generics ::yaml_rt::FromYamlDoc for #name #type_generics #where_clause {
629            fn from_yaml_doc(doc: &::yaml_rt::YamlDoc) -> Result<Self, ::yaml_rt::YamlError> {
630                let node = doc.document_root(0)?.ok_or_else(|| {
631                    ::yaml_rt::YamlError::new(::yaml_rt::Diagnostic::new(
632                        ::yaml_rt::DiagnosticKind::Typed,
633                        "document does not contain a YAML unit struct value",
634                        ::yaml_rt::Span::empty(0),
635                    ))
636                })?;
637                ::yaml_rt::__read_yaml_null(doc, node)?;
638                Ok(Self)
639            }
640        }
641
642        impl #impl_generics ::yaml_rt::ToYamlDoc for #name #type_generics #where_clause {
643            fn apply_to_yaml_doc(&self, doc: &mut ::yaml_rt::YamlDoc) -> Result<(), ::yaml_rt::YamlError> {
644                ::yaml_rt::__write_yaml_document(self, doc)
645            }
646        }
647
648        impl #impl_generics ::yaml_rt::YamlValue for #name #type_generics #where_clause {
649            fn read_yaml(
650                doc: &::yaml_rt::YamlDoc,
651                node: ::yaml_rt::NodeId,
652            ) -> Result<Self, ::yaml_rt::YamlError> {
653                ::yaml_rt::__read_yaml_null(doc, node)?;
654                Ok(Self)
655            }
656
657            fn write_yaml(
658                &self,
659                doc: &mut ::yaml_rt::YamlDoc,
660                node: Option<::yaml_rt::NodeId>,
661            ) -> Result<::yaml_rt::NodeId, ::yaml_rt::YamlError> {
662                let node = node.ok_or_else(|| {
663                    ::yaml_rt::YamlError::new(::yaml_rt::Diagnostic::new(
664                        ::yaml_rt::DiagnosticKind::Typed,
665                        "cannot insert a standalone YAML unit struct without collection context",
666                        ::yaml_rt::Span::empty(0),
667                    ))
668                })?;
669                if ::yaml_rt::__read_yaml_null(doc, node).is_ok() {
670                    Ok(node)
671                } else {
672                    <Option<u8> as ::yaml_rt::YamlValue>::write_yaml(
673                        &None,
674                        doc,
675                        Some(node),
676                    )
677                }
678            }
679        }
680
681        impl #impl_generics ::yaml_rt::ToYamlFragment for #name #type_generics #where_clause {
682            fn to_yaml_fragment(
683                &self,
684                _indent: usize,
685                _line_ending: &str,
686            ) -> Result<String, ::yaml_rt::YamlError> {
687                Ok("null".to_owned())
688            }
689        }
690    })
691}
692
693fn expand_tuple_struct(
694    attrs: &[Attribute],
695    name: &syn::Ident,
696    generics: syn::Generics,
697    fields: syn::punctuated::Punctuated<syn::Field, syn::token::Comma>,
698) -> syn::Result<TokenStream2> {
699    reject_tuple_container_attributes(attrs, "tuple structs")?;
700    let mut read_bounds = Vec::new();
701    let mut write_bounds = Vec::new();
702    let fields = fields
703        .into_iter()
704        .map(|field| {
705            parse_unnamed_field(
706                field,
707                &mut read_bounds,
708                &mut write_bounds,
709                "tuple struct fields support only yaml(with)",
710            )
711        })
712        .collect::<syn::Result<Vec<_>>>()?;
713    let arity = fields.len();
714    let reads = fields
715        .iter()
716        .enumerate()
717        .map(|(index, field)| {
718            let ty = &field.ty;
719            if let Some(with) = &field.with {
720                quote! {{
721                    let __yaml_rt_repr = <#with::Repr as ::yaml_rt::YamlValue>::read_yaml(
722                        doc,
723                        __yaml_rt_items[#index],
724                    )?;
725                    #with::from_yaml(__yaml_rt_repr)?
726                }}
727            } else {
728                quote! {
729                    <#ty as ::yaml_rt::YamlValue>::read_yaml(doc, __yaml_rt_items[#index])?
730                }
731            }
732        })
733        .collect::<Vec<_>>();
734    let bindings = (0..arity)
735        .map(|index| syn::Ident::new(&format!("field_{index}"), name.span()))
736        .collect::<Vec<_>>();
737    let writes = fields
738        .iter()
739        .zip(&bindings)
740        .enumerate()
741        .map(|(index, (field, binding))| {
742            let ty = &field.ty;
743            if let Some(with) = &field.with {
744                quote! {
745                    let __yaml_rt_repr = #with::to_yaml(#binding)?;
746                    <#with::Repr as ::yaml_rt::YamlValue>::write_yaml(
747                        &__yaml_rt_repr,
748                        doc,
749                        Some(__yaml_rt_items[#index]),
750                    )?;
751                }
752            } else {
753                quote! {
754                    <#ty as ::yaml_rt::YamlValue>::write_yaml(
755                        #binding,
756                        doc,
757                        Some(__yaml_rt_items[#index]),
758                    )?;
759                }
760            }
761        })
762        .collect::<Vec<_>>();
763    let fragments = fields
764        .iter()
765        .zip(&bindings)
766        .map(|(field, binding)| {
767            let ty = &field.ty;
768            if let Some(with) = &field.with {
769                quote! {{
770                    let __yaml_rt_repr = #with::to_yaml(#binding)?;
771                    <#with::Repr as ::yaml_rt::ToYamlFragment>::to_yaml_fragment(
772                        &__yaml_rt_repr,
773                        indent + 2,
774                        line_ending,
775                    )?
776                }}
777            } else {
778                quote! {
779                    <#ty as ::yaml_rt::ToYamlFragment>::to_yaml_fragment(
780                        #binding,
781                        indent + 2,
782                        line_ending,
783                    )?
784                }
785            }
786        })
787        .collect::<Vec<_>>();
788    let read_body = quote! {
789        if !matches!(doc.semantic_kind(node), Some(::yaml_rt::SemanticKind::Sequence { .. })) {
790            return Err(::yaml_rt::__typed_node_error(
791                doc,
792                node,
793                concat!("YAML tuple struct `", stringify!(#name), "` requires a sequence"),
794                &["a YAML sequence"],
795            ));
796        }
797        let __yaml_rt_items = doc.sequence_items(node).collect::<::std::vec::Vec<_>>();
798        if __yaml_rt_items.len() != #arity {
799            return Err(::yaml_rt::__typed_node_error(
800                doc,
801                node,
802                format!(
803                    "YAML tuple struct `{}` expects {} fields, found {}",
804                    stringify!(#name),
805                    #arity,
806                    __yaml_rt_items.len(),
807                ),
808                &[concat!(#arity, " sequence items")],
809            ));
810        }
811        Ok(Self(#(#reads),*))
812    };
813    let (read_generics, write_generics, combined_generics) =
814        enum_generics_with_bounds(generics, read_bounds, write_bounds);
815    let (read_impl_generics, read_type_generics, read_where_clause) =
816        read_generics.split_for_impl();
817    let (write_impl_generics, write_type_generics, write_where_clause) =
818        write_generics.split_for_impl();
819    let (combined_impl_generics, combined_type_generics, combined_where_clause) =
820        combined_generics.split_for_impl();
821
822    Ok(quote! {
823        impl #read_impl_generics ::yaml_rt::FromYamlDoc for #name #read_type_generics #read_where_clause {
824            fn from_yaml_doc(doc: &::yaml_rt::YamlDoc) -> Result<Self, ::yaml_rt::YamlError> {
825                let node = doc.document_root(0)?.ok_or_else(|| {
826                    ::yaml_rt::YamlError::new(::yaml_rt::Diagnostic::new(
827                        ::yaml_rt::DiagnosticKind::Typed,
828                        "document does not contain a YAML tuple struct value",
829                        ::yaml_rt::Span::empty(0),
830                    ))
831                })?;
832                #read_body
833            }
834        }
835
836        impl #combined_impl_generics ::yaml_rt::ToYamlDoc for #name #combined_type_generics #combined_where_clause {
837            fn apply_to_yaml_doc(&self, doc: &mut ::yaml_rt::YamlDoc) -> Result<(), ::yaml_rt::YamlError> {
838                ::yaml_rt::__write_yaml_document(self, doc)
839            }
840        }
841
842        impl #combined_impl_generics ::yaml_rt::YamlValue for #name #combined_type_generics #combined_where_clause {
843            fn read_yaml(doc: &::yaml_rt::YamlDoc, node: ::yaml_rt::NodeId) -> Result<Self, ::yaml_rt::YamlError> {
844                #read_body
845            }
846
847            fn write_yaml(
848                &self,
849                doc: &mut ::yaml_rt::YamlDoc,
850                node: Option<::yaml_rt::NodeId>,
851            ) -> Result<::yaml_rt::NodeId, ::yaml_rt::YamlError> {
852                let node = node.ok_or_else(|| {
853                    ::yaml_rt::YamlError::new(::yaml_rt::Diagnostic::new(
854                        ::yaml_rt::DiagnosticKind::Typed,
855                        "cannot insert a standalone YAML tuple struct without collection context",
856                        ::yaml_rt::Span::empty(0),
857                    ))
858                })?;
859                if !matches!(doc.semantic_kind(node), Some(::yaml_rt::SemanticKind::Sequence { .. })) {
860                    return Err(::yaml_rt::__typed_node_error(
861                        doc,
862                        node,
863                        concat!("YAML tuple struct `", stringify!(#name), "` requires a sequence"),
864                        &["a YAML sequence"],
865                    ));
866                }
867                let __yaml_rt_items = doc.sequence_items(node).collect::<::std::vec::Vec<_>>();
868                if __yaml_rt_items.len() != #arity {
869                    return Err(::yaml_rt::__typed_node_error(
870                        doc,
871                        node,
872                        format!(
873                            "YAML tuple struct `{}` expects {} fields, found {}",
874                            stringify!(#name),
875                            #arity,
876                            __yaml_rt_items.len(),
877                        ),
878                        &[concat!(#arity, " sequence items")],
879                    ));
880                }
881                let Self(#(#bindings),*) = self;
882                #(#writes)*
883                Ok(node)
884            }
885        }
886
887        impl #write_impl_generics ::yaml_rt::ToYamlFragment for #name #write_type_generics #write_where_clause {
888            fn to_yaml_fragment(
889                &self,
890                indent: usize,
891                line_ending: &str,
892            ) -> Result<String, ::yaml_rt::YamlError> {
893                let Self(#(#bindings),*) = self;
894                let __yaml_rt_fields = [#(#fragments),*];
895                Ok(::yaml_rt::__sequence_fields_to_yaml_fragment(
896                    &__yaml_rt_fields,
897                    indent,
898                    line_ending,
899                ))
900            }
901        }
902    })
903}
904
905struct UnitVariant {
906    ident: syn::Ident,
907    canonical: String,
908    aliases: Vec<String>,
909}
910
911fn expand_enum(
912    attrs: &[Attribute],
913    name: &syn::Ident,
914    generics: syn::Generics,
915    variants: syn::punctuated::Punctuated<syn::Variant, syn::token::Comma>,
916) -> syn::Result<TokenStream2> {
917    if variants
918        .iter()
919        .all(|variant| matches!(variant.fields, Fields::Unit))
920    {
921        expand_unit_enum(attrs, name, &generics, variants)
922    } else {
923        expand_tagged_enum(attrs, name, generics, variants)
924    }
925}
926
927fn expand_unit_enum(
928    attrs: &[Attribute],
929    name: &syn::Ident,
930    generics: &syn::Generics,
931    variants: syn::punctuated::Punctuated<syn::Variant, syn::token::Comma>,
932) -> syn::Result<TokenStream2> {
933    let expanded = parse_unit_variants(attrs, variants)?;
934    Ok(render_unit_enum(name, generics, &expanded))
935}
936
937fn parse_unit_variants(
938    attrs: &[Attribute],
939    variants: syn::punctuated::Punctuated<syn::Variant, syn::token::Comma>,
940) -> syn::Result<Vec<UnitVariant>> {
941    let options = parse_enum_options(attrs)?;
942    let mut expanded = Vec::new();
943    let mut names = BTreeMap::<String, String>::new();
944    for variant in variants {
945        if !matches!(variant.fields, Fields::Unit) {
946            return Err(syn::Error::new_spanned(
947                variant,
948                "tagged enum payload variants are not available yet",
949            ));
950        }
951        let variant_options = parse_variant_options(&variant.attrs)?;
952        if variant_options.rename_all.is_some() {
953            return Err(syn::Error::new_spanned(
954                &variant.ident,
955                "yaml(rename_all) is supported only on enum variants with named fields",
956            ));
957        }
958        let rust_name = variant.ident.to_string();
959        let canonical = variant_options
960            .rename
961            .unwrap_or_else(|| apply_rename_rule(&rust_name, options.rename_all));
962        register_enum_variant_names(
963            &variant.ident,
964            &canonical,
965            &variant_options.aliases,
966            &mut names,
967        )?;
968        expanded.push(UnitVariant {
969            ident: variant.ident,
970            canonical,
971            aliases: variant_options.aliases,
972        });
973    }
974    Ok(expanded)
975}
976
977fn render_unit_enum(
978    name: &syn::Ident,
979    generics: &syn::Generics,
980    expanded: &[UnitVariant],
981) -> TokenStream2 {
982    let expected = expanded
983        .iter()
984        .map(|variant| variant.canonical.as_str())
985        .collect::<Vec<_>>();
986    let read_arms = expanded.iter().map(unit_variant_read_arm);
987    let write_arms = expanded.iter().map(unit_variant_write_arm);
988    let fragment_arms = expanded.iter().map(unit_variant_fragment_arm);
989    let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
990
991    quote! {
992        impl #impl_generics ::yaml_rt::FromYamlDoc for #name #type_generics #where_clause {
993            fn from_yaml_doc(doc: &::yaml_rt::YamlDoc) -> Result<Self, ::yaml_rt::YamlError> {
994                ::yaml_rt::__read_yaml_document(doc)
995            }
996        }
997
998        impl #impl_generics ::yaml_rt::ToYamlDoc for #name #type_generics #where_clause {
999            fn apply_to_yaml_doc(&self, doc: &mut ::yaml_rt::YamlDoc) -> Result<(), ::yaml_rt::YamlError> {
1000                ::yaml_rt::__write_yaml_document(self, doc)
1001            }
1002        }
1003
1004        impl #impl_generics ::yaml_rt::YamlValue for #name #type_generics #where_clause {
1005            fn read_yaml(
1006                doc: &::yaml_rt::YamlDoc,
1007                node: ::yaml_rt::NodeId,
1008            ) -> Result<Self, ::yaml_rt::YamlError> {
1009                if let Some(tag) = doc.raw_tag(node).filter(|tag| {
1010                    tag.starts_with('!') && !tag.starts_with("!!")
1011                }) {
1012                    return Err(::yaml_rt::__typed_node_error(
1013                        doc,
1014                        node,
1015                        format!("unknown YAML enum tag `{tag}`"),
1016                        &[#(#expected),*],
1017                    ));
1018                }
1019                let value = <String as ::yaml_rt::YamlValue>::read_yaml(doc, node)?;
1020                match value.as_str() {
1021                    #(#read_arms,)*
1022                    _ => Err(::yaml_rt::__typed_node_error(
1023                        doc,
1024                        node,
1025                        format!("unknown YAML enum variant `{value}`"),
1026                        &[#(#expected),*],
1027                    )),
1028                }
1029            }
1030
1031            fn write_yaml(
1032                &self,
1033                doc: &mut ::yaml_rt::YamlDoc,
1034                node: Option<::yaml_rt::NodeId>,
1035            ) -> Result<::yaml_rt::NodeId, ::yaml_rt::YamlError> {
1036                let node = node.ok_or_else(|| {
1037                    ::yaml_rt::YamlError::new(::yaml_rt::Diagnostic::new(
1038                        ::yaml_rt::DiagnosticKind::Typed,
1039                        "cannot insert a standalone YAML enum without collection context",
1040                        ::yaml_rt::Span::empty(0),
1041                    ))
1042                })?;
1043                match self {
1044                    #(#write_arms,)*
1045                }
1046            }
1047        }
1048
1049        impl #impl_generics ::yaml_rt::ToYamlFragment for #name #type_generics #where_clause {
1050            fn to_yaml_fragment(
1051                &self,
1052                indent: usize,
1053                line_ending: &str,
1054            ) -> Result<String, ::yaml_rt::YamlError> {
1055                match self {
1056                    #(#fragment_arms,)*
1057                }
1058            }
1059        }
1060    }
1061}
1062
1063fn unit_variant_read_arm(variant: &UnitVariant) -> TokenStream2 {
1064    let ident = &variant.ident;
1065    let names = unit_variant_names(variant);
1066    quote! {
1067        #(#names)|* => Ok(Self::#ident)
1068    }
1069}
1070
1071fn unit_variant_write_arm(variant: &UnitVariant) -> TokenStream2 {
1072    let ident = &variant.ident;
1073    let canonical = &variant.canonical;
1074    let names = unit_variant_names(variant);
1075    quote! {
1076        Self::#ident => {
1077            let __yaml_rt_has_local_tag = doc.raw_tag(node).is_some_and(|tag| {
1078                tag.starts_with('!') && !tag.starts_with("!!")
1079            });
1080            if !__yaml_rt_has_local_tag
1081                && <String as ::yaml_rt::YamlValue>::read_yaml(doc, node)
1082                    .is_ok_and(|value| matches!(value.as_str(), #(#names)|*))
1083            {
1084                return Ok(node);
1085            }
1086            <String as ::yaml_rt::YamlValue>::write_yaml(
1087                &#canonical.to_owned(),
1088                doc,
1089                Some(node),
1090            )
1091        }
1092    }
1093}
1094
1095fn unit_variant_fragment_arm(variant: &UnitVariant) -> TokenStream2 {
1096    let ident = &variant.ident;
1097    let canonical = &variant.canonical;
1098    quote! {
1099        Self::#ident => <String as ::yaml_rt::ToYamlFragment>::to_yaml_fragment(
1100            &#canonical.to_owned(),
1101            indent,
1102            line_ending,
1103        )
1104    }
1105}
1106
1107fn unit_variant_names(variant: &UnitVariant) -> Vec<&String> {
1108    std::iter::once(&variant.canonical)
1109        .chain(variant.aliases.iter())
1110        .collect()
1111}
1112
1113struct PayloadField {
1114    ty: syn::Type,
1115    with: Option<Path>,
1116}
1117
1118enum EnumVariantKind {
1119    Unit,
1120    Newtype(PayloadField),
1121    Tuple(Vec<PayloadField>),
1122    Struct {
1123        fields: Vec<syn::Ident>,
1124        expansion: FieldExpansion,
1125    },
1126}
1127
1128struct EnumVariant {
1129    ident: syn::Ident,
1130    canonical: String,
1131    aliases: Vec<String>,
1132    kind: EnumVariantKind,
1133}
1134
1135struct TaggedEnumExpansion {
1136    variants: Vec<EnumVariant>,
1137    read_bounds: Vec<syn::WherePredicate>,
1138    write_bounds: Vec<syn::WherePredicate>,
1139}
1140
1141fn expand_tagged_enum(
1142    attrs: &[Attribute],
1143    name: &syn::Ident,
1144    generics: syn::Generics,
1145    variants: syn::punctuated::Punctuated<syn::Variant, syn::token::Comma>,
1146) -> syn::Result<TokenStream2> {
1147    let expansion = parse_tagged_enum_variants(attrs, variants)?;
1148    Ok(render_tagged_enum(name, generics, expansion))
1149}
1150
1151fn parse_tagged_enum_variants(
1152    attrs: &[Attribute],
1153    variants: syn::punctuated::Punctuated<syn::Variant, syn::token::Comma>,
1154) -> syn::Result<TaggedEnumExpansion> {
1155    let options = parse_enum_options(attrs)?;
1156    let mut expanded = Vec::new();
1157    let mut names = BTreeMap::<String, String>::new();
1158    let mut read_bounds = Vec::new();
1159    let mut write_bounds = Vec::new();
1160
1161    for variant in variants {
1162        let variant_options = parse_variant_options(&variant.attrs)?;
1163        let rust_name = variant.ident.to_string();
1164        let canonical = variant_options
1165            .rename
1166            .unwrap_or_else(|| apply_rename_rule(&rust_name, options.rename_all));
1167        register_enum_variant_names(
1168            &variant.ident,
1169            &canonical,
1170            &variant_options.aliases,
1171            &mut names,
1172        )?;
1173        if variant_options.rename_all.is_some() && !matches!(variant.fields, Fields::Named(_)) {
1174            return Err(syn::Error::new_spanned(
1175                &variant.ident,
1176                "yaml(rename_all) is supported only on enum variants with named fields",
1177            ));
1178        }
1179
1180        let kind = match variant.fields {
1181            Fields::Unit => EnumVariantKind::Unit,
1182            Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
1183                validate_enum_tag_names(&variant.ident, &canonical, &variant_options.aliases)?;
1184                let field = parse_payload_field(
1185                    fields
1186                        .unnamed
1187                        .into_iter()
1188                        .next()
1189                        .expect("one unnamed field was checked"),
1190                    &mut read_bounds,
1191                    &mut write_bounds,
1192                )?;
1193                EnumVariantKind::Newtype(field)
1194            }
1195            Fields::Unnamed(fields) => {
1196                validate_enum_tag_names(&variant.ident, &canonical, &variant_options.aliases)?;
1197                let fields = fields
1198                    .unnamed
1199                    .into_iter()
1200                    .map(|field| parse_payload_field(field, &mut read_bounds, &mut write_bounds))
1201                    .collect::<syn::Result<Vec<_>>>()?;
1202                EnumVariantKind::Tuple(fields)
1203            }
1204            Fields::Named(fields) => {
1205                validate_enum_tag_names(&variant.ident, &canonical, &variant_options.aliases)?;
1206                let field_names = fields
1207                    .named
1208                    .iter()
1209                    .filter_map(|field| field.ident.clone())
1210                    .collect::<Vec<_>>();
1211                let expansion = expand_fields(
1212                    fields.named,
1213                    InsertOrder::Append,
1214                    FieldAccess::Bindings,
1215                    variant_options.rename_all,
1216                )?;
1217                validate_struct_options(
1218                    &variant.ident,
1219                    &StructOptions::default(),
1220                    expansion.has_flatten,
1221                )?;
1222                read_bounds.extend(expansion.read_bounds.iter().cloned());
1223                write_bounds.extend(expansion.write_bounds.iter().cloned());
1224                EnumVariantKind::Struct {
1225                    fields: field_names,
1226                    expansion,
1227                }
1228            }
1229        };
1230        expanded.push(EnumVariant {
1231            ident: variant.ident,
1232            canonical,
1233            aliases: variant_options.aliases,
1234            kind,
1235        });
1236    }
1237
1238    Ok(TaggedEnumExpansion {
1239        variants: expanded,
1240        read_bounds,
1241        write_bounds,
1242    })
1243}
1244
1245fn tagged_enum_read_body(expanded: &[EnumVariant]) -> TokenStream2 {
1246    let expected_units = expanded
1247        .iter()
1248        .filter(|variant| matches!(variant.kind, EnumVariantKind::Unit))
1249        .map(|variant| variant.canonical.as_str())
1250        .collect::<Vec<_>>();
1251    let expected_tags = expanded
1252        .iter()
1253        .filter(|variant| !matches!(variant.kind, EnumVariantKind::Unit))
1254        .map(|variant| variant.canonical.as_str())
1255        .collect::<Vec<_>>();
1256    let unit_read_arms = expanded
1257        .iter()
1258        .filter(|variant| matches!(variant.kind, EnumVariantKind::Unit))
1259        .map(|variant| {
1260            let ident = &variant.ident;
1261            let accepted = accepted_variant_names(variant);
1262            quote! { #(#accepted)|* => Ok(Self::#ident) }
1263        })
1264        .collect::<Vec<_>>();
1265    let tagged_read_arms = expanded
1266        .iter()
1267        .filter(|variant| !matches!(variant.kind, EnumVariantKind::Unit))
1268        .map(tagged_variant_read_arm)
1269        .collect::<Vec<_>>();
1270    let untagged_scalar_read = if unit_read_arms.is_empty() {
1271        quote! {
1272            Err(::yaml_rt::__typed_node_error(
1273                doc,
1274                node,
1275                "enum data variant requires a local YAML tag",
1276                &[#(#expected_tags),*],
1277            ))
1278        }
1279    } else {
1280        quote! {
1281            let value = <String as ::yaml_rt::YamlValue>::read_yaml(doc, node)?;
1282            match value.as_str() {
1283                #(#unit_read_arms,)*
1284                _ => Err(::yaml_rt::__typed_node_error(
1285                    doc,
1286                    node,
1287                    format!("unknown YAML enum variant `{value}`"),
1288                    &[#(#expected_units),*],
1289                )),
1290            }
1291        }
1292    };
1293
1294    quote! {
1295        let __yaml_rt_raw_tag = doc.raw_tag(node);
1296        let __yaml_rt_local_tag = __yaml_rt_raw_tag.and_then(|tag| {
1297            let suffix = tag.strip_prefix('!')?;
1298            (!suffix.is_empty()
1299                && !suffix.starts_with('!')
1300                && !suffix.starts_with('<'))
1301                .then_some(suffix)
1302        });
1303        if let Some(tag) = __yaml_rt_local_tag {
1304            match tag {
1305                #(#tagged_read_arms,)*
1306                _ => Err(::yaml_rt::__typed_node_error(
1307                    doc,
1308                    node,
1309                    format!("unknown YAML enum tag `!{tag}`"),
1310                    &[#(#expected_tags),*],
1311                )),
1312            }
1313        } else if __yaml_rt_raw_tag.is_some_and(|tag| {
1314            tag.starts_with('!') && !tag.starts_with("!!")
1315        }) {
1316            Err(::yaml_rt::__typed_node_error(
1317                doc,
1318                node,
1319                format!(
1320                    "unknown YAML enum tag `{}`",
1321                    __yaml_rt_raw_tag.unwrap_or_default()
1322                ),
1323                &[#(#expected_tags),*],
1324            ))
1325        } else if matches!(
1326            doc.semantic_kind(node),
1327            Some(::yaml_rt::SemanticKind::Scalar { .. })
1328        ) {
1329            #untagged_scalar_read
1330        } else {
1331            Err(::yaml_rt::__typed_node_error(
1332                doc,
1333                node,
1334                "enum data variant requires a local YAML tag",
1335                &[#(#expected_tags),*],
1336            ))
1337        }
1338    }
1339}
1340
1341fn render_tagged_enum(
1342    name: &syn::Ident,
1343    generics: syn::Generics,
1344    expansion: TaggedEnumExpansion,
1345) -> TokenStream2 {
1346    let TaggedEnumExpansion {
1347        variants,
1348        read_bounds,
1349        write_bounds,
1350    } = expansion;
1351    let read_body = tagged_enum_read_body(&variants);
1352    let write_arms = variants.iter().map(enum_variant_write_arm);
1353    let fragment_arms = variants.iter().map(enum_variant_fragment_arm);
1354    let (read_generics, write_generics, combined_generics) =
1355        enum_generics_with_bounds(generics, read_bounds, write_bounds);
1356    let (read_impl_generics, read_type_generics, read_where_clause) =
1357        read_generics.split_for_impl();
1358    let (write_impl_generics, write_type_generics, write_where_clause) =
1359        write_generics.split_for_impl();
1360    let (combined_impl_generics, combined_type_generics, combined_where_clause) =
1361        combined_generics.split_for_impl();
1362
1363    quote! {
1364        impl #read_impl_generics ::yaml_rt::FromYamlDoc for #name #read_type_generics #read_where_clause {
1365            fn from_yaml_doc(doc: &::yaml_rt::YamlDoc) -> Result<Self, ::yaml_rt::YamlError> {
1366                let node = doc.document_root(0)?.ok_or_else(|| {
1367                    ::yaml_rt::YamlError::new(::yaml_rt::Diagnostic::new(
1368                        ::yaml_rt::DiagnosticKind::Typed,
1369                        "document does not contain a YAML enum value",
1370                        ::yaml_rt::Span::empty(0),
1371                    ))
1372                })?;
1373                #read_body
1374            }
1375        }
1376
1377        impl #combined_impl_generics ::yaml_rt::ToYamlDoc for #name #combined_type_generics #combined_where_clause {
1378            fn apply_to_yaml_doc(&self, doc: &mut ::yaml_rt::YamlDoc) -> Result<(), ::yaml_rt::YamlError> {
1379                ::yaml_rt::__write_yaml_document(self, doc)
1380            }
1381        }
1382
1383        impl #combined_impl_generics ::yaml_rt::YamlValue for #name #combined_type_generics #combined_where_clause {
1384            fn read_yaml(
1385                doc: &::yaml_rt::YamlDoc,
1386                node: ::yaml_rt::NodeId,
1387            ) -> Result<Self, ::yaml_rt::YamlError> {
1388                #read_body
1389            }
1390
1391            fn write_yaml(
1392                &self,
1393                doc: &mut ::yaml_rt::YamlDoc,
1394                node: Option<::yaml_rt::NodeId>,
1395            ) -> Result<::yaml_rt::NodeId, ::yaml_rt::YamlError> {
1396                let node = node.ok_or_else(|| {
1397                    ::yaml_rt::YamlError::new(::yaml_rt::Diagnostic::new(
1398                        ::yaml_rt::DiagnosticKind::Typed,
1399                        "cannot insert a standalone YAML enum without collection context",
1400                        ::yaml_rt::Span::empty(0),
1401                    ))
1402                })?;
1403                match self {
1404                    #(#write_arms,)*
1405                }
1406            }
1407        }
1408
1409        impl #write_impl_generics ::yaml_rt::ToYamlFragment for #name #write_type_generics #write_where_clause {
1410            fn to_yaml_fragment(
1411                &self,
1412                indent: usize,
1413                line_ending: &str,
1414            ) -> Result<String, ::yaml_rt::YamlError> {
1415                match self {
1416                    #(#fragment_arms,)*
1417                }
1418            }
1419        }
1420    }
1421}
1422
1423fn enum_generics_with_bounds(
1424    generics: syn::Generics,
1425    read_bounds: Vec<syn::WherePredicate>,
1426    write_bounds: Vec<syn::WherePredicate>,
1427) -> (syn::Generics, syn::Generics, syn::Generics) {
1428    let mut read_generics = generics.clone();
1429    read_generics
1430        .make_where_clause()
1431        .predicates
1432        .extend(read_bounds.iter().cloned());
1433    let mut write_generics = generics.clone();
1434    write_generics
1435        .make_where_clause()
1436        .predicates
1437        .extend(write_bounds.iter().cloned());
1438    let mut combined_generics = generics;
1439    combined_generics
1440        .make_where_clause()
1441        .predicates
1442        .extend(read_bounds);
1443    combined_generics
1444        .make_where_clause()
1445        .predicates
1446        .extend(write_bounds);
1447    (read_generics, write_generics, combined_generics)
1448}
1449
1450fn accepted_variant_names(variant: &EnumVariant) -> Vec<&String> {
1451    std::iter::once(&variant.canonical)
1452        .chain(variant.aliases.iter())
1453        .collect()
1454}
1455
1456fn register_enum_variant_names(
1457    ident: &syn::Ident,
1458    canonical: &str,
1459    aliases: &[String],
1460    names: &mut BTreeMap<String, String>,
1461) -> syn::Result<()> {
1462    let rust_name = ident.to_string();
1463    for accepted in std::iter::once(canonical).chain(aliases.iter().map(String::as_str)) {
1464        if let Some(previous) = names.insert(accepted.to_owned(), rust_name.clone()) {
1465            return Err(syn::Error::new_spanned(
1466                ident,
1467                format!(
1468                    "yaml enum variant name `{accepted}` is used by both `{previous}` and `{rust_name}`"
1469                ),
1470            ));
1471        }
1472    }
1473    Ok(())
1474}
1475
1476fn validate_enum_tag_names(
1477    ident: &syn::Ident,
1478    canonical: &str,
1479    aliases: &[String],
1480) -> syn::Result<()> {
1481    for name in std::iter::once(canonical).chain(aliases.iter().map(String::as_str)) {
1482        if name.is_empty()
1483            || !name.chars().all(|character| {
1484                character.is_ascii_alphanumeric() || matches!(character, '_' | '-')
1485            })
1486        {
1487            return Err(syn::Error::new_spanned(
1488                ident,
1489                format!(
1490                    "`{name}` is not a valid local YAML tag name; use only ASCII letters, digits, `_`, or `-`"
1491                ),
1492            ));
1493        }
1494    }
1495    Ok(())
1496}
1497
1498fn parse_payload_field(
1499    field: syn::Field,
1500    read_bounds: &mut Vec<WherePredicate>,
1501    write_bounds: &mut Vec<WherePredicate>,
1502) -> syn::Result<PayloadField> {
1503    parse_unnamed_field(
1504        field,
1505        read_bounds,
1506        write_bounds,
1507        "unnamed enum fields support only yaml(with)",
1508    )
1509}
1510
1511fn parse_unnamed_field(
1512    field: syn::Field,
1513    read_bounds: &mut Vec<WherePredicate>,
1514    write_bounds: &mut Vec<WherePredicate>,
1515    unsupported_message: &str,
1516) -> syn::Result<PayloadField> {
1517    let options = parse_field_options(&field.attrs)?;
1518    if options.rename.is_some()
1519        || !options.aliases.is_empty()
1520        || options.default.is_some()
1521        || options.comment.is_some()
1522        || options.skip
1523        || options.skip_serializing_if.is_some()
1524        || options.flatten
1525    {
1526        return Err(syn::Error::new_spanned(&field, unsupported_message));
1527    }
1528    let ty = field.ty;
1529    if let Some(with) = &options.with {
1530        read_bounds.push(syn::parse_quote! {
1531            #with::Repr: ::yaml_rt::YamlValue
1532        });
1533        write_bounds.push(syn::parse_quote! {
1534            #with::Repr: ::yaml_rt::YamlValue + ::yaml_rt::ToYamlFragment
1535        });
1536    } else {
1537        read_bounds.push(syn::parse_quote! {
1538            #ty: ::yaml_rt::YamlValue
1539        });
1540        write_bounds.push(syn::parse_quote! {
1541            #ty: ::yaml_rt::YamlValue + ::yaml_rt::ToYamlFragment
1542        });
1543    }
1544    Ok(PayloadField {
1545        ty,
1546        with: options.with,
1547    })
1548}
1549
1550fn tagged_variant_read_arm(variant: &EnumVariant) -> TokenStream2 {
1551    let ident = &variant.ident;
1552    let accepted = accepted_variant_names(variant);
1553    let read = match &variant.kind {
1554        EnumVariantKind::Unit => unreachable!("unit variants do not use YAML tags"),
1555        EnumVariantKind::Newtype(field) => {
1556            let ty = &field.ty;
1557            if let Some(with) = &field.with {
1558                quote! {
1559                    {
1560                        let __yaml_rt_repr =
1561                            ::yaml_rt::__read_tagged_yaml_value::<#with::Repr>(doc, node)?;
1562                        Ok(Self::#ident(#with::from_yaml(__yaml_rt_repr)?))
1563                    }
1564                }
1565            } else {
1566                quote! {
1567                    Ok(Self::#ident(
1568                        ::yaml_rt::__read_tagged_yaml_value::<#ty>(doc, node)?
1569                    ))
1570                }
1571            }
1572        }
1573        EnumVariantKind::Tuple(fields) => {
1574            let arity = fields.len();
1575            let reads = fields.iter().enumerate().map(|(index, field)| {
1576                let ty = &field.ty;
1577                if let Some(with) = &field.with {
1578                    quote! {
1579                        {
1580                            let __yaml_rt_repr =
1581                                <#with::Repr as ::yaml_rt::YamlValue>::read_yaml(
1582                                    doc,
1583                                    __yaml_rt_items[#index],
1584                                )?;
1585                            #with::from_yaml(__yaml_rt_repr)?
1586                        }
1587                    }
1588                } else {
1589                    quote! {
1590                        <#ty as ::yaml_rt::YamlValue>::read_yaml(
1591                            doc,
1592                            __yaml_rt_items[#index],
1593                        )?
1594                    }
1595                }
1596            });
1597            quote! {
1598                {
1599                    if !matches!(
1600                        doc.semantic_kind(node),
1601                        Some(::yaml_rt::SemanticKind::Sequence { .. })
1602                    ) {
1603                        return Err(::yaml_rt::__typed_node_error(
1604                            doc,
1605                            node,
1606                            concat!(
1607                                "YAML enum variant `",
1608                                stringify!(#ident),
1609                                "` requires a sequence payload"
1610                            ),
1611                            &["a YAML sequence"],
1612                        ));
1613                    }
1614                    let __yaml_rt_items =
1615                        doc.sequence_items(node).collect::<::std::vec::Vec<_>>();
1616                    if __yaml_rt_items.len() != #arity {
1617                        return Err(::yaml_rt::__typed_node_error(
1618                            doc,
1619                            node,
1620                            format!(
1621                                "YAML enum variant `{}` expects {} tuple fields, found {}",
1622                                stringify!(#ident),
1623                                #arity,
1624                                __yaml_rt_items.len(),
1625                            ),
1626                            &[concat!(#arity, " sequence items")],
1627                        ));
1628                    }
1629                    Ok(Self::#ident(#(#reads),*))
1630                }
1631            }
1632        }
1633        EnumVariantKind::Struct { expansion, .. } => {
1634            let reads = &expansion.reads;
1635            let catch_all_count = flatten_catch_all_count(expansion);
1636            let claimed_keys = flatten_claimed_keys_binding(expansion, quote! { &[] });
1637            quote! {
1638                ::yaml_rt::__read_mapping_fields(doc, node, |doc| {
1639                    ::yaml_rt::__validate_yaml_flatten_layout(doc, #catch_all_count)?;
1640                    #claimed_keys
1641                    Ok(Self::#ident {
1642                        #(#reads,)*
1643                    })
1644                })
1645            }
1646        }
1647    };
1648    quote! {
1649        #(#accepted)|* => #read
1650    }
1651}
1652
1653#[expect(
1654    clippy::too_many_lines,
1655    reason = "all variant shapes must generate parallel write match arms"
1656)]
1657fn enum_variant_write_arm(variant: &EnumVariant) -> TokenStream2 {
1658    let ident = &variant.ident;
1659    let accepted = accepted_variant_names(variant);
1660    let same_tag = quote! {
1661        doc.raw_tag(node)
1662            .and_then(|tag| tag.strip_prefix('!'))
1663            .is_some_and(|tag| matches!(tag, #(#accepted)|*))
1664    };
1665
1666    match &variant.kind {
1667        EnumVariantKind::Unit => {
1668            quote! {
1669                Self::#ident => {
1670                    let __yaml_rt_has_local_tag = doc.raw_tag(node).is_some_and(|tag| {
1671                        tag.starts_with('!') && !tag.starts_with("!!")
1672                    });
1673                    if !__yaml_rt_has_local_tag
1674                        && <String as ::yaml_rt::YamlValue>::read_yaml(doc, node)
1675                            .is_ok_and(|value| matches!(value.as_str(), #(#accepted)|*))
1676                    {
1677                        Ok(node)
1678                    } else {
1679                        ::yaml_rt::__replace_yaml_value(self, doc, node)
1680                    }
1681                }
1682            }
1683        }
1684        EnumVariantKind::Newtype(field) => {
1685            let write = if let Some(with) = &field.with {
1686                quote! {
1687                    let __yaml_rt_repr = #with::to_yaml(value)?;
1688                    ::yaml_rt::__write_tagged_yaml_value(
1689                        &__yaml_rt_repr,
1690                        doc,
1691                        node,
1692                    )
1693                }
1694            } else {
1695                quote! {
1696                    ::yaml_rt::__write_tagged_yaml_value(value, doc, node)
1697                }
1698            };
1699            quote! {
1700                Self::#ident(value) => {
1701                    if #same_tag {
1702                        #write
1703                    } else {
1704                        ::yaml_rt::__replace_yaml_value(self, doc, node)
1705                    }
1706                }
1707            }
1708        }
1709        EnumVariantKind::Tuple(fields) => {
1710            let arity = fields.len();
1711            let bindings = (0..arity)
1712                .map(|index| syn::Ident::new(&format!("field_{index}"), ident.span()))
1713                .collect::<Vec<_>>();
1714            let writes =
1715                fields
1716                    .iter()
1717                    .zip(bindings.iter())
1718                    .enumerate()
1719                    .map(|(index, (field, binding))| {
1720                        let ty = &field.ty;
1721                        if let Some(with) = &field.with {
1722                            quote! {
1723                                let __yaml_rt_repr = #with::to_yaml(#binding)?;
1724                                <#with::Repr as ::yaml_rt::YamlValue>::write_yaml(
1725                                    &__yaml_rt_repr,
1726                                    doc,
1727                                    Some(__yaml_rt_items[#index]),
1728                                )?;
1729                            }
1730                        } else {
1731                            quote! {
1732                                <#ty as ::yaml_rt::YamlValue>::write_yaml(
1733                                    #binding,
1734                                    doc,
1735                                    Some(__yaml_rt_items[#index]),
1736                                )?;
1737                            }
1738                        }
1739                    });
1740            quote! {
1741                Self::#ident(#(#bindings),*) => {
1742                    if !(#same_tag) {
1743                        return ::yaml_rt::__replace_yaml_value(self, doc, node);
1744                    }
1745                    if !matches!(
1746                        doc.semantic_kind(node),
1747                        Some(::yaml_rt::SemanticKind::Sequence { .. })
1748                    ) {
1749                        return Err(::yaml_rt::__typed_node_error(
1750                            doc,
1751                            node,
1752                            concat!(
1753                                "YAML enum variant `",
1754                                stringify!(#ident),
1755                                "` requires a sequence payload"
1756                            ),
1757                            &["a YAML sequence"],
1758                        ));
1759                    }
1760                    let __yaml_rt_items =
1761                        doc.sequence_items(node).collect::<::std::vec::Vec<_>>();
1762                    if __yaml_rt_items.len() != #arity {
1763                        return Err(::yaml_rt::__typed_node_error(
1764                            doc,
1765                            node,
1766                            format!(
1767                                "YAML enum variant `{}` expects {} tuple fields, found {}",
1768                                stringify!(#ident),
1769                                #arity,
1770                                __yaml_rt_items.len(),
1771                            ),
1772                            &[concat!(#arity, " sequence items")],
1773                        ));
1774                    }
1775                    #(#writes)*
1776                    Ok(node)
1777                }
1778            }
1779        }
1780        EnumVariantKind::Struct { fields, expansion } => {
1781            let writes = &expansion.writes;
1782            let catch_all_count = flatten_catch_all_count(expansion);
1783            let claimed_keys = flatten_claimed_keys_binding(expansion, quote! { &[] });
1784            let validations = flatten_validation_tokens(expansion);
1785            quote! {
1786                Self::#ident { #(#fields),* } => {
1787                    if !(#same_tag) {
1788                        return ::yaml_rt::__replace_yaml_value(self, doc, node);
1789                    }
1790                    ::yaml_rt::__write_mapping_fields(doc, node, |doc| {
1791                        ::yaml_rt::__validate_yaml_flatten_layout(doc, #catch_all_count)?;
1792                        #claimed_keys
1793                        #(#validations)*
1794                        let root = doc.root_mapping()?;
1795                        #(#writes)*
1796                        Ok(())
1797                    })
1798                }
1799            }
1800        }
1801    }
1802}
1803
1804#[expect(
1805    clippy::too_many_lines,
1806    reason = "all variant shapes must generate parallel fragment match arms"
1807)]
1808fn enum_variant_fragment_arm(variant: &EnumVariant) -> TokenStream2 {
1809    let ident = &variant.ident;
1810    let canonical = &variant.canonical;
1811    match &variant.kind {
1812        EnumVariantKind::Unit => quote! {
1813            Self::#ident => <String as ::yaml_rt::ToYamlFragment>::to_yaml_fragment(
1814                &#canonical.to_owned(),
1815                indent,
1816                line_ending,
1817            )
1818        },
1819        EnumVariantKind::Newtype(field) => {
1820            let payload = if let Some(with) = &field.with {
1821                quote! {
1822                    let __yaml_rt_repr = #with::to_yaml(value)?;
1823                    <#with::Repr as ::yaml_rt::ToYamlFragment>::to_yaml_fragment(
1824                        &__yaml_rt_repr,
1825                        indent,
1826                        line_ending,
1827                    )?
1828                }
1829            } else {
1830                let ty = &field.ty;
1831                quote! {
1832                    <#ty as ::yaml_rt::ToYamlFragment>::to_yaml_fragment(
1833                        value,
1834                        indent,
1835                        line_ending,
1836                    )?
1837                }
1838            };
1839            quote! {
1840                Self::#ident(value) => {
1841                    let __yaml_rt_payload = { #payload };
1842                    ::yaml_rt::__tag_yaml_fragment(
1843                        #canonical,
1844                        &__yaml_rt_payload,
1845                        indent,
1846                        line_ending,
1847                    )
1848                }
1849            }
1850        }
1851        EnumVariantKind::Tuple(fields) => {
1852            let bindings = (0..fields.len())
1853                .map(|index| syn::Ident::new(&format!("field_{index}"), ident.span()))
1854                .collect::<Vec<_>>();
1855            let fragments = fields.iter().zip(bindings.iter()).map(|(field, binding)| {
1856                let ty = &field.ty;
1857                if let Some(with) = &field.with {
1858                    quote! {
1859                        {
1860                            let __yaml_rt_repr = #with::to_yaml(#binding)?;
1861                            <#with::Repr as ::yaml_rt::ToYamlFragment>::to_yaml_fragment(
1862                                &__yaml_rt_repr,
1863                                indent + 2,
1864                                line_ending,
1865                            )?
1866                        }
1867                    }
1868                } else {
1869                    quote! {
1870                        <#ty as ::yaml_rt::ToYamlFragment>::to_yaml_fragment(
1871                            #binding,
1872                            indent + 2,
1873                            line_ending,
1874                        )?
1875                    }
1876                }
1877            });
1878            quote! {
1879                Self::#ident(#(#bindings),*) => {
1880                    let __yaml_rt_fields = [#(#fragments),*];
1881                    let __yaml_rt_payload = ::yaml_rt::__sequence_fields_to_yaml_fragment(
1882                        &__yaml_rt_fields,
1883                        indent,
1884                        line_ending,
1885                    );
1886                    ::yaml_rt::__tag_yaml_fragment(
1887                        #canonical,
1888                        &__yaml_rt_payload,
1889                        indent,
1890                        line_ending,
1891                    )
1892                }
1893            }
1894        }
1895        EnumVariantKind::Struct { fields, expansion } => {
1896            let writes = &expansion.writes;
1897            let catch_all_count = flatten_catch_all_count(expansion);
1898            let claimed_keys = flatten_claimed_keys_binding(expansion, quote! { &[] });
1899            let validations = flatten_validation_tokens(expansion);
1900            quote! {
1901                Self::#ident { #(#fields),* } => {
1902                    let __yaml_rt_payload =
1903                        ::yaml_rt::__mapping_fields_to_yaml_fragment(
1904                            indent,
1905                            line_ending,
1906                            |doc| {
1907                                ::yaml_rt::__validate_yaml_flatten_layout(
1908                                    doc,
1909                                    #catch_all_count,
1910                                )?;
1911                                #claimed_keys
1912                                #(#validations)*
1913                                let root = doc.root_mapping()?;
1914                                #(#writes)*
1915                                Ok(())
1916                            },
1917                        )?;
1918                    ::yaml_rt::__tag_yaml_fragment(
1919                        #canonical,
1920                        &__yaml_rt_payload,
1921                        indent,
1922                        line_ending,
1923                    )
1924                }
1925            }
1926        }
1927    }
1928}
1929
1930fn apply_rename_rule(name: &str, rule: Option<RenameRule>) -> String {
1931    let name = name.strip_prefix("r#").unwrap_or(name);
1932    match rule {
1933        None | Some(RenameRule::PascalCase) => name.to_owned(),
1934        Some(RenameRule::Lowercase) => name.to_ascii_lowercase(),
1935        Some(RenameRule::SnakeCase) => variant_snake_case(name),
1936        Some(RenameRule::KebabCase) => variant_snake_case(name).replace('_', "-"),
1937        Some(RenameRule::ScreamingSnakeCase) => variant_snake_case(name).to_ascii_uppercase(),
1938        Some(RenameRule::CamelCase) => {
1939            let mut value = name.to_owned();
1940            if let Some(first) = value.get_mut(0..1) {
1941                first.make_ascii_lowercase();
1942            }
1943            value
1944        }
1945    }
1946}
1947
1948fn variant_snake_case(name: &str) -> String {
1949    let mut output = String::with_capacity(name.len());
1950    for (index, character) in name.char_indices() {
1951        if index > 0 && character.is_uppercase() {
1952            output.push('_');
1953        }
1954        output.push(character.to_ascii_lowercase());
1955    }
1956    output
1957}
1958
1959fn apply_field_rename_rule(name: &str, rule: Option<RenameRule>) -> String {
1960    let name = name.strip_prefix("r#").unwrap_or(name);
1961    match rule {
1962        None | Some(RenameRule::SnakeCase) => name.to_owned(),
1963        Some(RenameRule::Lowercase) => name.to_ascii_lowercase(),
1964        Some(RenameRule::KebabCase) => name.replace('_', "-"),
1965        Some(RenameRule::ScreamingSnakeCase) => name.to_ascii_uppercase(),
1966        Some(RenameRule::PascalCase) => name
1967            .split('_')
1968            .filter(|word| !word.is_empty())
1969            .map(|word| {
1970                let mut word = word.to_owned();
1971                if let Some(first) = word.get_mut(0..1) {
1972                    first.make_ascii_uppercase();
1973                }
1974                word
1975            })
1976            .collect(),
1977        Some(RenameRule::CamelCase) => {
1978            let mut value = apply_field_rename_rule(name, Some(RenameRule::PascalCase));
1979            if let Some(first) = value.get_mut(0..1) {
1980                first.make_ascii_lowercase();
1981            }
1982            value
1983        }
1984    }
1985}
1986
1987fn expand_fields(
1988    fields: syn::punctuated::Punctuated<syn::Field, syn::token::Comma>,
1989    insert_order: InsertOrder,
1990    access: FieldAccess,
1991    rename_all: Option<RenameRule>,
1992) -> syn::Result<FieldExpansion> {
1993    let mut expansion = FieldExpansion::default();
1994    let mut names = BTreeMap::<String, String>::new();
1995
1996    for field in fields {
1997        let options = parse_field_options(&field.attrs)?;
1998        let Some(field_name) = field.ident else {
1999            return Err(syn::Error::new_spanned(
2000                field,
2001                "YamlRt supports only named fields",
2002            ));
2003        };
2004        let field_type = field.ty;
2005        if options.flatten {
2006            expansion.has_flatten = true;
2007            push_flatten_field(&mut expansion, &field_name, &field_type, &options, access)?;
2008            continue;
2009        }
2010
2011        let canonical = options
2012            .rename
2013            .clone()
2014            .unwrap_or_else(|| apply_field_rename_rule(&field_name.to_string(), rename_all));
2015        register_field_names(&field_name, &canonical, &options.aliases, &mut names)?;
2016
2017        push_regular_field(
2018            &mut expansion,
2019            &field_name,
2020            &field_type,
2021            &options,
2022            insert_order,
2023            access,
2024            &canonical,
2025        )?;
2026    }
2027
2028    Ok(expansion)
2029}
2030
2031fn register_field_names(
2032    field: &syn::Ident,
2033    canonical: &str,
2034    aliases: &[String],
2035    names: &mut BTreeMap<String, String>,
2036) -> syn::Result<()> {
2037    let rust_name = field.to_string();
2038    for accepted in std::iter::once(canonical).chain(aliases.iter().map(String::as_str)) {
2039        if let Some(previous) = names.insert(accepted.to_owned(), rust_name.clone()) {
2040            return Err(syn::Error::new_spanned(
2041                field,
2042                format!(
2043                    "yaml field name `{accepted}` is used by both `{previous}` and `{rust_name}`"
2044                ),
2045            ));
2046        }
2047    }
2048    Ok(())
2049}
2050
2051fn push_flatten_field(
2052    expansion: &mut FieldExpansion,
2053    field_name: &syn::Ident,
2054    field_type: &syn::Type,
2055    options: &FieldOptions,
2056    access: FieldAccess,
2057) -> syn::Result<()> {
2058    if options.skip {
2059        return Err(syn::Error::new_spanned(
2060            field_name,
2061            "yaml(flatten) cannot be combined with yaml(skip)",
2062        ));
2063    }
2064    if options.with.is_some() {
2065        return Err(syn::Error::new_spanned(
2066            field_name,
2067            "yaml(with) cannot be combined with yaml(flatten)",
2068        ));
2069    }
2070    if options.rename.is_some()
2071        || !options.aliases.is_empty()
2072        || options.default.is_some()
2073        || options.comment.is_some()
2074        || options.skip_serializing_if.is_some()
2075    {
2076        return Err(syn::Error::new_spanned(
2077            field_name,
2078            "yaml(flatten) cannot be combined with rename, alias, default, comment, or skip_serializing_if",
2079        ));
2080    }
2081
2082    expansion.read_bounds.push(syn::parse_quote! {
2083        #field_type: ::yaml_rt::YamlFlatten
2084    });
2085    expansion.write_bounds.push(syn::parse_quote! {
2086        #field_type: ::yaml_rt::YamlFlatten
2087    });
2088    expansion.reads.push(quote! {
2089        #field_name: <#field_type as ::yaml_rt::YamlFlatten>::from_yaml_flattened(
2090            doc,
2091            &__yaml_rt_claimed_keys,
2092        )?
2093    });
2094    let field_value = field_reference(field_name, access);
2095    expansion.writes.push(quote! {
2096        <#field_type as ::yaml_rt::YamlFlatten>::apply_to_yaml_flattened(
2097            #field_value,
2098            doc,
2099            &__yaml_rt_claimed_keys,
2100        )?;
2101    });
2102    expansion.flatten_types.push(field_type.clone());
2103    expansion.flatten_values.push(field_value);
2104    Ok(())
2105}
2106
2107#[expect(
2108    clippy::too_many_lines,
2109    reason = "field read, write, and insertion tokens share one validated option set"
2110)]
2111fn push_regular_field(
2112    expansion: &mut FieldExpansion,
2113    field_name: &syn::Ident,
2114    field_type: &syn::Type,
2115    options: &FieldOptions,
2116    insert_order: InsertOrder,
2117    access: FieldAccess,
2118    yaml_key: &str,
2119) -> syn::Result<()> {
2120    let yaml_key = yaml_key.to_owned();
2121    expansion.known_keys.push(yaml_key.clone());
2122    let aliases = options.aliases.clone();
2123    expansion.known_keys.extend(aliases.iter().cloned());
2124    let insert_comment = if let Some(comment) = options
2125        .comment
2126        .clone()
2127        .or_else(|| options.doc_comment.clone())
2128    {
2129        quote! { Some(#comment) }
2130    } else {
2131        quote! { None }
2132    };
2133    let skip_serializing_if = options.skip_serializing_if.clone();
2134    let field_value = field_reference(field_name, access);
2135
2136    if options.skip {
2137        if options.with.is_some() {
2138            return Err(syn::Error::new_spanned(
2139                field_name,
2140                "yaml(with) cannot be combined with yaml(skip)",
2141            ));
2142        }
2143        expansion.read_bounds.push(syn::parse_quote! {
2144            #field_type: ::core::default::Default
2145        });
2146        expansion.reads.push(quote! {
2147            #field_name: ::core::default::Default::default()
2148        });
2149        return Ok(());
2150    }
2151
2152    let (read_present_value, read_required_field, write_type, write_value_binding, write_value_ref) =
2153        if let Some(with) = &options.with {
2154            expansion.read_bounds.push(syn::parse_quote! {
2155                #with::Repr: ::yaml_rt::YamlValue
2156            });
2157            expansion.write_bounds.push(syn::parse_quote! {
2158                #with::Repr: ::yaml_rt::YamlValue + ::yaml_rt::ToYamlFragment
2159            });
2160            (
2161                quote! {
2162                    {
2163                        let __yaml_rt_repr =
2164                            <#with::Repr as ::yaml_rt::YamlValue>::read_yaml(doc, node)?;
2165                        #with::from_yaml(__yaml_rt_repr)?
2166                    }
2167                },
2168                quote! {
2169                    {
2170                        let __yaml_rt_repr =
2171                            <#with::Repr as ::yaml_rt::YamlValue>::read_yaml_field(
2172                                doc,
2173                                node,
2174                                #yaml_key,
2175                            )?;
2176                        #with::from_yaml(__yaml_rt_repr)?
2177                    }
2178                },
2179                quote! { #with::Repr },
2180                quote! {
2181                    let __yaml_rt_repr = #with::to_yaml(#field_value)?;
2182                },
2183                quote! { &__yaml_rt_repr },
2184            )
2185        } else {
2186            expansion.read_bounds.push(syn::parse_quote! {
2187                #field_type: ::yaml_rt::YamlValue
2188            });
2189            expansion.write_bounds.push(syn::parse_quote! {
2190                #field_type: ::yaml_rt::YamlValue + ::yaml_rt::ToYamlFragment
2191            });
2192            (
2193                quote! {
2194                    <#field_type as ::yaml_rt::YamlValue>::read_yaml(doc, node)?
2195                },
2196                quote! {
2197                    <#field_type as ::yaml_rt::YamlValue>::read_yaml_field(
2198                        doc,
2199                        node,
2200                        #yaml_key,
2201                    )?
2202                },
2203                quote! { #field_type },
2204                quote! {},
2205                field_value.clone(),
2206            )
2207        };
2208    let read_value = if let Some(default) = options.default.clone() {
2209        quote! {
2210            match node {
2211                Some(node) => #read_present_value,
2212                None => { #default }
2213            }
2214        }
2215    } else {
2216        read_required_field
2217    };
2218    expansion.reads.push(quote! {
2219        #field_name: {
2220            let mut node = doc.get_path(&[#yaml_key])?;
2221            #(
2222                if node.is_none() {
2223                    node = doc.get_path(&[#aliases])?;
2224                }
2225            )*
2226            #read_value
2227        }
2228    });
2229
2230    let write_field = write_field_tokens(
2231        &write_type,
2232        &write_value_ref,
2233        &yaml_key,
2234        &aliases,
2235        insert_order,
2236        &insert_comment,
2237    );
2238    let write_field = quote! {
2239        #write_value_binding
2240        #write_field
2241    };
2242    push_field_write(
2243        &mut expansion.writes,
2244        &field_value,
2245        &yaml_key,
2246        &aliases,
2247        skip_serializing_if,
2248        write_field,
2249    );
2250    Ok(())
2251}
2252
2253fn write_field_tokens(
2254    field_type: &TokenStream2,
2255    field_value: &TokenStream2,
2256    yaml_key: &str,
2257    aliases: &[String],
2258    insert_order: InsertOrder,
2259    insert_comment: &TokenStream2,
2260) -> TokenStream2 {
2261    let insert_missing_field = match insert_order {
2262        InsertOrder::Append => quote! {
2263            doc.insert_mapping_value_with_comment(
2264                root,
2265                #yaml_key,
2266                #field_value,
2267                ::yaml_rt::MappingEntryStyle::default(),
2268                #insert_comment,
2269            )?;
2270        },
2271        InsertOrder::Struct => quote! {
2272            doc.insert_mapping_value_ordered_with_comment(
2273                root,
2274                #yaml_key,
2275                #field_value,
2276                ::yaml_rt::MappingEntryStyle::default(),
2277                #insert_comment,
2278                __yaml_rt_ordered_keys,
2279            )?;
2280        },
2281    };
2282
2283    quote! {
2284        let mut node = doc.get_path(&[#yaml_key])?;
2285        #(
2286            if node.is_none() {
2287                node = doc.get_path(&[#aliases])?;
2288            }
2289        )*
2290        if let Some(node) = node {
2291            <#field_type as ::yaml_rt::YamlValue>::write_yaml(#field_value, doc, Some(node))?;
2292        } else {
2293            #insert_missing_field
2294        }
2295    }
2296}
2297
2298fn push_field_write(
2299    field_writes: &mut Vec<TokenStream2>,
2300    field_value: &TokenStream2,
2301    yaml_key: &str,
2302    aliases: &[String],
2303    skip_serializing_if: Option<Path>,
2304    write_field: TokenStream2,
2305) {
2306    if let Some(predicate) = skip_serializing_if {
2307        field_writes.push(quote! {
2308            if #predicate(#field_value) {
2309                if doc.get_mapping_entry(root, #yaml_key)?.is_some() {
2310                    doc.remove_mapping_entry(root, #yaml_key)?;
2311                } else {
2312                    #(
2313                        if doc.get_mapping_entry(root, #aliases)?.is_some() {
2314                            doc.remove_mapping_entry(root, #aliases)?;
2315                        }
2316                    )*
2317                }
2318            } else {
2319                #write_field
2320            }
2321        });
2322    } else {
2323        field_writes.push(write_field);
2324    }
2325}
2326
2327fn field_reference(field_name: &syn::Ident, access: FieldAccess) -> TokenStream2 {
2328    match access {
2329        FieldAccess::SelfFields => quote! { &self.#field_name },
2330        FieldAccess::Bindings => quote! { #field_name },
2331    }
2332}
2333
2334fn validate_struct_options(
2335    name: &syn::Ident,
2336    struct_options: &StructOptions,
2337    has_flatten: bool,
2338) -> syn::Result<()> {
2339    if struct_options.insert_order == InsertOrder::Struct && has_flatten {
2340        return Err(syn::Error::new_spanned(
2341            name.clone(),
2342            "yaml(insert_order = \"struct\") cannot be combined with yaml(flatten)",
2343        ));
2344    }
2345
2346    if struct_options.unknown_field_policy == UnknownFieldPolicy::Prune && has_flatten {
2347        return Err(syn::Error::new_spanned(
2348            name.clone(),
2349            "yaml(prune_unknown_fields) cannot be combined with yaml(flatten)",
2350        ));
2351    }
2352
2353    Ok(())
2354}
2355
2356fn parse_struct_options(attrs: &[Attribute]) -> syn::Result<StructOptions> {
2357    let mut options = StructOptions::default();
2358
2359    for attr in attrs {
2360        if attr.path().is_ident("yaml") {
2361            parse_struct_yaml_attr(attr, &mut options)?;
2362        }
2363    }
2364
2365    Ok(options)
2366}
2367
2368fn parse_enum_options(attrs: &[Attribute]) -> syn::Result<EnumOptions> {
2369    let mut options = EnumOptions::default();
2370    for attr in attrs {
2371        if !attr.path().is_ident("yaml") {
2372            continue;
2373        }
2374        attr.parse_nested_meta(|meta| {
2375            if !meta.path.is_ident("rename_all") {
2376                return Err(meta.error("unsupported yaml enum attribute"));
2377            }
2378            let value = meta.value()?.parse::<LitStr>()?;
2379            options.rename_all = Some(parse_rename_rule(&value)?);
2380            Ok(())
2381        })?;
2382    }
2383    Ok(options)
2384}
2385
2386fn parse_variant_options(attrs: &[Attribute]) -> syn::Result<VariantOptions> {
2387    let mut options = VariantOptions::default();
2388    for attr in attrs {
2389        if !attr.path().is_ident("yaml") {
2390            continue;
2391        }
2392        attr.parse_nested_meta(|meta| {
2393            if meta.path.is_ident("rename") {
2394                options.rename = Some(meta.value()?.parse::<LitStr>()?.value());
2395                Ok(())
2396            } else if meta.path.is_ident("alias") {
2397                options
2398                    .aliases
2399                    .push(meta.value()?.parse::<LitStr>()?.value());
2400                Ok(())
2401            } else if meta.path.is_ident("rename_all") {
2402                let value = meta.value()?.parse::<LitStr>()?;
2403                options.rename_all = Some(parse_rename_rule(&value)?);
2404                Ok(())
2405            } else {
2406                Err(meta.error(
2407                    "enum variants support only yaml(rename), yaml(alias), and yaml(rename_all)",
2408                ))
2409            }
2410        })?;
2411    }
2412    Ok(options)
2413}
2414
2415fn parse_struct_yaml_attr(attr: &Attribute, options: &mut StructOptions) -> syn::Result<()> {
2416    attr.parse_nested_meta(|meta| {
2417        if meta.path.is_ident("preserve_unknown_fields") {
2418            options.unknown_field_policy = UnknownFieldPolicy::Preserve;
2419            Ok(())
2420        } else if meta.path.is_ident("prune_unknown_fields") {
2421            options.unknown_field_policy = UnknownFieldPolicy::Prune;
2422            Ok(())
2423        } else if meta.path.is_ident("insert_order") {
2424            let value = meta.value()?;
2425            let insert_order = value.parse::<LitStr>()?;
2426            match insert_order.value().as_str() {
2427                "append" => options.insert_order = InsertOrder::Append,
2428                "struct" => options.insert_order = InsertOrder::Struct,
2429                _ => {
2430                    return Err(meta.error("insert_order must be `append` or `struct`"));
2431                }
2432            }
2433            Ok(())
2434        } else if meta.path.is_ident("rename_all") {
2435            let value = meta.value()?.parse::<LitStr>()?;
2436            options.rename_all = Some(parse_rename_rule(&value)?);
2437            Ok(())
2438        } else {
2439            Err(meta.error("unsupported yaml struct attribute"))
2440        }
2441    })
2442}
2443
2444fn parse_rename_rule(value: &LitStr) -> syn::Result<RenameRule> {
2445    match value.value().as_str() {
2446        "lowercase" => Ok(RenameRule::Lowercase),
2447        "snake_case" => Ok(RenameRule::SnakeCase),
2448        "kebab-case" => Ok(RenameRule::KebabCase),
2449        "SCREAMING_SNAKE_CASE" => Ok(RenameRule::ScreamingSnakeCase),
2450        "camelCase" => Ok(RenameRule::CamelCase),
2451        "PascalCase" => Ok(RenameRule::PascalCase),
2452        _ => Err(syn::Error::new_spanned(
2453            value,
2454            "rename_all must be lowercase, snake_case, kebab-case, SCREAMING_SNAKE_CASE, camelCase, or PascalCase",
2455        )),
2456    }
2457}
2458
2459fn parse_field_options(attrs: &[Attribute]) -> syn::Result<FieldOptions> {
2460    let mut options = FieldOptions::default();
2461
2462    for attr in attrs {
2463        if attr.path().is_ident("doc") {
2464            collect_doc_comment(attr, &mut options);
2465        } else if attr.path().is_ident("yaml") {
2466            parse_yaml_attr(attr, &mut options)?;
2467        }
2468    }
2469
2470    Ok(options)
2471}
2472
2473fn collect_doc_comment(attr: &Attribute, options: &mut FieldOptions) {
2474    let Meta::NameValue(meta) = &attr.meta else {
2475        return;
2476    };
2477    let syn::Expr::Lit(expr) = &meta.value else {
2478        return;
2479    };
2480    let syn::Lit::Str(text) = &expr.lit else {
2481        return;
2482    };
2483
2484    let text = text.value().trim().to_owned();
2485    if text.is_empty() {
2486        return;
2487    }
2488
2489    if let Some(existing) = &mut options.doc_comment {
2490        existing.push('\n');
2491        existing.push_str(&text);
2492    } else {
2493        options.doc_comment = Some(text);
2494    }
2495}
2496
2497fn parse_yaml_attr(attr: &Attribute, options: &mut FieldOptions) -> syn::Result<()> {
2498    attr.parse_nested_meta(|meta| {
2499        if meta.path.is_ident("rename") {
2500            let value = meta.value()?;
2501            options.rename = Some(value.parse::<LitStr>()?.value());
2502            Ok(())
2503        } else if meta.path.is_ident("comment") {
2504            let value = meta.value()?;
2505            options.comment = Some(value.parse::<LitStr>()?.value());
2506            Ok(())
2507        } else if meta.path.is_ident("alias") {
2508            let value = meta.value()?;
2509            options.aliases.push(value.parse::<LitStr>()?.value());
2510            Ok(())
2511        } else if meta.path.is_ident("default") {
2512            if meta.input.peek(syn::Token![=]) {
2513                let value = meta.value()?;
2514                let default = value.parse::<syn::Expr>()?;
2515                options.default = Some(quote! { #default });
2516            } else {
2517                options.default = Some(quote! { ::core::default::Default::default() });
2518            }
2519            Ok(())
2520        } else if meta.path.is_ident("skip") {
2521            options.skip = true;
2522            Ok(())
2523        } else if meta.path.is_ident("skip_serializing_if") {
2524            let value = meta.value()?;
2525            let predicate = value.parse::<LitStr>()?.parse::<Path>()?;
2526            options.skip_serializing_if = Some(predicate);
2527            Ok(())
2528        } else if meta.path.is_ident("flatten") {
2529            options.flatten = true;
2530            Ok(())
2531        } else if meta.path.is_ident("with") {
2532            let value = meta.value()?;
2533            options.with = Some(value.parse::<LitStr>()?.parse::<Path>()?);
2534            Ok(())
2535        } else {
2536            Err(meta.error("unsupported yaml attribute"))
2537        }
2538    })
2539}
2540
2541#[cfg(test)]
2542mod tests {
2543    use super::*;
2544
2545    #[test]
2546    fn with_and_skip_report_a_targeted_error() {
2547        let input: DeriveInput = syn::parse_quote! {
2548            struct Invalid {
2549                #[yaml(with = "adapter", skip)]
2550                value: String,
2551            }
2552        };
2553
2554        let error = expand_yaml_rt(input).expect_err("with plus skip must fail");
2555
2556        assert!(
2557            error
2558                .to_string()
2559                .contains("yaml(with) cannot be combined with yaml(skip)")
2560        );
2561    }
2562
2563    #[test]
2564    fn with_and_flatten_report_a_targeted_error() {
2565        let input: DeriveInput = syn::parse_quote! {
2566            struct Invalid {
2567                #[yaml(with = "adapter", flatten)]
2568                value: String,
2569            }
2570        };
2571
2572        let error = expand_yaml_rt(input).expect_err("with plus flatten must fail");
2573
2574        assert!(
2575            error
2576                .to_string()
2577                .contains("yaml(with) cannot be combined with yaml(flatten)")
2578        );
2579    }
2580
2581    #[test]
2582    fn duplicate_variant_names_report_both_variants() {
2583        let input: DeriveInput = syn::parse_quote! {
2584            enum Invalid {
2585                First,
2586                #[yaml(rename = "First")]
2587                Second,
2588            }
2589        };
2590
2591        let error = expand_yaml_rt(input).expect_err("duplicate names must fail");
2592        let message = error.to_string();
2593
2594        assert!(message.contains("yaml enum variant name `First`"));
2595        assert!(message.contains("both `First` and `Second`"));
2596    }
2597
2598    #[test]
2599    fn data_variant_tags_reject_invalid_local_tag_characters() {
2600        let input: DeriveInput = syn::parse_quote! {
2601            enum Invalid {
2602                #[yaml(rename = "not/a/tag")]
2603                Value(u16),
2604            }
2605        };
2606
2607        let error = expand_yaml_rt(input).expect_err("invalid tag must fail");
2608
2609        assert!(
2610            error
2611                .to_string()
2612                .contains("not a valid local YAML tag name")
2613        );
2614    }
2615
2616    #[test]
2617    fn unsupported_rename_rule_is_targeted() {
2618        let enum_input: DeriveInput = syn::parse_quote! {
2619            #[yaml(rename_all = "UPPERCASE")]
2620            enum Invalid {
2621                Value,
2622            }
2623        };
2624        let struct_input: DeriveInput = syn::parse_quote! {
2625            #[yaml(rename_all = "UPPERCASE")]
2626            struct Invalid {
2627                value: String,
2628            }
2629        };
2630
2631        for input in [enum_input, struct_input] {
2632            let error = expand_yaml_rt(input).expect_err("unsupported rename rule must fail");
2633
2634            assert!(error.to_string().contains(
2635                "rename_all must be lowercase, snake_case, kebab-case, SCREAMING_SNAKE_CASE, camelCase, or PascalCase"
2636            ));
2637        }
2638    }
2639
2640    #[test]
2641    fn duplicate_struct_field_names_report_both_fields() {
2642        let input: DeriveInput = syn::parse_quote! {
2643            #[yaml(rename_all = "camelCase")]
2644            struct Invalid {
2645                first_value: String,
2646                #[yaml(alias = "firstValue")]
2647                second_value: String,
2648            }
2649        };
2650
2651        let error = expand_yaml_rt(input).expect_err("duplicate field names must fail");
2652        let message = error.to_string();
2653        assert!(message.contains("yaml field name `firstValue`"));
2654        assert!(message.contains("both `first_value` and `second_value`"));
2655    }
2656
2657    #[test]
2658    fn invalid_variant_and_unnamed_payload_attributes_are_targeted() {
2659        let variant_input: DeriveInput = syn::parse_quote! {
2660            enum Invalid {
2661                #[yaml(default)]
2662                Value(u16),
2663            }
2664        };
2665        let payload_input: DeriveInput = syn::parse_quote! {
2666            enum Invalid {
2667                Value(#[yaml(rename = "value")] u16),
2668            }
2669        };
2670
2671        let variant_error =
2672            expand_yaml_rt(variant_input).expect_err("invalid variant attr must fail");
2673        let payload_error =
2674            expand_yaml_rt(payload_input).expect_err("invalid payload attr must fail");
2675
2676        assert!(variant_error.to_string().contains(
2677            "enum variants support only yaml(rename), yaml(alias), and yaml(rename_all)"
2678        ));
2679        assert!(
2680            payload_error
2681                .to_string()
2682                .contains("unnamed enum fields support only yaml(with)")
2683        );
2684    }
2685
2686    #[test]
2687    fn tuple_and_unit_struct_attributes_report_targeted_errors() {
2688        let tuple_field: DeriveInput = syn::parse_quote! {
2689            struct Invalid(#[yaml(default)] u16, bool);
2690        };
2691        let tuple_container: DeriveInput = syn::parse_quote! {
2692            #[yaml(rename_all = "lowercase")]
2693            struct Invalid(u16, bool);
2694        };
2695        let unit_container: DeriveInput = syn::parse_quote! {
2696            #[yaml(rename_all = "lowercase")]
2697            struct Invalid;
2698        };
2699
2700        assert!(
2701            expand_yaml_rt(tuple_field)
2702                .expect_err("tuple field attribute must fail")
2703                .to_string()
2704                .contains("tuple struct fields support only yaml(with)")
2705        );
2706        assert!(
2707            expand_yaml_rt(tuple_container)
2708                .expect_err("tuple container attribute must fail")
2709                .to_string()
2710                .contains("tuple structs do not support container-level yaml attributes")
2711        );
2712        assert!(
2713            expand_yaml_rt(unit_container)
2714                .expect_err("unit container attribute must fail")
2715                .to_string()
2716                .contains("unit structs do not support container-level yaml attributes")
2717        );
2718    }
2719}