Skip to main content

fints_client_derive/
lib.rs

1//! Derive macros for fints-client's declarative FinTS segments.
2//!
3//! `#[derive(Segment)]` and `#[derive(DataElementGroup)]` generate the parse
4//! and serialise code for one segment version or one data element group. The
5//! generated code calls into `fints_client::codec`; the rules it implements
6//! (positions, optional elements, repetition, trailing elements) are
7//! documented there and in `docs/codec.md`.
8//!
9//! Attributes:
10//!
11//! - on a segment struct: `#[segment(code = "HKSAL", version = 7)]`
12//! - on a field: `#[de(max = 35)]` (maximum length), `#[de(len = 12)]`
13//!   (fixed length), `#[de(min_count = 1, max_count = 98)]` (repetition,
14//!   field type `Vec<T>`).
15//!
16//! Optional elements are `Option<T>` fields; nothing else marks them.
17//!
18//! Both derives also generate a static description of the definition
19//! (`Segment::SCHEMA`, `Element::KIND`; `fints_client::codec::schema`).
20
21use proc_macro::TokenStream;
22use proc_macro2::{Span, TokenStream as TokenStream2};
23use quote::{quote, quote_spanned};
24use syn::spanned::Spanned;
25use syn::{
26    Data, DeriveInput, Fields, GenericArgument, Ident, LitInt, LitStr, PathArguments, Type,
27    parse_macro_input,
28};
29
30/// Derives `fints_client::codec::Segment` for one segment version.
31///
32/// The struct lists the data elements after the segment header, in wire
33/// order. The header (`code:number:version[:reference]`) is handled by the
34/// codec and is not a field.
35#[proc_macro_derive(Segment, attributes(segment, de))]
36pub fn derive_segment(input: TokenStream) -> TokenStream {
37    let input = parse_macro_input!(input as DeriveInput);
38    expand_segment(&input)
39        .unwrap_or_else(syn::Error::into_compile_error)
40        .into()
41}
42
43/// Derives `fints_client::codec::Element` for a data element group (DEG).
44///
45/// The fields are the group's elements in wire order. A group nested in
46/// another group is flattened on the wire (`a:b:c:d`), as FinTS requires.
47#[proc_macro_derive(DataElementGroup, attributes(de))]
48pub fn derive_data_element_group(input: TokenStream) -> TokenStream {
49    let input = parse_macro_input!(input as DeriveInput);
50    expand_group(&input)
51        .unwrap_or_else(syn::Error::into_compile_error)
52        .into()
53}
54
55/// One field of a derived struct, with its `#[de(...)]` attributes.
56struct FieldSpec {
57    ident: Ident,
58    ty: Type,
59    /// `Some(T)` for a `Vec<T>` field (a repeated element).
60    repeated: Option<Type>,
61    max: Option<usize>,
62    len: Option<usize>,
63    min_count: Option<usize>,
64    max_count: Option<usize>,
65    span: Span,
66}
67
68impl FieldSpec {
69    fn name(&self) -> String {
70        self.ident.to_string()
71    }
72
73    fn rules(&self) -> TokenStream2 {
74        let max = opt_usize(self.max);
75        let len = opt_usize(self.len);
76        quote! { __p::Rules { max: #max, len: #len } }
77    }
78
79    /// The type that carries the length rules: `T` for `Vec<T>`, else the field type.
80    fn element_type(&self) -> &Type {
81        self.repeated.as_ref().unwrap_or(&self.ty)
82    }
83
84    /// Compile-time check that `max`/`len` sit on a data element, not on a group.
85    fn scalar_check(&self) -> TokenStream2 {
86        if self.max.is_none() && self.len.is_none() {
87            return TokenStream2::new();
88        }
89        let ty = self.element_type();
90        quote_spanned! {self.span=>
91            const _: () = __p::assert_length_rules_allowed(<#ty as __p::Element>::SCALAR);
92        }
93    }
94
95    /// The field's `__p::FieldSchema` entry (see `fints_client::codec::schema`).
96    fn schema(&self) -> TokenStream2 {
97        let name = self.name();
98        let max = opt_usize(self.max);
99        let len = opt_usize(self.len);
100        let (ty, min_count, max_count, repeated) = match &self.repeated {
101            Some(inner) => {
102                let min = self.min_count.unwrap_or(0);
103                (inner, quote! { #min }, opt_usize(self.max_count), true)
104            }
105            None => {
106                let ty = &self.ty;
107                (
108                    ty,
109                    quote! { if <#ty as __p::Element>::OPTIONAL { 0 } else { 1 } },
110                    quote! { ::core::option::Option::Some(1) },
111                    false,
112                )
113            }
114        };
115        quote! {
116            __p::FieldSchema {
117                name: #name,
118                kind: <#ty as __p::Element>::KIND,
119                max: #max,
120                len: #len,
121                min_count: #min_count,
122                max_count: #max_count,
123                repeated: #repeated,
124            }
125        }
126    }
127
128    fn width(&self) -> TokenStream2 {
129        match &self.repeated {
130            Some(inner) => {
131                let max = opt_usize(self.max_count);
132                quote! { __p::repeat_width(<#inner as __p::Element>::WIDTH, #max) }
133            }
134            None => {
135                let ty = &self.ty;
136                quote! { <#ty as __p::Element>::WIDTH }
137            }
138        }
139    }
140}
141
142fn opt_usize(v: Option<usize>) -> TokenStream2 {
143    match v {
144        Some(n) => quote! { ::core::option::Option::Some(#n) },
145        None => quote! { ::core::option::Option::None },
146    }
147}
148
149/// `Some(T)` if `ty` is `<path>::Name<T>` with the given last segment name.
150fn generic_arg_of<'a>(ty: &'a Type, name: &str) -> Option<&'a Type> {
151    let Type::Path(p) = ty else { return None };
152    if p.qself.is_some() {
153        return None;
154    }
155    let last = p.path.segments.last()?;
156    if last.ident != name {
157        return None;
158    }
159    let PathArguments::AngleBracketed(args) = &last.arguments else {
160        return None;
161    };
162    if args.args.len() != 1 {
163        return None;
164    }
165    match args.args.first()? {
166        GenericArgument::Type(t) => Some(t),
167        _ => None,
168    }
169}
170
171fn parse_fields(input: &DeriveInput) -> syn::Result<Vec<FieldSpec>> {
172    if !input.generics.params.is_empty() {
173        return Err(syn::Error::new(
174            input.generics.span(),
175            "fints-client: generic segment and group structs are not supported",
176        ));
177    }
178    let Data::Struct(data) = &input.data else {
179        return Err(syn::Error::new(
180            input.ident.span(),
181            "fints-client: only structs with named fields can be derived",
182        ));
183    };
184    let fields = match &data.fields {
185        Fields::Named(named) => named.named.iter().collect::<Vec<_>>(),
186        Fields::Unit => Vec::new(),
187        Fields::Unnamed(f) => {
188            return Err(syn::Error::new(
189                f.span(),
190                "fints-client: tuple structs are not supported; name every element",
191            ));
192        }
193    };
194
195    let count = fields.len();
196    let mut specs = Vec::with_capacity(count);
197    for (i, field) in fields.into_iter().enumerate() {
198        let Some(ident) = field.ident.clone() else {
199            return Err(syn::Error::new(field.span(), "fints-client: unnamed field"));
200        };
201        let mut spec = FieldSpec {
202            ident,
203            ty: field.ty.clone(),
204            repeated: generic_arg_of(&field.ty, "Vec").cloned(),
205            max: None,
206            len: None,
207            min_count: None,
208            max_count: None,
209            span: field.span(),
210        };
211        for attr in &field.attrs {
212            if !attr.path().is_ident("de") {
213                continue;
214            }
215            attr.parse_nested_meta(|meta| {
216                let slot = if meta.path.is_ident("max") {
217                    &mut spec.max
218                } else if meta.path.is_ident("len") {
219                    &mut spec.len
220                } else if meta.path.is_ident("min_count") {
221                    &mut spec.min_count
222                } else if meta.path.is_ident("max_count") {
223                    &mut spec.max_count
224                } else {
225                    return Err(meta.error(
226                        "fints-client: unknown `de` attribute; expected `max`, `len`, \
227                         `min_count` or `max_count`",
228                    ));
229                };
230                let lit: LitInt = meta.value()?.parse()?;
231                let value: usize = lit.base10_parse()?;
232                if slot.is_some() {
233                    return Err(meta.error("fints-client: attribute given twice"));
234                }
235                *slot = Some(value);
236                Ok(())
237            })?;
238        }
239        validate_field(&spec, i + 1 == count)?;
240        specs.push(spec);
241    }
242    Ok(specs)
243}
244
245fn validate_field(spec: &FieldSpec, is_last: bool) -> syn::Result<()> {
246    let err = |msg: &str| Err(syn::Error::new(spec.span, format!("fints-client: {msg}")));
247    if spec.max.is_some() && spec.len.is_some() {
248        return err("`max` and `len` exclude each other: a length is either a maximum or fixed");
249    }
250    if spec.max == Some(0) || spec.len == Some(0) {
251        return err("a length of 0 is not allowed");
252    }
253    if generic_arg_of(&spec.ty, "Option")
254        .is_some_and(|inner| generic_arg_of(inner, "Vec").is_some())
255    {
256        return err("use `Vec<T>` with `min_count = 0` instead of `Option<Vec<T>>`");
257    }
258    match &spec.repeated {
259        None => {
260            if spec.min_count.is_some() || spec.max_count.is_some() {
261                return err("`min_count`/`max_count` need a `Vec<T>` field");
262            }
263        }
264        Some(inner) => {
265            if generic_arg_of(inner, "Option").is_some() || generic_arg_of(inner, "Vec").is_some() {
266                return err("a repeated element is `Vec<T>` with T a data element or group");
267            }
268            if spec.max_count == Some(0) {
269                return err("`max_count` must be at least 1");
270            }
271            if let (Some(min), Some(max)) = (spec.min_count, spec.max_count)
272                && min > max
273            {
274                return err("`min_count` is larger than `max_count`");
275            }
276            if !is_last && spec.max_count.is_none() {
277                return err(
278                    "a repeated element that is not the last element needs `max_count`: \
279                     its unused repetitions are kept as empty positions (Formals H.1.2)",
280                );
281            }
282        }
283    }
284    Ok(())
285}
286
287fn expand_group(input: &DeriveInput) -> syn::Result<TokenStream2> {
288    let ident = &input.ident;
289    let ident_name = ident.to_string();
290    let fields = parse_fields(input)?;
291    if fields.is_empty() {
292        return Err(syn::Error::new(
293            ident.span(),
294            "fints-client: a data element group needs at least one element",
295        ));
296    }
297
298    let mut decode = Vec::new();
299    let mut encode = Vec::new();
300    let mut widths = Vec::new();
301    let mut checks = Vec::new();
302    let mut names = Vec::new();
303    let mut schema = Vec::new();
304    for f in &fields {
305        let fid = &f.ident;
306        let name = f.name();
307        let rules = f.rules();
308        names.push(fid.clone());
309        schema.push(f.schema());
310        widths.push(f.width());
311        checks.push(f.scalar_check());
312        match &f.repeated {
313            Some(inner) => {
314                let min = f.min_count.unwrap_or(0);
315                let max = opt_usize(f.max_count);
316                decode.push(quote! {
317                    let #fid = __p::decode_repeated::<#inner>(__cur, &#rules, #min, #max)
318                        .map_err(|e| e.in_field(#name))?;
319                });
320                encode.push(quote! {
321                    __p::encode_repeated::<#inner>(&self.#fid, __out, &#rules, #min, #max)
322                        .map_err(|e| e.in_field(#name))?;
323                });
324            }
325            None => {
326                let ty = &f.ty;
327                decode.push(quote! {
328                    let #fid = <#ty as __p::Element>::decode(__cur, &#rules)
329                        .map_err(|e| e.in_field(#name))?;
330                });
331                encode.push(quote! {
332                    <#ty as __p::Element>::encode(&self.#fid, __out, &#rules)
333                        .map_err(|e| e.in_field(#name))?;
334                });
335            }
336        }
337    }
338
339    Ok(quote! {
340        const _: () = {
341            use ::fints_client::codec::__private as __p;
342
343            impl __p::Element for #ident {
344                const WIDTH: ::core::option::Option<usize> = __p::seq_width(&[#(#widths),*]);
345                const SCALAR: bool = false;
346                const KIND: __p::ElementKind = __p::ElementKind::Group {
347                    name: #ident_name,
348                    fields: &[#(#schema),*],
349                };
350
351                fn decode(
352                    __cur: &mut __p::Cursor<'_>,
353                    _rules: &__p::Rules,
354                ) -> ::core::result::Result<Self, __p::CodecError> {
355                    #(#decode)*
356                    ::core::result::Result::Ok(Self { #(#names),* })
357                }
358
359                fn encode(
360                    &self,
361                    __out: &mut ::std::vec::Vec<__p::DataElement>,
362                    _rules: &__p::Rules,
363                ) -> ::core::result::Result<(), __p::CodecError> {
364                    #(#encode)*
365                    ::core::result::Result::Ok(())
366                }
367            }
368
369            // Evaluated at compile time: rejects an open-ended repetition that
370            // is not the last element of the group.
371            const _: ::core::option::Option<usize> = <#ident as __p::Element>::WIDTH;
372            #(#checks)*
373        };
374    })
375}
376
377struct SegmentAttr {
378    code: String,
379    version: u16,
380}
381
382fn parse_segment_attr(input: &DeriveInput) -> syn::Result<SegmentAttr> {
383    let mut code: Option<LitStr> = None;
384    let mut version: Option<LitInt> = None;
385    for attr in &input.attrs {
386        if !attr.path().is_ident("segment") {
387            continue;
388        }
389        attr.parse_nested_meta(|meta| {
390            if meta.path.is_ident("code") {
391                if code.is_some() {
392                    return Err(meta.error("fints-client: `code` given twice"));
393                }
394                code = Some(meta.value()?.parse()?);
395            } else if meta.path.is_ident("version") {
396                if version.is_some() {
397                    return Err(meta.error("fints-client: `version` given twice"));
398                }
399                version = Some(meta.value()?.parse()?);
400            } else {
401                return Err(meta.error(
402                    "fints-client: unknown `segment` attribute; expected `code` or `version`",
403                ));
404            }
405            Ok(())
406        })?;
407    }
408    let missing = || {
409        syn::Error::new(
410            input.ident.span(),
411            "fints-client: `#[segment(code = \"HKSAL\", version = 7)]` is required",
412        )
413    };
414    let code = code.ok_or_else(missing)?;
415    let version = version.ok_or_else(missing)?;
416    let code_value = code.value();
417    // Formals F, "Segmentkennung": an ..6. Segment codes are upper-case letters
418    // (first letter: H, B, D, G, V, X, I per Formals A).
419    if code_value.is_empty()
420        || code_value.len() > 6
421        || !code_value
422            .bytes()
423            .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
424    {
425        return Err(syn::Error::new(
426            code.span(),
427            "fints-client: a segment code is 1 to 6 upper-case letters or digits",
428        ));
429    }
430    let version_value: u16 = version.base10_parse()?;
431    if version_value == 0 || version_value > 999 {
432        return Err(syn::Error::new(
433            version.span(),
434            "fints-client: a segment version is a number from 1 to 999 (num ..3)",
435        ));
436    }
437    Ok(SegmentAttr {
438        code: code_value,
439        version: version_value,
440    })
441}
442
443fn expand_segment(input: &DeriveInput) -> syn::Result<TokenStream2> {
444    let ident = &input.ident;
445    let attr = parse_segment_attr(input)?;
446    let fields = parse_fields(input)?;
447    let code = &attr.code;
448    let version = attr.version;
449
450    let count = fields.len();
451    let mut decode = Vec::new();
452    let mut encode = Vec::new();
453    let mut checks = Vec::new();
454    let mut names = Vec::new();
455    let mut schema = Vec::new();
456    for (i, f) in fields.iter().enumerate() {
457        let fid = &f.ident;
458        let name = f.name();
459        let rules = f.rules();
460        let is_last = i + 1 == count;
461        names.push(fid.clone());
462        schema.push(f.schema());
463        checks.push(f.scalar_check());
464        match &f.repeated {
465            Some(inner) => {
466                let min = f.min_count.unwrap_or(0);
467                let max = opt_usize(f.max_count);
468                decode.push(quote! {
469                    let #fid = __slots.repeated::<#inner>(&#rules, #min, #max, #is_last)
470                        .map_err(|e| e.in_field(#name))?;
471                });
472                encode.push(quote! {
473                    __writer.repeated::<#inner>(&self.#fid, &#rules, #min, #max, #is_last)
474                        .map_err(|e| e.in_field(#name))?;
475                });
476            }
477            None => {
478                let ty = &f.ty;
479                decode.push(quote! {
480                    let #fid = __slots.single::<#ty>(&#rules)
481                        .map_err(|e| e.in_field(#name))?;
482                });
483                encode.push(quote! {
484                    __writer.single::<#ty>(&self.#fid, &#rules)
485                        .map_err(|e| e.in_field(#name))?;
486                });
487            }
488        }
489    }
490
491    let construct = if count == 0 {
492        quote! { Self {} }
493    } else {
494        quote! { Self { #(#names),* } }
495    };
496    // A unit struct is written `Self`, a braced struct `Self {}`.
497    let construct = match &input.data {
498        Data::Struct(s) if matches!(s.fields, Fields::Unit) => quote! { Self },
499        _ => construct,
500    };
501
502    Ok(quote! {
503        const _: () = {
504            use ::fints_client::codec::__private as __p;
505
506            impl __p::Segment for #ident {
507                const CODE: &'static str = #code;
508                const VERSION: u16 = #version;
509                const SCHEMA: &'static [__p::FieldSchema] = &[#(#schema),*];
510
511                fn decode_body(
512                    __body: &[__p::DEG],
513                ) -> ::core::result::Result<Self, __p::CodecError> {
514                    #[allow(unused_mut)]
515                    let mut __slots = __p::SlotReader::new(__body);
516                    #(#decode)*
517                    __slots.finish()?;
518                    ::core::result::Result::Ok(#construct)
519                }
520
521                fn encode_body(
522                    &self,
523                ) -> ::core::result::Result<::std::vec::Vec<__p::DEG>, __p::CodecError> {
524                    #[allow(unused_mut)]
525                    let mut __writer = __p::SlotWriter::new();
526                    #(#encode)*
527                    ::core::result::Result::Ok(__writer.finish())
528                }
529            }
530            #(#checks)*
531        };
532    })
533}