Skip to main content

taba_derive/
lib.rs

1//! Taba's derives.
2//!
3//! [`Output`](macro@Output) describes what `#[derive(Serialize)]` writes as a TypeScript type,
4//! and [`Input`](macro@Input) what `#[derive(Deserialize)]` reads. Both read serde's `#[serde(...)]`
5//! attributes with serde's own parser, `serde_derive_internals`.
6//!
7//! # Attributes
8//!
9//! Every serde [container], [variant] and [field] attribute works as serde documents it, except
10//! these, which fail to compile.
11//!
12//! Not supported yet:
13//!
14//! * `untagged` on a variant of a tagged enum
15//! * `remote`, `variant_identifier` and `field_identifier` on a type
16//! * `with`, `serialize_with` and `deserialize_with` on a variant
17//! * `skip_serializing_if` on a tuple field
18//!
19//! Never supported:
20//!
21//! * `skip` on a newtype's field (a newtype is its one value)
22//! * `flatten` with `deny_unknown_fields` (serde's docs rule out the pair)
23//! * a const parameter the JSON uses (TypeScript has none)
24//!
25//! `#[taba(with = "Type")]` names a type with the same JSON, for both directions. Its
26//! `serialize_with` and `deserialize_with` keys do the same for [`Output`](macro@Output) or
27//! [`Input`](macro@Input) alone.
28//!
29//! Use it on a field that has serde's `with`, `serialize_with` or `deserialize_with`, or whose type
30//! is from another crate. Use it on a type whose serde impls you wrote by hand.
31//!
32//! # Type parameters
33//!
34//! A generic type is declared once in TypeScript, like `Page<T>`. Its field types can ask only
35//! taba's traits and std's derivable ones of a type parameter, and one that needs more fails to
36//! compile, even when the type declares the bound:
37//!
38//! ```rust,ignore
39//! trait Freight {}
40//!
41//! #[derive(Serialize, Output)]
42//! struct Shipment<T: Freight> {
43//!     cargo: T,
44//! }
45//!
46//! // the trait bound `T: Freight` is not satisfied
47//! #[derive(Serialize, Output)]
48//! struct Load<T: Freight> {
49//!     shipments: Vec<Shipment<T>>,
50//! }
51//! ```
52//!
53//! Add a bound only where it's needed. Here that's `Shipment`'s impls rather than its definition,
54//! as the [API guidelines] recommend, and then `Load` needs no bound and both derive. A field of
55//! another crate's type takes `#[taba(with = "...")]` instead.
56//!
57//! [API guidelines]: https://rust-lang.github.io/api-guidelines/future-proofing.html#c-struct-bounds
58//! [container]: https://serde.rs/container-attrs.html
59//! [variant]: https://serde.rs/variant-attrs.html
60//! [field]: https://serde.rs/field-attrs.html
61#![cfg_attr(docsrs, feature(doc_cfg))]
62
63use std::iter;
64
65use proc_macro::TokenStream;
66use proc_macro2::{Span, TokenStream as Tokens};
67use quote::{ToTokens, quote, quote_spanned};
68use serde_derive_internals::{
69    Ctxt, Derive,
70    ast::{Container, Data, Field, Style, Variant},
71    attr::{self, Identifier, TagType},
72    name::MultiName,
73    replace_receiver,
74};
75use syn::{
76    Attribute, DeriveInput, Generics, Ident, LitStr,
77    ext::IdentExt,
78    parse_macro_input, parse_quote,
79    spanned::Spanned,
80    visit::{self, Visit},
81    visit_mut::{self, VisitMut},
82};
83
84/// Describes what `#[derive(Serialize)]` writes, from the same [attributes](crate#attributes).
85#[proc_macro_derive(Output, attributes(serde, taba))]
86pub fn output(input: TokenStream) -> TokenStream {
87    derive(Direction::Output, parse_macro_input!(input))
88}
89
90/// Describes what `#[derive(Deserialize)]` reads, from the same [attributes](crate#attributes).
91#[proc_macro_derive(Input, attributes(serde, taba))]
92pub fn input(input: TokenStream) -> TokenStream {
93    derive(Direction::Input, parse_macro_input!(input))
94}
95
96#[derive(Copy, Clone)]
97enum Direction {
98    Output,
99    Input,
100}
101
102impl From<Direction> for Derive {
103    fn from(value: Direction) -> Self {
104        match value {
105            Direction::Output => Self::Serialize,
106            Direction::Input => Self::Deserialize,
107        }
108    }
109}
110
111impl ToTokens for Direction {
112    fn to_tokens(&self, tokens: &mut Tokens) {
113        tokens.extend(match self {
114            Direction::Output => quote!(_taba::Direction::Output),
115            Direction::Input => quote!(_taba::Direction::Input),
116        });
117    }
118}
119
120impl Direction {
121    fn shape(self, ty: impl ToTokens) -> Tokens {
122        let path = self.trait_path();
123        quote!(<#ty as #path>::__SHAPE)
124    }
125
126    fn tagged(self, ty: impl ToTokens) -> Tokens {
127        let path = self.trait_path();
128        quote!(<#ty as #path>::__TAGGED)
129    }
130
131    fn optional(self, ty: impl ToTokens) -> Option<Tokens> {
132        match self {
133            Direction::Output => None,
134            Direction::Input => Some(quote!(<#ty as _taba::Input>::__OPTIONAL)),
135        }
136    }
137
138    fn trait_path(self) -> Tokens {
139        match self {
140            Direction::Output => quote!(_taba::Output),
141            Direction::Input => quote!(_taba::Input),
142        }
143    }
144
145    fn with_key(self) -> &'static str {
146        match self {
147            Direction::Output => "serialize_with",
148            Direction::Input => "deserialize_with",
149        }
150    }
151
152    fn name(self, name: &MultiName) -> String {
153        match self {
154            Direction::Output => name.serialize_name().value.clone(),
155            Direction::Input => name.deserialize_name().value.clone(),
156        }
157    }
158
159    fn converted(self, container: &attr::Container) -> Option<&syn::Type> {
160        match self {
161            Direction::Output => container.type_into(),
162            Direction::Input => container.type_from().or(container.type_try_from()),
163        }
164    }
165
166    fn skips(self, field: &attr::Field) -> bool {
167        match self {
168            Direction::Output => field.skip_serializing(),
169            Direction::Input => field.skip_deserializing(),
170        }
171    }
172
173    fn skips_variant(self, variant: &attr::Variant) -> bool {
174        match self {
175            Direction::Output => variant.skip_serializing(),
176            Direction::Input => variant.skip_deserializing(),
177        }
178    }
179
180    /// Whether `skip_serializing_if` may leave the field out.
181    fn skips_if(self, field: &attr::Field) -> bool {
182        match self {
183            Direction::Output => field.skip_serializing_if().is_some(),
184            Direction::Input => false,
185        }
186    }
187
188    /// Whether serde's `default` fills in the field when its key is missing.
189    fn defaults(self, container: &attr::Container, field: &attr::Field) -> bool {
190        match self {
191            Direction::Output => false,
192            Direction::Input => !field.default().is_none() || !container.default().is_none(),
193        }
194    }
195
196    /// Whether serde promises to reject keys the type doesn't declare.
197    fn rejects(self, container: &attr::Container) -> bool {
198        match self {
199            Direction::Output => false,
200            Direction::Input => container.deny_unknown_fields(),
201        }
202    }
203
204    /// The `tag` key serde leads a named struct's object with, when writing.
205    fn struct_tag(self, container: &attr::Container) -> Option<&str> {
206        let TagType::Internal { tag } = container.tag() else { return None };
207        match self {
208            Direction::Output => Some(tag),
209            Direction::Input => None,
210        }
211    }
212
213    fn hides(self, field: &attr::Field) -> bool {
214        match self {
215            Direction::Output => field.serialize_with().is_some(),
216            Direction::Input => field.deserialize_with().is_some(),
217        }
218    }
219
220    fn hides_variant(self, variant: &attr::Variant) -> bool {
221        match self {
222            Direction::Output => variant.serialize_with().is_some(),
223            Direction::Input => variant.deserialize_with().is_some(),
224        }
225    }
226}
227
228fn derive(direction: Direction, mut input: DeriveInput) -> TokenStream {
229    // serde's parser requires its private module (serde_derive_internals)
230    let private = syn::Ident::new("__private", Span::call_site());
231    replace_receiver(&mut input);
232    let mut itself = Itself { ident: input.ident.clone(), swapped: None };
233    itself.visit_data_mut(&mut input.data);
234    let serde = Ctxt::new();
235    let container = Container::from_ast(&serde, &input, Derive::from(direction), &private);
236    if let Err(error) = serde.check() {
237        return error.to_compile_error().into();
238    }
239    let container = container.expect("serde's parser reports an error whenever it returns none");
240
241    let ctxt = Ctxt::new();
242    let expander = Expander { ctxt: &ctxt, direction, container: &container };
243    let expanded = expander.expand(itself.swapped);
244    match ctxt.check() {
245        Ok(()) => expanded.into(),
246        Err(error) => error.to_compile_error().into(),
247    }
248}
249
250struct Expander<'a> {
251    ctxt: &'a Ctxt,
252    direction: Direction,
253    container: &'a Container<'a>,
254}
255
256/// Where a type's JSON comes from.
257enum Source<'a> {
258    /// A type `#[taba(...)]` names, on the type or a transparent type's field.
259    StandIn(Box<syn::Type>),
260
261    /// serde's `into`, `from` or `try_from` type, or a transparent type's field.
262    Through(&'a syn::Type),
263
264    /// Its own fields or variants.
265    Own(&'a Data<'a>),
266}
267
268impl Expander<'_> {
269    /// The derive's output.
270    ///
271    /// `itself` is the name the type's references to itself were swapped for, if it has any.
272    fn expand(&self, itself: Option<Ident>) -> Tokens {
273        self.refuse_unsupported();
274        self.check_taba();
275
276        let source = self.source();
277        let parameters = self.parameters(&source);
278        let named = named(self.container.generics, &parameters);
279        let reference = self.reference(&named, &parameters);
280        let named_fn = self.named_fn(&source, &parameters);
281        let itself = itself.map(|itself| self.itself(&itself, &parameters, &reference));
282        let trait_impl = self.trait_impl(&source, &parameters, &reference);
283        let request = self.request(&parameters, &named);
284        quote! {
285            const _: () = {
286                use ::taba::__private::typescript as _taba;
287
288                #named_fn
289                #itself
290                #trait_impl
291                #request
292            };
293        }
294    }
295
296    /// The block-local `named`, which returns the type's `Named`.
297    fn named_fn(&self, source: &Source, parameters: &[Ident]) -> Tokens {
298        let container = self.container;
299        let generics = container.generics;
300        let lifetimes: Vec<_> = generics.lifetimes().map(|param| &param.lifetime).collect();
301        let type_params: Vec<_> = generics.type_params().map(|param| &param.ident).collect();
302        let consts = generics.const_params().map(|param| &param.ident);
303        let const_types = generics.const_params().map(|param| &param.ty);
304        let name = container.ident.unraw().to_string();
305        let names = parameters.iter().map(|parameter| parameter.unraw().to_string());
306        let docs = docs(&container.original.attrs);
307        let direction = self.direction;
308        let shape = self.shape(source);
309        let location = location(container.ident.span());
310        quote! {
311            fn named<#(#lifetimes,)* #(#type_params,)* #(const #consts: #const_types),*>()
312            -> &'static _taba::Named
313            where
314                #(#lifetimes: 'static,)*
315                #(#type_params: 'static,)*
316                #(#parameters: _taba::Placeholder,)*
317            {
318                &const {
319                    _taba::Named {
320                        module_path: ::core::module_path!(),
321                        name: #name,
322                        parameters: &[#(#names),*],
323                        docs: #docs,
324                        direction: #direction,
325                        location: ::core::option::Option::Some(#location),
326                        shape: #shape,
327                    }
328                }
329            }
330        }
331    }
332
333    /// `__Itself`, which stands in for the type in its own fields.
334    fn itself(&self, itself: &Ident, parameters: &[Ident], reference: &Tokens) -> Tokens {
335        let path = self.direction.trait_path();
336        let mut generics = self.container.generics.clone();
337        for param in generics.type_params_mut() {
338            param.bounds = parse_quote!(?Sized);
339        }
340        let lifetimes = generics.lifetimes().map(|param| &param.lifetime);
341        let type_params = generics.type_params().map(|param| &param.ident);
342        let (params, ty_generics, _) = generics.split_for_impl();
343        quote! {
344            struct #itself #params(
345                ::core::marker::PhantomData<(#(&#lifetimes (),)* #(*const #type_params,)*)>,
346            );
347
348            impl #params #path for #itself #ty_generics
349            where
350                #(#parameters: #path,)*
351            {
352                const __SHAPE: _taba::Shape = #reference;
353            }
354        }
355    }
356
357    /// The `Input` or `Output` impl.
358    fn trait_impl(&self, source: &Source, parameters: &[Ident], reference: &Tokens) -> Tokens {
359        let ident = &self.container.ident;
360        let path = self.direction.trait_path();
361        let (impl_generics, ty_generics, where_clause) = self.container.generics.split_for_impl();
362        let predicates = where_clause.map(|clause| &clause.predicates);
363        let inner = self.inner(source);
364        let inner_bound = self.inner_bound(inner.as_ref(), parameters);
365        let optional = self.optional(source);
366        let tagged = self.tagged(inner.as_ref());
367        quote! {
368            impl #impl_generics #path for #ident #ty_generics
369            where
370                #(#parameters: #path,)*
371                #inner_bound
372                #predicates
373            {
374                const __SHAPE: _taba::Shape = #reference;
375                #optional
376                #tagged
377            }
378        }
379    }
380
381    /// The `Request` impl, for a type that isn't generic in TypeScript.
382    fn request(&self, parameters: &[Ident], named: &Tokens) -> Option<Tokens> {
383        let (Direction::Input, []) = (self.direction, parameters) else { return None };
384        let ident = &self.container.ident;
385        let (impl_generics, ty_generics, where_clause) = self.container.generics.split_for_impl();
386        Some(quote! {
387            #[diagnostic::do_not_recommend]
388            impl #impl_generics _taba::Request for #ident #ty_generics #where_clause {
389                fn named() -> &'static _taba::Named {
390                    #named()
391                }
392            }
393        })
394    }
395
396    /// A reference to the type, with each parameter it uses as an argument.
397    fn reference(&self, named: &Tokens, parameters: &[Ident]) -> Tokens {
398        let arguments = parameters.iter().map(|parameter| self.direction.shape(parameter));
399        quote!(_taba::Shape::Reference(#named, &[#(#arguments),*]))
400    }
401
402    /// The bound the items taken from `inner` need at the real parameters.
403    ///
404    /// `BTreeMap<T, u32>: Input` also needs `T: Key`.
405    fn inner_bound(&self, inner: Option<&syn::Type>, parameters: &[Ident]) -> Option<Tokens> {
406        let inner = inner?;
407        let path = self.direction.trait_path();
408        // without parameters the bound adds nothing, and rustc would report a missing impl twice
409        (!parameters.is_empty()).then(|| quote!(#inner: #path,))
410    }
411
412    /// The type parameters its TypeScript declaration takes, in order.
413    fn parameters(&self, source: &Source) -> Vec<Ident> {
414        let mentioned = self.mentioned(source);
415        let generics = self.container.generics;
416        for param in generics.const_params().filter(|param| mentioned.contains(&param.ident)) {
417            let message = "a const parameter in the JSON isn't supported: TypeScript has none";
418            self.ctxt.error_spanned_by(param, message);
419        }
420        let used = generics.type_params().filter(|param| mentioned.contains(&param.ident));
421        used.map(|param| param.ident.clone()).collect()
422    }
423
424    /// The bare identifiers in the types the shape is built from.
425    fn mentioned(&self, source: &Source) -> Vec<Ident> {
426        let mut mentions = Mentions(Vec::new());
427        match source {
428            Source::StandIn(ty) => mentions.visit_type(ty),
429            Source::Through(ty) => mentions.visit_type(ty),
430            Source::Own(data) => {
431                let fields: Vec<_> = match data {
432                    Data::Struct(_, fields) => self.present(fields).collect(),
433                    Data::Enum(variants) => variants
434                        .iter()
435                        .filter(|variant| !self.direction.skips_variant(&variant.attrs))
436                        .flat_map(|variant| self.present(&variant.fields))
437                        .collect(),
438                };
439                for field in fields {
440                    let stand_in = self.stand_in(&field.original.attrs);
441                    mentions.visit_type(stand_in.as_ref().unwrap_or(field.ty));
442                }
443            }
444        }
445        mentions.0
446    }
447
448    /// Refuses a type the derive can't describe yet.
449    fn refuse_unsupported(&self) {
450        let container = self.container;
451        let original = container.original;
452        if container.attrs.remote().is_some() {
453            self.ctxt.error_spanned_by(original, "`remote` isn't supported yet");
454        }
455        if !matches!(container.attrs.identifier(), Identifier::No) {
456            self.ctxt.error_spanned_by(original, "identifier enums aren't supported yet");
457        }
458        let tagged = !matches!(container.attrs.tag(), TagType::None);
459        if tagged && let Data::Enum(variants) = &container.data {
460            for variant in variants.iter().filter(|variant| variant.attrs.untagged()) {
461                let message = "`untagged` on a variant of a tagged enum isn't supported yet";
462                self.ctxt.error_spanned_by(variant.original, message);
463            }
464        }
465    }
466
467    fn source(&self) -> Source<'_> {
468        let container = self.container;
469        if let Some(ty) = self.stand_in(&container.original.attrs) {
470            return Source::StandIn(Box::new(ty));
471        }
472        if let Some(ty) = self.direction.converted(&container.attrs) {
473            return Source::Through(ty);
474        }
475        let field = container.data.all_fields().find(|field| field.attrs.transparent());
476        let Some(field) = field else {
477            return Source::Own(&container.data);
478        };
479        match self.field_stand_in(field) {
480            Some(ty) => Source::StandIn(Box::new(ty)),
481            None => Source::Through(field.ty),
482        }
483    }
484
485    fn shape(&self, source: &Source) -> Tokens {
486        match source {
487            Source::StandIn(ty) => self.direction.shape(ty),
488            Source::Through(ty) => self.direction.shape(ty),
489            Source::Own(Data::Enum(variants)) => self.variants(variants),
490            Source::Own(Data::Struct(Style::Struct, fields)) => {
491                self.struct_object(self.struct_tag(), fields)
492            }
493            Source::Own(Data::Struct(style, fields)) => self.fields(*style, fields),
494        }
495    }
496
497    /// The type's `__OPTIONAL` item, if it has one.
498    fn optional(&self, source: &Source) -> Option<Tokens> {
499        let Source::Through(ty) = source else { return None };
500        let optional = self.direction.optional(ty)?;
501        Some(quote!(const __OPTIONAL: bool = #optional;))
502    }
503
504    /// The type serde hands the value to, whose impl this one takes items from.
505    ///
506    /// A newtype struct passes on only `__TAGGED`. serde reports its missing field even when it
507    /// holds an `Option`.
508    fn inner(&self, source: &Source) -> Option<syn::Type> {
509        match source {
510            Source::Through(ty) => Some((*ty).clone()),
511            Source::Own(Data::Struct(Style::Newtype, fields)) => {
512                let field = &fields[0];
513                Some(self.stand_in(&field.original.attrs).unwrap_or_else(|| field.ty.clone()))
514            }
515            Source::StandIn(_) | Source::Own(_) => None,
516        }
517    }
518
519    /// The type's `__TAGGED` item, taken from `inner`.
520    fn tagged(&self, inner: Option<&syn::Type>) -> Option<Tokens> {
521        let tagged = self.direction.tagged(inner?);
522        Some(quote!(const __TAGGED: _taba::Shape = #tagged;))
523    }
524
525    fn struct_tag(&self) -> Option<Tokens> {
526        let tag = self.direction.struct_tag(&self.container.attrs)?;
527        let name = self.direction.name(self.container.attrs.name());
528        Some(required(tag, self.container.ident.span(), literal(&name)))
529    }
530
531    /// An object of `fields`, led by `tag` when there is one.
532    fn struct_object(&self, tag: Option<Tokens>, fields: &[Field]) -> Tokens {
533        let (flattened, keyed): (Vec<_>, Vec<_>) =
534            self.present(fields).partition(|field| field.attrs.flatten());
535        let properties = tag.into_iter().chain(keyed.iter().map(|field| self.property(field)));
536        if flattened.is_empty() {
537            return object(properties, self.rest());
538        }
539        let shapes = flattened.iter().map(|field| self.flattened(field));
540        object(properties, quote!(_taba::Rest::Parts(&[#(#shapes),*])))
541    }
542
543    /// The `Rest` of an object no field flattens into.
544    fn rest(&self) -> Tokens {
545        match self.direction.rejects(&self.container.attrs) {
546            true => quote!(_taba::Rest::Rejected),
547            false => quote!(_taba::Rest::Ignored),
548        }
549    }
550
551    /// The keys a flattened field adds, none when `skip_serializing_if` skips it.
552    fn flattened(&self, field: &Field) -> Tokens {
553        if self.direction.rejects(&self.container.attrs) {
554            let message = "`flatten` with `deny_unknown_fields` isn't supported";
555            self.ctxt.error_spanned_by(field.original, message);
556        }
557        let shape = self.field_shape(field);
558        if self.direction.skips_if(&field.attrs) {
559            return union([shape, quote!(_taba::Shape::Null)]);
560        }
561        shape
562    }
563
564    /// The fields serde writes or reads, in order.
565    fn present<'f>(&self, fields: &'f [Field<'f>]) -> impl Iterator<Item = &'f Field<'f>> {
566        fields.iter().filter(|field| !self.direction.skips(&field.attrs))
567    }
568
569    fn fields(&self, style: Style, fields: &[Field]) -> Tokens {
570        match style {
571            Style::Struct => self.struct_object(None, fields),
572            Style::Tuple => self.tuple(fields),
573            Style::Newtype => self.direction.shape(self.newtype(&fields[0])),
574            Style::Unit => quote!(_taba::Shape::Null),
575        }
576    }
577
578    fn tuple(&self, fields: &[Field]) -> Tokens {
579        let elements = self.present(fields).map(|field| self.element(field));
580        quote!(_taba::Shape::Tuple(&[#(#elements),*]))
581    }
582
583    fn element(&self, field: &Field) -> Tokens {
584        if self.direction.skips_if(&field.attrs) {
585            // skipping a tuple element shifts later positions
586            let message = "`skip_serializing_if` on a tuple field isn't supported";
587            self.ctxt.error_spanned_by(field.original, message);
588        }
589        self.field_shape(field)
590    }
591
592    /// The type a newtype's JSON comes from.
593    fn newtype(&self, field: &Field) -> syn::Type {
594        if self.direction.skips(&field.attrs) {
595            // a newtype has only one field
596            let message = "`skip` on a newtype's field isn't supported";
597            self.ctxt.error_spanned_by(field.original, message);
598        }
599        self.field_type(field)
600    }
601
602    fn property(&self, field: &Field) -> Tokens {
603        let key = self.direction.name(field.attrs.name());
604        let stand_in = self.field_stand_in(field);
605        let optional = self.optional_key(field, stand_in.as_ref());
606        let docs = docs(&field.original.attrs);
607        let location = location(field.member.span());
608        let ty = stand_in.as_ref().unwrap_or(field.ty);
609        let shape = self.direction.shape(ty);
610        quote! {
611            _taba::Property {
612                key: #key,
613                location: #location,
614                optional: #optional,
615                docs: #docs,
616                shape: #shape,
617            }
618        }
619    }
620
621    /// Whether serde lets the field's key be missing.
622    fn optional_key(&self, field: &Field, stand_in: Option<&syn::Type>) -> Tokens {
623        let skipped = self.direction.skips_if(&field.attrs);
624        let defaulted = self.direction.defaults(&self.container.attrs, &field.attrs);
625        if skipped || defaulted {
626            return quote!(true);
627        }
628        if stand_in.is_some() {
629            return quote!(false);
630        }
631        self.direction.optional(field.ty).unwrap_or_else(|| quote!(false))
632    }
633
634    fn field_shape(&self, field: &Field) -> Tokens {
635        self.direction.shape(self.field_type(field))
636    }
637
638    /// The field's type, or the type `#[taba(...)]` names for it.
639    fn field_type(&self, field: &Field) -> syn::Type {
640        self.field_stand_in(field).unwrap_or_else(|| field.ty.clone())
641    }
642
643    fn field_stand_in(&self, field: &Field) -> Option<syn::Type> {
644        let stand_in = self.stand_in(&field.original.attrs);
645        if stand_in.is_none() && self.direction.hides(&field.attrs) {
646            let key = self.direction.with_key();
647            let message = format!(
648                "serde's `with` or `{key}` hides this field's JSON: name a type with the same JSON \
649                 under the matching key, like `#[taba(with = \"String\")]`"
650            );
651            self.ctxt.error_spanned_by(field.original, message);
652        }
653        stand_in
654    }
655
656    /// Reports each `#[taba(...)]` that's malformed or on a variant, once.
657    fn check_taba(&self) {
658        let container = self.container;
659        let field_attrs = container.data.all_fields().map(|field| &field.original.attrs);
660        for attrs in iter::once(&container.original.attrs).chain(field_attrs) {
661            if let Err(error) = self.parse_stand_in(attrs) {
662                self.ctxt.syn_error(error);
663            }
664        }
665        if let Data::Enum(variants) = &container.data {
666            for variant in variants {
667                if variant.original.attrs.iter().any(|attr| attr.path().is_ident("taba")) {
668                    let message = "`#[taba(...)]` on a variant isn't supported";
669                    self.ctxt.error_spanned_by(variant.original, message);
670                }
671            }
672        }
673    }
674
675    /// The type `#[taba(...)]` names.
676    ///
677    /// Only its JSON is the same.
678    fn stand_in(&self, attrs: &[Attribute]) -> Option<syn::Type> {
679        self.parse_stand_in(attrs).ok().flatten()
680    }
681
682    fn parse_stand_in(&self, attrs: &[Attribute]) -> syn::Result<Option<syn::Type>> {
683        let mut stand_in = None;
684        for attr in attrs.iter().filter(|attr| attr.path().is_ident("taba")) {
685            attr.parse_nested_meta(|meta| {
686                let keys = ["with", "serialize_with", "deserialize_with"];
687                if !keys.iter().any(|key| meta.path.is_ident(key)) {
688                    return Err(meta.error("unknown `taba` attribute"));
689                }
690                let ty: syn::Type = meta.value()?.parse::<LitStr>()?.parse()?;
691                let applies =
692                    meta.path.is_ident("with") || meta.path.is_ident(self.direction.with_key());
693                if !applies {
694                    return Ok(());
695                }
696                if stand_in.is_some() {
697                    let key = meta.path.require_ident()?;
698                    return Err(meta.error(format!("duplicate `taba` attribute `{key}`")));
699                }
700                stand_in = Some(ty);
701                Ok(())
702            })?;
703        }
704        Ok(stand_in)
705    }
706
707    fn variants(&self, variants: &[Variant]) -> Tokens {
708        for variant in variants {
709            if self.direction.hides_variant(&variant.attrs) {
710                self.ctxt.error_spanned_by(variant.original, "`with` on a variant isn't supported");
711            }
712        }
713        let present =
714            variants.iter().filter(|variant| !self.direction.skips_variant(&variant.attrs));
715        // refused in `refuse_unsupported`, this keeps them from a second error
716        let tagged = present.clone().filter(|variant| !variant.attrs.untagged());
717        match self.container.attrs.tag() {
718            TagType::None => union(present.map(|variant| self.untagged(variant))),
719            TagType::External => union(tagged.map(|variant| self.externally_tagged(variant))),
720            TagType::Internal { tag } => {
721                union(tagged.map(|variant| self.internally_tagged(tag, variant)))
722            }
723            TagType::Adjacent { tag, content } => {
724                union(tagged.map(|variant| self.adjacently_tagged(tag, content, variant)))
725            }
726        }
727    }
728
729    /// The variant's JSON without a tag.
730    fn untagged(&self, variant: &Variant) -> Tokens {
731        self.fields(variant.style, &variant.fields)
732    }
733
734    fn externally_tagged(&self, variant: &Variant) -> Tokens {
735        let name = self.direction.name(variant.attrs.name());
736        if matches!(variant.style, Style::Unit) {
737            return literal(&name);
738        }
739        object([required(&name, variant.ident.span(), self.untagged(variant))], self.rest())
740    }
741
742    fn internally_tagged(&self, tag: &str, variant: &Variant) -> Tokens {
743        let name = self.direction.name(variant.attrs.name());
744        let tag = required(tag, variant.ident.span(), literal(&name));
745        match variant.style {
746            // serde takes extra keys here, with `deny_unknown_fields` or without
747            Style::Unit => object([tag], quote!(_taba::Rest::Ignored)),
748            Style::Struct => self.struct_object(Some(tag), &variant.fields),
749            Style::Newtype => {
750                let inner = self.direction.tagged(self.newtype(&variant.fields[0]));
751                object([tag], quote!(_taba::Rest::Parts(&[#inner])))
752            }
753            Style::Tuple => {
754                unreachable!("serde_derive_internals refuses tuple variants under internal tagging")
755            }
756        }
757    }
758
759    fn adjacently_tagged(&self, tag: &str, content: &str, variant: &Variant) -> Tokens {
760        let name = self.direction.name(variant.attrs.name());
761        let tag = required(tag, variant.ident.span(), literal(&name));
762        if matches!(variant.style, Style::Unit) {
763            return object([tag], self.rest());
764        }
765        let value = required(content, variant.ident.span(), self.untagged(variant));
766        object([tag, value], self.rest())
767    }
768}
769
770/// Swaps each field type naming the type itself, like `Tree<T>`, for `__Itself<T>`.
771struct Itself {
772    ident: Ident,
773    swapped: Option<Ident>,
774}
775
776impl VisitMut for Itself {
777    fn visit_path_mut(&mut self, path: &mut syn::Path) {
778        if path.leading_colon.is_none()
779            && path.segments.len() == 1
780            && let Some(segment) = path.segments.first_mut()
781            && segment.ident == self.ident
782        {
783            let swapped = &mut self.swapped;
784            let itself = swapped.get_or_insert_with(|| Ident::new("__Itself", Span::call_site()));
785            segment.ident = itself.clone();
786        }
787        visit_mut::visit_path_mut(self, path);
788    }
789}
790
791/// The bare identifiers some types mention.
792struct Mentions(Vec<Ident>);
793
794impl<'ast> Visit<'ast> for Mentions {
795    fn visit_path(&mut self, path: &'ast syn::Path) {
796        // serde's bounds skip it too, since `PhantomData<T>` is `null` whatever `T` is
797        if path.segments.last().is_some_and(|segment| segment.ident == "PhantomData") {
798            return;
799        }
800        if let Some(ident) = path.get_ident() {
801            self.0.push(ident.clone());
802        }
803        visit::visit_path(self, path);
804    }
805}
806
807/// The generated `named`, with an argument for each generic parameter.
808///
809/// A type parameter the shape uses gets its placeholder, and any other gets `()`. A const
810/// parameter is passed as itself.
811fn named(generics: &Generics, parameters: &[Ident]) -> Tokens {
812    let placeholders = generics.type_params().map(|param| {
813        match parameters.iter().position(|parameter| *parameter == param.ident) {
814            Some(index) => quote!(_taba::Parameter<#index>),
815            // any type, since nothing reads it
816            None => quote!(()),
817        }
818    });
819    let consts = generics.const_params().map(|param| &param.ident);
820    quote!(named::<#(#placeholders,)* #(#consts),*>)
821}
822
823fn literal(name: &str) -> Tokens {
824    quote!(_taba::Shape::Literal(#name))
825}
826
827/// A key serde adds, at the variant or struct it's for.
828fn required(key: &str, span: Span, shape: Tokens) -> Tokens {
829    let location = location(span);
830    quote! {
831        _taba::Property {
832            key: #key,
833            location: #location,
834            optional: false,
835            docs: &[],
836            shape: #shape,
837        }
838    }
839}
840
841/// `Location::caller()` at `span`, rather than the derive attribute above it.
842fn location(span: Span) -> Tokens {
843    quote_spanned!(span=> ::core::panic::Location::caller())
844}
845
846fn object(properties: impl IntoIterator<Item = Tokens>, rest: Tokens) -> Tokens {
847    let properties = properties.into_iter();
848    quote! {
849        _taba::Shape::Object(&_taba::Object {
850            properties: &[#(#properties),*],
851            rest: #rest,
852        })
853    }
854}
855
856fn union(shapes: impl IntoIterator<Item = Tokens>) -> Tokens {
857    let shapes = shapes.into_iter();
858    quote!(_taba::Shape::Union(&[#(#shapes),*]))
859}
860
861/// The `#[doc]` values on a type or field, as written.
862fn docs(attrs: &[Attribute]) -> Tokens {
863    let metas = attrs.iter().filter_map(|attr| attr.meta.require_name_value().ok());
864    let values = metas.filter(|meta| meta.path.is_ident("doc")).map(|meta| &meta.value);
865    quote!(&[#(#values),*])
866}